diff --git a/.oss-scanner/threat_model.md b/.oss-scanner/threat_model.md index c27f6976bde..01f5b394931 100644 --- a/.oss-scanner/threat_model.md +++ b/.oss-scanner/threat_model.md @@ -11,7 +11,7 @@ Treat everything a peer sends as hostile, before and after authentication: - **WebSocket and HTTP** on the relay's `[web]` listeners: the upgrade, the public `/announced`, `/fetch` and `/certificate.sha256` endpoints, and query strings. - **Authorization inputs**: the JWT (`moq-auth`), the SETUP token, the dialed path and query, and the relay's handling of grants (root, publish and subscribe pattern unions, mounts, expiry, revalidation). - **Media payloads**: catalogs (`hang`, `moq-msf`, JSON in `moq-json`) and containers and codecs parsed by `moq-mux` (fMP4, MPEG-TS, FLV, MKV, LOC, and the H.264, H.265, AV1, VP8, VP9, AAC, Opus and FLAC bitstream parsers). A publisher controls these bytes, and the relay or a subscriber may parse them. -- **Ingest gateways**: RTMP (`moq-rtmp`), RTSP (`moq-rtsp`), SRT (`moq-srt`), WebRTC WHIP/WHEP with ICE/STUN (`moq-webrtc`, including the str0m and dimpl copies vendored in `rs/moq-webrtc/src/vendor`), and HLS playlists and segments (`moq-hls`). +- **Ingest gateways**: RTMP (`moq-rtmp`), RTSP (`moq-rtsp`), SRT (`moq-srt`), WebRTC WHIP/WHEP with ICE/STUN (`moq-webrtc`, on the upstream str0m and dimpl crates), and HLS playlists and segments (`moq-hls`). - **Peer relays** in a cluster are authenticated but should not be able to break a node beyond what their grant allows. ## Security properties the relay must hold diff --git a/Cargo.lock b/Cargo.lock index 34f8c0c6d96..c47dc26e6c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -33,16 +33,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" -[[package]] -name = "aead" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" -dependencies = [ - "crypto-common 0.2.2", - "inout 0.2.6", -] - [[package]] name = "aes" version = "0.8.4" @@ -50,21 +40,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher 0.4.4", + "cipher", "cpufeatures 0.2.17", ] -[[package]] -name = "aes" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" -dependencies = [ - "cipher 0.5.2", - "cpubits", - "cpufeatures 0.3.1", -] - [[package]] name = "ahash" version = "0.8.12" @@ -717,6 +696,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.22.1" @@ -976,15 +961,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" -[[package]] -name = "byteorder_slice" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b294e30387378958e8bf8f4242131b930ea615ff81e8cac2440cea0a6013190" -dependencies = [ - "byteorder", -] - [[package]] name = "bytes" version = "1.12.1" @@ -1123,18 +1099,6 @@ dependencies = [ "shlex 2.0.1", ] -[[package]] -name = "ccm" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0be9b34d99d395af800e996c5784f810f8400ccd64202f91859dc677825b5378" -dependencies = [ - "aead", - "cipher 0.5.2", - "ctr 0.10.1", - "ctutils", -] - [[package]] name = "cexpr" version = "0.6.0" @@ -1225,18 +1189,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", - "inout 0.1.4", -] - -[[package]] -name = "cipher" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" -dependencies = [ - "block-buffer 0.12.1", - "crypto-common 0.2.2", - "inout 0.2.6", + "inout", ] [[package]] @@ -1613,12 +1566,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "cpubits" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" - [[package]] name = "cpufeatures" version = "0.2.17" @@ -1802,16 +1749,7 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher 0.4.4", -] - -[[package]] -name = "ctr" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" -dependencies = [ - "cipher 0.5.2", + "cipher", ] [[package]] @@ -1977,6 +1915,7 @@ dependencies = [ "const-oid 0.10.2", "der_derive", "flagset", + "pem-rfc7468", "zeroize", ] @@ -2014,17 +1953,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "derive-into-owned" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d94d81e3819a7b06a8638f448bc6339371ca9b6076a99d4a43eece3c4c923" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "derive_arbitrary" version = "1.5.0" @@ -2095,6 +2023,27 @@ dependencies = [ "ctutils", ] +[[package]] +name = "dimpl" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2c7b707106416bb46237cf25b702975015079fc5fa8791232b639bc4619c2de" +dependencies = [ + "arrayvec", + "der 0.8.3", + "log", + "nom 8.0.0", + "once_cell", + "pkcs8 0.11.0", + "rand 0.10.3", + "sec1", + "signature 3.0.0", + "spki 0.8.1", + "subtle", + "time", + "x509-cert", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -3497,15 +3446,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "inout" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" -dependencies = [ - "hybrid-array", -] - [[package]] name = "io-uring" version = "0.7.15" @@ -3523,6 +3463,19 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72dd0494853a6c3769c87adc610e8b228fd8c65c41cc4d2717ff6151ee2d6c73" +dependencies = [ + "crc", + "serde", + "str0m-proto", + "subtle", + "tracing", +] + [[package]] name = "is-terminal" version = "0.4.17" @@ -3740,7 +3693,7 @@ dependencies = [ "pem 3.0.6", "serde", "serde_json", - "signature", + "signature 2.2.0", "simple_asn1", "zeroize", ] @@ -5212,43 +5165,25 @@ dependencies = [ name = "moq-webrtc" version = "0.3.12" dependencies = [ - "aes 0.9.4", - "arrayvec", "axum", "bytes", - "ccm", - "combine", - "crc", - "fastrand", "hang", "kio", "moq-crypto", "moq-mux", "moq-net", "moq-tokio", - "nom 8.0.0", - "once_cell", - "pcap-file", - "rand 0.10.3", - "rcgen", "reqwest", "rind", - "rind-rcgen", - "serde", - "serde_json", - "spki 0.8.1", - "subtle", + "rind-str0m", + "str0m", "thiserror 2.0.21", - "time", "tokio", "tracing", - "tracing-subscriber", "tracing-test", "url", "uuid", "workspace-hack", - "x509-cert", - "x509-parser", ] [[package]] @@ -6336,17 +6271,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "pcap-file" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc1f139757b058f9f37b76c48501799d12c9aa0aa4c0d4c980b062ee925d1b2" -dependencies = [ - "byteorder_slice", - "derive-into-owned", - "thiserror 1.0.69", -] - [[package]] name = "pem" version = "3.0.6" @@ -6367,6 +6291,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -6923,10 +6856,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.3" @@ -6948,6 +6891,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -6957,6 +6910,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.1" @@ -7251,6 +7213,17 @@ dependencies = [ "libcrux-traits", ] +[[package]] +name = "rind-dimpl" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adbe61386677e9c3f6e0523608e465dc91b308a8e4845063e52e9d0be23dfaf5" +dependencies = [ + "dimpl", + "rind", + "x509-cert", +] + [[package]] name = "rind-jsonwebtoken" version = "11.0.3" @@ -7295,6 +7268,21 @@ dependencies = [ "rustls", ] +[[package]] +name = "rind-str0m" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98da3edaa7b4de2421e124d21f6f3928277dc0bc46521bbd22fd602fe794958" +dependencies = [ + "dimpl", + "rcgen", + "rind", + "rind-dimpl", + "rind-rcgen", + "str0m", + "time", +] + [[package]] name = "ring" version = "0.17.14" @@ -7753,6 +7741,21 @@ dependencies = [ "tiny-skia", ] +[[package]] +name = "sctp-proto" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28aca56f649fa088cbdda778a5121f2227995ed057e77de462112b2e5890d591" +dependencies = [ + "bytes", + "crc", + "log", + "rand 0.9.5", + "rustc-hash 2.1.3", + "slab", + "thiserror 2.0.21", +] + [[package]] name = "scuffle-av1" version = "0.1.4" @@ -7802,6 +7805,18 @@ dependencies = [ "fallible-iterator", ] +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "der 0.8.3", + "hybrid-array", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -8075,6 +8090,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" + [[package]] name = "simd-adler32" version = "0.3.10" @@ -8333,13 +8354,13 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22790a85cd5d34355e9fc246ded6a1f037add6fd0e0efe4d4914c2d51c20f246" dependencies = [ - "aes 0.8.4", + "aes", "array-init", "arraydeque", "bitflags 2.13.2", "bytes", - "cipher 0.4.4", - "ctr 0.9.2", + "cipher", + "ctr", "derive_more 0.99.20", "hex", "hmac 0.12.1", @@ -8409,6 +8430,40 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "str0m" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357c7e453c033c8bb59e912312f9f9ff07c2a9ce7268bcb94f0c828a5b47e58f" +dependencies = [ + "arrayvec", + "base64ct", + "combine", + "dimpl", + "fastrand", + "is", + "sctp-proto", + "serde", + "str0m-proto", + "subtle", + "time", + "tracing", +] + +[[package]] +name = "str0m-proto" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6a9a46a0f013add7a1d0d53d9bc92c85c1ac95243140fe0d073fb6e57c99b63" +dependencies = [ + "base64ct", + "dimpl", + "fastrand", + "serde", + "subtle", + "time", +] + [[package]] name = "streaming-stats" version = "0.2.3" @@ -10589,6 +10644,7 @@ dependencies = [ "object_store", "once_cell", "percent-encoding", + "pkcs8 0.11.0", "portable-atomic", "proc-macro2", "proptest", @@ -10612,6 +10668,7 @@ dependencies = [ "slab", "smallvec", "socket2 0.6.5", + "spki 0.8.1", "subtle", "syn 2.0.119", "syn 3.0.6", diff --git a/Cargo.toml b/Cargo.toml index d1c4790b9d3..6594c345a93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,9 +78,7 @@ rust-version = "1.91" allow_attributes_without_reason = "warn" [workspace.dependencies] -aes = "0.9" anyhow = "1" -arrayvec = "0.7.6" ash = "0.38" async-trait = "0.1" # Keep axum's defaults except tower-log, which enables tracing-to-log macros workspace-wide. @@ -102,17 +100,13 @@ bitflags = "2" bitstream-io = "4.10" block2 = "0.6.2" bytes = "1" -ccm = { version = "0.6", default-features = false } clap = { version = "4", features = ["derive"] } -combine = "4.6.6" -crc = "3" # CUDA driver bindings for the NVENC/NVDEC path. dlopen'd at runtime # (`fallback-dynamic-loading`), so nothing links against libcuda at build time. cudarc = { version = "0.19", default-features = false, features = ["driver", "fallback-dynamic-loading", "cuda-12020"] } data-encoding = "2.11" dispatch2 = "0.3.1" ebml-iterable = "0.7.1" -fastrand = "2" flate2 = { version = "1.1", default-features = false } futures = "0.3" h2 = "0.4" @@ -191,7 +185,6 @@ moq-video = { version = "0.1.10", path = "rs/moq-video", default-features = fals moq-webrtc = { version = "0.3.12", path = "rs/moq-webrtc" } mp4-atom = "0.17.1" nix = { version = "0.31.3", features = ["net", "socket", "uio"] } -nom = { version = "8", default-features = false, features = ["std"] } num_enum = "0.7" objc2 = "0.6.4" objc2-av-foundation = "0.3.2" @@ -201,8 +194,6 @@ objc2-screen-capture-kit = "0.3.2" # Default features off so a consumer that only needs InMemory does not pull the # local-filesystem stack; `fs` (and cloud backends) are opted in by the caller. object_store = { version = "0.14", default-features = false } -once_cell = "1.21.3" -pcap-file = "2" pem = "4.0.0" percent-encoding = "2" pkcs1 = { version = "0.8.0", features = ["alloc"] } @@ -225,6 +216,7 @@ rind-jsonwebtoken = "11.0.2" rind-object-store = "0.14.2" rind-rcgen = "0.14.2" rind-rustls = "0.23.2" +rind-str0m = "0.25.2" rustc-hash = "2.1.3" rustls-native-certs = "0.8.5" sd-notify = "0.5" @@ -234,8 +226,8 @@ serde_json = "1" serde_with = "3" slab = "0.4.12" socket2 = "0.6" -spki = "0.8" -subtle = "2.6" +# default-features off drops str0m's aws-lc-rs crypto provider; rind-str0m supplies rind's. +str0m = { version = "0.25", default-features = false } tempfile = "3" thiserror = "2" time = "0.3" @@ -258,7 +250,6 @@ web-transport-proto = "0.6.4" web-transport-trait = "0.5" wgpu = "30" x11rb = { version = "0.14.0", features = ["randr", "xfixes"] } -x509-cert = { version = "0.3", default-features = false } x509-parser = "0.18" zeroize = { version = "1", features = ["derive"] } diff --git a/doc/bin/rtc.md b/doc/bin/rtc.md index c72365778df..dc1e4e995a8 100644 --- a/doc/bin/rtc.md +++ b/doc/bin/rtc.md @@ -43,5 +43,5 @@ Once the original publisher leaves, the session ends with an error, and the player or `export rtc --connect` must reconnect to reach the replacement. `--connect` runs until its session ends. -Built on a vendored, trimmed copy of [str0m](https://github.com/algesten/str0m), with DTLS and SRTP on [rind](https://github.com/kixel-ai/rind); the library is +Built on [str0m](https://github.com/algesten/str0m), with DTLS and SRTP on [rind](https://github.com/kixel-ai/rind); the library is [`moq-webrtc`](https://github.com/moq-dev/moq/tree/main/rs/moq-webrtc). diff --git a/nix/Cargo.nix b/nix/Cargo.nix index e851542f990..f8e84c5543c 100644 --- a/nix/Cargo.nix +++ b/nix/Cargo.nix @@ -720,42 +720,7 @@ rec { "rustc-dep-of-std" = [ "core" ]; }; }; - "aead" = rec { - crateName = "aead"; - version = "0.6.1"; - edition = "2024"; - sha256 = "16acx2vq8lfwr6v8yhg1q7cggrr8ih41ykp7a3srrbrd3aycywqr"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "crypto-common"; - packageId = "crypto-common 0.2.2"; - rename = "common"; - } - { - name = "inout"; - packageId = "inout 0.2.6"; - } - ]; - features = { - "arrayvec" = [ "dep:arrayvec" ]; - "blobby" = [ "dep:blobby" ]; - "bytes" = [ "dep:bytes" ]; - "default" = [ "rand_core" ]; - "dev" = [ - "blobby" - "alloc" - ]; - "getrandom" = [ - "common/getrandom" - "rand_core" - ]; - "rand_core" = [ "common/rand_core" ]; - }; - }; - "aes 0.8.4" = rec { + "aes" = rec { crateName = "aes"; version = "0.8.4"; edition = "2021"; @@ -770,7 +735,7 @@ rec { } { name = "cipher"; - packageId = "cipher 0.4.4"; + packageId = "cipher"; } { name = "cpufeatures"; @@ -787,47 +752,7 @@ rec { devDependencies = [ { name = "cipher"; - packageId = "cipher 0.4.4"; - features = [ "dev" ]; - } - ]; - features = { - "zeroize" = [ "dep:zeroize" ]; - }; - }; - "aes 0.9.4" = rec { - crateName = "aes"; - version = "0.9.4"; - edition = "2024"; - sha256 = "1labw01pbfwqc8f62k01ppmmdq403si0ifk8ajs1bl20finw63zw"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "cipher"; - packageId = "cipher 0.5.2"; - } - { - name = "cpubits"; - packageId = "cpubits"; - } - { - name = "cpufeatures"; - packageId = "cpufeatures 0.3.1"; - target = - { target, features }: - ( - ("aarch64" == target."arch" or null) - || ("x86_64" == target."arch" or null) - || ("x86" == target."arch" or null) - ); - } - ]; - devDependencies = [ - { - name = "cipher"; - packageId = "cipher 0.5.2"; + packageId = "cipher"; features = [ "dev" ]; } ]; @@ -3374,6 +3299,17 @@ rec { "std" ]; }; + "base16ct" = rec { + crateName = "base16ct"; + version = "1.0.0"; + edition = "2024"; + sha256 = "1xi6jy6y08hbxfy14pxjlxcggl9kfsvsn3jbyyk7lii4ss878c7x"; + authors = [ + "RustCrypto Developers" + ]; + features = { + }; + }; "base64 0.22.1" = rec { crateName = "base64"; version = "0.22.1"; @@ -4290,22 +4226,6 @@ rec { "std" ]; }; - "byteorder_slice" = rec { - crateName = "byteorder_slice"; - version = "3.0.0"; - edition = "2021"; - sha256 = "141i06ka1kj04jn8q7pqbxhylc5r64hj9x7qif79ay3k70q4wa8b"; - authors = [ - "courvoif " - ]; - dependencies = [ - { - name = "byteorder"; - packageId = "byteorder"; - } - ]; - - }; "bytes" = rec { crateName = "bytes"; version = "1.12.1"; @@ -4740,55 +4660,6 @@ rec { }; resolvedDefaultFeatures = [ "parallel" ]; }; - "ccm" = rec { - crateName = "ccm"; - version = "0.6.1"; - edition = "2024"; - sha256 = "0y2kbf17gilxhn8jy834rl641y0hz225fv4r1s0az5fkk56v7s8b"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "aead"; - packageId = "aead"; - usesDefaultFeatures = false; - } - { - name = "cipher"; - packageId = "cipher 0.5.2"; - usesDefaultFeatures = false; - } - { - name = "ctr"; - packageId = "ctr 0.10.1"; - usesDefaultFeatures = false; - } - { - name = "ctutils"; - packageId = "ctutils"; - } - ]; - devDependencies = [ - { - name = "aead"; - packageId = "aead"; - usesDefaultFeatures = false; - features = [ "dev" ]; - } - ]; - features = { - "alloc" = [ "aead/alloc" ]; - "arrayvec" = [ "aead/arrayvec" ]; - "bytes" = [ "aead/bytes" ]; - "default" = [ - "alloc" - "getrandom" - ]; - "getrandom" = [ "aead/getrandom" ]; - "rand_core" = [ "aead/rand_core" ]; - }; - }; "cexpr" = rec { crateName = "cexpr"; version = "0.6.0"; @@ -5100,7 +4971,7 @@ rec { ]; }; }; - "cipher 0.4.4" = rec { + "cipher" = rec { crateName = "cipher"; version = "0.4.4"; edition = "2021"; @@ -5115,7 +4986,7 @@ rec { } { name = "inout"; - packageId = "inout 0.1.4"; + packageId = "inout"; } ]; features = { @@ -5131,49 +5002,6 @@ rec { "zeroize" = [ "dep:zeroize" ]; }; }; - "cipher 0.5.2" = rec { - crateName = "cipher"; - version = "0.5.2"; - edition = "2024"; - sha256 = "0v7sic43nmz4rgql62wmxq0z63s80gnmd0w5q1vlhw6djcn2mkz8"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "block-buffer"; - packageId = "block-buffer 0.12.1"; - optional = true; - } - { - name = "crypto-common"; - packageId = "crypto-common 0.2.2"; - rename = "common"; - } - { - name = "inout"; - packageId = "inout 0.2.6"; - } - ]; - features = { - "blobby" = [ "dep:blobby" ]; - "block-buffer" = [ "dep:block-buffer" ]; - "block-padding" = [ "inout/block-padding" ]; - "dev" = [ "blobby" ]; - "getrandom" = [ "common/getrandom" ]; - "rand_core" = [ "common/rand_core" ]; - "stream-wrapper" = [ "block-buffer" ]; - "zeroize" = [ - "dep:zeroize" - "common/zeroize" - "block-buffer?/zeroize" - ]; - }; - resolvedDefaultFeatures = [ - "block-buffer" - "stream-wrapper" - ]; - }; "clang-sys" = rec { crateName = "clang-sys"; version = "1.9.1"; @@ -6874,16 +6702,6 @@ rec { } ]; - }; - "cpubits" = rec { - crateName = "cpubits"; - version = "0.1.1"; - edition = "2024"; - sha256 = "1bh6rvanxm00myf1rmnh44hq2jdxn69971c92s4klz0k76f5zf0m"; - authors = [ - "RustCrypto Developers" - ]; - }; "cpufeatures 0.2.17" = rec { crateName = "cpufeatures"; @@ -7513,35 +7331,7 @@ rec { "zeroize" = [ "hybrid-array/zeroize" ]; }; }; - "ctr 0.10.1" = rec { - crateName = "ctr"; - version = "0.10.1"; - edition = "2024"; - sha256 = "088z8sa9aw7ij1sy4hlpxz20jhffnsfiwmsdysb2a29pnb2a3b5s"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "cipher"; - packageId = "cipher 0.5.2"; - features = [ "stream-wrapper" ]; - } - ]; - devDependencies = [ - { - name = "cipher"; - packageId = "cipher 0.5.2"; - features = [ "dev" ]; - } - ]; - features = { - "alloc" = [ "cipher/alloc" ]; - "block-padding" = [ "cipher/block-padding" ]; - "zeroize" = [ "cipher/zeroize" ]; - }; - }; - "ctr 0.9.2" = rec { + "ctr" = rec { crateName = "ctr"; version = "0.9.2"; edition = "2021"; @@ -7552,13 +7342,13 @@ rec { dependencies = [ { name = "cipher"; - packageId = "cipher 0.4.4"; + packageId = "cipher"; } ]; devDependencies = [ { name = "cipher"; - packageId = "cipher 0.4.4"; + packageId = "cipher"; features = [ "dev" ]; } ]; @@ -8136,6 +7926,12 @@ rec { packageId = "flagset"; optional = true; } + { + name = "pem-rfc7468"; + packageId = "pem-rfc7468"; + optional = true; + features = [ "alloc" ]; + } { name = "zeroize"; packageId = "zeroize"; @@ -8173,6 +7969,7 @@ rec { "derive" "flagset" "oid" + "pem" "std" "zeroize" ]; @@ -8298,32 +8095,6 @@ rec { "serde" ]; }; - "derive-into-owned" = rec { - crateName = "derive-into-owned"; - version = "0.2.0"; - edition = "2021"; - sha256 = "08y9qkiyqgm4sjcnl1xnm4f3ffb3pi4g8f46daqaf69q3vc9979c"; - procMacro = true; - libName = "derive_into_owned"; - authors = [ - "Joonas Koivunen " - ]; - dependencies = [ - { - name = "proc-macro2"; - packageId = "proc-macro2"; - } - { - name = "quote"; - packageId = "quote"; - } - { - name = "syn"; - packageId = "syn 1.0.109"; - } - ]; - - }; "derive_arbitrary" = rec { crateName = "derive_arbitrary"; version = "1.5.0"; @@ -8786,6 +8557,120 @@ rec { "oid" ]; }; + "dimpl" = rec { + crateName = "dimpl"; + version = "0.9.0"; + edition = "2024"; + sha256 = "1pn2353bqfdn6897ka2zziwm00bm55q5pwkw4d3bn5k4203vgixj"; + authors = [ + "Martin Algesten " + ]; + dependencies = [ + { + name = "arrayvec"; + packageId = "arrayvec"; + } + { + name = "der"; + packageId = "der 0.8.3"; + optional = true; + } + { + name = "log"; + packageId = "log"; + } + { + name = "nom"; + packageId = "nom 8.0.0"; + usesDefaultFeatures = false; + features = [ "std" ]; + } + { + name = "once_cell"; + packageId = "once_cell"; + } + { + name = "pkcs8"; + packageId = "pkcs8 0.11.0"; + optional = true; + features = [ "pem" ]; + } + { + name = "rand"; + packageId = "rand 0.10.3"; + } + { + name = "sec1"; + packageId = "sec1"; + optional = true; + } + { + name = "signature"; + packageId = "signature 3.0.0"; + optional = true; + } + { + name = "spki"; + packageId = "spki 0.8.1"; + optional = true; + } + { + name = "subtle"; + packageId = "subtle"; + } + { + name = "time"; + packageId = "time"; + features = [ "formatting" ]; + } + { + name = "x509-cert"; + packageId = "x509-cert"; + optional = true; + usesDefaultFeatures = false; + } + ]; + features = { + "_crypto-common" = [ + "dep:der" + "dep:pkcs8" + "dep:sec1" + "dep:signature" + "dep:spki" + "dep:x509-cert" + ]; + "aws-lc-rs" = [ + "dep:aws-lc-rs" + "dep:ccm" + "dep:aes" + "_crypto-common" + ]; + "default" = [ + "aws-lc-rs" + "rcgen" + ]; + "rcgen" = [ + "dep:rcgen" + "aws-lc-rs" + ]; + "rust-crypto" = [ + "dep:aes-gcm" + "dep:chacha20poly1305" + "dep:chacha20" + "dep:p256" + "dep:p384" + "dep:x25519-dalek" + "dep:sha2" + "dep:hmac" + "dep:hkdf" + "dep:ecdsa" + "dep:ccm" + "dep:aes" + "_crypto-common" + ]; + }; + resolvedDefaultFeatures = [ "_crypto-common" ]; + }; "dispatch" = rec { crateName = "dispatch"; version = "0.2.0"; @@ -10665,6 +10550,7 @@ rec { "dep:js-sys" ]; }; + resolvedDefaultFeatures = [ "std" ]; }; "getrandom 0.4.3" = rec { crateName = "getrandom"; @@ -15140,7 +15026,7 @@ rec { features = { }; }; - "inout 0.1.4" = rec { + "inout" = rec { crateName = "inout"; version = "0.1.4"; edition = "2021"; @@ -15159,24 +15045,6 @@ rec { "std" = [ "block-padding/std" ]; }; }; - "inout 0.2.6" = rec { - crateName = "inout"; - version = "0.2.6"; - edition = "2024"; - sha256 = "1ydvvz2v7pbgmaixjmhnbqf0a9mp84d6ngyx8bpkbhzzy09hqn1s"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "hybrid-array"; - packageId = "hybrid-array"; - } - ]; - features = { - "block-padding" = [ "dep:block-padding" ]; - }; - }; "io-uring" = rec { crateName = "io-uring"; version = "0.7.15"; @@ -15237,6 +15105,49 @@ rec { "std" ]; }; + "is" = rec { + crateName = "is"; + version = "0.12.0"; + edition = "2024"; + sha256 = "0wvc5pp52qgz2wklvk21bk3di3r2ic763p3sr1lkfv1shna09pbj"; + authors = [ + "Martin Algesten " + "Thomas Eizinger " + ]; + dependencies = [ + { + name = "crc"; + packageId = "crc"; + } + { + name = "serde"; + packageId = "serde"; + features = [ "derive" ]; + } + { + name = "str0m-proto"; + packageId = "str0m-proto"; + usesDefaultFeatures = false; + } + { + name = "subtle"; + packageId = "subtle"; + } + { + name = "tracing"; + packageId = "tracing"; + } + ]; + features = { + "_internal_test_exports" = [ "str0m-proto/_internal_test_exports" ]; + "default" = [ "sha1" ]; + "pii" = [ "str0m-proto/pii" ]; + "sha1" = [ + "dep:hmac" + "dep:sha1_" + ]; + }; + }; "is-terminal" = rec { crateName = "is-terminal"; version = "0.4.17"; @@ -16017,7 +15928,7 @@ rec { } { name = "signature"; - packageId = "signature"; + packageId = "signature 2.2.0"; features = [ "std" ]; } { @@ -23060,14 +22971,6 @@ rec { "Luke Curley " ]; dependencies = [ - { - name = "aes"; - packageId = "aes 0.9.4"; - } - { - name = "arrayvec"; - packageId = "arrayvec"; - } { name = "axum"; packageId = "axum"; @@ -23088,23 +22991,6 @@ rec { name = "bytes"; packageId = "bytes"; } - { - name = "ccm"; - packageId = "ccm"; - usesDefaultFeatures = false; - } - { - name = "combine"; - packageId = "combine"; - } - { - name = "crc"; - packageId = "crc"; - } - { - name = "fastrand"; - packageId = "fastrand"; - } { name = "hang"; packageId = "hang"; @@ -23134,25 +23020,6 @@ rec { packageId = "moq-tokio"; usesDefaultFeatures = false; } - { - name = "nom"; - packageId = "nom 8.0.0"; - usesDefaultFeatures = false; - features = [ "std" ]; - } - { - name = "once_cell"; - packageId = "once_cell"; - } - { - name = "rand"; - packageId = "rand 0.10.3"; - } - { - name = "rcgen"; - packageId = "rcgen"; - usesDefaultFeatures = false; - } { name = "reqwest"; packageId = "reqwest"; @@ -23160,36 +23027,18 @@ rec { features = [ "rustls-no-provider" ]; } { - name = "rind"; - packageId = "rind"; - features = [ "wipe" ]; + name = "rind-str0m"; + packageId = "rind-str0m"; } { - name = "rind-rcgen"; - packageId = "rind-rcgen"; - } - { - name = "serde"; - packageId = "serde"; - features = [ "derive" ]; - } - { - name = "spki"; - packageId = "spki 0.8.1"; - } - { - name = "subtle"; - packageId = "subtle"; + name = "str0m"; + packageId = "str0m"; + usesDefaultFeatures = false; } { name = "thiserror"; packageId = "thiserror 2.0.21"; } - { - name = "time"; - packageId = "time"; - features = [ "formatting" ]; - } { name = "tokio"; packageId = "tokio"; @@ -23208,11 +23057,6 @@ rec { packageId = "uuid"; features = [ "v4" ]; } - { - name = "x509-cert"; - packageId = "x509-cert"; - usesDefaultFeatures = false; - } ]; devDependencies = [ { @@ -23221,23 +23065,15 @@ rec { usesDefaultFeatures = false; } { - name = "pcap-file"; - packageId = "pcap-file"; - } - { - name = "serde_json"; - packageId = "serde_json"; + name = "rind"; + packageId = "rind"; + features = [ "wipe" ]; } { name = "tokio"; packageId = "tokio"; features = [ "test-util" ]; } - { - name = "tracing-subscriber"; - packageId = "tracing-subscriber"; - features = [ "env-filter" ]; - } { name = "tracing-test"; packageId = "tracing-test"; @@ -23246,10 +23082,6 @@ rec { name = "workspace-hack"; packageId = "workspace-hack"; } - { - name = "x509-parser"; - packageId = "x509-parser"; - } ]; features = { "default" = [ "server" ]; @@ -37966,31 +37798,6 @@ rec { "std" = [ "password-hash/std" ]; }; }; - "pcap-file" = rec { - crateName = "pcap-file"; - version = "2.0.0"; - edition = "2021"; - sha256 = "1cni4pljw1hbk160sk5al2d2rlcr2x84hv5p6ygqy1bvflwz3h8z"; - libName = "pcap_file"; - authors = [ - "Courvoif " - ]; - dependencies = [ - { - name = "byteorder_slice"; - packageId = "byteorder_slice"; - } - { - name = "derive-into-owned"; - packageId = "derive-into-owned"; - } - { - name = "thiserror"; - packageId = "thiserror 1.0.69"; - } - ]; - - }; "pem 3.0.6" = rec { crateName = "pem"; version = "3.0.6"; @@ -38061,6 +37868,30 @@ rec { "std" ]; }; + "pem-rfc7468" = rec { + crateName = "pem-rfc7468"; + version = "1.0.0"; + edition = "2024"; + sha256 = "1nck8ig71axy21lsick2f9vcw7329mlx2hs88d382wz7w0im8c56"; + libName = "pem_rfc7468"; + authors = [ + "RustCrypto Developers" + ]; + dependencies = [ + { + name = "base64ct"; + packageId = "base64ct"; + } + ]; + features = { + "alloc" = [ "base64ct/alloc" ]; + "std" = [ + "alloc" + "base64ct/std" + ]; + }; + resolvedDefaultFeatures = [ "alloc" ]; + }; "percent-encoding" = rec { crateName = "percent-encoding"; version = "2.3.2"; @@ -38713,6 +38544,10 @@ rec { "spki/std" ]; }; + resolvedDefaultFeatures = [ + "alloc" + "pem" + ]; }; "pkg-config" = rec { crateName = "pkg-config"; @@ -40254,7 +40089,7 @@ rec { } { name = "rand_chacha"; - packageId = "rand_chacha"; + packageId = "rand_chacha 0.3.1"; optional = true; usesDefaultFeatures = false; } @@ -40296,7 +40131,64 @@ rec { "std_rng" ]; }; - "rand_chacha" = rec { + "rand 0.9.5" = rec { + crateName = "rand"; + version = "0.9.5"; + edition = "2021"; + sha256 = "0hbvllk8g28mqjld6hqmckk69w296qpzg95whm3didsyg46ivvxr"; + authors = [ + "The Rand Project Developers" + "The Rust Project Developers" + ]; + dependencies = [ + { + name = "rand_chacha"; + packageId = "rand_chacha 0.9.0"; + optional = true; + usesDefaultFeatures = false; + } + { + name = "rand_core"; + packageId = "rand_core 0.9.5"; + usesDefaultFeatures = false; + } + ]; + features = { + "default" = [ + "std" + "std_rng" + "os_rng" + "small_rng" + "thread_rng" + ]; + "os_rng" = [ "rand_core/os_rng" ]; + "serde" = [ + "dep:serde" + "rand_core/serde" + ]; + "std" = [ + "rand_core/std" + "rand_chacha?/std" + "alloc" + ]; + "std_rng" = [ "dep:rand_chacha" ]; + "thread_rng" = [ + "std" + "std_rng" + "os_rng" + ]; + }; + resolvedDefaultFeatures = [ + "alloc" + "default" + "os_rng" + "small_rng" + "std" + "std_rng" + "thread_rng" + ]; + }; + "rand_chacha 0.3.1" = rec { crateName = "rand_chacha"; version = "0.3.1"; edition = "2018"; @@ -40326,6 +40218,46 @@ rec { }; resolvedDefaultFeatures = [ "std" ]; }; + "rand_chacha 0.9.0" = rec { + crateName = "rand_chacha"; + version = "0.9.0"; + edition = "2021"; + sha256 = "1jr5ygix7r60pz0s1cv3ms1f6pd1i9pcdmnxzzhjc3zn3mgjn0nk"; + authors = [ + "The Rand Project Developers" + "The Rust Project Developers" + "The CryptoCorrosion Contributors" + ]; + dependencies = [ + { + name = "ppv-lite86"; + packageId = "ppv-lite86"; + usesDefaultFeatures = false; + features = [ "simd" ]; + } + { + name = "rand_core"; + packageId = "rand_core 0.9.5"; + } + ]; + devDependencies = [ + { + name = "rand_core"; + packageId = "rand_core 0.9.5"; + features = [ "os_rng" ]; + } + ]; + features = { + "default" = [ "std" ]; + "os_rng" = [ "rand_core/os_rng" ]; + "serde" = [ "dep:serde" ]; + "std" = [ + "ppv-lite86/std" + "rand_core/std" + ]; + }; + resolvedDefaultFeatures = [ "std" ]; + }; "rand_core 0.10.1" = rec { crateName = "rand_core"; version = "0.10.1"; @@ -40368,6 +40300,32 @@ rec { "std" ]; }; + "rand_core 0.9.5" = rec { + crateName = "rand_core"; + version = "0.9.5"; + edition = "2021"; + sha256 = "0g6qc5r3f0hdmz9b11nripyp9qqrzb0xqk9piip8w8qlvqkcibvn"; + authors = [ + "The Rand Project Developers" + "The Rust Project Developers" + ]; + dependencies = [ + { + name = "getrandom"; + packageId = "getrandom 0.3.4"; + optional = true; + } + ]; + features = { + "os_rng" = [ "dep:getrandom" ]; + "serde" = [ "dep:serde" ]; + "std" = [ "getrandom?/std" ]; + }; + resolvedDefaultFeatures = [ + "os_rng" + "std" + ]; + }; "rand_pcg" = rec { crateName = "rand_pcg"; version = "0.10.2"; @@ -42475,6 +42433,42 @@ rec { "wipe" ]; }; + "rind-dimpl" = rec { + crateName = "rind-dimpl"; + version = "0.9.3"; + edition = "2024"; + sha256 = "1xgs7pi0p79fwmim1174m04b74fwcpj0hdjjw3vc7sbpcqw63gmd"; + libName = "rind_dimpl"; + dependencies = [ + { + name = "dimpl"; + packageId = "dimpl"; + usesDefaultFeatures = false; + features = [ "_crypto-common" ]; + } + { + name = "rind"; + packageId = "rind"; + } + { + name = "x509-cert"; + packageId = "x509-cert"; + usesDefaultFeatures = false; + } + ]; + devDependencies = [ + { + name = "dimpl"; + packageId = "dimpl"; + usesDefaultFeatures = false; + features = [ + "aws-lc-rs" + "_crypto-common" + ]; + } + ]; + + }; "rind-jsonwebtoken" = rec { crateName = "rind-jsonwebtoken"; version = "11.0.3"; @@ -42617,6 +42611,49 @@ rec { }; resolvedDefaultFeatures = [ "default" ]; }; + "rind-str0m" = rec { + crateName = "rind-str0m"; + version = "0.25.2"; + edition = "2024"; + sha256 = "0n29g7z05migsaxj2rf41gf7g0ljygv22k8j3r1f4kbvmbns73fr"; + libName = "rind_str0m"; + dependencies = [ + { + name = "dimpl"; + packageId = "dimpl"; + usesDefaultFeatures = false; + } + { + name = "rcgen"; + packageId = "rcgen"; + usesDefaultFeatures = false; + } + { + name = "rind"; + packageId = "rind"; + } + { + name = "rind-dimpl"; + packageId = "rind-dimpl"; + } + { + name = "rind-rcgen"; + packageId = "rind-rcgen"; + } + { + name = "str0m"; + packageId = "str0m"; + usesDefaultFeatures = false; + } + { + name = "time"; + packageId = "time"; + usesDefaultFeatures = false; + features = [ "std" ]; + } + ]; + + }; "ring" = rec { crateName = "ring"; version = "0.17.14"; @@ -44917,6 +44954,49 @@ rec { "memmap2" ]; }; + "sctp-proto" = rec { + crateName = "sctp-proto"; + version = "0.10.8"; + edition = "2024"; + sha256 = "14fmj1c2waqicbj7vrsps1g9j9r23w9aay57vp5qi84zcipsbb18"; + libName = "sctp_proto"; + authors = [ + "Rain Liu " + "Martin Algesten" + ]; + dependencies = [ + { + name = "bytes"; + packageId = "bytes"; + } + { + name = "crc"; + packageId = "crc"; + } + { + name = "log"; + packageId = "log"; + } + { + name = "rand"; + packageId = "rand 0.9.5"; + } + { + name = "rustc-hash"; + packageId = "rustc-hash 2.1.3"; + } + { + name = "slab"; + packageId = "slab"; + } + { + name = "thiserror"; + packageId = "thiserror 2.0.21"; + } + ]; + features = { + }; + }; "scuffle-av1" = rec { crateName = "scuffle-av1"; version = "0.1.4"; @@ -45034,6 +45114,80 @@ rec { "serde" = [ "dep:serde" ]; }; }; + "sec1" = rec { + crateName = "sec1"; + version = "0.8.1"; + edition = "2024"; + sha256 = "0k8fm3c0j2hb9bs5mgnksk9g75ny65w50bhjyzjkq80r5xy46vfm"; + authors = [ + "RustCrypto Developers" + ]; + dependencies = [ + { + name = "base16ct"; + packageId = "base16ct"; + optional = true; + usesDefaultFeatures = false; + } + { + name = "der"; + packageId = "der 0.8.3"; + optional = true; + features = [ "oid" ]; + } + { + name = "hybrid-array"; + packageId = "hybrid-array"; + optional = true; + usesDefaultFeatures = false; + } + { + name = "zeroize"; + packageId = "zeroize"; + optional = true; + usesDefaultFeatures = false; + } + ]; + features = { + "alloc" = [ + "der?/alloc" + "zeroize?/alloc" + ]; + "ctutils" = [ "dep:ctutils" ]; + "default" = [ + "der" + "point" + ]; + "der" = [ + "dep:der" + "zeroize" + ]; + "pem" = [ + "alloc" + "der/pem" + ]; + "point" = [ + "dep:base16ct" + "dep:hybrid-array" + ]; + "serde" = [ "dep:serdect" ]; + "std" = [ + "alloc" + "der?/std" + ]; + "subtle" = [ "dep:subtle" ]; + "zeroize" = [ + "dep:zeroize" + "der?/zeroize" + ]; + }; + resolvedDefaultFeatures = [ + "default" + "der" + "point" + "zeroize" + ]; + }; "security-framework" = rec { crateName = "security-framework"; version = "3.7.0"; @@ -46093,7 +46247,7 @@ rec { ]; }; - "signature" = rec { + "signature 2.2.0" = rec { crateName = "signature"; version = "2.2.0"; edition = "2021"; @@ -46123,6 +46277,19 @@ rec { "std" ]; }; + "signature 3.0.0" = rec { + crateName = "signature"; + version = "3.0.0"; + edition = "2024"; + sha256 = "1x9pfp51h2a0xs4x768q5r0y9yazv5naf216mjw9q17hpbf6gm98"; + authors = [ + "RustCrypto Developers" + ]; + features = { + "digest" = [ "dep:digest" ]; + "rand_core" = [ "dep:rand_core" ]; + }; + }; "simd-adler32" = rec { crateName = "simd-adler32"; version = "0.3.10"; @@ -46959,7 +47126,10 @@ rec { "alloc" ]; }; - resolvedDefaultFeatures = [ "alloc" ]; + resolvedDefaultFeatures = [ + "alloc" + "pem" + ]; }; "srt-protocol" = rec { crateName = "srt-protocol"; @@ -46973,7 +47143,7 @@ rec { dependencies = [ { name = "aes"; - packageId = "aes 0.8.4"; + packageId = "aes"; } { name = "array-init"; @@ -46993,11 +47163,11 @@ rec { } { name = "cipher"; - packageId = "cipher 0.4.4"; + packageId = "cipher"; } { name = "ctr"; - packageId = "ctr 0.9.2"; + packageId = "ctr"; } { name = "derive_more"; @@ -47231,6 +47401,144 @@ rec { "std" ]; }; + "str0m" = rec { + crateName = "str0m"; + version = "0.25.0"; + edition = "2024"; + sha256 = "13z58xdqm0hc9ywvqs3jrslw41zzz7wi48wikssqng037i2pwz1m"; + authors = [ + "Martin Algesten " + "Hugo Tunius " + "Davide Bertola " + ]; + dependencies = [ + { + name = "arrayvec"; + packageId = "arrayvec"; + } + { + name = "base64ct"; + packageId = "base64ct"; + } + { + name = "combine"; + packageId = "combine"; + } + { + name = "dimpl"; + packageId = "dimpl"; + usesDefaultFeatures = false; + } + { + name = "fastrand"; + packageId = "fastrand"; + } + { + name = "is"; + packageId = "is"; + usesDefaultFeatures = false; + } + { + name = "sctp-proto"; + packageId = "sctp-proto"; + } + { + name = "serde"; + packageId = "serde"; + features = [ "derive" ]; + } + { + name = "str0m-proto"; + packageId = "str0m-proto"; + usesDefaultFeatures = false; + features = [ "dtls" ]; + } + { + name = "subtle"; + packageId = "subtle"; + } + { + name = "time"; + packageId = "time"; + } + { + name = "tracing"; + packageId = "tracing"; + } + ]; + features = { + "_internal_test_exports" = [ + "str0m-proto/_internal_test_exports" + "is/_internal_test_exports" + ]; + "apple-crypto" = [ "dep:str0m-apple-crypto" ]; + "aws-lc-rs" = [ "dep:str0m-aws-lc-rs" ]; + "default" = [ + "aws-lc-rs" + "examples" + ]; + "drv" = [ "dep:drv" ]; + "examples" = [ "rouille/rustls" ]; + "openssl" = [ "dep:str0m-openssl" ]; + "openssl-dimpl" = [ + "dep:str0m-openssl" + "str0m-openssl/dimpl" + ]; + "pii" = [ + "str0m-proto/pii" + "is/pii" + ]; + "rust-crypto" = [ "dep:str0m-rust-crypto" ]; + "vendored" = [ "str0m-openssl?/vendored" ]; + "wincrypto" = [ "dep:str0m-wincrypto" ]; + "wincrypto-dimpl" = [ "wincrypto" ]; + }; + }; + "str0m-proto" = rec { + crateName = "str0m-proto"; + version = "0.8.0"; + edition = "2024"; + sha256 = "0qwvr5bnxyvks3h0y523ab4ilp68jaydjlqd3mxdsfh11xma9ag6"; + libName = "str0m_proto"; + authors = [ + "Martin Algesten " + ]; + dependencies = [ + { + name = "base64ct"; + packageId = "base64ct"; + } + { + name = "dimpl"; + packageId = "dimpl"; + optional = true; + usesDefaultFeatures = false; + } + { + name = "fastrand"; + packageId = "fastrand"; + } + { + name = "serde"; + packageId = "serde"; + features = [ "derive" ]; + } + { + name = "subtle"; + packageId = "subtle"; + } + { + name = "time"; + packageId = "time"; + } + ]; + features = { + "default" = [ "dtls" ]; + "dtls" = [ "dep:dimpl" ]; + "openssl" = [ "dep:openssl" ]; + }; + resolvedDefaultFeatures = [ "dtls" ]; + }; "streaming-stats" = rec { crateName = "streaming-stats"; version = "0.2.3"; @@ -58935,8 +59243,8 @@ rec { "derive" "flagset" "oid" + "pem" "std" - "zeroize" ]; } { @@ -59535,6 +59843,12 @@ rec { name = "percent-encoding"; packageId = "percent-encoding"; } + { + name = "pkcs8"; + packageId = "pkcs8 0.11.0"; + usesDefaultFeatures = false; + features = [ "pem" ]; + } { name = "portable-atomic"; packageId = "portable-atomic"; @@ -59772,6 +60086,12 @@ rec { usesDefaultFeatures = false; features = [ "all" ]; } + { + name = "spki"; + packageId = "spki 0.8.1"; + usesDefaultFeatures = false; + features = [ "pem" ]; + } { name = "subtle"; packageId = "subtle"; @@ -60392,8 +60712,8 @@ rec { "derive" "flagset" "oid" + "pem" "std" - "zeroize" ]; } { @@ -61006,6 +61326,12 @@ rec { name = "percent-encoding"; packageId = "percent-encoding"; } + { + name = "pkcs8"; + packageId = "pkcs8 0.11.0"; + usesDefaultFeatures = false; + features = [ "pem" ]; + } { name = "portable-atomic"; packageId = "portable-atomic"; @@ -61231,6 +61557,12 @@ rec { usesDefaultFeatures = false; features = [ "all" ]; } + { + name = "spki"; + packageId = "spki 0.8.1"; + usesDefaultFeatures = false; + features = [ "pem" ]; + } { name = "subtle"; packageId = "subtle"; diff --git a/nix/crates.nix b/nix/crates.nix index 24f30c3b488..de8a1d0da7a 100644 --- a/nix/crates.nix +++ b/nix/crates.nix @@ -12,18 +12,14 @@ let inherit (pkgs) lib; # The files cargo compiles from (.rs and .toml, as crane's filter keeps), plus - # what crates embed at compile time: moq-video's PTX and moq-webrtc's crypto - # validation data. A README or CHANGELOG edit rebuilds nothing. + # what crates embed at compile time: moq-video's PTX. A README or CHANGELOG + # edit rebuilds nothing. filterSources = path: type: type == "directory" || lib.hasSuffix ".rs" path || lib.hasSuffix ".toml" path - || lib.hasSuffix ".ptx" path - || ( - lib.hasInfix "/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/" path - && (lib.hasSuffix ".der" path || lib.hasSuffix ".bin" path) - ); + || lib.hasSuffix ".ptx" path; buildRustCrate = pkgs.buildRustCrate.override { rustc = rustToolchain; diff --git a/pyproject.toml b/pyproject.toml index 650c9956f3e..3d12af1e04d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,8 +50,6 @@ exclude = [ { path = "**/target/**", format = "sdist" }, # Media fixtures are only read by Rust tests, not source installs. { path = "**/test_data/**", format = "sdist" }, - # The vendored WebRTC stack's RTP captures, which its crate also excludes. - { path = "**/tests/data/**", format = "sdist" }, ] # Listed explicitly (not `py/*`) so build output like py/dist isn't mistaken diff --git a/quest/m0/rind-adapters.md b/quest/m0/rind-adapters.md index abee818aa75..48df8a20dbb 100644 --- a/quest/m0/rind-adapters.md +++ b/quest/m0/rind-adapters.md @@ -7,10 +7,11 @@ rind-rustls, rind-jsonwebtoken, rind-object-store, and rind-rcgen that make each adapter's API its upstream's, on the day they publish: the PR is ready before they publish and merges when they do. -Non-goal: replacing the dimpl and str0m providers vendored under -`rs/moq-webrtc/src/vendor`, which are MoQ's own code and depend on neither -rind-dimpl nor rind-str0m. They call rind directly, so rind 0.4 still reaches -them. +moq-webrtc also depends on rind-str0m, and rind-dimpl through it, since it +moved to upstream str0m ([moq-dev/moq#8963](https://github.com/moq-dev/moq/pull/8963)). +Their crates.io releases require rind 0.3, so the rind 0.4 release carries +patch releases of both too, and this PR raises `rind-str0m` with the other +adapters. ## Plan @@ -74,10 +75,9 @@ Shipped code, each call and what it becomes: becomes `PrivatePkcs8KeyDer::from(key_pair.serialize_der())`. The serial it sets on lines 1263-1265 already covers rind-rcgen's removed `serial_number()`. -- `rs/moq-webrtc/src/vendor/dimpl/certificate.rs:39` (rind-rcgen): - `generate(..)` becomes `generate_for(..)`; line 76's - `key_pair.to_pkcs8().secret_pkcs8_der().to_vec()` becomes - `key_pair.serialize_der()`. +- `rs/moq-webrtc/src/session.rs`'s `rtc_config` (rind-str0m): drop the + `.expect(..)` after `rind_str0m::default_provider()` if the CPU-check + removal makes it infallible, with the `moq_crypto::cpu::check()` before it. - `rs/moq-relay/examples/embed.rs:23` (rind-rustls): drop the `.unwrap()` after `rind_rustls::default_provider()`. @@ -87,9 +87,9 @@ all the same mechanical edits. Find them with: - `rind_rustls::default_provider()`: 105 lines in 40 files, plus 5 bare `default_provider()` calls in `rs/moq-quic/src/tests/mod.rs` and `rs/moq-tokio/src/quic/driver/tests.rs`, which import it by `use`. -- `KeyPair::generate(&`: 78 lines in 38 files. One asks for P-384, - `rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs:841`, so use - `generate_for` everywhere rather than the P-256 default. +- `KeyPair::generate(&`: 78 lines in 38 files at `985e8897`, fewer since + the vendored dimpl left. Use `generate_for` everywhere rather than the + P-256 default. - `to_pkcs8().secret_pkcs8_der()`: 60 lines in 33 files. The other `to_pkcs8()` calls (`rs/moq-auth/src/key.rs:574`, `:587`, and `rs/moq-auth/src/generate.rs:41`) are rind's own key types and do not @@ -122,18 +122,10 @@ rind 0.4 itself changes three things, of which MoQ uses two: moq-auth, moq-crypto's e2ee, moq-hls, moq-quic, moq-rtmp, moq-tokio (`rs/moq-tokio/src/crypto.rs:7`), moq-uring, moq-webrtc, and qmux, with the doc comments that name it. - - The vendored providers, which call rind directly: - `rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs:24-25` and - `rs/moq-webrtc/src/vendor/str0m_rind/lib.rs:19-20` return - `rind::cpu::MissingFeature` after `rind::cpu::check()`, so their - `default_provider()` becomes infallible, and - `rs/moq-webrtc/src/vendor/dimpl/error.rs:363` drops - `UnsupportedCpu(rind::cpu::MissingFeature)`. - Agreement keys keep their public key ([kixel-ai/rind#529](https://github.com/kixel-ai/rind/pull/529)): - `agreement::PrivateKey::public_key()` returns a borrow. The vendored dimpl - provider calls it at `rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs:38`; - check that line and the rest of that file against #529's Public API section. + `agreement::PrivateKey::public_key()` returns a borrow. Only rind-dimpl + calls it, so its patch release absorbs the change. - AES-CBC encryption takes a typed `CbcIv` ([kixel-ai/rind#530](https://github.com/kixel-ai/rind/pull/530)): MoQ calls no AES-CBC encryption, by grep at that commit. diff --git a/quest/m2/README.md b/quest/m2/README.md index 42df4d4cfa6..6b53e5e44d9 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -68,7 +68,7 @@ removal, a rename, or a wire, catalog, or format change that is free until [moq-vaapi's exports](/quest/m2/vaapi-exports.md), [the WebRTC bind](/quest/m2/webrtc-bind.md), [gateway admission](/quest/m2/gateway-align.md), and - [upstream str0m](/quest/m2/str0m-upstream.md), which reverses the + [upstream str0m](https://github.com/moq-dev/moq/pull/8963), which reverses the 2026-10-30 vendoring. - **JS and browser.** [`@moq/net`](/quest/m2/js-net-api.md), [signals](/quest/m2/signals-semantics.md), [`@moq/ui`](/quest/m2/ui-private.md), diff --git a/quest/m2/str0m-upstream.md b/quest/m2/str0m-upstream.md deleted file mode 100644 index 37927fb7966..00000000000 --- a/quest/m2/str0m-upstream.md +++ /dev/null @@ -1,106 +0,0 @@ -# [L] moq-webrtc runs on upstream str0m - -## Goal - -moq-webrtc depends on crates.io str0m 0.25 and its DTLS, with rind as the -crypto provider through the published `rind-str0m` and `rind-dimpl` -adapters, and `rs/moq-webrtc/src/vendor/` is gone: about 98,600 vendored -lines and 1.6 MB of packet captures. The WHIP and WHEP gateway behaves as it -does today, an offered data channel is still refused, and `cargo deny` sees -the stack's advisories again. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - -- ✅ Return to upstream str0m (rejected: keep the vendored stack and gate - the cut on a browser test, which the audit recommended; keep as is). This - reverses the 2026-10-30 decision to own the stack - ([the WebRTC epic](/quest/m3/webrtc/README.md)). What changed since: none - of the four fixes that motivated vendoring has landed; peer-to-peer and - data channels left on 2026-11-14 - ([moq-dev/moq#8771](https://github.com/moq-dev/moq/pull/8771)), so the - stack serves one WHIP and WHEP gateway; upstream 0.25 has the pluggable - crypto provider the rind port needed; and nobody merges upstream fixes - into a vendored copy. The vendored modules are private, so the switch - breaks no caller. - -The choice is unverified: nobody has built moq-webrtc against 0.25. So the -PR starts by finding out, and reports before it deletes. - -Facts found by the audit: - -- Vendored size, by `find rs/moq-webrtc/src/vendor -name '*.rs' | xargs wc - -l`: 98,582 lines (str0m 62,368; dimpl 23,998; `is` 8,962; netem 1,467; - `str0m_proto` 1,360; `str0m_rind` 372). Hand-written moq-webrtc is 6,997 - lines. -- The vendored revision is str0m "0.24.1+" at `dc317173` and dimpl 0.9.0 - (`rs/moq-webrtc/src/vendor/mod.rs:14-20`). crates.io has str0m 0.25.0, - dimpl 0.9.0, `rind-str0m` 0.25.2, and `rind-dimpl` 0.9.3 - (`cargo search`, 2026-11-16). -- Six commits touched the vendored tree - (`git log --first-parent -- rs/moq-webrtc/src/vendor`): the vendoring and - trim ([moq-dev/moq#8163](https://github.com/moq-dev/moq/pull/8163)), the - move to rind (#8229, #8248), a doc sweep (#8392, #8608), and the SCTP cut - (#8771). None is one of the four planned fixes; their quests are all open. -- moq-webrtc reaches the stack through `crate::vendor::str0m` in 13 files - outside `vendor/` (`grep -rln 'vendor::str0m' rs/moq-webrtc/src`). -- The workarounds vendoring was meant to remove are still in moq-webrtc and - work against upstream as written: the `b=TIAS` splice - (`rs/moq-webrtc/src/sdp.rs:49`), the early DTLS failure reported as a - timeout ([moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379)), - and eleven `into_std()` clock conversions. - -For the PR: - -1. Build against str0m 0.25 with the two adapters on a branch that keeps - `vendor/` in place, and write down what differs. Check at least: - - rind: the adapters must target the rind the workspace pins. - [rind 0.4](/quest/m0/rind-adapters.md) is about to move that pin, and - its Non-goal says the vendored providers "depend on neither rind-dimpl - nor rind-str0m"; after this quest they do, so land after it or carry - the adapter bump here. - - Data channels: the vendored copy cut SCTP and answers an offered - `m=application` rejected (the test at `rs/moq-webrtc/src/sdp.rs:117`). - Upstream compiles data channels in, so find how 0.25 refuses one (a - feature or a config) and keep that test green. - - DTLS 1.2 only: the vendored dimpl dropped 1.3 and version - auto-selection. Pin 1.2 through configuration, or record that 1.3 is - now offered and that a browser run covered it. - - The typed DTLS timeout: the vendored `dtls.rs` carries dimpl's error - through where upstream flattened it to a string - ([its quest](/quest/m3/webrtc/dtls-timeout.md)). See what 0.25 returns. - - Anything str0m's API renamed between `dc317173` and 0.25.0. -2. If something the gateway needs cannot be had from upstream, stop and - report it on the PR with the evidence, for the maintainer to weigh - against the decision, before deleting anything. -3. Otherwise switch those imports, delete `vendor/` with its `LICENSE-*` - files and the `exclude` in `rs/moq-webrtc/Cargo.toml:15`, and drop the - module's lint allows. Run moq-webrtc's own tests, moq-cli's WHIP and WHEP - tests, and one manual Chrome publish and play, since - [no test drives a browser yet](/quest/m3/whip-whep-browser.md). -4. Leave the quest tree accurate. Delete the quests that exist only for the - vendored copy: [the vendored stack's sync](/quest/m3/vendor-sync/webrtc-stack.md) - (with its paragraph in `quest/m3/vendor-sync/README.md`), - [kio clock time](/quest/m4/webrtc-clock.md), - [the dead-API trim](/quest/m4/webrtc-dead-api.md), and - [the browser-only trim](/quest/m4/webrtc-browser-only.md), and the - vendored-tree line in `quest/m4/test-inventory-followups.md`. The four - fixes become work at moq-webrtc's boundary or upstream reports; their - quests already say so ([DTLS waits for ICE](/quest/m3/webrtc/dtls-after-ice.md), - [the typed DTLS timeout](/quest/m3/webrtc/dtls-timeout.md), - [several bandwidth lines](/quest/m4/webrtc-sdp-bandwidth.md), - [WHEP pacing](/quest/m3/rtc-pacing.md)). - -Docs: `doc/lib/rs` and `rs/moq-webrtc/README.md` where they say the stack -is vendored. - -Public API: none (`mod vendor` is private). Dependencies: str0m, dimpl, -`rind-str0m`, and `rind-dimpl` join the published graph. Wire: none intended -toward browsers; record any change step 1 finds. - -## Related - -- [MoQ builds against rind 0.4](/quest/m0/rind-adapters.md) - moves the rind pin the adapters must match, and edits vendored files this deletes -- [moq-webrtc's server binds at startup](/quest/m2/webrtc-bind.md) - changes the same crate's server -- [The gateways admit a session the same way](/quest/m2/gateway-align.md) - changes the same crate's request types diff --git a/quest/m2/webrtc-bind.md b/quest/m2/webrtc-bind.md index 2fcb6ad4877..07d74a8fdd8 100644 --- a/quest/m2/webrtc-bind.md +++ b/quest/m2/webrtc-bind.md @@ -80,5 +80,4 @@ CLI: `--public-addr` now advertises its port. Wire: none. ## Related - [The gateways admit a session the same way](/quest/m2/gateway-align.md) - changes the same crate's request and client names, and renames the CLI endpoint -- [moq-webrtc runs on upstream str0m](/quest/m2/str0m-upstream.md) - swaps the stack under the same session code - [A WebRTC feed on the shared port](/quest/m3/one-port/rtc-feed.md) - adds the second socket source this leaves room for diff --git a/quest/m3/rtc-pacing.md b/quest/m3/rtc-pacing.md index a62e924fc22..3e2464c429d 100644 --- a/quest/m3/rtc-pacing.md +++ b/quest/m3/rtc-pacing.md @@ -34,7 +34,7 @@ WHEP enforcement needs it and nobody owned it. hook on that path. Decided 2026-10-30 (maintainer): add it to the vendored str0m ([WebRTC epic](/quest/m3/webrtc/README.md)) rather than upstream. Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md), so + moq-webrtc [returns to upstream str0m](https://github.com/moq-dev/moq/pull/8963), so there is no vendored copy to add the hook to. Start by finding out whether str0m 0.25's public API can charge or withhold a resend (its RTP mode, or turning off its own NACK handling and serving resends from a @@ -82,4 +82,3 @@ audit). Wire: none. ## Related - [SRT rate handle](/quest/m3/srt-rate-handle.md) - the same pacing and retransmit charging on SRT -- [moq-webrtc runs on upstream str0m](/quest/m2/str0m-upstream.md) - removes the vendored copy the NACK hook was planned for diff --git a/quest/m3/vendor-sync/README.md b/quest/m3/vendor-sync/README.md index d9a45aa7e3c..ca57f18b4c5 100644 --- a/quest/m3/vendor-sync/README.md +++ b/quest/m3/vendor-sync/README.md @@ -59,11 +59,6 @@ moq-audio's NetEq time stretch port, once part of the WebRTC child, was replaced by a stretch written from its published description. moq-congestion's Cubic came from quinn and stays with the quinn child. -The 2026-11-12 audit found moq-webrtc's vendored str0m, dimpl, and `is` -(vendored 2026-11-07, after that scan) with no child, so they got -[one](/quest/m3/vendor-sync/webrtc-stack.md) starting from the revisions -`rs/moq-webrtc/src/vendor/mod.rs` records. - Out of scope: forks moq no longer consumes (moq-dev/quiche, moq-dev/noq, kixelated/cros-codecs, kixelated/openh264-rs, kixelated/fflate, and kixelated/goog_cc, now in-tree as moq-congestion's `gcc`), the diff --git a/quest/m3/vendor-sync/webrtc-stack.md b/quest/m3/vendor-sync/webrtc-stack.md deleted file mode 100644 index 5286b899731..00000000000 --- a/quest/m3/vendor-sync/webrtc-stack.md +++ /dev/null @@ -1,48 +0,0 @@ -# [S] moq-webrtc's vendored stack has every upstream fix it needs - -## Goal - -moq-webrtc's vendored str0m, `str0m_proto`, `is`, and dimpl carry every fix -their upstreams ([algesten/str0m](https://github.com/algesten/str0m) and -[algesten/dimpl](https://github.com/algesten/dimpl)) have landed -since the last check, each ported with its test or recorded as not applying, -and the `Upstream` section of `rs/moq-webrtc/src/vendor/mod.rs` names the -newest upstream commit checked for each. - -## Plan - -Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc -[returns to upstream str0m](/quest/m2/str0m-upstream.md) before the cut, -and that quest's PR deletes this one with the vendored copy, since -`cargo deny` then sees the stack's advisories. This quest stays only if that -PR reports it cannot make the switch. - -Recurring child of the [vendor sync](/quest/m3/vendor-sync/README.md), which -says how each run works and recurs. New in the 2026-11-12 audit: the stack was -vendored on 2026-11-07 in -[moq-dev/moq#8163](https://github.com/moq-dev/moq/pull/8163), after the -2026-11-05 scan. - -Start from the revisions the module doc records: str0m `main` at -[`dc317173`](https://github.com/algesten/str0m/commit/dc317173b16fc6ed86633e6b08b229c9195deb87) -(2026-10-26; `str0m_proto`, `is`, and the test-only `netem` come from the same -repository), and dimpl 0.9.0 at -[`c17b3b8`](https://github.com/algesten/dimpl/commit/c17b3b8b971b6eb2ecf7284f5dc0ecb86680ac4d). -Check each repository's security advisories too: the stack parses untrusted -SRTP, RTCP, DTLS, and STUN input from browsers, and cargo-deny cannot see an advisory against -vendored code. - -The vendored code was trimmed to what MoQ uses (the -[WebRTC epic](/quest/m3/webrtc/README.md)'s "What goes" list: GCC bandwidth -estimation, the leaky pacer, H.266, RED, DTMF, G.7xx and comfort noise, VLA -and simulcast layers, RTCP app feedback, stats, DTLS 1.3, and str0m's data -channels), so a fix -confined to removed code does not apply. Deleting an API with no consumer -beats porting a fix to it. - -Out of scope: `str0m_rind` and dimpl's `crypto::rind`, ported from -moq-dev/rind, which moq maintains itself. - -## Required - -- [Cut and publish the prepared breaking release](/quest/m3/release/cut.md) - the next cycle starts after the cut diff --git a/quest/m3/webrtc/README.md b/quest/m3/webrtc/README.md index d8412cb69e5..113d643d41a 100644 --- a/quest/m3/webrtc/README.md +++ b/quest/m3/webrtc/README.md @@ -17,7 +17,7 @@ vendored copy before a fix has been shown to need one. Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): ✅ return to upstream str0m (rejected: keep the vendored stack and gate the cut on a browser test; keep as is). This reverses the 2026-10-30 decision below, -and [the switch](/quest/m2/str0m-upstream.md) lands before the cut. What +and [the switch](https://github.com/moq-dev/moq/pull/8963) lands before the cut. What changed: none of the four fixes that motivated vendoring had landed by the audit, peer-to-peer and data channels left on 2026-11-14 ([moq-dev/moq#8771](https://github.com/moq-dev/moq/pull/8771)), upstream @@ -40,10 +40,11 @@ What still holds from that plan: - **One crate.** The ICE driver lives in `moq-webrtc`, which depends on moq-tokio rather than the reverse, so moq-tokio needs no ICE. - **No SCTP.** Decided 2026-11-14 (maintainer): an offered `m=application` - line is answered rejected. On upstream this is a configuration, not a - deletion; the switch keeps the test that proves it. -- **DTLS 1.2** is what the rind provider offers and every browser - negotiates today. + line is answered rejected. str0m 0.25 has no setting for it, so + moq-webrtc's `sdp.rs` takes the section out of the offer and puts it back + rejected in the answer; str0m still compiles sctp-proto in. +- **DTLS 1.2** is what every browser negotiates today; moq-webrtc pins it + in `session::rtc_config`, str0m 0.25's default. What changes for the four fixes: each is first tried through str0m's public API. One that needs a change inside str0m becomes an upstream report, filed @@ -58,5 +59,4 @@ PR that makes them stale. ## Related -- [moq-webrtc runs on upstream str0m](/quest/m2/str0m-upstream.md) - deletes the vendored stack before the cut - [moq-webrtc paces WHEP viewers](/quest/m3/rtc-pacing.md) - needs retransmits charged to the cap, which upstream has no hook for diff --git a/quest/m3/webrtc/dtls-after-ice.md b/quest/m3/webrtc/dtls-after-ice.md index 0e7715f0322..f46e48977fb 100644 --- a/quest/m3/webrtc/dtls-after-ice.md +++ b/quest/m3/webrtc/dtls-after-ice.md @@ -6,12 +6,8 @@ DTLS sends its first flight only once ICE has nominated a pair, so a peer whose ## Plan -Decided 2026-10-30 with the maintainer (planning interview). Today DTLS starts before ICE connects and dimpl gives up after 1+2+4+8+16 s with jitter (`rs/moq-webrtc/src/vendor/dimpl/config.rs:86-88`), racing moq-webrtc's ICE module's 30 s deadline; [moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379) papered over the race by reporting an early DTLS failure as a timeout. Hold DTLS activation (str0m's `Rtc::init_dtls` in `rs/moq-webrtc/src/vendor/str0m/lib.rs`) until nomination, then remove #7379's remapping if nothing else needs it. Test on the paused clock: ICE nominating at 29 s still completes DTLS. Added 2026-10-31 from [moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379): also test that a DTLS failure after ICE has connected still reports a DTLS error (moq-webrtc's `ice::Error::Rtc`, or the [typed handshake timeout](/quest/m3/webrtc/dtls-timeout.md)), not `Timeout` (moq-webrtc's `IceTimeout`), so the remapping (or its removal) only ever changes a failure before nomination. +Decided 2026-10-30 with the maintainer (planning interview). Today DTLS starts before ICE connects and dimpl gives up after 1+2+4+8+16 s with jitter (dimpl 0.9's `flight_start_rto` of 1 s and `handshake_timeout` of 40 s, `src/config.rs:92-94`, which rind-str0m's DTLS provider leaves at their defaults), racing moq-webrtc's ICE module's 30 s deadline; [moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379) papered over the race by reporting an early DTLS failure as a timeout. Hold DTLS activation (str0m's `Rtc::init_dtls`) until nomination, then remove #7379's remapping if nothing else needs it. Test on the paused clock: ICE nominating at 29 s still completes DTLS. Added 2026-10-31 from [moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379): also test that a DTLS failure after ICE has connected still reports a DTLS error (moq-webrtc's `ice::Error::Rtc`, or the [typed handshake timeout](/quest/m3/webrtc/dtls-timeout.md)), not `Timeout` (moq-webrtc's `IceTimeout`), so the remapping (or its removal) only ever changes a failure before nomination. -Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md), so `Rtc::init_dtls` is no longer ours to move. Start by reading how str0m 0.25 starts DTLS and whether its public API can hold the first flight until ICE nominates. If it can, do it there and keep the tests above. If it cannot, the fix is a change inside str0m: write the report for [upstream reports](/quest/m4/upstream-reports.md), which the maintainer approves before it is filed, keep #7379's remapping, and reduce this quest to waiting on upstream. +Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](https://github.com/moq-dev/moq/pull/8963), so `Rtc::init_dtls` is no longer ours to move. In 0.25 it is private (`src/lib.rs:1519`), called from `accept_offer` and `accept_answer` through `init_dtls` (`src/change/sdp.rs:727`). Start by reading how str0m 0.25 starts DTLS and whether its public API can hold the first flight until ICE nominates. If it can, do it there and keep the tests above. If it cannot, the fix is a change inside str0m: write the report for [upstream reports](/quest/m4/upstream-reports.md), which the maintainer approves before it is filed, keep #7379's remapping, and reduce this quest to waiting on upstream. Public API: none. Wire: none. - -## Required - -- [moq-webrtc runs on upstream str0m](/quest/m2/str0m-upstream.md) - settles which stack starts DTLS diff --git a/quest/m3/webrtc/dtls-timeout.md b/quest/m3/webrtc/dtls-timeout.md index 1ca61f29312..f65ec6ef915 100644 --- a/quest/m3/webrtc/dtls-timeout.md +++ b/quest/m3/webrtc/dtls-timeout.md @@ -26,21 +26,22 @@ where upstream flattened it into `CryptoError::Other(String)`. never finished the handshake. Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): -moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md), where +moq-webrtc [returns to upstream str0m](https://github.com/moq-dev/moq/pull/8963), where the vendored copy's typed pass-through is gone and the timeout arrived as -`CryptoError::Other(String)` at the vendored revision. That quest records -what 0.25 returns. If it is typed, classify it as planned. If it is still a -string, don't match on its text (AGENTS.md): the typed error is a change -inside str0m, so write the report for -[upstream reports](/quest/m4/upstream-reports.md) and reduce this quest to -waiting on upstream. +`CryptoError::Other(String)` at the vendored revision. If it is typed, +classify it as planned. If it is still a string, don't match on its text +(AGENTS.md): the typed error is a change inside str0m, so write the report +for [upstream reports](/quest/m4/upstream-reports.md) and reduce this quest +to waiting on upstream. + +Found by [the switch](https://github.com/moq-dev/moq/pull/8963): 0.25 still +flattens every dimpl error with `CryptoError::Other(format!("DTLS error: +{e}"))` (`src/dtls.rs:164`, `:182`, `:200`, `:207`), though str0m-proto 0.8 +already has the `CryptoError::DtlsImpl` variant that would carry it typed. +So this is the string case: the upstream change is those four `map_err`s. Public API: additive variants on non-exhaustive error enums. Wire: none. -## Required - -- [moq-webrtc runs on upstream str0m](/quest/m2/str0m-upstream.md) - settles what type the timeout arrives as - ## Related - [DTLS waits for ICE](/quest/m3/webrtc/dtls-after-ice.md) - after it, every DTLS handshake timeout comes after nomination, which is the case this types diff --git a/quest/m3/whip-whep-browser.md b/quest/m3/whip-whep-browser.md index ae67ee1e9d7..e39416a4636 100644 --- a/quest/m3/whip-whep-browser.md +++ b/quest/m3/whip-whep-browser.md @@ -21,7 +21,7 @@ Moved to m3 2026-11-12 (maintainer, /quest-audit): a downstream deployment serve Kept in m3 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): the audit recommended making this recipe a gate for the cut while the stack stayed vendored; the maintainer chose to -[return to upstream str0m](/quest/m2/str0m-upstream.md) instead (rejected: +[return to upstream str0m](https://github.com/moq-dev/moq/pull/8963) instead (rejected: keep the vendored stack and gate the cut on this). That switch is checked by one manual Chrome publish and play, so this recipe is still the first automated browser run against the gateway. diff --git a/quest/m4/fuzz-gateway-parsers.md b/quest/m4/fuzz-gateway-parsers.md index 25bd82dba4d..882635a4e64 100644 --- a/quest/m4/fuzz-gateway-parsers.md +++ b/quest/m4/fuzz-gateway-parsers.md @@ -20,8 +20,11 @@ Agent's choices, for the implementer to revisit: - Order by exposure: the listeners an unauthenticated peer reaches (WebRTC, RTSP, SRT) before the formats read from a trusted publisher or a file. -- moq-webrtc's parsers are vendored (`rs/moq-webrtc/src/vendor`): fuzz them - where they sit, and report a finding upstream as well as fixing it here. +- moq-webrtc's SDP, STUN, DTLS, and RTP parsers are upstream str0m, `is`, + and dimpl crates: fuzz them through moq-webrtc's entry points (an offer + body, a datagram to the mux), and report a finding upstream. str0m fuzzes + its own network input (algesten/str0m `54bf16ee`), so start with the + parts it does not, such as moq-webrtc's SDP text handling in `sdp.rs`. - The same shape as the relay parsers' targets (`rs/qmux/fuzz/`, `rs/moq-auth/fuzz/`). Where JS has the same decoder (JSON, the catalog, MSF), commit findings to the shared `fixtures/` corpus. diff --git a/quest/m4/test-inventory-followups.md b/quest/m4/test-inventory-followups.md index 98540c9cb71..5b8f0cba3f2 100644 --- a/quest/m4/test-inventory-followups.md +++ b/quest/m4/test-inventory-followups.md @@ -22,13 +22,6 @@ for the `#[ignore]` check. Left over: - A Python orchestrator that dispatches on its first argument (argparse subcommands or an `if`/`match` on `sys.argv`) has all branches counted; follow only the selected one, or report it as unresolved. -- Modules nested in a `#[path]`-loaded file resolve against that file's - directory, but the walker places them under `//` unless the file - is `mod.rs` (`sh/gh/test-inventory.py:663` and `:694-696`). So the vendored - crates `rs/moq-webrtc/src/vendor/mod.rs:43-55` loads go unseen, with their - `#[ignore]` test `str0m/tests/poll-scaling.rs:50`. Walk a `#[path]` child as - owning its directory, and give the test a caller or an allowlist entry (added 2026-11-12 by /quest-plan, from moq's trimmed - Pullfrog learnings). - The failure output lists `benchmark_stream_import` twice. Deduplicate orphans by name and location. - JS bench scripts are left to diff --git a/quest/m4/upstream-reports.md b/quest/m4/upstream-reports.md index 01c9deb3d6c..2d29fa531dd 100644 --- a/quest/m4/upstream-reports.md +++ b/quest/m4/upstream-reports.md @@ -52,7 +52,7 @@ Not to be filed: - **str0m/dimpl:** the DTLS retry budget runs out before ICE picks a path, found in #7379. Not filed while the [WebRTC epic](/quest/m3/webrtc/README.md) vendored str0m. Since - 2026-11-16 moq-webrtc [returns to upstream](/quest/m2/str0m-upstream.md), + 2026-11-16 moq-webrtc [returns to upstream](https://github.com/moq-dev/moq/pull/8963), so this and three more become candidates once their quests show the public API cannot do it: [DTLS waits for ICE](/quest/m3/webrtc/dtls-after-ice.md), [the typed DTLS timeout](/quest/m3/webrtc/dtls-timeout.md), @@ -60,5 +60,17 @@ Not to be filed: NACK hook of [WHEP pacing](/quest/m3/rtc-pacing.md). Each needs the maintainer's approval and a read of the repository's AI policy before it is filed. +- **str0m:** no setting refuses an offered data channel, so moq-webrtc + takes the `m=application` section out of the offer's text and answers it + rejected (`rs/moq-webrtc/src/sdp.rs`, `refuse_channels`). A + `RtcConfig` switch that answers it rejected and starts no SCTP would + retire that. The switch's PR body holds a draft. Same approval rule. +- **str0m:** two bugs the vendored copy had patched, worked around in + moq-webrtc since the switch, each with a test that fails without it. + An answer puts its candidates only on the first section even when that + section is rejected and out of BUNDLE (`sdp.rs`, + `candidates_on_accepted`). ICE asks for no timeout until its first one, + so a side that hears no checks, facing an ICE-lite peer, never sends any + (`ice/agent.rs`, `Agent::new`). Same approval rule. Public API: none. Wire: none. diff --git a/quest/m4/webrtc-browser-only.md b/quest/m4/webrtc-browser-only.md deleted file mode 100644 index a178a35d5b2..00000000000 --- a/quest/m4/webrtc-browser-only.md +++ /dev/null @@ -1,28 +0,0 @@ -# [S] The vendored stack keeps only what browsers negotiate - -## Goal - -The vendored str0m, dimpl, and `is` drop every feature no -browser's WebRTC negotiates today, starting with dimpl's PSK cipher suites -and the `ccm` dependency they pull in, so nothing MoQ can't reach from a -browser peer stays compiled. - -## Plan - -Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md) before the cut, and that quest's PR deletes this one with the vendored copy. It stays only if that PR reports it cannot make the switch. - -Planned 2026-11-07 (maintainer, /quest-complete), a follow-up of -[moq-dev/moq#8163](https://github.com/moq-dev/moq/pull/8163). The maintainer -widened the suggestion from PSK alone: delete anything browsers don't use -now. Browser DTLS authenticates with certificates and fingerprints, never -PSK. Inventory what Chrome, Firefox, and Safari offer and accept (cipher -suites, extensions, SDP attributes, codecs' packetizers) against what the -vendored code still carries, cite the evidence for each removal in the PR, -and keep what a browser negotiates even if MoQ doesn't call it yet. The -[WebRTC epic](/quest/m3/webrtc/README.md)'s settled removals (its "What goes" list, such as G.7xx, DTMF, and -comfort noise) and non-goals (TURN, DTLS 1.3, data channels) stay as decided: this trim -only removes more, never restores. API -that moq-webrtc never calls but a browser could need stays for -[the dead-API trim](/quest/m4/webrtc-dead-api.md). - -Public API: none. Wire: none toward browsers. diff --git a/quest/m4/webrtc-clock.md b/quest/m4/webrtc-clock.md deleted file mode 100644 index 9c9264d4cd6..00000000000 --- a/quest/m4/webrtc-clock.md +++ /dev/null @@ -1,13 +0,0 @@ -# [XS] The WebRTC stack takes kio clock time - -## Goal - -The vendored str0m and dimpl take `kio::clock::Instant` instead of `std::time::Instant`, so moq-webrtc drops its `into_std()` conversions and sim tests drive the stack's timers directly. - -## Plan - -Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md) before the cut, and that quest's PR deletes this one with the vendored copy. It stays only if that PR reports it cannot make the switch. - -Decided 2026-10-30 with the maintainer (planning interview). Every call into str0m converts with `Instant::into_std` today, the way the workspace handles any third-party API that takes `std::time::Instant`. Change the vendored modules' time type, delete the conversions, and move any moq-webrtc test that pauses tokio time onto the sim. - -Public API: none. Wire: none. diff --git a/quest/m4/webrtc-dead-api.md b/quest/m4/webrtc-dead-api.md deleted file mode 100644 index 26396b8eb34..00000000000 --- a/quest/m4/webrtc-dead-api.md +++ /dev/null @@ -1,24 +0,0 @@ -# [M] The vendored stack exposes only what moq-webrtc calls - -## Goal - -Every item in the vendored modules is reached from moq-webrtc or its -tests; dead upstream API is deleted. - -## Plan - -Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md) before the cut, and that quest's PR deletes this one with the vendored copy. It stays only if that PR reports it cannot make the switch. - -Planned 2026-11-07 (maintainer, /quest-complete), a follow-up of -[moq-dev/moq#8163](https://github.com/moq-dev/moq/pull/8163). It waits on -the clock quest, which reshapes the time seams moq-webrtc calls through, as -the move to rind already did the crypto seams. The vendored tree opens with `#![allow(warnings, reason = "vendored -upstream code")]` (`rs/moq-webrtc/src/vendor/mod.rs`), so first narrow that -allow to let `dead_code` fire, then delete what the report shows unreached, -keeping upstream's tests for what stays. - -Public API: none. Wire: none. - -## Required - -- [The stack takes kio clock time](/quest/m4/webrtc-clock.md) - settles the time seams diff --git a/quest/m4/webrtc-sdp-bandwidth.md b/quest/m4/webrtc-sdp-bandwidth.md index 3bc732635e4..2736faa85d3 100644 --- a/quest/m4/webrtc-sdp-bandwidth.md +++ b/quest/m4/webrtc-sdp-bandwidth.md @@ -6,8 +6,8 @@ A capped WHIP answer carries both `b=TIAS` and `b=AS`, and moq-webrtc stops stri ## Plan -Decided 2026-10-30 with the maintainer (planning interview) as a change to the vendored str0m. Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](/quest/m2/str0m-upstream.md), so the parser is upstream's again. +Decided 2026-10-30 with the maintainer (planning interview) as a change to the vendored str0m. Changed 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): moq-webrtc [returns to upstream str0m](https://github.com/moq-dev/moq/pull/8963), so the parser is upstream's again. -At the vendored revision str0m read `optional(bandwidth_line())` into `bw: Option`, so a second line made the whole answer unparseable, and [moq-dev/moq#7373](https://github.com/moq-dev/moq/pull/7373) shipped TIAS only through `sdp::cap_answer` (`rs/moq-webrtc/src/sdp.rs`). Check whether 0.25 still does. If it does, the change (a `Vec`) is upstream's to take: write the report for [upstream reports](/quest/m4/upstream-reports.md), which the maintainer approves before it is filed, and keep the splice until a release carries it. Then emit both lines on a capped answer, delete the splice, and test that our own WHIP client parses the answer. +At the vendored revision str0m read `optional(bandwidth_line())` into `bw: Option`, so a second line made the whole answer unparseable, and [moq-dev/moq#7373](https://github.com/moq-dev/moq/pull/7373) shipped TIAS only through `sdp::cap_answer` (`rs/moq-webrtc/src/sdp.rs`). 0.25 still does (`bw: Option` at `src/sdp/data.rs:174` and `:290`, found by [the switch](https://github.com/moq-dev/moq/pull/8963)), so the change (a `Vec`) is upstream's to take: write the report for [upstream reports](/quest/m4/upstream-reports.md), which the maintainer approves before it is filed, and keep the splice until a release carries it. Then emit both lines on a capped answer, delete the splice, and test that our own WHIP client parses the answer. Public API: none. Wire: capped answers gain `b=AS`. diff --git a/rs/moq-webrtc/Cargo.toml b/rs/moq-webrtc/Cargo.toml index eeb7ec127e9..0ddc05e9de6 100644 --- a/rs/moq-webrtc/Cargo.toml +++ b/rs/moq-webrtc/Cargo.toml @@ -11,12 +11,6 @@ rust-version.workspace = true keywords = ["webrtc", "whip", "whep", "moq", "media"] categories = ["multimedia", "network-programming", "web-programming"] -# The vendored stack's RTP captures are only read by its tests. -exclude = ["src/vendor/str0m/tests/data"] - -# Vendored modules are loaded through path attributes. -[package.metadata.cargo-shear] -ignored-paths = ["src/vendor/**/*.rs"] [features] default = ["server"] @@ -29,16 +23,8 @@ server = ["dep:axum"] # lives in `moq-cli` (the `rtc` subcommand); embedders mount the routers / dial with # `Client` against their own origin. [dependencies] -# The vendored stack's AES-CCM DTLS suites. -aes = { workspace = true } -arrayvec = { workspace = true } axum = { workspace = true, optional = true } bytes = { workspace = true } -ccm = { workspace = true } -# The vendored stack's SDP parser. -combine = { workspace = true } -crc = { workspace = true } -fastrand = { workspace = true } hang = { workspace = true } # Drives each WebRTC connection over its UDP socket. kio = { workspace = true, features = ["runtime"] } @@ -48,39 +34,25 @@ moq-mux = { workspace = true, features = ["async"] } moq-net = { workspace = true } # `RedactedUrl` keeps a dialed URL's query token and userinfo out of the logs. moq-tokio = { workspace = true } -# The vendored DTLS's record parser. -nom = { workspace = true } -once_cell = { workspace = true } -rand = { workspace = true } -# The vendored DTLS's self-signed certificates. -rcgen = { workspace = true } reqwest = { workspace = true, features = ["rustls-no-provider"] } -# The vendored stack's crypto: DTLS, SRTP, and STUN MESSAGE-INTEGRITY. -rind = { workspace = true } -rind-rcgen = { workspace = true } -serde = { workspace = true } -spki = { workspace = true } -subtle = { workspace = true } +# str0m's crypto: DTLS (dimpl on rind), SRTP, and STUN MESSAGE-INTEGRITY. +rind-str0m = { workspace = true } +# The WebRTC stack: SDP, ICE, DTLS, RTP/RTCP, and SRTP. +str0m = { workspace = true } thiserror = { workspace = true } -time = { workspace = true, features = ["formatting"] } tokio = { workspace = true, features = ["full"] } tracing = { workspace = true } url = { workspace = true } uuid = { version = "1", features = ["v4"] } -# The vendored DTLS's certificate parsing. -x509-cert = { workspace = true } [dev-dependencies] # The tests host their broadcasts on `origin::spawn`, and dial a session over TCP. moq-tokio = { workspace = true } -# The vendored stack's tests replay RTP captures. -pcap-file = { workspace = true } -serde_json = { workspace = true } +# Signs the tests' STUN requests as str0m does. +rind = { workspace = true } tokio = { workspace = true, features = ["test-util"] } -tracing-subscriber = { workspace = true, features = ["env-filter"] } tracing-test = { workspace = true } workspace-hack = { path = "../workspace-hack" } -x509-parser = { workspace = true } [lints] workspace = true diff --git a/rs/moq-webrtc/src/client/whep.rs b/rs/moq-webrtc/src/client/whep.rs index 94104e30e8b..70eb3a29f7d 100644 --- a/rs/moq-webrtc/src/client/whep.rs +++ b/rs/moq-webrtc/src/client/whep.rs @@ -6,7 +6,6 @@ //! returned answer, then hands the resulting `str0m::Rtc` to the internal //! session driver in ingest mode (the same sink the WHIP server uses). -use crate::vendor::str0m; use str0m::{ Candidate, change::SdpAnswer, diff --git a/rs/moq-webrtc/src/client/whip.rs b/rs/moq-webrtc/src/client/whip.rs index adad3d92a35..2e34f0b417a 100644 --- a/rs/moq-webrtc/src/client/whip.rs +++ b/rs/moq-webrtc/src/client/whip.rs @@ -7,7 +7,6 @@ //! bitstream / RTP packetization is identical to the WHEP server path, so //! most of the work lives in the crate-private egress source. -use crate::vendor::str0m; use str0m::{ Candidate, change::SdpAnswer, diff --git a/rs/moq-webrtc/src/codec/mod.rs b/rs/moq-webrtc/src/codec/mod.rs index 67decc236de..eba0e8161b3 100644 --- a/rs/moq-webrtc/src/codec/mod.rs +++ b/rs/moq-webrtc/src/codec/mod.rs @@ -6,7 +6,7 @@ //! moq-mux importer expects and publishes it. //! - **Egress** ([`Track`]): the egress source subscribes to a moq-mux //! broadcast and the track yields RTP-ready codec frames that the -//! session loop hands to [`str0m::media::Writer::write`](crate::vendor::str0m::media::Writer::write). +//! session loop hands to [`str0m::media::Writer::write`](str0m::media::Writer::write). pub mod av1; pub mod h264; @@ -26,7 +26,7 @@ use crate::Result; /// One codec frame received from str0m, paired with a microsecond timestamp. /// /// Used by the ingest path. The session loop converts str0m's -/// [`MediaTime`](crate::vendor::str0m::media::MediaTime) to microseconds so individual +/// [`MediaTime`](str0m::media::MediaTime) to microseconds so individual /// bridges don't need to repeat the math. #[derive(Clone, Debug)] pub struct Frame { @@ -37,7 +37,7 @@ pub struct Frame { /// Bridges depacketized media frames from str0m to a hang broadcast track. /// /// One bridge per `m=` line on the ingest side. The session loop calls -/// [`Bridge::push`] once per [`MediaData`](crate::vendor::str0m::media::MediaData) event +/// [`Bridge::push`] once per [`MediaData`](str0m::media::MediaData) event /// with the codec frame; the bridge handles any codec-specific transformations /// (e.g. Annex-B to AVCC for H.264) and forwards the frame into the matching /// moq-mux importer. @@ -192,7 +192,7 @@ impl DeferredVideo { /// /// `timestamp_us` stays in microseconds; the session loop converts it to /// the negotiated codec's clock domain when calling -/// [`Writer::write`](crate::vendor::str0m::media::Writer::write). +/// [`Writer::write`](str0m::media::Writer::write). #[derive(Clone, Debug)] pub struct PacketizedFrame { pub timestamp_us: u64, diff --git a/rs/moq-webrtc/src/egress.rs b/rs/moq-webrtc/src/egress.rs index 14a9e343892..0bebcb21c50 100644 --- a/rs/moq-webrtc/src/egress.rs +++ b/rs/moq-webrtc/src/egress.rs @@ -11,7 +11,6 @@ //! client). SDP negotiation lives in the matching modules; this file is //! transport-agnostic. -use crate::vendor::str0m; use std::collections::VecDeque; use std::time::Duration; diff --git a/rs/moq-webrtc/src/ice/agent.rs b/rs/moq-webrtc/src/ice/agent.rs index c895e7e997c..74a9bd3b520 100644 --- a/rs/moq-webrtc/src/ice/agent.rs +++ b/rs/moq-webrtc/src/ice/agent.rs @@ -1,4 +1,3 @@ -use crate::vendor::str0m; use std::collections::VecDeque; use std::net::{IpAddr, SocketAddr}; use std::ops::{Deref, DerefMut}; @@ -96,8 +95,14 @@ impl Agent { outbox: VecDeque::new(), phase: Phase::Establishing { started: now }, }; - // Signaling already changed the connection. - agent.drain(); + // str0m's ICE has no clock, and asks for no timeout, until its first one. Without + // it a side that hears no checks, such as one facing an ICE-lite peer, would never + // check the candidates signaling gave it. Draining on drop sends what this + // and signaling produced. + let result = agent.rtc_mut().handle_input(Input::Timeout(now.into_std())); + if let Err(err) = result { + agent.fail(Error::rtc(err)); + } Ok(agent) } @@ -326,7 +331,11 @@ mod tests { let socket = Arc::new(UdpSocket::from_std(socket).unwrap()); let local = socket.local_addr().unwrap(); let socket = Socket::new(socket.clone(), vec![local], crate::ice::reader(socket)).unwrap(); - Agent::new(Rtc::builder().build(Instant::now().into_std()), socket).unwrap() + Agent::new( + crate::session::rtc_config().unwrap().build(Instant::now().into_std()), + socket, + ) + .unwrap() } #[tokio::test] @@ -343,7 +352,7 @@ mod tests { /// connects, which reports as ICE never connecting rather than a DTLS failure. #[tokio::test(start_paused = true)] async fn a_handshake_giving_up_before_ice_connects_is_a_timeout() { - let mut offerer = Rtc::builder().build(Instant::now().into_std()); + let mut offerer = crate::session::rtc_config().unwrap().build(Instant::now().into_std()); let mut api = offerer.sdp_api(); api.add_media( str0m::media::MediaKind::Audio, @@ -353,7 +362,8 @@ mod tests { None, ); let (offer, pending) = api.apply().unwrap(); - let answer = Rtc::builder() + let answer = crate::session::rtc_config() + .unwrap() .build(Instant::now().into_std()) .sdp_api() .accept_offer(offer) @@ -382,6 +392,55 @@ mod tests { assert!(matches!(again, Err(Error::Timeout)), "{again:?}"); } + /// Facing an ICE-lite offerer, which never sends a check, the answerer checks the + /// offer's candidate on its own. + #[tokio::test] + async fn an_ice_lite_offerers_candidate_is_checked_unprompted() { + let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let now = Instant::now().into_std(); + let mut offerer = crate::session::rtc_config().unwrap().set_ice_lite(true).build(now); + offerer.add_local_candidate(str0m::Candidate::host(peer.local_addr().unwrap(), "udp").unwrap()); + let mut api = offerer.sdp_api(); + api.add_media( + str0m::media::MediaKind::Audio, + str0m::media::Direction::SendOnly, + None, + None, + None, + ); + let (offer, _) = api.apply().unwrap(); + // An offerer taking the DTLS client role, with no SSRCs declared, leaves the + // answerer no DTLS or media timer that would start ICE's clock instead. + let offer: String = offer + .to_sdp_string() + .replace("a=setup:actpass", "a=setup:active") + .split_inclusive("\r\n") + .filter(|line| !line.starts_with("a=ssrc")) + .collect(); + let offer = str0m::change::SdpOffer::from_sdp_string(&offer).unwrap(); + + let socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let local = socket.local_addr().unwrap(); + let mut answerer = crate::session::rtc_config().unwrap().build(now); + answerer.add_local_candidate(str0m::Candidate::host(local, "udp").unwrap()); + answerer.sdp_api().accept_offer(offer).unwrap(); + let socket = Socket::new(socket.clone(), vec![local], crate::ice::reader(socket)).unwrap(); + let mut agent = Agent::new(answerer, socket).unwrap(); + + let mut buf = [0u8; 1500]; + tokio::select! { + received = peer.recv_from(&mut buf) => { + let (len, src) = received.unwrap(); + assert_eq!(src, local); + // A STUN Binding request. + assert!(len >= 20 && buf[..2] == [0x00, 0x01], "{:?}", &buf[..len]); + } + err = async { loop { if let Err(err) = agent.next().await { break err } } } => { + panic!("the agent ended without a check: {err:?}"); + } + } + } + #[test] fn mapped_addresses_round_trip() { let v4: SocketAddr = "1.2.3.4:5000".parse().unwrap(); diff --git a/rs/moq-webrtc/src/ice/mod.rs b/rs/moq-webrtc/src/ice/mod.rs index 1c4d1cd3c0a..5641e59cb68 100644 --- a/rs/moq-webrtc/src/ice/mod.rs +++ b/rs/moq-webrtc/src/ice/mod.rs @@ -1,5 +1,5 @@ //! The ICE side of a str0m peer connection: one UDP socket, its candidates, and -//! the loop that drives an [`str0m::Rtc`](crate::vendor::str0m::Rtc) over it. +//! the loop that drives an [`str0m::Rtc`](str0m::Rtc) over it. //! //! str0m is sans-IO, so [`Agent::next`] alternates between feeding it datagrams //! and timeouts and draining what it produces (transmits, events, the next diff --git a/rs/moq-webrtc/src/ingest.rs b/rs/moq-webrtc/src/ingest.rs index 4841510f2a0..15b3c1e0101 100644 --- a/rs/moq-webrtc/src/ingest.rs +++ b/rs/moq-webrtc/src/ingest.rs @@ -6,7 +6,6 @@ //! On `MediaAdded`, it inspects the negotiated codec and instantiates the //! matching bridge; on each `MediaData`, it forwards into the bridge. -use crate::vendor::str0m; use crate::{Error, Result, codec, session}; pub struct IngestSink { diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index 9099a876637..64a9f256647 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -59,8 +59,6 @@ mod ice; mod ingest; mod sdp; mod session; -// str0m, dimpl, and `is`, vendored and trimmed; see the module docs. -mod vendor; pub use client::Client; pub use error::*; @@ -403,7 +401,7 @@ mod tests { logged("bps=900000").await; // Lifting the cap lifts the publisher's ceiling rather than leaving the last one. rate.set(None); - logged(&format!("bps={}", crate::vendor::str0m::bwe::Bitrate::MAX.as_u64())).await; + logged(&format!("bps={}", str0m::bwe::Bitrate::MAX.as_u64())).await; assert!(!session.is_finished(), "a publisher under the cap was closed"); assert!(!pushed.is_finished(), "a publisher under the cap stopped"); session.abort(); diff --git a/rs/moq-webrtc/src/rate.rs b/rs/moq-webrtc/src/rate.rs index 4693562b4bb..0e5c7ba721c 100644 --- a/rs/moq-webrtc/src/rate.rs +++ b/rs/moq-webrtc/src/rate.rs @@ -41,7 +41,7 @@ fn burst_bytes(cap: Cap) -> f64 { /// /// It charges whole frames as str0m completes them, stamped with their first packet's /// arrival, so frames can be charged out of order: a frame that completes after a -/// later-starting one is charged behind it. str0m 0.24 surfaces individual RTP packets +/// later-starting one is charged behind it. str0m surfaces individual RTP packets /// only in `rtp_mode`, which gives up depacketization. The meter refills to each frame's /// completion, remembers the credit it discarded while full, and refunds a frame what was /// discarded since its arrival, up to its size. So a frame is credited for its own diff --git a/rs/moq-webrtc/src/sdp.rs b/rs/moq-webrtc/src/sdp.rs index 112d234c9a2..7c871f74acc 100644 --- a/rs/moq-webrtc/src/sdp.rs +++ b/rs/moq-webrtc/src/sdp.rs @@ -1,20 +1,169 @@ //! SDP plumbing. //! //! WHIP/WHEP both shovel SDP between a peer and str0m as `application/sdp` -//! request/response bodies. The only thing we add on top of str0m's offer/answer -//! parse/serialize is a tiny wrapper to keep the call sites readable. +//! request/response bodies. On top of str0m's offer/answer parse/serialize this +//! refuses data channels and repairs the answer's text where str0m's falls short. -use crate::vendor::str0m; -use std::borrow::Cow; +use std::{borrow::Cow, collections::HashSet}; use crate::{Error, Result}; -/// Parse an `application/sdp` body as an offer. -pub fn parse_offer(body: &str) -> Result { - str0m::change::SdpOffer::from_sdp_string(body).map_err(|err| Error::InvalidSdp(err.to_string())) +/// An offer's data channel sections, each answered rejected beside str0m's answer. +/// +/// The gateway carries no data channels, and str0m has no setting that refuses one: it +/// accepts an offered `m=application` section and runs SCTP that nobody reads. So +/// [`parse_offer`] takes those sections out before str0m sees the offer, and +/// [`render_answer`] puts each back at its index, with port 0 and out of the BUNDLE +/// group. +#[derive(Debug, Default)] +pub struct Refused { + /// Each refused section's index among the offer's media sections, in order, and + /// its rejected answer. + sections: Vec<(usize, String)>, +} + +/// Parse an `application/sdp` body as an offer, setting its data channels aside. +pub fn parse_offer(body: &str) -> Result<(str0m::change::SdpOffer, Refused)> { + let (body, refused) = refuse_channels(body); + let offer = str0m::change::SdpOffer::from_sdp_string(&body).map_err(|err| Error::InvalidSdp(err.to_string()))?; + Ok((offer, refused)) +} + +/// The attributes of the transport a BUNDLE group shares. A max-bundle offer can carry +/// them only on the group's first section, which may be a data channel. +const TRANSPORT: [&str; 7] = [ + "a=ice-ufrag:", + "a=ice-pwd:", + "a=ice-options:", + "a=fingerprint:", + "a=setup:", + "a=candidate:", + "a=end-of-candidates", +]; + +/// Split SDP text into its session lines and each media section's lines, every line +/// keeping its own ending. +fn split_sections<'a>(sdp: &'a str, ending: &str) -> (Vec<&'a str>, Vec>) { + let mut session = Vec::new(); + let mut sections: Vec> = Vec::new(); + for line in sdp.split_inclusive(ending) { + if line.starts_with("m=") { + sections.push(vec![line]); + } else if let Some(section) = sections.last_mut() { + section.push(line); + } else { + session.push(line); + } + } + (session, sections) } -/// Serialize an SDP answer for the `application/sdp` response body. +/// The port of a section's `m= ...` line. +fn port<'a>(section: &[&'a str]) -> Option<&'a str> { + section.first()?.split_whitespace().nth(1) +} + +/// Take each `m=application` section out of an offer, and its mid out of the BUNDLE group. +/// +/// A refused section in the group keeps its share of the group's transport: each +/// attribute no other section or the session carries moves to the session, as do its +/// candidates, which str0m reads from either. +fn refuse_channels(offer: &str) -> (Cow<'_, str>, Refused) { + let mut refused = Refused::default(); + if !offer.contains("m=application") { + return (Cow::Borrowed(offer), refused); + } + + // The offer's CRLF or LF survives. + let (session, sections) = split_sections(offer, "\n"); + let group: HashSet<&str> = session + .iter() + .find_map(|line| line.trim_end().strip_prefix("a=group:BUNDLE")) + .map(|group| group.split_whitespace().collect()) + .unwrap_or_default(); + + let mut kept = Vec::new(); + let mut mids = HashSet::new(); + let mut transport = Vec::new(); + for (index, section) in sections.into_iter().enumerate() { + let mut tokens = section[0].split_whitespace(); + if tokens.next() != Some("m=application") { + kept.push(section); + continue; + } + // m=application ...; the answer echoes the proto and formats. + let _port = tokens.next(); + let mut answer = format!( + "m=application 0 {}\r\nc=IN IP4 0.0.0.0\r\n", + tokens.collect::>().join(" ") + ); + let mid = section.iter().find_map(|line| line.trim_end().strip_prefix("a=mid:")); + if let Some(mid) = mid { + answer.push_str(&format!("a=mid:{mid}\r\n")); + mids.insert(mid); + if group.contains(&mid) { + transport.extend( + section + .into_iter() + .filter(|line| TRANSPORT.iter().any(|a| line.starts_with(a))), + ); + } + } + refused.sections.push((index, answer)); + } + + // At most one of each other key, decided up front so the work stays linear in the + // offer. Every candidate moves: str0m dedupes them. + let mut taken: Vec<&str> = TRANSPORT + .iter() + .copied() + .filter(|key| { + session + .iter() + .chain(kept.iter().flatten()) + .any(|line| line.starts_with(key)) + }) + .collect(); + let mut hoisted: Vec<&str> = Vec::new(); + for line in transport { + let key = TRANSPORT + .iter() + .copied() + .find(|a| line.starts_with(a)) + .unwrap_or_default(); + if key == "a=candidate:" { + hoisted.push(line); + } else if !taken.contains(&key) { + taken.push(key); + hoisted.push(line); + } + } + + let mut out = String::with_capacity(offer.len()); + for line in session { + let text = line.trim_end(); + match text.strip_prefix("a=group:BUNDLE") { + Some(group) => { + let group: Vec<&str> = group.split_whitespace().filter(|mid| !mids.contains(mid)).collect(); + if !group.is_empty() { + let ending = &line[text.len()..]; + out.push_str(&format!("a=group:BUNDLE {}{ending}", group.join(" "))); + } + } + None => out.push_str(line), + } + } + for line in hoisted { + out.push_str(line); + } + for line in kept.into_iter().flatten() { + out.push_str(line); + } + (Cow::Owned(out), refused) +} + +/// Serialize an SDP answer for the `application/sdp` response body, with each of the +/// offer's [`Refused`] data channels answered rejected in its place. /// /// str0m can emit a *rejected* media line (port 0) with an EMPTY format list, /// e.g. `m=audio 0 UDP/TLS/RTP/SAVPF `. This happens when we restrict the @@ -26,15 +175,65 @@ pub fn parse_offer(body: &str) -> Result { /// of the media (e.g. video) that WAS negotiated. So we give any such line a /// placeholder static payload; the media stays rejected (port 0), so the /// placeholder is never used. -pub fn render_answer(answer: &str0m::change::SdpAnswer) -> String { +pub fn render_answer(answer: &str0m::change::SdpAnswer, refused: &Refused) -> String { // SDP uses CRLF line endings (RFC 4566); splitting and rejoining on "\r\n" // round-trips exactly, including the trailing CRLF. - answer + let answer = answer .to_sdp_string() .split("\r\n") .map(ensure_media_format) .collect::>>() - .join("\r\n") + .join("\r\n"); + restore_channels(&candidates_on_accepted(&answer), refused) +} + +/// Move the answer's candidates off a rejected first section onto the first accepted one. +/// +/// str0m writes them only on the first section, where the BUNDLE group's tag usually +/// sits. A rejected first section, such as audio a broadcast can't egress, is out of the +/// group, so a browser would ignore its candidates. +fn candidates_on_accepted(answer: &str) -> Cow<'_, str> { + let (session, mut sections) = split_sections(answer, "\r\n"); + let is_candidate = |line: &&str| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates"); + let Some(first) = sections.first() else { + return Cow::Borrowed(answer); + }; + if port(first) != Some("0") || !first.iter().any(is_candidate) { + return Cow::Borrowed(answer); + } + let Some(accepted) = sections.iter().position(|section| port(section) != Some("0")) else { + return Cow::Borrowed(answer); + }; + let (candidates, rest): (Vec<&str>, Vec<&str>) = sections[0].iter().copied().partition(is_candidate); + sections[0] = rest; + sections[accepted].extend(candidates); + Cow::Owned(session.into_iter().chain(sections.into_iter().flatten()).collect()) +} + +/// Put each refused data channel section back into the answer at its offer's index. +fn restore_channels(answer: &str, refused: &Refused) -> String { + if refused.sections.is_empty() { + return answer.to_string(); + } + let mut out = String::with_capacity(answer.len() + 64 * refused.sections.len()); + let mut pending = refused.sections.iter().peekable(); + let mut index = 0; + for line in answer.split_inclusive("\r\n") { + if line.starts_with("m=") { + // Refused sections come before the accepted one now at their index. + while let Some((_, section)) = pending.next_if(|(at, _)| *at == index) { + out.push_str(section); + index += 1; + } + index += 1; + } + out.push_str(line); + } + // Those after the last accepted section. + for (_, section) in pending { + out.push_str(section); + } + out } /// Add a `b=TIAS` line at `rate` to every audio and video section the answer accepts, so @@ -100,7 +299,206 @@ pub fn parse_resource_id(path: &str) -> Result { #[cfg(test)] mod tests { - use super::{cap_answer, ensure_media_format}; + use str0m::Candidate; + use str0m::change::SdpAnswer; + use str0m::media::{Direction, MediaKind}; + + use super::{cap_answer, ensure_media_format, parse_offer, render_answer}; + + /// Answer `offer` as the WHIP server does, with one local candidate. + fn answer(offer: &str) -> String { + let (offer, refused) = parse_offer(offer).unwrap(); + let mut rtc = crate::session::rtc_with_codecs(&[str0m::format::Codec::Opus]).unwrap(); + let candidate = Candidate::host(([1, 1, 1, 1], 1000).into(), "udp").unwrap(); + rtc.add_local_candidate(candidate); + let answer = rtc.sdp_api().accept_offer(offer).unwrap(); + render_answer(&answer, &refused) + } + + /// The gateway carries no data channels, so an offered one is answered rejected and + /// left out of the BUNDLE group, while the media beside it is accepted, and the + /// offerer takes that answer. + #[test] + fn an_offered_data_channel_is_answered_rejected() { + let now = kio::clock::now().into_std(); + let mut offerer = crate::session::rtc_config().unwrap().build(now); + let mut api = offerer.sdp_api(); + let audio = api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + api.add_channel("chat".into()); + let (offer, pending) = api.apply().unwrap(); + let offer = offer.to_sdp_string(); + let channel = offer + .split("\r\n") + .filter_map(|line| line.strip_prefix("a=mid:")) + .find(|mid| *mid != audio.to_string()) + .unwrap(); + assert!(offer.contains("m=application 9 "), "{offer}"); + + let answer = answer(&offer); + let audio_at = answer.find("m=audio 9 ").expect("the audio was rejected"); + let rejected = + format!("m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\nc=IN IP4 0.0.0.0\r\na=mid:{channel}\r\n"); + let channel_at = answer.find(&rejected).expect(&answer); + assert!(audio_at < channel_at, "the sections changed order: {answer}"); + assert!(answer.ends_with(&rejected), "{answer}"); + assert!(answer.contains(&format!("a=group:BUNDLE {audio}\r\n")), "{answer}"); + + let answer = SdpAnswer::from_sdp_string(&answer).unwrap(); + offerer.sdp_api().accept_answer(pending, answer).unwrap(); + } + + /// An offer that puts its data channel first gets it answered first, and the + /// candidates on the accepted media rather than the rejected line. + #[test] + fn a_data_channel_offered_first_is_answered_first() { + let now = kio::clock::now().into_std(); + let mut offerer = crate::session::rtc_config().unwrap().build(now); + let mut api = offerer.sdp_api(); + let audio = api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _) = api.apply().unwrap(); + let offer = offer.to_sdp_string(); + let (session, media) = offer.split_at(offer.find("m=audio").unwrap()); + let session = session.replace( + &format!("a=group:BUNDLE {audio}\r\n"), + &format!("a=group:BUNDLE dc {audio}\r\n"), + ); + // LF line endings, as some clients send, survive the refusal. + let offer = format!( + "{session}m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ + c=IN IP4 0.0.0.0\r\n\ + a=mid:dc\r\n\ + a=sctp-port:5000\r\n{media}" + ) + .replace("\r\n", "\n"); + + let answer = answer(&offer); + let sections: Vec<&str> = answer.split("m=").skip(1).collect(); + assert_eq!(sections.len(), 2, "{answer}"); + assert_eq!( + sections[0], + "application 0 UDP/DTLS/SCTP webrtc-datachannel\r\nc=IN IP4 0.0.0.0\r\na=mid:dc\r\n" + ); + assert!(sections[1].starts_with("audio 9 "), "{answer}"); + assert!(sections[1].contains("a=candidate:"), "{answer}"); + assert!(answer.contains(&format!("a=group:BUNDLE {audio}\r\n")), "{answer}"); + } + + /// A max-bundle offer whose data channel tags the group carries the shared transport + /// only there, with its media bundle-only; the media still gets that transport. + #[test] + fn a_data_channel_tagging_the_bundle_keeps_its_transport() { + let now = kio::clock::now().into_std(); + let mut offerer = crate::session::rtc_config().unwrap().build(now); + offerer.add_local_candidate(Candidate::host(([2, 2, 2, 2], 2000).into(), "udp").unwrap()); + let mut api = offerer.sdp_api(); + let audio = api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _) = api.apply().unwrap(); + let offer = offer.to_sdp_string(); + let (session, media) = offer.split_at(offer.find("m=audio").unwrap()); + let session = session.replace( + &format!("a=group:BUNDLE {audio}\r\n"), + &format!("a=group:BUNDLE dc {audio}\r\n"), + ); + let is_transport = |line: &&str| super::TRANSPORT.iter().any(|a| line.starts_with(a)); + let transport: String = media.split_inclusive("\r\n").filter(is_transport).collect(); + assert!(transport.contains("a=candidate:"), "{offer}"); + let media: String = media + .split_inclusive("\r\n") + .filter(|line| !is_transport(line)) + .collect::() + .replacen("m=audio 9 ", "m=audio 0 ", 1) + + "a=bundle-only\r\n"; + let offer = format!( + "{session}m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ + c=IN IP4 0.0.0.0\r\n\ + a=mid:dc\r\n\ + {transport}\ + a=sctp-port:5000\r\n{media}" + ); + + let answer = answer(&offer); + let sections: Vec<&str> = answer.split("m=").skip(1).collect(); + assert!(sections[0].starts_with("application 0 "), "{answer}"); + assert!(sections[1].starts_with("audio 9 "), "{answer}"); + assert!(answer.contains(&format!("a=group:BUNDLE {audio}\r\n")), "{answer}"); + } + + /// A rejected first section, such as audio a broadcast can't egress, leaves the + /// answer's candidates to the first accepted one. + #[test] + fn candidates_skip_a_rejected_first_section() { + let now = kio::clock::now().into_std(); + let mut offerer = crate::session::rtc_config().unwrap().build(now); + let mut api = offerer.sdp_api(); + api.add_media(MediaKind::Audio, Direction::RecvOnly, None, None, None); + let video = api.add_media(MediaKind::Video, Direction::RecvOnly, None, None, None); + let (offer, pending) = api.apply().unwrap(); + + let (offer, refused) = parse_offer(&offer.to_sdp_string()).unwrap(); + let mut rtc = crate::session::rtc_with_codecs(&[str0m::format::Codec::Vp8]).unwrap(); + rtc.add_local_candidate(Candidate::host(([1, 1, 1, 1], 1000).into(), "udp").unwrap()); + let answer = render_answer(&rtc.sdp_api().accept_offer(offer).unwrap(), &refused); + + let sections: Vec<&str> = answer.split("m=").skip(1).collect(); + assert!(sections[0].starts_with("audio 0 "), "{answer}"); + assert!(!sections[0].contains("a=candidate:"), "{answer}"); + assert!(sections[1].starts_with("video 9 "), "{answer}"); + assert!(sections[1].contains("a=candidate:"), "{answer}"); + assert!(answer.contains(&format!("a=group:BUNDLE {video}\r\n")), "{answer}"); + + let answer = SdpAnswer::from_sdp_string(&answer).unwrap(); + offerer.sdp_api().accept_answer(pending, answer).unwrap(); + } + + /// An offer of only a data channel has nothing to answer. + #[test] + fn an_offer_of_only_a_data_channel_has_no_bundle() { + let offer = "v=0\r\n\ + o=- 1 2 IN IP4 0.0.0.0\r\n\ + s=-\r\n\ + t=0 0\r\n\ + a=group:BUNDLE dc\r\n\ + m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ + c=IN IP4 0.0.0.0\r\n\ + a=mid:dc\r\n"; + let (body, refused) = super::refuse_channels(offer); + assert_eq!(body, "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n"); + assert_eq!(refused.sections.len(), 1); + } + + /// A body near the request limit of transport lines and data channels stays linear: + /// each key and mid is checked against a set decided once, not rescanned per line. + #[test] + fn a_flood_of_refused_transport_stays_linear() { + const LINES: usize = 100_000; + let mut offer = String::from("v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE x"); + for mid in 0..LINES { + offer.push_str(&format!(" {mid}")); + } + offer.push_str("\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=mid:x\r\n"); + for _ in 0..LINES { + offer.push_str("a=ice-ufrag:u\r\n"); + } + for _ in 0..LINES { + offer.push_str("a=setup:actpass\r\n"); + } + for n in 0..LINES { + offer.push_str(&format!("a=candidate:{n} 1 udp 1 1.1.1.1 1000 typ host\r\n")); + } + for mid in 0..LINES { + offer.push_str(&format!( + "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=mid:{mid}\r\n" + )); + } + + // Quadratic work here takes ~10^10 comparisons, past nextest's timeout. + let (body, refused) = super::refuse_channels(&offer); + assert_eq!(refused.sections.len(), LINES + 1); + assert_eq!(body.matches("a=ice-ufrag:").count(), 1); + assert_eq!(body.matches("a=setup:").count(), 1); + assert_eq!(body.matches("a=candidate:").count(), LINES); + assert!(!body.contains("a=group:BUNDLE")); + } #[test] fn a_capped_answer_bounds_each_accepted_media_section() { diff --git a/rs/moq-webrtc/src/server/mux.rs b/rs/moq-webrtc/src/server/mux.rs index af9e98c572f..bb05dc158d9 100644 --- a/rs/moq-webrtc/src/server/mux.rs +++ b/rs/moq-webrtc/src/server/mux.rs @@ -19,7 +19,6 @@ //! (session ended) evicts the address-cache entry; the ufrag entry is removed by //! the [`Registration`] guard the accept path holds for the session's lifetime. -use crate::vendor::str0m; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index 0d7b49de17c..aa1477ecffc 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -3,7 +3,6 @@ //! `POST /` accepts a WHEP SDP offer and returns an SDP //! answer sourced from the matching MoQ broadcast on the subscribe origin. -use crate::vendor::str0m::Candidate; #[cfg(feature = "server")] use axum::{ Router, @@ -13,6 +12,7 @@ use axum::{ response::{IntoResponse, Response as HttpResponse}, routing::post, }; +use str0m::Candidate; use std::time::Duration; @@ -158,7 +158,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { broadcast, offer, } = request; - let offer = sdp::parse_offer(offer)?; + let (offer, refused) = sdp::parse_offer(offer)?; let source = resolve(subscriber, broadcast).await?; let codecs = source.catalog_codecs(); @@ -191,7 +191,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { Ok(Response { resource_id: resource_id.clone(), - answer: sdp::render_answer(&answer), + answer: sdp::render_answer(&answer, &refused), session: crate::server::AcceptedSession { server: server.clone(), resource_id, diff --git a/rs/moq-webrtc/src/server/whip.rs b/rs/moq-webrtc/src/server/whip.rs index 9a642355ee4..e3259a61006 100644 --- a/rs/moq-webrtc/src/server/whip.rs +++ b/rs/moq-webrtc/src/server/whip.rs @@ -4,7 +4,6 @@ //! and returns an SDP answer. The request path becomes the broadcast name on //! the upstream publish origin. -use crate::vendor::str0m; #[cfg(feature = "server")] use axum::{ Router, @@ -165,7 +164,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { ingest, rate, } = request; - let offer = sdp::parse_offer(offer)?; + let (offer, refused) = sdp::parse_offer(offer)?; // Create the broadcast hidden up front, so an out-of-scope offer is refused before // any mux work. It announces only once negotiation succeeds (below). @@ -210,7 +209,7 @@ pub async fn accept(server: &Server, request: Request<'_>) -> Result { let cancel = server.register_session(resource_id.clone()); tracing::info!(%broadcast, %instance, cap = cap.map(|cap| cap.rate.as_bps()), "whip publish accepted"); - let mut answer = sdp::render_answer(&answer); + let mut answer = sdp::render_answer(&answer, &refused); if let Some(cap) = cap { answer = sdp::cap_answer(&answer, rate::steer(cap)); } diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index 51eab73941a..d528b60ef2b 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -8,7 +8,6 @@ //! to a remote URL (client side), or whether the media flow is RTP-in //! ([`MediaSink`]) or RTP-out ([`crate::egress::EgressSource`]). -use crate::vendor::str0m; use std::collections::{HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; @@ -652,7 +651,7 @@ pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> Result config.enable_opus(true), + Codec::Opus => config.enable_opus(true, false), Codec::H264 => config.enable_h264(true), Codec::H265 => config.enable_h265(true), Codec::Vp8 => config.enable_vp8(true), @@ -665,12 +664,16 @@ pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> Result std::result::Result { moq_crypto::cpu::check()?; - Ok(str0m::RtcConfig::new()) + // rind-str0m repeats the check above, so its error is unreachable here. + let crypto = rind_str0m::default_provider().expect("the CPU check passed"); + Ok(str0m::RtcConfig::new() + .set_crypto_provider(Arc::new(crypto)) + // str0m's default today, pinned so a release that turns on DTLS 1.3 or + // version auto-selection changes the wire only when MoQ opts in. + .set_dtls_version(str0m::config::DtlsVersion::Dtls12)) } /// Build a codec-restricted [`Rtc`] for the client egress path (which lets diff --git a/rs/moq-webrtc/src/vendor/dimpl/LICENSE-APACHE.txt b/rs/moq-webrtc/src/vendor/dimpl/LICENSE-APACHE.txt deleted file mode 100644 index 261eeb9e9f8..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/LICENSE-APACHE.txt +++ /dev/null @@ -1,201 +0,0 @@ - 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. diff --git a/rs/moq-webrtc/src/vendor/dimpl/LICENSE-MIT.txt b/rs/moq-webrtc/src/vendor/dimpl/LICENSE-MIT.txt deleted file mode 100644 index 235abe2ca4c..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/LICENSE-MIT.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2022 Martin Algesten - -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. diff --git a/rs/moq-webrtc/src/vendor/dimpl/buffer.rs b/rs/moq-webrtc/src/vendor/dimpl/buffer.rs deleted file mode 100644 index 708ee957bee..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/buffer.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! Buffer management for efficient memory reuse. -//! -//! This module provides buffer types used throughout dimpl for managing byte data -//! with minimal allocations. The [`BufferPool`] allows reusing buffers, and [`Buf`] -//! wraps `Vec` with convenient operations for protocol data handling. - -use std::collections::VecDeque; -use std::fmt; -use std::ops::{Deref, DerefMut}; - -/// Buffer pool for reusing allocated buffers. -/// -/// This pool manages a collection of reusable `Buf` instances to reduce allocations -/// during DTLS operations. Buffers are returned to the pool when no longer needed -/// and can be reused for subsequent operations. -#[derive(Default)] -pub struct BufferPool { - free: VecDeque, -} - -impl BufferPool { - /// Take a Buffer from the pool. - /// - /// Creates a new buffer if none is free. - pub fn pop(&mut self) -> Buf { - let mut buffer = self.free.pop_front().unwrap_or_default(); - buffer.from_pool = true; - buffer - } - - /// Return a buffer to the pool. - /// - /// Panics if the buffer was not acquired from a pool. - pub fn push(&mut self, mut buffer: Buf) { - assert!(buffer.from_pool, "only buffers acquired from a pool may be returned"); - buffer.clear(); - self.free.push_front(buffer); - } -} - -impl fmt::Debug for BufferPool { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("BufferPool").field("free", &self.free.len()).finish() - } -} - -/// Growable buffer wrapper used throughout dimpl for efficient memory management. -/// -/// This wrapper around `Vec` provides convenient access to byte buffers -/// and integrates with dimpl's buffer pooling system. -/// When filling a borrowed `&mut Buf`, mutate its contents instead of replacing -/// the buffer so its pool provenance is preserved. -#[derive(Default)] -pub struct Buf { - data: Vec, - from_pool: bool, -} - -impl Buf { - /// Create an empty buffer for temporary or independently owned data. - /// - /// This buffer must not be returned to a pool. Recyclable buffers must be - /// acquired from their pool. - pub fn new() -> Self { - Self::default() - } - - /// Clear the buffer, removing all data. - pub fn clear(&mut self) { - self.data.clear(); - } - - /// Extend the buffer with a slice of bytes. - pub fn extend_from_slice(&mut self, other: &[u8]) { - self.data.extend_from_slice(other); - } - - /// Push a single byte onto the buffer. - pub fn push(&mut self, byte: u8) { - self.data.push(byte); - } - - /// Resize the buffer to the specified length, filling with the given value. - pub fn resize(&mut self, len: usize, value: u8) { - self.data.resize(len, value); - } - - /// Convert the buffer into the underlying `Vec`. - pub fn into_vec(self) -> Vec { - self.data - } -} - -// AEAD backends may append their authentication tags through Extend<&u8> -impl<'a> Extend<&'a u8> for Buf { - fn extend>(&mut self, iter: T) { - self.data.extend(iter.into_iter().copied()); - } -} - -impl Deref for Buf { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.data - } -} - -impl DerefMut for Buf { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.data - } -} - -impl AsRef<[u8]> for Buf { - fn as_ref(&self) -> &[u8] { - &self.data - } -} - -impl AsMut<[u8]> for Buf { - fn as_mut(&mut self) -> &mut [u8] { - &mut self.data - } -} - -impl fmt::Debug for Buf { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Buf").field("len", &self.data.len()).finish() - } -} - -/// Trait for types that can be converted into a `Buf`. -pub trait ToBuf { - /// Convert this value into a `Buf`. - fn to_buf(self) -> Buf; -} - -impl ToBuf for Vec { - fn to_buf(self) -> Buf { - Buf { - data: self, - from_pool: false, - } - } -} - -impl ToBuf for &[u8] { - fn to_buf(self) -> Buf { - self.to_vec().to_buf() - } -} - -/// Temporary mutable buffer wrapper for in-place operations. -/// -/// Used primarily for decryption operations where data needs to be modified in-place. -/// Provides mutable access to a slice with tracked length. -#[allow(clippy::len_without_is_empty)] -pub struct TmpBuf<'a>(&'a mut [u8], usize); - -impl core::fmt::Debug for TmpBuf<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TmpBuf").field("data_len", &self.1).finish() - } -} - -impl<'a> TmpBuf<'a> { - /// Create a new temporary buffer from a mutable slice. - pub fn new(buf: &'a mut [u8]) -> Self { - Self(buf, buf.len()) - } -} - -impl<'a> TmpBuf<'a> { - /// Get the length of the buffer - pub fn len(&self) -> usize { - self.1 - } - - /// Truncate the buffer to the specified length - pub fn truncate(&mut self, len: usize) { - self.1 = len; - } -} - -impl<'a> AsRef<[u8]> for TmpBuf<'a> { - fn as_ref(&self) -> &[u8] { - &self.0[..self.1] - } -} - -impl<'a> AsMut<[u8]> for TmpBuf<'a> { - fn as_mut(&mut self) -> &mut [u8] { - &mut self.0[..self.1] - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn pooled_buffers_keep_capacity_and_are_cleared() { - let mut pool = BufferPool::default(); - let mut buffer = pool.pop(); - buffer.extend_from_slice(&[0xAA; 256]); - let allocation = buffer.as_ptr(); - pool.push(buffer); - - let reused = pool.pop(); - assert!(reused.is_empty()); - assert_eq!(reused.as_ptr(), allocation); - assert!(reused.into_vec().capacity() >= 256); - } - - #[test] - #[should_panic(expected = "only buffers acquired from a pool may be returned")] - fn rejects_unpooled_buffer() { - BufferPool::default().push(Buf::new()); - } - - #[test] - #[should_panic(expected = "only buffers acquired from a pool may be returned")] - fn rejects_converted_buffer() { - BufferPool::default().push(vec![0xAA; 256].to_buf()); - } - - #[test] - #[should_panic(expected = "only buffers acquired from a pool may be returned")] - fn converting_to_vec_does_not_keep_pool_provenance() { - let mut pool = BufferPool::default(); - let buffer = pool.pop(); - pool.push(buffer.into_vec().to_buf()); - } - - #[test] - #[should_panic(expected = "only buffers acquired from a pool may be returned")] - fn taking_buffer_does_not_make_replacement_pooled() { - let mut pool = BufferPool::default(); - let mut buffer = pool.pop(); - pool.push(std::mem::take(&mut buffer)); - pool.push(buffer); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/certificate.rs b/rs/moq-webrtc/src/vendor/dimpl/certificate.rs deleted file mode 100644 index 16ac1350138..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/certificate.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Certificate generation and formatting utilities exposed via the public `certificate` module. -//! -//! This module provides helpers to generate self-signed certificates suitable for DTLS, -//! compute fingerprints, and format them for display. - -use rcgen::{CertificateParams, DistinguishedName, DnType, IsCa, PKCS_ECDSA_P256_SHA256, SerialNumber}; -use rind::digest; -use std::fmt; - -/// Certificate utility error types -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum CertificateError { - /// Invalid certificate format - InvalidFormat, - /// Fingerprint verification failed - FingerprintMismatch, - /// Certificate generation failed - GenerationFailed, -} - -impl fmt::Display for CertificateError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - CertificateError::InvalidFormat => write!(f, "Invalid certificate format"), - CertificateError::FingerprintMismatch => write!(f, "Fingerprint mismatch"), - CertificateError::GenerationFailed => write!(f, "Certificate generation failed"), - } - } -} - -impl std::error::Error for CertificateError {} - -pub use crate::vendor::dimpl::DtlsCertificate; - -/// Generate a self-signed ECDSA P-256 certificate for DTLS, valid for a year. -pub fn generate_self_signed_certificate() -> Result { - // Create a key pair for the certificate - let key_pair = - rind_rcgen::KeyPair::generate(&PKCS_ECDSA_P256_SHA256).map_err(|_| CertificateError::GenerationFailed)?; - - // Set up certificate parameters - let mut params = CertificateParams::new(Vec::::new()).map_err(|_| CertificateError::GenerationFailed)?; - - // Set up distinguished name - let mut distinguished_name = DistinguishedName::new(); - distinguished_name.push(DnType::OrganizationName, "DTLS".to_string()); - distinguished_name.push(DnType::CommonName, "DTLS Peer".to_string()); - params.distinguished_name = distinguished_name; - - // Configure as end entity certificate (not a CA) - params.is_ca = IsCa::NoCa; - - // Set validity period (1 year) - let not_before = time::OffsetDateTime::now_utc(); - let not_after = not_before + time::Duration::days(365); - params.not_before = not_before; - params.not_after = not_after; - - // Serial number: must be unique for Firefox compatibility, not only across all certificates - // of this process, but also across all certificates of other processes/machines! - // See: https://github.com/versatica/mediasoup/issues/127#issuecomment-474460153 - // and https://github.com/algesten/str0m/issues/517 - let mut serial = [0u8; 16]; - rind::rand::fill(&mut serial).map_err(|_| CertificateError::GenerationFailed)?; - params.serial_number = Some(SerialNumber::from_slice(&serial)); - - // Build the certificate - let cert = params - .self_signed(&key_pair) - .map_err(|_| CertificateError::GenerationFailed)?; - - // Get the certificate in DER format - let cert_der = cert.der().to_vec(); - - // Get the private key in PKCS#8 DER format - let key_der = key_pair.to_pkcs8().secret_pkcs8_der().to_vec(); - - Ok(DtlsCertificate { - certificate: cert_der, - private_key: key_der, - }) -} - -/// Calculate a certificate fingerprint using SHA-256 -pub fn calculate_fingerprint(cert_der: &[u8]) -> Vec { - // Use SHA-256 to calculate the fingerprint - digest::digest(&digest::SHA256, cert_der).as_ref().to_vec() -} - -/// Format a fingerprint as a colon-separated hex string -/// Example: "AF:12:F6:..." -pub fn format_fingerprint(fingerprint: &[u8]) -> String { - fingerprint - .iter() - .map(|byte| format!("{:02X}", byte)) - .collect::>() - .join(":") -} - -impl DtlsCertificate { - /// Returns the certificate fingerprint as raw bytes. - /// - /// The fingerprint is computed by hashing the DER-encoded certificate - /// with SHA-256 and is therefore 32 bytes long. - /// - /// This method requires the `rcgen` feature to be enabled. - pub fn fingerprint(&self) -> Vec { - calculate_fingerprint(&self.certificate) - } - - /// Returns the certificate fingerprint as a human-readable string. - /// - /// The string is the SHA-256 fingerprint formatted as uppercase - /// hex byte pairs separated by colons, for example "AF:12:F6:...". - /// - /// This method requires the `rcgen` feature to be enabled. - pub fn fingerprint_str(&self) -> String { - format_fingerprint(&self.fingerprint()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_self_signed_certificate() { - // Generate a certificate - let cert = generate_self_signed_certificate().unwrap(); - - // Check certificate format - assert!(!cert.certificate.is_empty()); - assert!(!cert.private_key.is_empty()); - - // Fingerprint should be 32 bytes (SHA-256) - assert_eq!(cert.fingerprint().len(), 32); - } - - #[test] - fn test_unique_serial_numbers() { - // Generate two certificates - let cert1 = generate_self_signed_certificate().unwrap(); - let cert2 = generate_self_signed_certificate().unwrap(); - - // Fingerprints should be different (unique serial numbers + keys) - assert_ne!(cert1.fingerprint(), cert2.fingerprint()); - - // Parse the certificates to verify serial numbers are different - use x509_parser::prelude::*; - let (_, parsed1) = X509Certificate::from_der(&cert1.certificate).unwrap(); - let (_, parsed2) = X509Certificate::from_der(&cert2.certificate).unwrap(); - assert_ne!( - parsed1.serial, parsed2.serial, - "Serial numbers must be unique for Firefox compatibility" - ); - } - - #[test] - fn test_fingerprint_formatting() { - let test_fingerprint = vec![0xAF, 0x12, 0xF6, 0x38, 0x2A]; - let formatted = format_fingerprint(&test_fingerprint); - assert_eq!(formatted, "AF:12:F6:38:2A"); - - // Test with an actual generated certificate - let cert = generate_self_signed_certificate().unwrap(); - let formatted = format_fingerprint(&cert.fingerprint()); - - // Verify the format - assert_eq!(formatted.len(), 95); // 32 bytes * 3 - 1 = 95 (32 hex pairs with : between them) - assert!(formatted.contains(':')); - - // Each segment should be 2 hex chars - for segment in formatted.split(':') { - assert_eq!(segment.len(), 2); - // Verify it's valid hex - assert!(u8::from_str_radix(segment, 16).is_ok()); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/config.rs b/rs/moq-webrtc/src/vendor/dimpl/config.rs deleted file mode 100644 index 5c03feab5bc..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/config.rs +++ /dev/null @@ -1,861 +0,0 @@ -use std::fmt; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::sync::Arc; -use std::time::Duration; - -use crate::vendor::dimpl::crypto::SupportedKxGroup; -use crate::vendor::dimpl::crypto::{CryptoProvider, SupportedDtls12CipherSuite}; -use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; -use crate::vendor::dimpl::types::NamedGroup; -use crate::vendor::dimpl::{ConfigError, Error}; - -const MAX_TIMING_DURATION: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60); - -/// Callback for resolving PSK identities to shared secrets. -/// -/// Implement this trait and provide it via [`ConfigBuilder::with_psk_client`] -/// or [`ConfigBuilder::with_psk_server`] to enable PSK cipher suites. -pub trait PskResolver: Send + Sync + UnwindSafe + RefUnwindSafe { - /// Look up a pre-shared key by the peer's identity. - /// - /// Returns the shared secret bytes, or `None` if the identity is unknown. - fn resolve(&self, identity: &[u8]) -> Option>; -} - -/// PSK configuration for a DTLS endpoint. -/// -/// Use [`Psk::Client`] for endpoints that initiate PSK handshakes (send identity), -/// and [`Psk::Server`] for endpoints that resolve incoming identities. -/// -/// `#[non_exhaustive]` so new variants or fields can be added without a major -/// version bump. -#[derive(Clone)] -#[non_exhaustive] -pub enum Psk { - /// Client-side PSK: sends `identity` during handshake, uses `resolver` - /// to look up the shared secret. - #[non_exhaustive] - Client { - /// The identity to send to the server. - identity: Vec, - /// Resolver for looking up shared secrets. - resolver: Arc, - }, - /// Server-side PSK: optionally sends a `hint` to help the client choose - /// an identity, uses `resolver` to look up secrets by client identity. - #[non_exhaustive] - Server { - /// Optional hint sent to the client in ServerKeyExchange. - hint: Option>, - /// Resolver for looking up shared secrets. - resolver: Arc, - }, -} - -/// DTLS configuration shared by all connections. -/// -/// Build with [`Config::builder()`] or use [`Config::default()`]. -#[derive(Clone)] -pub struct Config { - mtu: usize, - max_queue_rx: usize, - max_queue_tx: usize, - require_client_certificate: bool, - use_server_cookie: bool, - flight_start_rto: Duration, - flight_retries: usize, - handshake_timeout: Duration, - crypto_provider: CryptoProvider, - rng_seed: Option, - dtls12_cipher_suites: Option>, - kx_groups: Option>, - psk: Option, -} - -impl Config { - /// Create a new configuration builder. - pub fn builder() -> ConfigBuilder { - ConfigBuilder { - mtu: 1150, - max_queue_rx: 30, - max_queue_tx: 10, - require_client_certificate: true, - use_server_cookie: true, - flight_start_rto: Duration::from_secs(1), - flight_retries: 4, - handshake_timeout: Duration::from_secs(40), - crypto_provider: None, - rng_seed: None, - dtls12_cipher_suites: None, - kx_groups: None, - psk: None, - } - } - - /// Max transmission unit. - /// - /// The largest size UDP packets we will produce. - #[inline(always)] - pub fn mtu(&self) -> usize { - self.mtu - } - - /// Max amount of incoming packets to buffer before rejecting more input. - #[inline(always)] - pub fn max_queue_rx(&self) -> usize { - self.max_queue_rx - } - - /// Max amount of outgoing packets to buffer. - #[inline(always)] - pub fn max_queue_tx(&self) -> usize { - self.max_queue_tx - } - - /// For a server, require a client certificate. - /// - /// This will cause the server to send a CertificateRequest message. - /// Makes the server fail if the client does not send a certificate. - /// - /// Applies only to certificate-authenticated cipher suites. For RFC 4279 - /// PSK suites the client never sends a certificate, so this flag has no - /// effect on a negotiated PSK handshake. - #[inline(always)] - pub fn require_client_certificate(&self) -> bool { - self.require_client_certificate - } - - /// Whether the server sends a cookie exchange before the handshake. - /// - /// When true (the default), the server requires a stateless cookie - /// roundtrip for DoS protection: HelloVerifyRequest. - /// - /// When false, the server proceeds directly to ServerHello without - /// a cookie exchange. - #[inline(always)] - pub fn use_server_cookie(&self) -> bool { - self.use_server_cookie - } - - /// Time of first retry. - /// - /// Every flight restarts with this value. - /// Doubled for every retry with a ±25% jitter. - #[inline(always)] - pub fn flight_start_rto(&self) -> Duration { - self.flight_start_rto - } - - /// Max number of retries per flight. - #[inline(always)] - pub fn flight_retries(&self) -> usize { - self.flight_retries - } - - /// Timeout for the entire handshake, regardless of flights. - #[inline(always)] - pub fn handshake_timeout(&self) -> Duration { - self.handshake_timeout - } - - /// Cryptographic provider. - /// - /// Provides all cryptographic operations (ciphers, key exchange, signing, etc.). - #[inline(always)] - pub fn crypto_provider(&self) -> &CryptoProvider { - &self.crypto_provider - } - - /// Optional seed for deterministic random number generation. - /// - /// When set, most non-cryptographic randomness (backoff jitter, TLS random bytes, - /// AEAD nonces, cookie secrets) will be deterministic based on this seed. - /// This is useful for testing and reproducibility. - /// - /// Note: Cryptographic operations (key exchange, signatures) always use - /// secure system randomness regardless of this setting. - #[inline(always)] - pub fn rng_seed(&self) -> Option { - self.rng_seed - } - - /// PSK configuration, if any. - pub fn psk(&self) -> Option<&Psk> { - self.psk.as_ref() - } - - /// PSK identity for the client to send during handshake. - pub fn psk_identity(&self) -> Option<&[u8]> { - match &self.psk { - Some(Psk::Client { identity, .. }) => Some(identity), - _ => None, - } - } - - /// PSK identity hint for the server to send during handshake. - pub fn psk_identity_hint(&self) -> Option<&[u8]> { - match &self.psk { - Some(Psk::Server { hint, .. }) => hint.as_deref(), - _ => None, - } - } - - /// PSK resolver for looking up shared secrets by identity. - pub fn psk_resolver(&self) -> Option<&dyn PskResolver> { - match &self.psk { - Some(Psk::Client { resolver, .. } | Psk::Server { resolver, .. }) => Some(resolver.as_ref()), - None => None, - } - } - - /// Allowed DTLS 1.2 cipher suites, filtered by the config's allow-list. - /// - /// Returns all provider-supported DTLS 1.2 cipher suites when no filter - /// is set. When a filter is set via the builder's `dtls12_cipher_suites` - /// method, only suites in both the provider and the filter are returned. - /// - /// PSK cipher suites are excluded when no [`PskResolver`] is configured, - /// preventing a certificate-mode endpoint from negotiating a PSK suite - /// and inadvertently skipping certificate authentication. - pub fn dtls12_cipher_suites(&self) -> impl Iterator + '_ { - let filter = self.dtls12_cipher_suites.as_ref(); - let has_psk = self.psk.is_some(); - self.crypto_provider - .supported_cipher_suites() - .filter(move |cs| match filter { - Some(list) => list.contains(&cs.suite()), - None => true, - }) - .filter(move |cs| has_psk || !cs.suite().is_psk()) - } - - /// Allowed key exchange groups, filtered by the config's allow-list. - /// - /// Returns all provider-supported key exchange groups when no filter - /// is set. When a filter is set via the builder's `kx_groups` method, - /// only groups in both the provider and the filter are returned. - pub fn kx_groups(&self) -> impl Iterator + '_ { - let filter = self.kx_groups.as_ref(); - self.crypto_provider - .supported_kx_groups() - .filter(move |kx| match filter { - Some(list) => list.contains(&kx.name()), - None => true, - }) - } -} - -/// Builder for [`Config`]. See each setter for defaults. -pub struct ConfigBuilder { - mtu: usize, - max_queue_rx: usize, - max_queue_tx: usize, - require_client_certificate: bool, - use_server_cookie: bool, - flight_start_rto: Duration, - flight_retries: usize, - handshake_timeout: Duration, - crypto_provider: Option, - rng_seed: Option, - dtls12_cipher_suites: Option>, - kx_groups: Option>, - psk: Option, -} - -impl ConfigBuilder { - /// Set the max transmission unit (MTU). - /// - /// The largest size UDP packets we will produce. - /// Defaults to 1150. - pub fn mtu(mut self, mtu: usize) -> Self { - self.mtu = mtu; - self - } - - /// Set the max amount of incoming packets to buffer before rejecting more input. - /// - /// Defaults to 30. - pub fn max_queue_rx(mut self, max_queue_rx: usize) -> Self { - self.max_queue_rx = max_queue_rx; - self - } - - /// Set the max amount of outgoing packets to buffer. - /// - /// Defaults to 10. - pub fn max_queue_tx(mut self, max_queue_tx: usize) -> Self { - self.max_queue_tx = max_queue_tx; - self - } - - /// Set whether to require a client certificate (for servers). - /// - /// This will cause the server to send a CertificateRequest message. - /// Makes the server fail if the client does not send a certificate. - /// Defaults to true. - /// - /// Applies only to certificate-authenticated cipher suites. For RFC 4279 - /// PSK suites the client never sends a certificate, so this flag has no - /// effect on a negotiated PSK handshake; no opt-out is required when - /// combining this builder with [`with_psk_server`](Self::with_psk_server). - pub fn require_client_certificate(mut self, require: bool) -> Self { - self.require_client_certificate = require; - self - } - - /// Set whether the server sends a cookie exchange before the handshake. - /// - /// When true (the default), the server requires a stateless cookie - /// roundtrip for DoS protection: HelloVerifyRequest. - /// - /// When false, the server proceeds directly to ServerHello without - /// a cookie exchange. - pub fn use_server_cookie(mut self, use_cookie: bool) -> Self { - self.use_server_cookie = use_cookie; - self - } - - /// Set the time of first retry. - /// - /// Each flight starts its timer when its first packet is emitted. The base - /// interval doubles after every retry, with independent +/-25% jitter on - /// each interval. This is proportional even for sub-second values; the - /// minimum jittered interval is 1 nanosecond. Backoff arithmetic saturates - /// on overflow. - /// - /// Defaults to 1 second. Must be nonzero and at most ten years (3650 days). - pub fn flight_start_rto(mut self, rto: Duration) -> Self { - self.flight_start_rto = rto; - self - } - - /// Set the max number of retries per flight. - /// - /// Excludes the initial transmission: zero disables retransmissions. - /// Timer-driven and duplicate-triggered retransmissions share this budget. - /// Once the handshake has completed locally, the final flight is still - /// resent in answer to the peer's retransmitted final flight, as - /// RFC 6347 §4.2.4 requires. - /// Defaults to 4. - pub fn flight_retries(mut self, retries: usize) -> Self { - self.flight_retries = retries; - self - } - - /// Set the timeout for the entire handshake, regardless of flights. - /// - /// Starts when the client emits its first ClientHello packet through - /// [`crate::vendor::dimpl::Output::Packet`], or when the server accepts its first - /// structurally valid ClientHello fragment, even if its body is later rejected. - /// A corrected ClientHello shares the same deadline for this peer. - /// Construction and idle time consume no budget. Uses the logical time - /// supplied to [`crate::vendor::dimpl::Dtls::handle_timeout`]. - /// - /// The absolute deadline survives cookie exchanges, later flights, and - /// retransmissions. It is disabled after completion and does not apply to - /// application traffic. - /// - /// Retry exhaustion may fail earlier; increasing this timeout does not - /// increase [`Self::flight_retries`]. With the defaults, an unanswered flight - /// exhausts retries after roughly 31 seconds, before the 40-second deadline. - /// - /// Defaults to 40 seconds. Must be nonzero and at most ten years (3650 days). - pub fn handshake_timeout(mut self, timeout: Duration) -> Self { - self.handshake_timeout = timeout; - self - } - - /// Set a custom crypto provider. - /// - /// If not set, the process default or else rind's provider is used. - pub fn with_crypto_provider(mut self, provider: CryptoProvider) -> Self { - self.crypto_provider = Some(provider); - self - } - - /// Set a seed for deterministic random number generation. - /// - /// When set, most non-cryptographic randomness (backoff jitter, TLS random bytes, - /// AEAD nonces, cookie secrets) will be deterministic based on this seed. - /// - /// This is useful for testing and reproducibility. - /// - /// Note: Cryptographic operations (key exchange, signatures) always use - /// secure system randomness regardless of this setting. - pub fn dangerously_set_rng_seed(mut self, seed: u64) -> Self { - self.rng_seed = Some(seed); - self - } - - /// Restrict which DTLS 1.2 cipher suites are offered and accepted. - /// - /// Only cipher suites present in both this list and the provider will - /// be used. Passing an empty slice leaves no suites and fails the build. - /// - /// By default all provider-supported DTLS 1.2 cipher suites are used. - pub fn dtls12_cipher_suites(mut self, suites: &[Dtls12CipherSuite]) -> Self { - self.dtls12_cipher_suites = Some(suites.to_vec()); - self - } - - /// Restrict which key exchange groups are offered and accepted. - /// - /// Only groups present in both this list and the provider will be - /// used. Order determines preference (first = most preferred). - /// - /// By default all provider-supported key exchange groups are used. - pub fn kx_groups(mut self, groups: &[NamedGroup]) -> Self { - self.kx_groups = Some(groups.to_vec()); - self - } - - /// Configure PSK for a client endpoint. - /// - /// The `identity` is sent to the server during the handshake. - /// The `resolver` looks up the shared secret by identity. - pub fn with_psk_client(mut self, identity: Vec, resolver: Arc) -> Self { - self.psk = Some(Psk::Client { identity, resolver }); - self - } - - /// Configure PSK for a server endpoint. - /// - /// The optional `hint` is sent to the client in ServerKeyExchange. - /// The `resolver` looks up the shared secret by client identity. - pub fn with_psk_server(mut self, hint: Option>, resolver: Arc) -> Self { - self.psk = Some(Psk::Server { hint, resolver }); - self - } - - /// Build the configuration. - /// - /// Validates timing settings and the crypto provider before returning the - /// configuration. Returns `Error::ConfigError` for invalid settings. - /// - /// The crypto provider is selected in the following priority order: - /// 1. Explicit provider set via `with_crypto_provider()` - /// 2. Default provider installed via `CryptoProvider::install_default()` - /// 3. rind's provider, refusing a CPU rind cannot run on - pub fn build(self) -> Result { - if self.handshake_timeout.is_zero() || self.handshake_timeout > MAX_TIMING_DURATION { - return Err(ConfigError::InvalidHandshakeTimeout.into()); - } - if self.flight_start_rto.is_zero() || self.flight_start_rto > MAX_TIMING_DURATION { - return Err(ConfigError::InvalidFlightStartRto.into()); - } - - let crypto_provider = match self.crypto_provider.or_else(|| CryptoProvider::get_default().cloned()) { - Some(provider) => provider, - None => crate::vendor::dimpl::crypto::rind::default_provider().map_err(ConfigError::UnsupportedCpu)?, - }; - - // Always validate the crypto provider - crypto_provider.validate()?; - - // Validate MTU: must be large enough for DTLS record + handshake headers - if self.mtu < 64 { - return Err(Error::ConfigError(ConfigError::MtuTooSmall { - mtu: self.mtu as u16, - minimum: 64, - })); - } - - // Validate cipher suite filters: at least one suite must remain. - // Mirror Config::dtls12_cipher_suites() by dropping PSK suites when no PSK - // is configured, so a PSK-only filter without a PSK resolver fails fast. - let has_psk = self.psk.is_some(); - let dtls12_suites: Vec<_> = { - let all = crypto_provider.supported_cipher_suites(); - match &self.dtls12_cipher_suites { - Some(list) => all - .filter(|cs| list.contains(&cs.suite())) - .filter(|cs| has_psk || !cs.suite().is_psk()) - .collect(), - None => all.filter(|cs| has_psk || !cs.suite().is_psk()).collect(), - } - }; - if dtls12_suites.is_empty() { - return Err(Error::ConfigError(ConfigError::NoCipherSuitesAfterFiltering)); - } - - // When PSK is configured, at least one negotiable DTLS 1.2 suite must be - // a PSK suite: under AuthMode::Psk every non-PSK suite is rejected by - // CryptoContext::is_cipher_suite_compatible. - if has_psk && !dtls12_suites.iter().any(|cs| cs.suite().is_psk()) { - return Err(Error::ConfigError(ConfigError::PskConfiguredWithoutPskCipherSuite)); - } - - // Skip DTLS 1.2 kx-group validation only when the surviving DTLS 1.2 - // suites are exclusively PSK - those don't negotiate an ECDHE group. - // Any cert-based DTLS 1.2 suite left in the filter still needs a - // compatible key exchange group, even when PSK is also configured. - let has_non_psk_dtls12 = dtls12_suites.iter().any(|cs| !cs.suite().is_psk()); - - // Validate kx_groups filter: certificate suites need compatible groups - // (PSK-only configs don't need key exchange groups) - let filtered_kx = |kx: &&'static dyn SupportedKxGroup| -> bool { - match &self.kx_groups { - Some(list) => list.contains(&kx.name()), - None => true, - } - }; - if has_non_psk_dtls12 { - let dtls12_kx_count = crypto_provider.supported_kx_groups().filter(&filtered_kx).count(); - if dtls12_kx_count == 0 { - return Err(Error::ConfigError(ConfigError::NoDtls12KeyExchangeGroupsAfterFiltering)); - } - } - - Ok(Config { - mtu: self.mtu, - max_queue_rx: self.max_queue_rx, - max_queue_tx: self.max_queue_tx, - require_client_certificate: self.require_client_certificate, - use_server_cookie: self.use_server_cookie, - flight_start_rto: self.flight_start_rto, - flight_retries: self.flight_retries, - handshake_timeout: self.handshake_timeout, - crypto_provider, - rng_seed: self.rng_seed, - dtls12_cipher_suites: self.dtls12_cipher_suites, - kx_groups: self.kx_groups, - psk: self.psk, - }) - } -} - -impl Default for Config { - fn default() -> Self { - Config::builder() - .build() - .expect("Default config should always validate") - } -} - -impl fmt::Debug for Psk { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Psk::Client { identity, .. } => f - .debug_struct("Psk::Client") - .field("identity", &identity) - .field("resolver", &"...") - .finish(), - Psk::Server { hint, .. } => f - .debug_struct("Psk::Server") - .field("hint", &hint) - .field("resolver", &"...") - .finish(), - } - } -} - -impl fmt::Debug for Config { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Config") - .field("mtu", &self.mtu) - .field("max_queue_rx", &self.max_queue_rx) - .field("max_queue_tx", &self.max_queue_tx) - .field("require_client_certificate", &self.require_client_certificate) - .field("use_server_cookie", &self.use_server_cookie) - .field("flight_start_rto", &self.flight_start_rto) - .field("flight_retries", &self.flight_retries) - .field("handshake_timeout", &self.handshake_timeout) - .field("crypto_provider", &self.crypto_provider) - .field("rng_seed", &self.rng_seed) - .field("dtls12_cipher_suites", &self.dtls12_cipher_suites) - .field("kx_groups", &self.kx_groups) - .field("psk", &self.psk) - .finish() - } -} - -impl fmt::Debug for ConfigBuilder { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ConfigBuilder") - .field("mtu", &self.mtu) - .field("max_queue_rx", &self.max_queue_rx) - .field("max_queue_tx", &self.max_queue_tx) - .field("require_client_certificate", &self.require_client_certificate) - .field("use_server_cookie", &self.use_server_cookie) - .field("flight_start_rto", &self.flight_start_rto) - .field("flight_retries", &self.flight_retries) - .field("handshake_timeout", &self.handshake_timeout) - .field("crypto_provider", &self.crypto_provider) - .field("rng_seed", &self.rng_seed) - .field("dtls12_cipher_suites", &self.dtls12_cipher_suites) - .field("kx_groups", &self.kx_groups) - .field("psk", &self.psk) - .finish() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn timing_defaults() { - let config = Config::default(); - assert_eq!(config.handshake_timeout(), Duration::from_secs(40)); - assert_eq!(config.flight_start_rto(), Duration::from_secs(1)); - assert_eq!(config.flight_retries(), 4); - } - - #[test] - fn timing_duration_bounds() { - for duration in [ - Duration::ZERO, - MAX_TIMING_DURATION + Duration::from_nanos(1), - Duration::MAX, - ] { - let error = Config::builder() - .handshake_timeout(duration) - .build() - .expect_err("unsupported handshake timeout"); - assert_eq!(error, Error::ConfigError(ConfigError::InvalidHandshakeTimeout)); - assert_eq!( - error.to_string(), - "config error: handshake_timeout must be nonzero and at most 3650 days" - ); - let error = Config::builder() - .flight_start_rto(duration) - .build() - .expect_err("unsupported initial RTO"); - assert_eq!(error, Error::ConfigError(ConfigError::InvalidFlightStartRto)); - assert_eq!( - error.to_string(), - "config error: flight_start_rto must be nonzero and at most 3650 days" - ); - } - for duration in [Duration::from_nanos(1), MAX_TIMING_DURATION] { - for retries in [0, usize::MAX] { - let config = Config::builder() - .handshake_timeout(duration) - .flight_start_rto(duration) - .flight_retries(retries) - .build() - .expect("supported timing boundaries"); - assert_eq!(config.handshake_timeout(), duration); - assert_eq!(config.flight_start_rto(), duration); - assert_eq!(config.flight_retries(), retries); - } - } - } - - #[test] - fn rejects_zero_mtu() { - match Config::builder().mtu(0).build() { - Err(Error::ConfigError(ConfigError::MtuTooSmall { mtu, minimum })) => { - assert_eq!(mtu, 0); - assert_eq!(minimum, 64); - } - Err(other) => panic!("expected ConfigError, got: {other:?}"), - Ok(_) => panic!("expected error for MTU=0"), - } - } - - #[test] - fn rejects_small_mtu() { - match Config::builder().mtu(32).build() { - Err(Error::ConfigError(ConfigError::MtuTooSmall { mtu, minimum })) => { - assert_eq!(mtu, 32); - assert_eq!(minimum, 64); - } - Err(other) => panic!("expected ConfigError, got: {other:?}"), - Ok(_) => panic!("expected error for MTU=32"), - } - } - - #[test] - fn accepts_minimum_mtu() { - Config::builder().mtu(64).build().expect("MTU 64 should be accepted"); - } - - #[test] - fn filter_dtls12_cipher_suite() { - let config = Config::builder() - .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]) - .build() - .expect("should accept single DTLS 1.2 suite"); - let suites: Vec<_> = config.dtls12_cipher_suites().map(|cs| cs.suite()).collect(); - assert_eq!(suites, &[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]); - } - - #[test] - fn filter_kx_groups() { - let config = Config::builder() - .kx_groups(&[NamedGroup::Secp256r1]) - .build() - .expect("should accept single kx group"); - let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); - assert_eq!(groups, &[NamedGroup::Secp256r1]); - } - - #[test] - fn empty_filter_rejected() { - match Config::builder().dtls12_cipher_suites(&[]).build() { - Err(Error::ConfigError(ConfigError::NoCipherSuitesAfterFiltering)) => {} - Err(other) => panic!("expected ConfigError, got: {other:?}"), - Ok(_) => panic!("expected error when no suites remain"), - } - } - - #[test] - fn empty_kx_groups_filter_rejected() { - match Config::builder().kx_groups(&[]).build() { - Err(Error::ConfigError(ConfigError::NoDtls12KeyExchangeGroupsAfterFiltering)) => {} - Err(other) => panic!("expected ConfigError, got: {other:?}"), - Ok(_) => panic!("expected error for empty kx groups"), - } - } - - #[test] - fn x25519_only_accepted_for_dtls12() { - // X25519 is supported for DTLS 1.2 and should be accepted. - let config = Config::builder() - .kx_groups(&[NamedGroup::X25519]) - .build() - .expect("X25519-only should be accepted for DTLS 1.2"); - let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); - assert_eq!(groups, &[NamedGroup::X25519]); - } - - #[test] - fn kx_groups_match_provider_when_unfiltered() { - let config = Config::default(); - let from_config: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); - let from_provider: Vec<_> = config - .crypto_provider() - .supported_kx_groups() - .map(|g| g.name()) - .collect(); - assert_eq!(from_config, from_provider); - } - - #[test] - fn no_filter_returns_all() { - let config = Config::default(); - // Default provider should have at least 2 DTLS 1.2 suites - // (PSK suites are excluded without a resolver, so only non-PSK count) - assert!(config.dtls12_cipher_suites().count() >= 2); - assert!(config.kx_groups().count() >= 2); - } - - #[test] - fn psk_suites_excluded_without_resolver() { - let config = Config::default(); - assert!( - config.dtls12_cipher_suites().all(|cs| !cs.suite().is_psk()), - "PSK suites should be excluded when no PskResolver is configured" - ); - } - - #[test] - fn psk_suites_included_with_resolver() { - struct DummyResolver; - impl PskResolver for DummyResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - None - } - } - - let config = Config::builder() - .with_psk_server(None, Arc::new(DummyResolver)) - .build() - .expect("config with PSK resolver should build"); - assert!( - config.dtls12_cipher_suites().any(|cs| cs.suite().is_psk()), - "PSK suites should be included when a PskResolver is configured" - ); - } - - #[test] - fn psk_config_with_only_non_psk_dtls12_filter_rejected() { - struct DummyResolver; - impl PskResolver for DummyResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(b"key".to_vec()) - } - } - - // PSK config but the user filtered DTLS 1.2 down to a cert-only suite. - // AuthMode::Psk would reject every surviving - // suite at runtime, so build() should fail fast here. - let result = Config::builder() - .with_psk_client(b"identity".to_vec(), Arc::new(DummyResolver)) - .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]) - .build(); - match result { - Err(Error::ConfigError(ConfigError::PskConfiguredWithoutPskCipherSuite)) => {} - Err(other) => panic!("expected ConfigError, got: {other:?}"), - Ok(_) => panic!("expected error for PSK config with only non-PSK suites"), - } - } - - #[test] - fn psk_with_cert_dtls12_and_empty_kx_groups_rejected() { - struct DummyResolver; - impl PskResolver for DummyResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(b"key".to_vec()) - } - } - - // Mixed config: PSK is set, but a cert-based DTLS 1.2 suite is also in - // the filter alongside a PSK suite. That cert suite still needs an - // ECDHE group, so kx_groups(&[]) must fail build - the fact that PSK - // is also configured does not excuse the missing groups. - let result = Config::builder() - .with_psk_server(None, Arc::new(DummyResolver)) - .dtls12_cipher_suites(&[ - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, - Dtls12CipherSuite::PSK_AES128_CCM_8, - ]) - .kx_groups(&[]) - .build(); - match result { - Err(Error::ConfigError(ConfigError::NoDtls12KeyExchangeGroupsAfterFiltering)) => {} - Err(other) => panic!("expected ConfigError, got: {other:?}"), - Ok(_) => panic!( - "expected error when a cert-based DTLS 1.2 suite is enabled \ - without any kx groups, even alongside PSK" - ), - } - } - - #[test] - fn psk_client_with_empty_kx_groups_builds() { - struct DummyResolver; - impl PskResolver for DummyResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(b"key".to_vec()) - } - } - - // PSK suites don't need ECDHE groups. A truly PSK-only endpoint (with - // the DTLS 1.2 filter narrowed to PSK suites) - // should be able to opt out of kx_groups entirely. - Config::builder() - .with_psk_client(b"identity".to_vec(), Arc::new(DummyResolver)) - .dtls12_cipher_suites(&[Dtls12CipherSuite::PSK_AES128_CCM_8]) - .kx_groups(&[]) - .build() - .expect("PSK-only client with empty kx_groups should build"); - } - - #[test] - fn filter_with_explicit_provider() { - { - let config = Config::builder() - .with_crypto_provider(crate::vendor::dimpl::crypto::rind::default_provider().unwrap()) - .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384]) - .kx_groups(&[NamedGroup::X25519, NamedGroup::Secp256r1]) - .build() - .expect("should accept filtered config with explicit provider"); - let suites12: Vec<_> = config.dtls12_cipher_suites().map(|cs| cs.suite()).collect(); - assert_eq!(suites12, &[Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384]); - let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); - assert_eq!(groups, &[NamedGroup::X25519, NamedGroup::Secp256r1]); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs deleted file mode 100644 index 026dce094fc..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/ccm_cipher.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! AES-128-CCM-8 cipher implementation using the RustCrypto `ccm` crate. -//! -//! Backs the rind provider's PSK suite, since rind has no AES-CCM. - -use ccm::aead::AeadInOut; -use ccm::aead::KeyInit; -use ccm::consts::{U8, U12}; - -use super::{Aad, Cipher, Nonce}; -use crate::vendor::dimpl::buffer::{Buf, TmpBuf}; -use crate::vendor::dimpl::error::bounded_error_len; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; - -/// AES-128-CCM with 8-byte tag, 12-byte nonce. -type Aes128Ccm8 = ccm::Ccm; - -/// AES-128-CCM-8 cipher for TLS_PSK_WITH_AES_128_CCM_8. -pub struct AesCcm8Cipher { - cipher: Box, -} - -impl std::fmt::Debug for AesCcm8Cipher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("AesCcm8Cipher").finish_non_exhaustive() - } -} - -impl AesCcm8Cipher { - pub fn new(key: &[u8]) -> Result { - if key.len() != 16 { - return Err(CryptoError::InvalidAes128Ccm8KeySize { - actual: bounded_error_len(key.len()), - }); - } - let cipher = - Aes128Ccm8::new_from_slice(key).map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?; - Ok(AesCcm8Cipher { - cipher: Box::new(cipher), - }) - } -} - -impl Cipher for AesCcm8Cipher { - fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - let ccm_nonce = ccm::Nonce::::from(nonce.0); - let tag = self - .cipher - .encrypt_inout_detached(&ccm_nonce, &aad[..], plaintext.as_mut().into()) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; - - // Append the 8-byte tag - plaintext.extend_from_slice(&tag); - - Ok(()) - } - - fn decrypt(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - if ciphertext.len() < 8 { - return Err(CryptoError::CiphertextTooShort { - minimum: 8, - actual: ciphertext.len() as u8, - }); - } - - let ccm_nonce = ccm::Nonce::::from(nonce.0); - - // Split off the 8-byte tag from the end - let data_len = ciphertext.len() - 8; - let mut tag_bytes = [0u8; 8]; - tag_bytes.copy_from_slice(&ciphertext.as_ref()[data_len..]); - let tag = ccm::Tag::::from(tag_bytes); - - // Truncate to just the ciphertext (without tag) - ciphertext.truncate(data_len); - - self.cipher - .decrypt_inout_detached(&ccm_nonce, &aad[..], ciphertext.as_mut().into(), &tag) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; - - Ok(()) - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/dtls_aead.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/dtls_aead.rs deleted file mode 100644 index 8dbcbd108ed..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/dtls_aead.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! DTLS AEAD record formatting types and constants. -//! -//! This module contains types and constants specific to DTLS AEAD record formatting, -//! separate from the pluggable crypto provider abstraction. - -use arrayvec::ArrayVec; - -use crate::vendor::dimpl::types::{ContentType, Sequence}; - -/// Explicit nonce length for DTLS AEAD records. -/// -/// The explicit nonce is transmitted with each record. -#[cfg(test)] -pub(crate) const DTLS_EXPLICIT_NONCE_LEN: usize = 8; - -/// GCM authentication tag length. -/// -/// The tag is appended to the ciphertext. -#[cfg(test)] -pub(crate) const GCM_TAG_LEN: usize = 16; - -/// Overhead per DTLS 1.2 AES-GCM record (explicit nonce + tag). -/// -/// This equals 24 bytes for DTLS AES-GCM. -#[cfg(test)] -pub(crate) const DTLS_AEAD_OVERHEAD: usize = DTLS_EXPLICIT_NONCE_LEN + GCM_TAG_LEN; // 24 - -/// Compute AAD length from plaintext length for DTLS 1.2 AES-GCM records. -#[inline] -#[cfg(test)] -pub fn aad_len_from_plaintext_len(plaintext_len: u16) -> u16 { - plaintext_len -} - -/// Compute fragment length from plaintext length for DTLS 1.2 AES-GCM records. -/// fragment_len = explicit_nonce(8) + ciphertext(plaintext_len + 16 tag) -#[inline] -#[cfg(test)] -pub fn fragment_len_from_plaintext_len(plaintext_len: usize) -> usize { - DTLS_EXPLICIT_NONCE_LEN + plaintext_len + GCM_TAG_LEN -} - -/// Compute plaintext length from fragment length for DTLS 1.2 AES-GCM records. -/// Returns None if the fragment is smaller than the mandatory AEAD overhead. -#[inline] -#[cfg(test)] -pub fn plaintext_len_from_fragment_len(fragment_len: usize) -> Option { - fragment_len.checked_sub(DTLS_AEAD_OVERHEAD) -} - -/// Fixed IV portion for DTLS AEAD. -/// -/// DTLS 1.2 uses: -/// - AES-GCM: 4-byte fixed IV + 8-byte explicit nonce (per record) -/// - ChaCha20-Poly1305: 12-byte fixed IV + 0-byte explicit nonce -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct Iv { - bytes: [u8; 12], - len: u8, -} - -impl Iv { - pub(crate) fn new(iv: &[u8]) -> Self { - assert!(iv.len() <= 12, "invalid IV length: expected <= 12, got {}", iv.len()); - let mut bytes = [0u8; 12]; - bytes[..iv.len()].copy_from_slice(iv); - Self { - bytes, - len: iv.len() as u8, - } - } - - pub(crate) fn len(&self) -> usize { - self.len as usize - } - - pub(crate) fn as_slice(&self) -> &[u8] { - &self.bytes[..self.len()] - } - - /// Returns the full 12-byte backing array. - /// - /// Only valid for 12-byte IVs (ChaCha20-Poly1305). For 4-byte IVs - /// (AES-GCM), use [`as_slice`] instead. - pub(crate) fn as_12_bytes(&self) -> &[u8; 12] { - assert_eq!(self.len(), 12, "as_12_bytes called on {}-byte IV", self.len()); - &self.bytes - } -} - -/// Full AEAD nonce (fixed IV + explicit nonce). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Nonce(pub [u8; 12]); - -impl Nonce { - /// Create a new AEAD nonce by combining fixed IV and explicit nonce (DTLS 1.2). - pub(crate) fn new(iv: Iv, explicit_nonce: &[u8]) -> Self { - assert_eq!( - iv.len() + explicit_nonce.len(), - 12, - "invalid DTLS 1.2 nonce parts: iv_len={}, explicit_nonce_len={}", - iv.len(), - explicit_nonce.len() - ); - let mut nonce = [0u8; 12]; - let iv_len = iv.len(); - nonce[..iv_len].copy_from_slice(iv.as_slice()); - nonce[iv_len..].copy_from_slice(explicit_nonce); - Self(nonce) - } - - /// Create a nonce by XORing the IV with the padded sequence number. - /// - /// Used by DTLS 1.2 ChaCha20-Poly1305: - /// nonce = iv XOR pad_left(sequence_number, 12) - /// See RFC 8446 Section 5.3 / RFC 7905. - pub(crate) fn xor(iv: &[u8; 12], seq: u64) -> Self { - let mut nonce = *iv; - let seq_bytes = seq.to_be_bytes(); // 8 bytes - // XOR the last 8 bytes of the 12-byte IV with the sequence number - for i in 0..8 { - nonce[4 + i] ^= seq_bytes[i]; - } - Self(nonce) - } -} - -/// Additional Authenticated Data for DTLS records. -/// -/// DTLS 1.2 uses 13 bytes. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Aad(pub ArrayVec); - -impl Aad { - /// Create Additional Authenticated Data for a DTLS 1.2 record. - pub(crate) fn new_dtls12(content_type: ContentType, sequence: Sequence, length: u16) -> Self { - let mut aad = ArrayVec::new(); - - // First set the full 8-byte sequence number - let seq_bytes = sequence.sequence_number.to_be_bytes(); - aad.try_extend_from_slice(&seq_bytes).unwrap(); - - // Overwrite the first 2 bytes with epoch - let epoch_bytes = sequence.epoch.to_be_bytes(); - aad[0] = epoch_bytes[0]; - aad[1] = epoch_bytes[1]; - - // Content type at index 8 - aad.push(content_type.as_u8()); - - // Protocol version bytes (major:minor) at indexes 9-10 - aad.push(0xfe); // DTLS 1.2 major version - aad.push(0xfd); // DTLS 1.2 minor version - - // Payload length (2 bytes) at indexes 11-12 - aad.try_extend_from_slice(&length.to_be_bytes()).unwrap(); - - Aad(aad) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn aead_constants_and_length_helpers() { - assert_eq!(DTLS_EXPLICIT_NONCE_LEN, 8); - assert_eq!(GCM_TAG_LEN, 16); - assert_eq!(DTLS_AEAD_OVERHEAD, 24); - - for &pt_len in &[0usize, 1, 37, 512, 1350, 16384] { - let aad_len = aad_len_from_plaintext_len(pt_len as u16); - assert_eq!(aad_len as usize, pt_len); - - let frag_len = fragment_len_from_plaintext_len(pt_len); - assert_eq!(frag_len, DTLS_EXPLICIT_NONCE_LEN + pt_len + GCM_TAG_LEN); - - let roundtrip = plaintext_len_from_fragment_len(frag_len).expect("frag_len >= overhead"); - assert_eq!(roundtrip, pt_len); - } - - assert!(plaintext_len_from_fragment_len(0).is_none()); - assert!(plaintext_len_from_fragment_len(3).is_none()); - assert!(plaintext_len_from_fragment_len(DTLS_AEAD_OVERHEAD - 1).is_none()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/keying.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/keying.rs deleted file mode 100644 index f9a361e86cf..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/keying.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! SRTP keying material types and profiles used by DTLS-SRTP. -use std::ops::Deref; - -/// Keying material used as master key for SRTP. -pub struct KeyingMaterial(Vec); - -impl KeyingMaterial { - /// Create a new wrapper for DTLS-SRTP keying material bytes. - pub fn new(m: &[u8]) -> Self { - KeyingMaterial(m.to_vec()) - } -} - -impl Deref for KeyingMaterial { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl std::fmt::Debug for KeyingMaterial { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "KeyingMaterial") - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[allow(non_camel_case_types)] -#[non_exhaustive] -/// Supported SRTP protection profiles (RFC 5764). -pub enum SrtpProfile { - /// SRTP_AES128_CM_HMAC_SHA1_80 (RFC 5764) - AES128_CM_SHA1_80, - /// AEAD_AES_128_GCM (RFC 7714) - AEAD_AES_128_GCM, - /// AEAD_AES_256_GCM (RFC 7714) - AEAD_AES_256_GCM, -} - -impl SrtpProfile { - /// The length of keying material to extract from the DTLS session in bytes. - #[rustfmt::skip] - pub fn keying_material_len(&self) -> usize { - match self { - // MASTER_KEY_LEN * 2 + MASTER_SALT * 2 - // TODO: This is a duplication of info that is held in srtp.rs, because we - // don't want a dependency in that direction. - SrtpProfile::AES128_CM_SHA1_80 => 16 * 2 + 14 * 2, - SrtpProfile::AEAD_AES_128_GCM => 16 * 2 + 12 * 2, - SrtpProfile::AEAD_AES_256_GCM => 32 * 2 + 12 * 2, - } - } -} - -impl std::fmt::Display for SrtpProfile { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - SrtpProfile::AES128_CM_SHA1_80 => write!(f, "SRTP_AES128_CM_SHA1_80"), - SrtpProfile::AEAD_AES_128_GCM => write!(f, "SRTP_AEAD_AES_128_GCM"), - SrtpProfile::AEAD_AES_256_GCM => write!(f, "SRTP_AEAD_AES_256_GCM"), - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs deleted file mode 100644 index e8bf265ab0e..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/mod.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Cryptographic primitives and helpers used by the DTLS engine. - -use std::ops::Deref; - -// Internal module imports -mod keying; - -// Provider traits and implementations -pub mod rind; - -pub(crate) mod ccm_cipher; - -mod dtls_aead; -pub mod prf_hkdf; -mod provider; -mod validation; - -pub use keying::{KeyingMaterial, SrtpProfile}; - -// Re-export AEAD types needed for Cipher trait implementations (public API) -pub use dtls_aead::{Aad, Nonce}; - -// Re-export internal AEAD constants/types for crate-internal use -pub(crate) use dtls_aead::Iv; - -// Re-export buffer types for provider trait implementations -pub use crate::vendor::dimpl::buffer::{Buf, TmpBuf}; - -// Re-export all provider traits and types (similar to rustls structure) -// This allows users to do: use crate::vendor::dimpl::crypto::{CryptoProvider, SupportedDtls12CipherSuite, ...}; -pub use provider::{ - ActiveKeyExchange, Cipher, CryptoProvider, CryptoSafe, HashContext, HashProvider, HmacProvider, KeyProvider, - SecureRandom, SignatureVerifier, SigningKey, SupportedDtls12CipherSuite, SupportedKxGroup, check_verify_scheme, -}; -pub use provider::{OID_P256, OID_P384}; - -// Re-export shared types for provider trait implementations -pub use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; -pub use crate::vendor::dimpl::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm}; - -impl Deref for Aad { - type Target = [u8]; - fn deref(&self) -> &Self::Target { - &self.0[..] - } -} - -impl Deref for Nonce { - type Target = [u8]; - fn deref(&self) -> &Self::Target { - &self.0 - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs deleted file mode 100644 index 75d7033d7bf..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/prf_hkdf.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! PRF key derivation built on top of [`HmacProvider`]. -//! -//! The TLS 1.2 PRF is a pure composition of HMAC calls. This module provides a -//! generic implementation so that crypto backends only need to implement -//! [`HmacProvider`] - no separate PRF provider. - -use crate::vendor::dimpl::CryptoError; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::types::HashAlgorithm; - -use super::HmacProvider; - -/// Maximum HMAC output size we support (SHA-384 = 48 bytes). -const MAX_HASH_LEN: usize = 48; - -// ============================================================================ -// TLS 1.2 PRF (RFC 5246 Section 5) -// ============================================================================ - -/// TLS 1.2 PRF: `PRF(secret, label, seed)` writing `output_len` bytes to `out`. -/// -/// Uses `scratch` for temporary concatenation of label+seed. -#[allow(clippy::too_many_arguments)] -pub fn prf_tls12( - hmac: &dyn HmacProvider, - secret: &[u8], - label: &str, - seed: &[u8], - out: &mut Buf, - output_len: usize, - scratch: &mut Buf, - hash: HashAlgorithm, -) -> Result<(), CryptoError> { - let mut hmac_a = [0u8; MAX_HASH_LEN]; - - // Build label + seed - scratch.clear(); - scratch.extend_from_slice(label.as_bytes()); - scratch.extend_from_slice(seed); - let label_seed = scratch.as_ref(); - - // A(1) = HMAC(secret, label_seed) - let hash_len = hmac.hmac(hash, secret, label_seed, &mut hmac_a)?; - - // Build payload = A(i) || label || seed - scratch.clear(); - scratch.extend_from_slice(&hmac_a[..hash_len]); - scratch.extend_from_slice(label.as_bytes()); - scratch.extend_from_slice(seed); - let payload = scratch.as_mut(); - - out.clear(); - while out.len() < output_len { - // P(i) = HMAC(secret, A(i) || label || seed) - let mut hmac_block = [0u8; MAX_HASH_LEN]; - let block_len = hmac.hmac(hash, secret, payload, &mut hmac_block)?; - - let remaining = output_len - out.len(); - let to_copy = remaining.min(block_len); - out.extend_from_slice(&hmac_block[..to_copy]); - - if out.len() < output_len { - // A(i+1) = HMAC(secret, A(i)) - hmac.hmac(hash, secret, &payload[..hash_len], &mut hmac_a)?; - payload[..hash_len].copy_from_slice(&hmac_a[..hash_len]); - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn hex_to_vec(hex: &str) -> Vec { - let hex = hex.replace([' ', '\n'], ""); - let mut v = Vec::new(); - for i in 0..hex.len() / 2 { - // unwrap: test-only hex parsing - let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap(); - v.push(byte); - } - v - } - - fn slice_to_hex(data: &[u8]) -> String { - let mut s = String::new(); - for byte in data.iter() { - s.push_str(&format!("{:02x}", byte)); - } - s - } - - /// Convert an ASCII hex array into a byte array at compile time. - macro_rules! hex_as_bytes { - ($input:expr) => {{ - const fn from_hex_char(c: u8) -> u8 { - match c { - b'0'..=b'9' => c - b'0', - b'a'..=b'f' => c - b'a' + 10, - b'A'..=b'F' => c - b'A' + 10, - _ => panic!("Invalid hex character"), - } - } - - const INPUT: &[u8] = $input; - const LEN: usize = INPUT.len(); - const OUTPUT_LEN: usize = LEN / 2; - - const fn convert() -> [u8; OUTPUT_LEN] { - assert!(LEN % 2 == 0, "Hex string length must be even"); - - let mut out = [0u8; OUTPUT_LEN]; - let mut i = 0; - while i < LEN { - out[i / 2] = (from_hex_char(INPUT[i]) << 4) | from_hex_char(INPUT[i + 1]); - i += 2; - } - out - } - - convert() - }}; - } - - /// We need a concrete HmacProvider for tests. - fn hmac_provider() -> &'static dyn HmacProvider { - &crate::vendor::dimpl::crypto::rind::HMAC - } - - // ======================================================================== - // HMAC-SHA-256 Test Vectors from RFC 4231 - // ======================================================================== - - #[test] - fn hmac_sha256_test_case_1() { - let key = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); - let data = b"Hi There"; - let expected = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; - - let result = hmac_provider().hmac_sha256(&key, data).unwrap(); - assert_eq!(slice_to_hex(&result), expected); - } - - #[test] - fn hmac_sha256_test_case_2() { - let key = b"Jefe"; - let data = b"what do ya want for nothing?"; - let expected = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"; - - let result = hmac_provider().hmac_sha256(key, data).unwrap(); - assert_eq!(slice_to_hex(&result), expected); - } - - #[test] - fn hmac_sha256_test_case_3() { - let key = hex_to_vec("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - let data = hex_to_vec( - "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\ - dddddddddddddddddddddddddddddddddddd", - ); - let expected = "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"; - - let result = hmac_provider().hmac_sha256(&key, &data).unwrap(); - assert_eq!(slice_to_hex(&result), expected); - } - - #[test] - fn hmac_sha256_test_case_4() { - let key = hex_to_vec("0102030405060708090a0b0c0d0e0f10111213141516171819"); - let data = hex_to_vec( - "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd\ - cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", - ); - let expected = "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"; - - let result = hmac_provider().hmac_sha256(&key, &data).unwrap(); - assert_eq!(slice_to_hex(&result), expected); - } - - #[test] - fn hmac_sha256_test_case_6() { - // Test with a key larger than block size (> 64 bytes) - let key = vec![0xaa; 131]; - let data = b"Test Using Larger Than Block-Size Key - Hash Key First"; - let expected = "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"; - - let result = hmac_provider().hmac_sha256(&key, data).unwrap(); - assert_eq!(slice_to_hex(&result), expected); - } - - #[test] - fn hmac_sha256_test_case_7() { - // Test with a key larger than block size and large data - let key = vec![0xaa; 131]; - let data = b"This is a test using a larger than block-size key and a larger than block-size \ - data. The key needs to be hashed before being used by the HMAC algorithm."; - let expected = "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"; - - let result = hmac_provider().hmac_sha256(&key, data).unwrap(); - assert_eq!(slice_to_hex(&result), expected); - } - - // ======================================================================== - // TLS 1.2 PRF - // ======================================================================== - - #[test] - fn prf_tls12_sha256() { - // Test vector from https://github.com/xomexh/TLS-PRF - let mut output = Buf::new(); - let mut scratch = Buf::new(); - prf_tls12( - hmac_provider(), - &hex_as_bytes!(b"9bbe436ba940f017b17652849a71db35"), - "test label", - &hex_as_bytes!(b"a0ba9f936cda311827a6f796ffd5198c"), - &mut output, - 100, - &mut scratch, - HashAlgorithm::SHA256, - ) - .unwrap(); - assert_eq!( - output.as_ref(), - &hex_as_bytes!( - b"e3f229ba727be17b8d122620557cd453c2aab21d\ - 07c3d495329b52d4e61edb5a6b301791e90d35c9\ - c9a46b4e14baf9af0fa022f7077def17abfd3797\ - c0564bab4fbc91666e9def9b97fce34f796789ba\ - a48082d122ee42c5a72e5a5110fff70187347b66" - ) - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs deleted file mode 100644 index f3c5b12cddb..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/provider.rs +++ /dev/null @@ -1,503 +0,0 @@ -//! Cryptographic provider traits for pluggable crypto backends. -//! -//! This module defines the trait-based interface for cryptographic operations -//! in dimpl, allowing users to provide custom crypto implementations. -//! -//! # Overview -//! -//! The crypto provider system is inspired by rustls's design and uses a component-based -//! approach where the [`CryptoProvider`] struct holds static references to various -//! trait objects, each representing a specific cryptographic capability. -//! -//! # Architecture -//! -//! The provider system is organized into these main components: -//! -//! - **Cipher Suites** ([`SupportedDtls12CipherSuite`]): Factory for AEAD ciphers -//! - **Key Exchange Groups** ([`SupportedKxGroup`]): Factory for ECDHE key exchanges -//! - **Signature Verification** ([`SignatureVerifier`]): Verify signatures in certificates -//! - **Key Provider** ([`KeyProvider`]): Parse and load private keys -//! - **Secure Random** ([`SecureRandom`]): Cryptographically secure RNG -//! - **Hash Provider** ([`HashProvider`]): Factory for hash contexts -//! - **HMAC Provider** ([`HmacProvider`]): Compute HMAC signatures (also drives PRF and HKDF) -//! -//! # Using a Custom Provider -//! -//! To use a custom crypto provider, create one and pass it to the [`Config`](crate::vendor::dimpl::Config): -//! -//! ```ignore -//! # #[cfg(all(all(), all()))] -//! # fn main() { -//! use std::sync::Arc; -//! use std::time::Instant; -//! use crate::vendor::dimpl::{Config, Dtls, certificate}; -//! use crate::vendor::dimpl::crypto::rind; -//! -//! let cert = certificate::generate_self_signed_certificate().unwrap(); -//! // Use the default rind provider (implicit) -//! let config = Arc::new(Config::default()); -//! -//! // Or explicitly set the provider -//! let config = Arc::new( -//! Config::builder() -//! .with_crypto_provider(rind::default_provider().unwrap()) -//! .build() -//! .unwrap() -//! ); -//! -//! // Or use your own custom provider -//! // let config = Arc::new( -//! // Config::builder() -//! // .with_crypto_provider(my_custom_provider()) -//! // .build() -//! // .unwrap() -//! // ); -//! -//! let dtls = Dtls::new_12(config, cert, Instant::now()); -//! # } -//! # #[cfg(not(all(all(), all())))] -//! # fn main() {} -//! ``` -//! -//! # Implementing a Custom Provider -//! -//! To implement a custom provider, you need to: -//! -//! 1. Implement the required traits for your crypto backend -//! 2. Create static instances of your implementations -//! 3. Build a [`CryptoProvider`] struct with references to those statics -//! -//! ## Example: Custom Cipher Suite -//! -//! ```ignore -//! use crate::vendor::dimpl::CryptoError; -//! use crate::vendor::dimpl::crypto::{SupportedDtls12CipherSuite, Cipher, Dtls12CipherSuite, HashAlgorithm}; -//! use crate::vendor::dimpl::crypto::{Buf, TmpBuf}; -//! use crate::vendor::dimpl::crypto::{Aad, Nonce}; -//! -//! #[derive(Debug)] -//! struct MyCipher; -//! -//! impl MyCipher { -//! fn new(_key: &[u8]) -> Result { -//! Ok(Self) -//! } -//! } -//! -//! impl Cipher for MyCipher { -//! fn encrypt(&mut self, _: &mut Buf, _: Aad, _: Nonce) -> Result<(), CryptoError> { -//! Ok(()) -//! } -//! fn decrypt(&mut self, _: &mut TmpBuf, _: Aad, _: Nonce) -> Result<(), CryptoError> { -//! Ok(()) -//! } -//! } -//! -//! #[derive(Debug)] -//! struct MyDtls12CipherSuite; -//! -//! impl SupportedDtls12CipherSuite for MyDtls12CipherSuite { -//! fn suite(&self) -> Dtls12CipherSuite { -//! Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 -//! } -//! -//! fn hash_algorithm(&self) -> HashAlgorithm { -//! HashAlgorithm::SHA256 -//! } -//! -//! fn key_lengths(&self) -> (usize, usize, usize) { -//! (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) -//! } -//! -//! fn explicit_nonce_len(&self) -> usize { -//! 8 // AES-GCM: 8-byte explicit nonce per record -//! } -//! -//! fn tag_len(&self) -> usize { -//! 16 // 128-bit authentication tag -//! } -//! -//! fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { -//! // Create your cipher implementation here -//! Ok(Box::new(MyCipher::new(key)?)) -//! } -//! } -//! -//! static MY_CIPHER_SUITE: MyDtls12CipherSuite = MyDtls12CipherSuite; -//! static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[&MY_CIPHER_SUITE]; -//! ``` -//! -//! # Requirements -//! -//! For DTLS 1.2, implementations must support: -//! -//! - **Cipher suites**: ECDHE_ECDSA with AES-128-GCM, AES-256-GCM, or CHACHA20_POLY1305 -//! - **Key exchange**: ECDHE with X25519, P-256, or P-384 curves -//! - **Signatures**: ECDSA with P-256/SHA-256 or P-384/SHA-384 -//! - **Hash**: SHA-256 and SHA-384 -//! - **HMAC**: HMAC-SHA256 and HMAC-SHA384 (used for PRF, HKDF, and cookies) -//! -//! # Thread Safety -//! -//! All provider traits require `Send + Sync + UnwindSafe + RefUnwindSafe` to ensure -//! safe usage across threads and panic boundaries. - -use std::fmt::Debug; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::sync::OnceLock; - -use crate::vendor::dimpl::buffer::{Buf, TmpBuf}; -use crate::vendor::dimpl::crypto::{Aad, Nonce}; -use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; -use crate::vendor::dimpl::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm}; -use crate::vendor::dimpl::{CertificateError, CryptoError}; - -/// OID for the P-256 elliptic curve (secp256r1 / prime256v1). -pub const OID_P256: spki::ObjectIdentifier = spki::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"); - -/// OID for the P-384 elliptic curve (secp384r1). -pub const OID_P384: spki::ObjectIdentifier = spki::ObjectIdentifier::new_unwrap("1.3.132.0.34"); - -// ============================================================================ -// Marker Trait -// ============================================================================ - -/// Marker trait for types that are safe to use in crypto provider components. -/// -/// This trait combines the common bounds required for crypto provider trait objects: -/// - [`Send`] + [`Sync`]: Thread-safe -/// - [`Debug`]: Support debugging -/// - [`UnwindSafe`] + [`RefUnwindSafe`]: Panic-safe -/// -/// This trait is automatically implemented for all types that satisfy these bounds. -pub trait CryptoSafe: Send + Sync + Debug + UnwindSafe + RefUnwindSafe {} - -/// Blanket implementation: any type satisfying the bounds implements [`CryptoSafe`]. -impl CryptoSafe for T {} - -// ============================================================================ -// Instance Traits (Level 2 - created by factories) -// ============================================================================ - -/// AEAD cipher for in-place encryption/decryption. -pub trait Cipher: CryptoSafe { - /// Encrypt plaintext in-place, appending authentication tag. - fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError>; - - /// Decrypt ciphertext in-place, verifying and removing authentication tag. - fn decrypt(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError>; -} - -/// Stateful hash context for incremental hashing. -pub trait HashContext: CryptoSafe { - /// Update the hash with new data. - fn update(&mut self, data: &[u8]); - - /// Clone the context and finalize it, writing the hash to `out`. - /// The original context can continue to be updated. - fn clone_and_finalize(&self, out: &mut Buf); -} - -/// Signing key for generating digital signatures. -pub trait SigningKey: CryptoSafe { - /// Sign data using the specified hash algorithm and return the signature. - fn sign(&mut self, data: &[u8], hash_alg: HashAlgorithm, out: &mut Buf) -> Result<(), CryptoError>; - - /// Signature algorithm used by this key. - fn algorithm(&self) -> SignatureAlgorithm; - - /// Default hash algorithm for this key. - fn hash_algorithm(&self) -> HashAlgorithm; - - /// Hash algorithms this key can sign with. - /// - /// Used during negotiation to intersect with the peer's offered - /// algorithms. Backends that lock the hash at key-load time (e.g. - /// rind) return only the locked hash; backends that support - /// arbitrary prehash signing (e.g. RustCrypto) may return several. - fn supported_hash_algorithms(&self) -> &[HashAlgorithm]; -} - -/// Active key exchange instance (ephemeral keypair for one handshake). -pub trait ActiveKeyExchange: CryptoSafe { - /// Get the public key for this exchange. - fn pub_key(&self) -> &[u8]; - - /// Complete exchange with peer's public key, returning shared secret. - fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError>; - - /// Get the named group for this exchange. - fn group(&self) -> NamedGroup; -} - -// ============================================================================ -// Factory Traits (Level 1 - used by CryptoProvider) -// ============================================================================ - -/// Cipher suite support (factory for Cipher instances). -pub trait SupportedDtls12CipherSuite: CryptoSafe { - /// The cipher suite this supports. - fn suite(&self) -> Dtls12CipherSuite; - - /// Hash algorithm used by this suite. - fn hash_algorithm(&self) -> HashAlgorithm; - - /// Key material lengths: (mac_key_len, enc_key_len, fixed_iv_len). - fn key_lengths(&self) -> (usize, usize, usize); - - /// Length in bytes of the per-record explicit nonce (carried in the record body). - /// - /// AES-GCM suites carry an 8-byte explicit nonce; ChaCha20-Poly1305 carries none. - fn explicit_nonce_len(&self) -> usize; - - /// AEAD authentication tag length in bytes. - fn tag_len(&self) -> usize; - - /// Minimum length, in bytes, of a protected record's encrypted fragment. - /// - /// For AEAD suites this equals explicit nonce + authentication tag; a CBC - /// suite would override this to `IV + MAC + 1` (one padding byte). Records - /// shorter than this cannot be valid regardless of cipher mode and are - /// rejected at the record boundary. - fn min_protected_fragment_len(&self) -> usize { - self.explicit_nonce_len() + self.tag_len() - } - - /// Create a cipher instance with the given key. - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError>; -} - -/// Key exchange group support (factory for ActiveKeyExchange). -pub trait SupportedKxGroup: CryptoSafe { - /// Named group for this key exchange group. - fn name(&self) -> NamedGroup; - - /// Start a new key exchange, generating ephemeral keypair. - /// The provided `buf` will be used to store the public key. - fn start_exchange(&self, buf: Buf) -> Result, CryptoError>; -} - -/// Signature verification against certificates. -pub trait SignatureVerifier: CryptoSafe { - /// Verify a signature on data using a DER-encoded X.509 certificate. - fn verify_signature( - &self, - cert_der: &[u8], - data: &[u8], - signature: &[u8], - hash_alg: HashAlgorithm, - sig_alg: SignatureAlgorithm, - ) -> Result<(), CryptoError>; -} - -/// Allow-list of supported (signature, hash, curve) combinations for -/// DTLS 1.2 signature verification. -/// -/// In DTLS 1.2 the hash algorithm and the certificate's curve are -/// independent choices, so all cross-combinations are valid. -/// -/// Signature | Hash | Curve -/// -----------+---------+----------- -/// ECDSA | SHA-256 | P-256 -/// ECDSA | SHA-256 | P-384 -/// ECDSA | SHA-384 | P-256 -/// ECDSA | SHA-384 | P-384 -const SUPPORTED_VERIFY_SCHEMES: &[(SignatureAlgorithm, HashAlgorithm, NamedGroup)] = &[ - (SignatureAlgorithm::ECDSA, HashAlgorithm::SHA256, NamedGroup::Secp256r1), - (SignatureAlgorithm::ECDSA, HashAlgorithm::SHA256, NamedGroup::Secp384r1), - (SignatureAlgorithm::ECDSA, HashAlgorithm::SHA384, NamedGroup::Secp256r1), - (SignatureAlgorithm::ECDSA, HashAlgorithm::SHA384, NamedGroup::Secp384r1), -]; - -/// Check that a (signature, hash, curve) combination is in the allow-list. -pub fn check_verify_scheme( - sig_alg: SignatureAlgorithm, - hash_alg: HashAlgorithm, - group: NamedGroup, -) -> Result<(), CryptoError> { - if SUPPORTED_VERIFY_SCHEMES - .iter() - .any(|(s, h, g)| *s == sig_alg && *h == hash_alg && *g == group) - { - Ok(()) - } else { - Err(CryptoError::UnsupportedSignatureVerification { - signature: sig_alg, - hash: hash_alg, - group, - }) - } -} - -/// Private key parser (factory for SigningKey). -pub trait KeyProvider: CryptoSafe { - /// Parse and load a private key from DER/PEM bytes. - fn load_private_key(&self, key_der: &[u8]) -> Result, CryptoError>; -} - -/// Secure random number generator. -pub trait SecureRandom: CryptoSafe { - /// Fill buffer with cryptographically secure random bytes. - fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError>; -} - -/// Hash provider (factory for HashContext). -pub trait HashProvider: CryptoSafe { - /// Create a new hash context for the specified algorithm. - fn create_hash(&self, algorithm: HashAlgorithm) -> Box; -} - -/// HMAC provider for computing HMAC signatures. -pub trait HmacProvider: CryptoSafe { - /// Compute HMAC-SHA256(key, data) and return the result. - fn hmac_sha256(&self, key: &[u8], data: &[u8]) -> Result<[u8; 32], CryptoError> { - let mut out = [0u8; 32]; - self.hmac(HashAlgorithm::SHA256, key, data, &mut out)?; - Ok(out) - } - - /// Compute HMAC for the given hash algorithm, writing the result to `out`. - /// - /// Returns the number of bytes written. - fn hmac(&self, hash: HashAlgorithm, key: &[u8], data: &[u8], out: &mut [u8]) -> Result; -} - -// ============================================================================ -// Core Provider Struct -// ============================================================================ - -/// Cryptographic provider for DTLS operations. -/// -/// This struct holds references to all cryptographic components needed -/// for DTLS. Users can provide custom implementations of each component -/// to replace the default rind-based provider. -/// -/// # Components -/// -/// PRF key derivation is built generically on top of `hmac_provider` - see the -/// [`prf_hkdf`](super::prf_hkdf) module. -/// -/// # Design -/// -/// The provider uses static trait object references (`&'static dyn Trait`) which -/// provides zero runtime overhead for trait dispatch. This design is inspired by -/// rustls's CryptoProvider and ensures efficient crypto operations. -/// -/// # Example -/// -/// ```ignore -/// # #[cfg(all())] -/// # fn main() { -/// use crate::vendor::dimpl::crypto::{CryptoProvider, rind}; -/// -/// // Use the default provider -/// let provider = rind::default_provider().unwrap(); -/// -/// // Or build a custom one (using defaults for demonstration) -/// let custom_provider = CryptoProvider { -/// // Shared components -/// kx_groups: provider.kx_groups, -/// signature_verification: provider.signature_verification, -/// key_provider: provider.key_provider, -/// secure_random: provider.secure_random, -/// hash_provider: provider.hash_provider, -/// hmac_provider: provider.hmac_provider, -/// // DTLS 1.2 components -/// cipher_suites: provider.cipher_suites, -/// }; -/// # } -/// # #[cfg(not(all()))] -/// # fn main() {} -/// ``` -#[derive(Debug, Clone)] -pub struct CryptoProvider { - // ========================================================================= - // Shared components - // ========================================================================= - /// Supported key exchange groups (P-256, P-384, X25519). - /// - /// Used for ECDHE key exchange. - pub kx_groups: &'static [&'static dyn SupportedKxGroup], - - /// Signature verification for certificates. - pub signature_verification: &'static dyn SignatureVerifier, - - /// Key provider for parsing private keys. - pub key_provider: &'static dyn KeyProvider, - - /// Secure random number generator. - pub secure_random: &'static dyn SecureRandom, - - /// Hash provider for handshake hashing. - pub hash_provider: &'static dyn HashProvider, - - /// HMAC provider for computing HMAC signatures. - pub hmac_provider: &'static dyn HmacProvider, - - // ========================================================================= - // DTLS 1.2 specific components - // ========================================================================= - /// Supported DTLS 1.2 cipher suites (for negotiation). - /// - /// These cipher suites bundle key exchange, authentication, encryption, - /// and MAC algorithms together (e.g., TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). - pub cipher_suites: &'static [&'static dyn SupportedDtls12CipherSuite], -} - -/// Static storage for the default crypto provider. -/// -/// This is set by `install_default()` and retrieved by `get_default()`. -static DEFAULT: OnceLock = OnceLock::new(); - -impl CryptoProvider { - /// Install a default crypto provider for the process. - /// - /// This sets a global default provider that will be used by - /// [`Config::builder()`](crate::vendor::dimpl::Config::builder) - /// when no explicit provider is specified. This is useful for applications that want - /// to override the default provider per process. - /// - /// # Panics - /// - /// Panics if called more than once. The default provider can only be set once per process. - /// - /// # Example - /// - /// ```ignore - /// # #[cfg(all())] - /// # fn main() { - /// use crate::vendor::dimpl::crypto::{CryptoProvider, rind}; - /// - /// // Install a default provider (can only be called once per process) - /// CryptoProvider::install_default(rind::default_provider().unwrap()); - /// # } - /// # #[cfg(not(all()))] - /// # fn main() {} - /// ``` - pub fn install_default(provider: CryptoProvider) { - DEFAULT - .set(provider) - .expect("CryptoProvider::install_default() called more than once"); - } - - /// Get the default crypto provider, if one has been installed. - /// - /// Returns `Some(&provider)` if a default provider has been installed via - /// [`Self::install_default()`], or `None` if no default provider is available. - /// - /// This method does not panic. Use [`Config::builder()`](crate::vendor::dimpl::Config::builder) which will handle - /// the fallback logic automatically. - /// - /// # Example - /// - /// ```ignore - /// use crate::vendor::dimpl::crypto::CryptoProvider; - /// - /// if let Some(provider) = CryptoProvider::get_default() { - /// // Use the installed default provider - /// } - /// ``` - pub fn get_default() -> Option<&'static CryptoProvider> { - DEFAULT.get() - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/digest.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/digest.rs deleted file mode 100644 index c0108529e11..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/digest.rs +++ /dev/null @@ -1,74 +0,0 @@ -use std::fmt; - -use crate::vendor::dimpl::crypto::{Buf, HashAlgorithm, HashProvider, HmacProvider, SecureRandom}; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; -use rind::{digest, hmac}; - -#[derive(Debug)] -pub(crate) struct Hasher; - -pub(crate) static HASH: Hasher = Hasher; - -impl HashProvider for Hasher { - fn create_hash(&self, algorithm: HashAlgorithm) -> Box { - // dimpl only asks for the hash of a suite this provider offers. - let algorithm = match algorithm { - HashAlgorithm::SHA256 => &digest::SHA256, - HashAlgorithm::SHA384 => &digest::SHA384, - _ => panic!("no suite uses {algorithm:?}"), - }; - Box::new(Running(digest::Context::new(algorithm))) - } -} - -struct Running(digest::Context); - -impl fmt::Debug for Running { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Running").finish_non_exhaustive() - } -} - -impl crate::vendor::dimpl::crypto::HashContext for Running { - fn update(&mut self, data: &[u8]) { - self.0.update(data); - } - - fn clone_and_finalize(&self, out: &mut Buf) { - let digest = self.0.clone().finish(); - out.clear(); - out.extend_from_slice(digest.as_ref()); - } -} - -#[derive(Debug)] -pub(crate) struct Mac; - -pub(crate) static HMAC: Mac = Mac; - -impl HmacProvider for Mac { - fn hmac(&self, hash: HashAlgorithm, key: &[u8], data: &[u8], out: &mut [u8]) -> Result { - let algorithm = match hash { - HashAlgorithm::SHA256 => &hmac::HMAC_SHA256, - HashAlgorithm::SHA384 => &hmac::HMAC_SHA384, - _ => return Err(CryptoError::UnsupportedHmacHash(hash)), - }; - let tag = hmac::sign(&hmac::Key::new(algorithm, key), data); - let tag = tag.as_ref(); - out.get_mut(..tag.len()) - .ok_or(CryptoError::OperationFailed(CryptoOperation::ComputeHmac))? - .copy_from_slice(tag); - Ok(tag.len()) - } -} - -#[derive(Debug)] -pub(crate) struct Random; - -pub(crate) static RANDOM: Random = Random; - -impl SecureRandom for Random { - fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> { - rind::rand::fill(buf).map_err(|_| CryptoError::OperationFailed(CryptoOperation::FillRandom)) - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs deleted file mode 100644 index 0f0f1966100..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/kx.rs +++ /dev/null @@ -1,81 +0,0 @@ -use std::fmt; - -use crate::vendor::dimpl::crypto::{ActiveKeyExchange, Buf, NamedGroup, SupportedKxGroup}; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; -use rind::agreement::{self, PrivateKey}; - -#[derive(Debug)] -struct Group { - name: NamedGroup, - algorithm: &'static agreement::Algorithm, -} - -/// Key exchange groups, in order of preference. -pub(crate) static ALL: &[&dyn SupportedKxGroup] = &[ - &Group { - name: NamedGroup::X25519, - algorithm: &agreement::X25519, - }, - &Group { - name: NamedGroup::Secp256r1, - algorithm: &agreement::ECDH_P256, - }, - &Group { - name: NamedGroup::Secp384r1, - algorithm: &agreement::ECDH_P384, - }, -]; - -impl SupportedKxGroup for Group { - fn name(&self) -> NamedGroup { - self.name - } - - fn start_exchange(&self, mut pub_key: Buf) -> Result, CryptoError> { - let key = PrivateKey::generate(self.algorithm) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::GenerateEphemeralKey))?; - pub_key.clear(); - pub_key.extend_from_slice(key.public_key().as_ref()); - Ok(Box::new(Exchange { - group: self.name, - key, - pub_key, - })) - } -} - -struct Exchange { - group: NamedGroup, - key: PrivateKey, - pub_key: Buf, -} - -impl fmt::Debug for Exchange { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Exchange") - .field("group", &self.group()) - .finish_non_exhaustive() - } -} - -impl ActiveKeyExchange for Exchange { - fn pub_key(&self) -> &[u8] { - &self.pub_key - } - - fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> { - // Covers a malformed or off-curve point, and X25519's all-zero output - // from a low-order point (RFC 7748 section 6.1). - let secret = self - .key - .agree(peer_pub) - .map_err(|_| CryptoError::InvalidPublicKey(self.group))?; - out.clear(); - out.extend_from_slice(secret.as_ref()); - Ok(()) - } - - fn group(&self) -> NamedGroup { - self.group - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs deleted file mode 100644 index f1c66f7400d..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! rind's cryptographic provider for dimpl. -//! -//! Ported from kixel-ai/rind's `rind-dimpl` 0.1.12, trimmed to DTLS 1.2, with -//! dimpl's PSK AES-128-CCM-8 suite kept from the provider it replaces. - -mod digest; -mod kx; -mod sign; -mod suite; - -use super::CryptoProvider; - -#[cfg(test)] -pub(crate) use digest::HMAC; - -/// Returns a dimpl [`CryptoProvider`] backed by rind, or the CPU feature rind -/// requires that this CPU lacks. -/// -/// It negotiates DTLS 1.2 ECDHE-ECDSA with AES-128-GCM, AES-256-GCM, and -/// ChaCha20-Poly1305 over X25519, P-256, and P-384, plus PSK with -/// AES-128-CCM-8, and signs with ECDSA P-256 or P-384 keys in PKCS#8 or SEC1 -/// DER. It prefers ChaCha20-Poly1305 where rind runs AES without CPU -/// instructions. -pub fn default_provider() -> Result { - rind::cpu::check()?; - let cipher_suites = if rind::cpu::has_aes_hardware() { - suite::DTLS12 - } else { - suite::DTLS12_CHACHA20_FIRST - }; - Ok(CryptoProvider { - kx_groups: kx::ALL, - signature_verification: &sign::VERIFIER, - key_provider: &sign::KEYS, - secure_random: &digest::RANDOM, - hash_provider: &digest::HASH, - hmac_provider: &digest::HMAC, - cipher_suites, - }) -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/sign.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/sign.rs deleted file mode 100644 index 3d3b28b420f..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/sign.rs +++ /dev/null @@ -1,162 +0,0 @@ -use std::fmt; - -use crate::vendor::dimpl::crypto::{ - Buf, HashAlgorithm, KeyProvider, NamedGroup, OID_P256, OID_P384, SignatureAlgorithm, SignatureVerifier, SigningKey, - check_verify_scheme, -}; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; -use rind::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, PublicKey, VerificationAlgorithm, sign, verify}; -use x509_cert::Certificate; -use x509_cert::der::Decode; -use x509_cert::spki::ObjectIdentifier; - -const ID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); - -/// Each curve, and the one hash its key signs with. -/// -/// A key is bound to its hash when loaded, so each curve signs with its own -/// hash only. -const CURVES: [(NamedGroup, HashAlgorithm, &EcdsaSigningAlgorithm); 2] = [ - ( - NamedGroup::Secp256r1, - HashAlgorithm::SHA256, - &sign::ECDSA_P256_SHA256_ASN1, - ), - ( - NamedGroup::Secp384r1, - HashAlgorithm::SHA384, - &sign::ECDSA_P384_SHA384_ASN1, - ), -]; - -#[derive(Debug)] -pub(crate) struct Keys; - -pub(crate) static KEYS: Keys = Keys; - -impl KeyProvider for Keys { - fn load_private_key(&self, der: &[u8]) -> Result, CryptoError> { - type Load = fn(&'static EcdsaSigningAlgorithm, &[u8]) -> Result; - let load = |load: Load| { - CURVES.into_iter().find_map(|(group, hash, algorithm)| { - let key = load(algorithm, der).ok()?; - Some(Box::new(Key { key, group, hash }) as Box) - }) - }; - load(EcdsaKeyPair::from_pkcs8) - .or_else(|| load(EcdsaKeyPair::from_sec1)) - .ok_or(CryptoError::InvalidPrivateKey) - } -} - -struct Key { - key: EcdsaKeyPair, - group: NamedGroup, - hash: HashAlgorithm, -} - -impl fmt::Debug for Key { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Key") - .field("group", &self.group) - .field("hash", &self.hash) - .finish_non_exhaustive() - } -} - -impl SigningKey for Key { - fn sign(&mut self, data: &[u8], hash: HashAlgorithm, out: &mut Buf) -> Result<(), CryptoError> { - if hash != self.hash { - return Err(CryptoError::SigningKeyHashMismatch { - key_hash: self.hash, - requested: hash, - }); - } - let signature = self - .key - .sign(data) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?; - out.clear(); - out.extend_from_slice(signature.as_ref()); - Ok(()) - } - - fn algorithm(&self) -> SignatureAlgorithm { - SignatureAlgorithm::ECDSA - } - - fn hash_algorithm(&self) -> HashAlgorithm { - self.hash - } - - fn supported_hash_algorithms(&self) -> &[HashAlgorithm] { - core::slice::from_ref(&self.hash) - } -} - -#[derive(Debug)] -pub(crate) struct Verifier; - -pub(crate) static VERIFIER: Verifier = Verifier; - -impl SignatureVerifier for Verifier { - fn verify_signature( - &self, - cert_der: &[u8], - data: &[u8], - signature: &[u8], - hash: HashAlgorithm, - algorithm: SignatureAlgorithm, - ) -> Result<(), CryptoError> { - if algorithm != SignatureAlgorithm::ECDSA { - return Err(CryptoError::UnsupportedSignatureAlgorithm(algorithm)); - } - - let cert = Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?; - let spki = cert.tbs_certificate().subject_public_key_info(); - if spki.algorithm.oid != ID_EC_PUBLIC_KEY { - return Err(CryptoError::UnsupportedPublicKeyAlgorithm); - } - let curve: ObjectIdentifier = spki - .algorithm - .parameters - .as_ref() - .ok_or(CryptoError::MissingEcCurveParameter)? - .decode_as() - .map_err(|_| CryptoError::InvalidEcCurveParameter)?; - let group = match curve { - OID_P256 => NamedGroup::Secp256r1, - OID_P384 => NamedGroup::Secp384r1, - _ => return Err(CryptoError::UnsupportedEcCurve), - }; - check_verify_scheme(algorithm, hash, group)?; - - // DTLS 1.2 may pair either curve with either hash. - let verification: &'static VerificationAlgorithm = match (group, hash) { - (NamedGroup::Secp256r1, HashAlgorithm::SHA256) => &verify::ECDSA_P256_SHA256_ASN1, - (NamedGroup::Secp256r1, HashAlgorithm::SHA384) => &verify::ECDSA_P256_SHA384_ASN1, - (NamedGroup::Secp384r1, HashAlgorithm::SHA256) => &verify::ECDSA_P384_SHA256_ASN1, - (NamedGroup::Secp384r1, HashAlgorithm::SHA384) => &verify::ECDSA_P384_SHA384_ASN1, - _ => { - return Err(CryptoError::UnsupportedSignatureVerification { - signature: algorithm, - hash, - group, - }); - } - }; - - let point = spki - .subject_public_key - .as_bytes() - .ok_or(CryptoError::InvalidSubjectPublicKey)?; - PublicKey::new(verification, point) - .map_err(|_| CryptoError::InvalidPublicKey(group))? - .verify(data, signature) - .map_err(|_| CryptoError::SignatureVerificationFailed { - signature: algorithm, - hash, - group, - }) - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/suite.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/suite.rs deleted file mode 100644 index bab10398a1f..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/rind/suite.rs +++ /dev/null @@ -1,183 +0,0 @@ -use std::fmt; - -use crate::vendor::dimpl::crypto::{ - Aad, Buf, Cipher, Dtls12CipherSuite, HashAlgorithm, Nonce, SupportedDtls12CipherSuite, TmpBuf, -}; -use crate::vendor::dimpl::{CryptoError, CryptoOperation}; -use rind::aead; - -const TAG_LEN: usize = 16; - -/// The AEAD behind a suite. -#[derive(Debug, Clone, Copy)] -enum Algorithm { - Aes128Gcm, - Aes256Gcm, - ChaCha20Poly1305, -} - -impl Algorithm { - fn aead(self) -> &'static aead::Algorithm { - match self { - Self::Aes128Gcm => &aead::AES_128_GCM, - Self::Aes256Gcm => &aead::AES_256_GCM, - Self::ChaCha20Poly1305 => &aead::CHACHA20_POLY1305, - } - } - - fn cipher(self, key: &[u8]) -> Result, CryptoError> { - let actual = key.len().min(u16::MAX as usize) as u16; - let key = aead::Key::new(self.aead(), key).map_err(|_| match self { - Self::Aes128Gcm | Self::Aes256Gcm => CryptoError::InvalidAesGcmKeySize { actual }, - Self::ChaCha20Poly1305 => CryptoError::InvalidChacha20Poly1305KeySize { actual }, - })?; - Ok(Box::new(Aead(key))) - } -} - -struct Aead(aead::Key); - -impl fmt::Debug for Aead { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("Aead") - } -} - -impl Cipher for Aead { - fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - self.0 - .seal_in_place_append_tag(aead::Nonce::assume_unique_for_key(nonce.0), &aad, plaintext) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt)) - } - - fn decrypt(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - let len = ciphertext.len(); - let Some(plaintext_len) = len.checked_sub(TAG_LEN) else { - return Err(CryptoError::CiphertextTooShort { - minimum: TAG_LEN as u8, - actual: len as u8, - }); - }; - - self.0 - .open_in_place(aead::Nonce::assume_unique_for_key(nonce.0), &aad, ciphertext.as_mut()) - .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; - - ciphertext.truncate(plaintext_len); - Ok(()) - } -} - -#[derive(Debug)] -struct Dtls12 { - suite: Dtls12CipherSuite, - hash: HashAlgorithm, - algorithm: Algorithm, -} - -impl SupportedDtls12CipherSuite for Dtls12 { - fn suite(&self) -> Dtls12CipherSuite { - self.suite - } - - fn hash_algorithm(&self) -> HashAlgorithm { - self.hash - } - - fn key_lengths(&self) -> (usize, usize, usize) { - // (MAC key, encryption key, fixed IV): RFC 5288 and RFC 7905. - let fixed_iv_len = match self.algorithm { - Algorithm::Aes128Gcm | Algorithm::Aes256Gcm => 4, - Algorithm::ChaCha20Poly1305 => 12, - }; - (0, self.algorithm.aead().key_len(), fixed_iv_len) - } - - fn explicit_nonce_len(&self) -> usize { - match self.algorithm { - Algorithm::Aes128Gcm | Algorithm::Aes256Gcm => 8, - Algorithm::ChaCha20Poly1305 => 0, - } - } - - fn tag_len(&self) -> usize { - TAG_LEN - } - - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { - self.algorithm.cipher(key) - } -} - -/// TLS_PSK_WITH_AES_128_CCM_8, on dimpl's own AES-CCM. -#[derive(Debug)] -struct PskAes128Ccm8; - -impl SupportedDtls12CipherSuite for PskAes128Ccm8 { - fn suite(&self) -> Dtls12CipherSuite { - Dtls12CipherSuite::PSK_AES128_CCM_8 - } - - fn hash_algorithm(&self) -> HashAlgorithm { - HashAlgorithm::SHA256 - } - - fn key_lengths(&self) -> (usize, usize, usize) { - (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) - } - - fn explicit_nonce_len(&self) -> usize { - 8 - } - - fn tag_len(&self) -> usize { - 8 - } - - fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { - Ok(Box::new(crate::vendor::dimpl::crypto::ccm_cipher::AesCcm8Cipher::new( - key, - )?)) - } -} - -const AES_128_GCM: &dyn SupportedDtls12CipherSuite = &Dtls12 { - suite: Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, - hash: HashAlgorithm::SHA256, - algorithm: Algorithm::Aes128Gcm, -}; -const AES_256_GCM: &dyn SupportedDtls12CipherSuite = &Dtls12 { - suite: Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384, - hash: HashAlgorithm::SHA384, - algorithm: Algorithm::Aes256Gcm, -}; -const CHACHA20_POLY1305: &dyn SupportedDtls12CipherSuite = &Dtls12 { - suite: Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, - hash: HashAlgorithm::SHA256, - algorithm: Algorithm::ChaCha20Poly1305, -}; -const PSK_AES_128_CCM_8: &dyn SupportedDtls12CipherSuite = &PskAes128Ccm8; - -/// DTLS 1.2 suites, in order of preference where rind runs AES on CPU instructions. -pub(super) static DTLS12: &[&dyn SupportedDtls12CipherSuite] = - &[AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, PSK_AES_128_CCM_8]; - -/// [`DTLS12`] with ChaCha20-Poly1305 first, which outruns AES without AES -/// instructions. -pub(super) static DTLS12_CHACHA20_FIRST: &[&dyn SupportedDtls12CipherSuite] = - &[CHACHA20_POLY1305, AES_128_GCM, AES_256_GCM, PSK_AES_128_CCM_8]; - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn chacha20_poly1305_key_len_validation() { - // incorrect length (should be 32) - let result = Algorithm::ChaCha20Poly1305.cipher(&[0, 1, 2, 3, 4, 5]); - assert_eq!( - CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 }, - result.unwrap_err() - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs deleted file mode 100644 index 6e0c14f48e5..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/mod.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! Validation and filtering for crypto providers. -//! -//! This module defines the validation rules for crypto providers used with dimpl, -//! based on the documented support in lib.rs. - -use arrayvec::ArrayVec; - -use super::{Aad, CryptoProvider, Nonce, SupportedDtls12CipherSuite, SupportedKxGroup}; -use crate::vendor::dimpl::buffer::{Buf, TmpBuf}; -use crate::vendor::dimpl::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm}; -use crate::vendor::dimpl::{ConfigError, CryptoProviderValidationError, Error}; - -fn provider_error(error: CryptoProviderValidationError) -> Error { - Error::ConfigError(ConfigError::CryptoProvider(error)) -} - -impl CryptoProvider { - /// Returns an iterator over validated cipher suites supported by dimpl. - /// - /// Only cipher suites documented in lib.rs are returned: - /// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` - /// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` - /// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` - pub fn supported_cipher_suites(&self) -> impl Iterator { - self.cipher_suites - .iter() - .copied() - .filter(|cs| cs.suite().is_supported()) - } - - /// Returns an iterator over validated key exchange groups supported by dimpl. - /// - /// Only key exchange groups documented in lib.rs are returned: - /// - X25519 - /// - P-256 (secp256r1) - /// - P-384 (secp384r1) - pub fn supported_kx_groups(&self) -> impl Iterator { - self.kx_groups.iter().copied().filter(|kx| { - matches!( - kx.name(), - NamedGroup::X25519 | NamedGroup::Secp256r1 | NamedGroup::Secp384r1 - ) - }) - } - - /// - /// Combines provider filtering with signature algorithm compatibility. - pub fn supported_cipher_suites_for_signature_algorithm( - &self, - sig_alg: SignatureAlgorithm, - ) -> impl Iterator { - self.supported_cipher_suites() - .filter(move |cs| cs.suite().signature_algorithm() == Some(sig_alg)) - } - - /// Check if provider supports ECDH-based cipher suites. - /// - /// Returns true if any supported cipher suite uses ECDH key exchange. - pub fn has_ecdh(&self) -> bool { - self.supported_cipher_suites().any(|cs| cs.suite().has_ecc()) - } - - /// Validates the provider configuration for use with dimpl. - /// - /// This ensures the provider meets dimpl's requirements: - /// - At least one supported cipher suite - /// - ECDH cipher suites have matching key exchange groups - /// - Hash providers support required algorithms - /// - HMAC provider supports required operations - /// - /// Returns `Error::ConfigError` if validation fails. - pub fn validate(&self) -> Result<(), Error> { - self.validate_cipher_suites()?; - self.validate_kx_groups()?; - let validated_hashes = self.validate_hash_providers()?; - self.validate_prf(&validated_hashes)?; - self.validate_signature_verifier(&validated_hashes)?; - self.validate_hmac_provider()?; - self.validate_kx_exchange()?; - Ok(()) - } - - /// Validate that at least one cipher suite is supported. - fn validate_cipher_suites(&self) -> Result<(), Error> { - let cipher_count = self.supported_cipher_suites().count(); - if cipher_count == 0 { - return Err(provider_error(CryptoProviderValidationError::NoCipherSuites)); - } - Ok(()) - } - - /// Validate that ECDH cipher suites have matching key exchange groups. - fn validate_kx_groups(&self) -> Result<(), Error> { - if self.has_ecdh() { - let kx_count = self.supported_kx_groups().count(); - if kx_count == 0 { - return Err(provider_error( - CryptoProviderValidationError::EcdhCipherSuitesWithoutKeyExchangeGroups, - )); - } - } - Ok(()) - } - - /// Validate that hash providers support required algorithms. - /// Returns the list of validated hash algorithms. - fn validate_hash_providers(&self) -> Result, Error> { - // Collect unique hash algorithms from supported cipher suites - let required_hashes: Vec = self - .cipher_suites - .iter() - .map(|cs| cs.suite().hash_algorithm()) - .collect(); - - // Test each required hash algorithm with known test vectors - for hash_alg in &required_hashes { - let mut hasher = self.hash_provider.create_hash(*hash_alg); - - // Test with empty input - use known hash values - hasher.update(&[]); - let mut result = Buf::new(); - hasher.clone_and_finalize(&mut result); - - let maybe_expected = HASH_TEST_VECTORS.iter().find(|(h, _)| *h == *hash_alg).map(|(_, v)| v); - - let Some(expected) = maybe_expected else { - return Err(provider_error(CryptoProviderValidationError::MissingHashTestVector( - *hash_alg, - ))); - }; - - if result.as_ref() != *expected { - return Err(provider_error(CryptoProviderValidationError::HashProviderIncorrect( - *hash_alg, - ))); - } - } - - Ok(required_hashes) - } - - /// Validate that PRF (via HMAC) works for every supported hash algorithm. - fn validate_prf(&self, validated_hashes: &[HashAlgorithm]) -> Result<(), Error> { - let secret = b"test_secret"; - let label = "test label"; - let seed = b"test_seed"; - let output_len = 32; - - for &hash_alg in validated_hashes { - let mut result = Buf::new(); - let mut scratch = Buf::new(); - super::prf_hkdf::prf_tls12( - self.hmac_provider, - secret, - label, - seed, - &mut result, - output_len, - &mut scratch, - hash_alg, - ) - .map_err(|e| { - provider_error(CryptoProviderValidationError::PrfFailed { - hash: hash_alg, - source: e, - }) - })?; - - let maybe_expected = PRF_TEST_VECTORS.iter().find(|(h, _)| *h == hash_alg).map(|(_, v)| v); - - let Some(expected) = maybe_expected else { - return Err(provider_error(CryptoProviderValidationError::MissingPrfTestVector( - hash_alg, - ))); - }; - - if result.as_ref() != *expected { - return Err(provider_error(CryptoProviderValidationError::PrfIncorrect(hash_alg))); - } - } - - Ok(()) - } - - /// Validate that signature verifier works for every supported cipher suite. - fn validate_signature_verifier(&self, _validated_hashes: &[HashAlgorithm]) -> Result<(), Error> { - // Test signature verification for each supported cipher suite - for cs in self.supported_cipher_suites() { - let hash_alg = cs.suite().hash_algorithm(); - let sig_alg = match cs.suite().signature_algorithm() { - Some(alg) => alg, - // PSK suites have no signature - skip validation - None => continue, - }; - - let (cert_der, signature, test_data) = match (hash_alg, sig_alg) { - (HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA) => { - (VALIDATION_P256_CERT, VALIDATION_P256_SHA256_SIG, VALIDATION_TEST_DATA) - } - (HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA) => { - (VALIDATION_P384_CERT, VALIDATION_P384_SHA384_SIG, VALIDATION_TEST_DATA) - } - _ => { - return Err(provider_error( - CryptoProviderValidationError::NoSignatureValidationVector { - hash: hash_alg, - signature: sig_alg, - }, - )); - } - }; - - // Verify the signature - self.signature_verification - .verify_signature(cert_der, test_data, signature, hash_alg, sig_alg) - .map_err(|e| { - provider_error(CryptoProviderValidationError::SignatureVerificationFailed { - hash: hash_alg, - signature: sig_alg, - source: e, - }) - })?; - } - - Ok(()) - } - - /// Validate key exchange round-trip for each supported group. - fn validate_kx_exchange(&self) -> Result<(), Error> { - for kx in self.supported_kx_groups() { - let group = kx.name(); - - let alice = kx.start_exchange(Buf::new()).map_err(|e| { - provider_error(CryptoProviderValidationError::KeyExchangeStartFailed { group, source: e }) - })?; - let bob = kx.start_exchange(Buf::new()).map_err(|e| { - provider_error(CryptoProviderValidationError::KeyExchangeStartFailed { group, source: e }) - })?; - - let alice_pub = alice.pub_key().to_vec(); - let bob_pub = bob.pub_key().to_vec(); - - let mut alice_secret = Buf::new(); - alice.complete(&bob_pub, &mut alice_secret).map_err(|e| { - provider_error(CryptoProviderValidationError::KeyExchangeCompleteFailed { group, source: e }) - })?; - - let mut bob_secret = Buf::new(); - bob.complete(&alice_pub, &mut bob_secret).map_err(|e| { - provider_error(CryptoProviderValidationError::KeyExchangeCompleteFailed { group, source: e }) - })?; - - if alice_secret.as_ref() != bob_secret.as_ref() { - return Err(provider_error( - CryptoProviderValidationError::KeyExchangeMismatchedSharedSecret(group), - )); - } - } - Ok(()) - } - - /// Validate that HMAC provider supports required operations. - /// - /// We require HMAC-SHA256 for DTLS cookie computation. - fn validate_hmac_provider(&self) -> Result<(), Error> { - // Test HMAC-SHA256 with known test vector (RFC 2104 test case) - // HMAC-SHA256(key="key", data="The quick brown fox jumps over the lazy dog") - let key = b"key"; - let data = b"The quick brown fox jumps over the lazy dog"; - - let result = self - .hmac_provider - .hmac_sha256(key, data) - .map_err(|e| provider_error(CryptoProviderValidationError::HmacFailed(e)))?; - - // Verify against known HMAC-SHA256 test vector - if result.as_slice() != HMAC_SHA256_TEST_VECTOR { - return Err(provider_error(CryptoProviderValidationError::HmacIncorrect)); - } - - Ok(()) - } -} - -const HASH_TEST_VECTORS: &[(HashAlgorithm, &[u8])] = &[ - ( - HashAlgorithm::SHA256, - &[ - 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, - 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, - ], - ), - ( - HashAlgorithm::SHA384, - &[ - 0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, 0x21, 0xfd, - 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, - 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b, - ], - ), -]; - -// Test vectors for TLS 1.2 PRF -// Generated using: PRF(secret="test_secret", label="test label", seed="test_seed", output_len=32) -const PRF_TEST_VECTORS: &[(HashAlgorithm, &[u8])] = &[ - ( - HashAlgorithm::SHA256, - &[ - 0xc7, 0x49, 0xce, 0xdf, 0xad, 0xaf, 0x3d, 0xf1, 0x18, 0x2c, 0xa2, 0x25, 0xab, 0xe9, 0x4e, 0x0c, 0x19, 0xc3, - 0x81, 0x49, 0x57, 0xbd, 0xdc, 0x28, 0x55, 0x78, 0x73, 0xdb, 0xb7, 0x9f, 0xce, 0x29, - ], - ), - ( - HashAlgorithm::SHA384, - &[ - 0x74, 0x9a, 0xf3, 0x03, 0x23, 0x9e, 0x3f, 0x65, 0x4e, 0x9a, 0xd1, 0xb1, 0xd1, 0x22, 0x31, 0x02, 0x1a, 0xd2, - 0x17, 0x26, 0x04, 0x75, 0x21, 0xf4, 0x66, 0xad, 0xcd, 0x37, 0x2b, 0xe4, 0x7e, 0x8b, - ], - ), -]; - -// Test vector for HMAC-SHA256 -// HMAC-SHA256(key="key", data="The quick brown fox jumps over the lazy dog") -// Computed using standard HMAC-SHA256 implementation -const HMAC_SHA256_TEST_VECTOR: &[u8] = &[ - 0xf7, 0xbc, 0x83, 0xf4, 0x30, 0x53, 0x84, 0x24, 0xb1, 0x32, 0x98, 0xe6, 0xaa, 0x6f, 0xb1, 0x43, 0xef, 0x4d, 0x59, - 0xa1, 0x49, 0x46, 0x17, 0x59, 0x97, 0x47, 0x9d, 0xbc, 0x2d, 0x1a, 0x3c, 0xd8, -]; - -// Test certificates and signatures for signature verification validation -const VALIDATION_TEST_DATA: &[u8] = include_bytes!("test_data.bin"); -const VALIDATION_P256_CERT: &[u8] = include_bytes!("p256_cert.der"); -const VALIDATION_P256_SHA256_SIG: &[u8] = include_bytes!("p256_sha256_sig.der"); -const VALIDATION_P384_CERT: &[u8] = include_bytes!("p384_cert.der"); -const VALIDATION_P384_SHA384_SIG: &[u8] = include_bytes!("p384_sha384_sig.der"); - -#[cfg(test)] -mod tests_rind { - use super::*; - use crate::vendor::dimpl::crypto::rind; - use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; - - #[test] - fn test_default_provider_validates() { - let provider = rind::default_provider().unwrap(); - assert!(provider.validate().is_ok()); - } - - #[test] - fn test_default_provider_has_cipher_suites() { - let provider = rind::default_provider().unwrap(); - let count = provider.supported_cipher_suites().count(); - // ECDHE: AES-128, AES-256, ChaCha20 - // PSK: CCM-8 - assert_eq!(count, 4); - } - - #[test] - fn test_default_provider_has_kx_groups() { - let provider = rind::default_provider().unwrap(); - let count = provider.supported_kx_groups().count(); - assert_eq!(count, 3); // X25519, P-256, and P-384 - } - - #[test] - fn test_default_provider_has_ecdh() { - let provider = rind::default_provider().unwrap(); - assert!(provider.has_ecdh()); - } - - #[test] - fn test_supported_cipher_suites_for_signature_algorithm() { - let provider = rind::default_provider().unwrap(); - let ecdsa_suites: Vec<_> = provider - .supported_cipher_suites_for_signature_algorithm(SignatureAlgorithm::ECDSA) - .map(|cs| cs.suite()) - .collect(); - - assert_eq!(ecdsa_suites.len(), 3); - assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256)); - assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384)); - assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256)); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p256_cert.der b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p256_cert.der deleted file mode 100644 index 7d1eba5d663..00000000000 Binary files a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p256_cert.der and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p256_sha256_sig.der b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p256_sha256_sig.der deleted file mode 100644 index 269044c407d..00000000000 Binary files a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p256_sha256_sig.der and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p384_cert.der b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p384_cert.der deleted file mode 100644 index ca1be6a9a10..00000000000 Binary files a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p384_cert.der and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p384_sha384_sig.der b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p384_sha384_sig.der deleted file mode 100644 index fb455bda1bc..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/p384_sha384_sig.der +++ /dev/null @@ -1 +0,0 @@ -0d0uçhI¶»۳I‚Ôà)<ݽм�ò#¼ºšzu¹•Ö|™)¤ý ëh¦ÏÛØã^djÒE08{ Aõ™ôÙ Ñìíé½Ìíðì¹]²™e¦=î(HºzDl‚�¢«„J hó \ No newline at end of file diff --git a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/test_data.bin b/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/test_data.bin deleted file mode 100644 index b21064a44f3..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/crypto/validation/test_data.bin +++ /dev/null @@ -1 +0,0 @@ -test data for signature validation \ No newline at end of file diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/client.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/client.rs deleted file mode 100644 index 1eaf721b3d3..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/client.rs +++ /dev/null @@ -1,1339 +0,0 @@ -// DTLS Client Handshake Flow: -// -// 1. Client sends ClientHello -// 2. Server may respond with HelloVerifyRequest containing a cookie -// - If so, Client sends another ClientHello with the cookie -// 3. Server sends ServerHello, Certificate, ServerKeyExchange, -// CertificateRequest (optional), ServerHelloDone -// 4. Client sends Certificate (if requested), ClientKeyExchange, -// CertificateVerify (if client cert present), ChangeCipherSpec, Finished -// 5. Server sends ChangeCipherSpec, Finished -// 6. Handshake complete, application data can flow -// -// This implementation is a Sans-IO DTLS client. - -use std::collections::VecDeque; -use std::time::Instant; -use tracing::{debug, trace}; - -use arrayvec::ArrayVec; -use subtle::ConstantTimeEq; - -use crate::vendor::dimpl::buffer::{Buf, ToBuf}; -use crate::vendor::dimpl::crypto::SrtpProfile; -use crate::vendor::dimpl::dtls12::Server; -use crate::vendor::dimpl::dtls12::context::AuthMode; -use crate::vendor::dimpl::dtls12::engine::Engine; -use crate::vendor::dimpl::dtls12::message::{Body, CipherSuiteVec, ClientHello, ClientKeyExchange}; -use crate::vendor::dimpl::dtls12::message::{ClientPskKeys, ServerKeyExchangeParams}; -use crate::vendor::dimpl::dtls12::message::{CompressionMethod, ContentType, Cookie}; -use crate::vendor::dimpl::dtls12::message::{DigitallySigned, Dtls12CipherSuite}; -use crate::vendor::dimpl::dtls12::message::{ExtensionType, KeyExchangeAlgorithm, MessageType, ProtocolVersion}; -use crate::vendor::dimpl::dtls12::message::{Random, SessionId, SignatureAndHashAlgorithm}; -use crate::vendor::dimpl::timer::HandshakeTimers; -use crate::vendor::dimpl::{Config, DtlsCertificate, Error, InternalError, KeyingMaterial, Output}; - -/// DTLS client -pub struct Client { - /// Current client state. - state: State, - - /// Engine in common between server and client. - engine: Engine, - - /// Random unique data (with gmt timestamp). Used for signature checks. - random: Option, - - /// SessionId is set by the server and only sent by the client if we - /// are reusing a session (key renegotiation). - session_id: Option, - - /// Cookie is sent by the server in the optional HelloVerifyRequest. - /// It might remain null if there is no HelloVerifyRequest. - cookie: Option, - - /// Storage for extension data - extension_data: Buf, - - /// The negotiated SRTP profile (if any) - negotiated_srtp_profile: Option, - - /// Server random. Set by ServerHello. - server_random: Option, - - /// Server certificates - server_certificates: Vec, - - /// Buffer for defragmenting handshakes - defragment_buffer: Buf, - - /// Whether we requested a CertificateVerify - certificate_verify: bool, - - /// Captured session hash for Extended Master Secret (RFC 7627) - /// This is captured after ServerHelloDone to include the correct handshake messages - captured_session_hash: Option, - - /// The last now we seen - last_now: Instant, - - /// Local events - local_events: VecDeque, - - /// Data that is sent before we are connected. - queued_data: Vec, -} - -#[derive(Debug, PartialEq, Eq)] -pub(crate) enum LocalEvent { - PeerCert, - Connected, - KeyingMaterial(ArrayVec, SrtpProfile), -} - -impl Client { - pub(crate) fn new_with_engine(mut engine: Engine, now: Instant) -> Client { - engine.set_client(true); - let extension_data = engine.pop_buffer(); - let defragment_buffer = engine.pop_buffer(); - - Client { - state: State::SendClientHello, - engine, - random: None, - session_id: None, - cookie: None, - extension_data, - negotiated_srtp_profile: None, - server_random: None, - server_certificates: Vec::with_capacity(3), - defragment_buffer, - certificate_verify: false, - captured_session_hash: None, - last_now: now, - local_events: VecDeque::new(), - queued_data: Vec::new(), - } - } - - pub fn into_server(self) -> Server { - Server::new_with_engine(self.engine, self.last_now) - } - - pub(crate) fn state_name(&self) -> &'static str { - self.state.name() - } - - pub fn is_closing(&self) -> bool { - self.state == State::Closed && !self.is_closed() - } - - pub fn is_closed(&self) -> bool { - self.state == State::Closed && self.local_events.is_empty() && !self.engine.has_pending_close_output() - } - - pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { - match self.engine.parse_packet(packet).and_then(|_| { - let result = self.make_progress(); - self.engine.discard_undecryptable(); - result - }) { - Ok(()) => Ok(()), - Err(e) => e.into_public_error().map_or(Ok(()), Err), - } - } - - pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { - if self.state == State::SendClientHello { - return Output::Timeout(self.last_now); - } - if let Some(event) = self.local_events.pop_front() { - return event.into_output(buf, &self.server_certificates); - } - self.engine.poll_output(buf, self.last_now) - } - - /// Explicitly start the handshake process by sending a ClientHello - pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { - self.last_now = now; - if self.random.is_none() { - self.random = Some(Random::new_with_time(now, &mut self.engine.rng)); - } - self.engine.handle_timeout(now)?; - match self.make_progress() { - Ok(()) => Ok(()), - Err(e) => e.into_public_error().map_or(Ok(()), Err), - } - } - - /// Send application data when the client is in the Running state - /// - /// This should only be called when the client is in the Running state, - /// after the handshake is complete. - pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { - if self.state == State::Closed { - return Err(Error::ConnectionClosed); - } - - if self.state != State::AwaitApplicationData { - self.queued_data.push(data.to_buf()); - return Ok(()); - } - - // Use the engine's create_record to send application data - // The encryption is now handled in the engine - self.engine - .create_record(ContentType::ApplicationData, 1, false, |body| { - body.extend_from_slice(data); - })?; - - Ok(()) - } - - /// Initiate graceful shutdown by sending a `close_notify` alert. - pub fn close(&mut self) -> Result<(), Error> { - if self.state == State::Closed { - return Ok(()); - } - if self.state != State::AwaitApplicationData { - self.engine.abort(); - self.state = State::Closed; - return Ok(()); - } - self.engine.create_record(ContentType::Alert, 1, false, |body| { - body.push(1); // level: warning - body.push(0); // description: close_notify - })?; - self.state = State::Closed; - Ok(()) - } - - fn make_progress(&mut self) -> Result<(), InternalError> { - loop { - let prev_state = self.state; - - let new_state = prev_state.make_progress(self)?; - if prev_state != new_state { - self.state = new_state; - trace!("{:?} -> {:?}", prev_state, new_state); - } else { - break; - } - } - Ok(()) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum State { - SendClientHello, - AwaitHelloVerifyRequest, - AwaitServerHello, - AwaitCertificate, - AwaitServerKeyExchange, - AwaitCertificateRequest, - AwaitServerHelloDone, - SendCertificate, - SendClientKeyExchange, - SendCertificateVerify, - SendChangeCipherSpec, - SendFinished, - AwaitChangeCipherSpec, - AwaitNewSessionTicket, - AwaitFinished, - AwaitApplicationData, - Closed, -} - -impl State { - fn name(&self) -> &'static str { - match self { - State::SendClientHello => "SendClientHello", - State::AwaitHelloVerifyRequest => "AwaitHelloVerifyRequest", - State::AwaitServerHello => "AwaitServerHello", - State::AwaitCertificate => "AwaitCertificate", - State::AwaitServerKeyExchange => "AwaitServerKeyExchange", - State::AwaitCertificateRequest => "AwaitCertificateRequest", - State::AwaitServerHelloDone => "AwaitServerHelloDone", - State::SendCertificate => "SendCertificate", - State::SendClientKeyExchange => "SendClientKeyExchange", - State::SendCertificateVerify => "SendCertificateVerify", - State::SendChangeCipherSpec => "SendChangeCipherSpec", - State::SendFinished => "SendFinished", - State::AwaitChangeCipherSpec => "AwaitChangeCipherSpec", - State::AwaitNewSessionTicket => "AwaitNewSessionTicket", - State::AwaitFinished => "AwaitFinished", - State::AwaitApplicationData => "AwaitApplicationData", - State::Closed => "Closed", - } - } - - fn make_progress(self, client: &mut Client) -> Result { - match self { - State::SendClientHello => self.send_client_hello(client), - State::AwaitHelloVerifyRequest => self.await_hello_verify_request(client), - State::AwaitServerHello => self.await_server_hello(client), - State::AwaitCertificate => self.await_certificate(client), - State::AwaitServerKeyExchange => self.await_server_key_exchange(client), - State::AwaitCertificateRequest => self.await_certificate_request(client), - State::AwaitServerHelloDone => self.await_server_hello_done(client), - State::SendCertificate => self.send_certificate(client), - State::SendClientKeyExchange => self.send_client_key_exchange(client), - State::SendCertificateVerify => self.send_certificate_verify(client), - State::SendChangeCipherSpec => self.send_change_cipher_spec(client), - State::SendFinished => self.send_finished(client), - State::AwaitChangeCipherSpec => self.await_change_cipher_spec(client), - State::AwaitNewSessionTicket => self.await_new_session_ticket(client), - State::AwaitFinished => self.await_finished(client), - State::AwaitApplicationData => self.await_application_data(client), - State::Closed => Ok(self), - } - } - - fn send_client_hello(self, client: &mut Client) -> Result { - let session_id = client.session_id.unwrap_or_else(SessionId::empty); - let cookie = client.cookie.unwrap_or_else(Cookie::empty); - // unwrap: is ok because we set the random in handle_timeout - let random = client.random.unwrap(); - - // Determine flight number: 1 for initial CH, 3 for retransmit with cookie - let flight_no = if client.cookie.is_none() { 1 } else { 3 }; - client.engine.flight_begin(flight_no); - - client - .engine - .create_handshake(MessageType::ClientHello, |body, engine| { - handshake_create_client_hello(body, engine, cookie, random, session_id, &mut client.extension_data) - })?; - - let can_hello_verify = client.cookie.is_none(); - - if can_hello_verify { - Ok(Self::AwaitHelloVerifyRequest) - } else { - Ok(Self::AwaitServerHello) - } - } - - fn await_hello_verify_request(self, client: &mut Client) -> Result { - let has_hello = client.engine.has_complete_handshake(MessageType::ServerHello); - - // Got ServerHello, skip HelloVerifyRequest - if has_hello { - return Ok(Self::AwaitServerHello); - } - - let maybe = client - .engine - .next_handshake(MessageType::HelloVerifyRequest, &mut client.defragment_buffer)?; - - let Some(handshake) = maybe else { - // Stay in this state - return Ok(self); - }; - - let Body::HelloVerifyRequest(h) = handshake.body else { - unreachable!() - }; - - // RFC 6347 4.2.1: The server_version field in the HelloVerifyRequest message MUST be set to DTLS 1.0 - // https://datatracker.ietf.org/doc/html/rfc6347#section-4.2.1 - if h.server_version != ProtocolVersion::DTLS1_2 && h.server_version != ProtocolVersion::DTLS1_0 { - return Err(Error::SecurityError( - crate::vendor::dimpl::SecurityError::UnsupportedHelloVerifyRequestVersion(h.server_version), - ) - .into()); - } - - debug!("Received HelloVerifyRequest with cookie length: {}", h.cookie.len()); - - // Set cookie for next ClientHello - client.cookie = Some(h.cookie); - - // HelloVerifyRequest exchange must not be part of the handshake transcript. - // Per RFC 6347 §4.2.2, the next ClientHello (with cookie) has message_seq=1. - trace!("Resetting handshake state after HelloVerifyRequest"); - client.engine.reset_client_for_hello_verify_request(); - - // Redo ClientHello, now with cookie. - Ok(Self::SendClientHello) - } - - fn await_server_hello(self, client: &mut Client) -> Result { - let maybe = client - .engine - .next_handshake(MessageType::ServerHello, &mut client.defragment_buffer)?; - - let Some(handshake) = maybe else { - // Stay in same state - return Ok(self); - }; - - let Body::ServerHello(server_hello) = &handshake.body else { - unreachable!() - }; - - debug!( - "Received ServerHello with cipher suite: {:?}", - server_hello.cipher_suite - ); - - // Enforce DTLS version - if server_hello.server_version != ProtocolVersion::DTLS1_2 { - return Err( - Error::SecurityError(crate::vendor::dimpl::SecurityError::UnsupportedServerVersion( - server_hello.server_version, - )) - .into(), - ); - } - - // Enforce Null compression only - if server_hello.compression_method != CompressionMethod::Null { - return Err( - Error::SecurityError(crate::vendor::dimpl::SecurityError::UnsupportedServerCompression( - server_hello.compression_method, - )) - .into(), - ); - } - - // Enforce cipher suite is known and allowed - let cs = server_hello.cipher_suite; - if cs.is_unknown() { - return Err( - (Error::SecurityError(crate::vendor::dimpl::SecurityError::ServerSelectedUnknownCipherSuite)).into(), - ); - } - - // Enforce cipher suite is compatible with our private key and allowed by config - let is_compatible = client.engine.crypto_context().is_cipher_suite_compatible(cs); - - if !is_compatible { - return Err(Error::SecurityError( - crate::vendor::dimpl::SecurityError::ServerSelectedIncompatibleCipherSuite(cs), - ) - .into()); - } - - if !client.engine.is_cipher_suite_allowed(cs) { - return Err(Error::SecurityError( - crate::vendor::dimpl::SecurityError::ServerSelectedDisallowedCipherSuite(cs), - ) - .into()); - } - - // Note: we keep offered suites local; we don't enforce echo here - client.engine.set_cipher_suite(cs); - client.session_id = Some(server_hello.session_id); - client.server_random = Some(server_hello.random); - - let Some(extensions) = &server_hello.extensions else { - return Err((Error::IncompleteServerHello).into()); - }; - let extended_master_secret = extensions - .iter() - .any(|ext| ext.extension_type == ExtensionType::ExtendedMasterSecret); - if let Some(profile) = server_hello.srtp_profiles().and_then(|profiles| profiles.first()) { - client.negotiated_srtp_profile = Some((*profile).into()); - } - - // Without extended master secret, in DTLS1.2 a security attack - // reusing the same master secret is possible. - if !extended_master_secret { - return Err( - Error::SecurityError(crate::vendor::dimpl::SecurityError::ExtendedMasterSecretNotNegotiated).into(), - ); - } - - if let Some(profile) = client.negotiated_srtp_profile { - debug!("Negotiated SRTP profile: {:?}", profile); - } - trace!("Extended Master Secret enabled"); - - // PSK suites skip Certificate; go directly to ServerKeyExchange - if cs.is_psk() { - Ok(Self::AwaitServerKeyExchange) - } else { - Ok(Self::AwaitCertificate) - } - } - - fn await_certificate(self, client: &mut Client) -> Result { - let maybe = client - .engine - .next_handshake(MessageType::Certificate, &mut client.defragment_buffer)?; - - let Some(ref handshake) = maybe else { - // Stay in same state - return Ok(self); - }; - - let Body::Certificate(certificate) = &handshake.body else { - unreachable!() - }; - - if certificate.certificate_list.is_empty() { - return Err( - (Error::CertificateError(crate::vendor::dimpl::CertificateError::NoServerCertificateReceived)).into(), - ); - } - - debug!( - "Received Certificate message with {} certificate(s)", - certificate.certificate_list.len() - ); - - // Extract certificate ranges before dropping handshake - let cert_ranges: ArrayVec<_, 32> = certificate.certificate_list.iter().map(|cert| cert.0.clone()).collect(); - - drop(maybe); - - // Convert ASN.1 certificates to byte arrays - for (i, range) in cert_ranges.iter().enumerate() { - let cert_data = &client.defragment_buffer[range.clone()]; - trace!("Certificate #{} size: {} bytes", i + 1, cert_data.len()); - client.server_certificates.push(cert_data.to_buf()); - } - - Ok(Self::AwaitServerKeyExchange) - } - - fn await_server_key_exchange(self, client: &mut Client) -> Result { - let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - if cipher_suite.is_psk() { - self.await_server_key_exchange_psk(client) - } else { - self.await_server_key_exchange_ecdhe(client) - } - } - - fn await_server_key_exchange_ecdhe(self, client: &mut Client) -> Result { - let maybe = client - .engine - .next_handshake(MessageType::ServerKeyExchange, &mut client.defragment_buffer)?; - - if maybe.is_none() { - // Stay in same state - return Ok(self); - }; - - // Extract all ranges/data we need before accessing buffer - let (signature_range, signature_algorithm, curve_type, named_group, public_key_range) = { - let handshake = maybe.as_ref().unwrap(); - let Body::ServerKeyExchange(server_key_exchange) = &handshake.body else { - unreachable!() - }; - - let Some(d_signed) = server_key_exchange.signature() else { - // We do not support anonymous key exchange - return Err(Error::UnexpectedMessage( - crate::vendor::dimpl::UnexpectedMessageError::ServerKeyExchangeWithoutSignature, - ) - .into()); - }; - - let signature_range = d_signed.signature_range.clone(); - let signature_algorithm = d_signed.algorithm; - - // Extract ECDH params ranges - let (curve_type, named_group, public_key_range) = match &server_key_exchange.params { - ServerKeyExchangeParams::Ecdh(ecdh) => { - (ecdh.curve_type, ecdh.named_group, ecdh.public_key_range.clone()) - } - ServerKeyExchangeParams::Psk(_) => { - return Err(Error::UnexpectedMessage( - crate::vendor::dimpl::UnexpectedMessageError::PskServerKeyExchangeInEcdhePath, - ) - .into()); - } - }; - - ( - signature_range, - signature_algorithm, - curve_type, - named_group, - public_key_range, - ) - }; - - // unwrap: is ok because we verify the order of the flight - let client_random = client.random.unwrap(); - let server_random = client.server_random.unwrap(); - - // Drop maybe to release the buffer borrow - drop(maybe); - - // Now we can access the buffer to get the actual bytes - let signature_bytes = &client.defragment_buffer[signature_range]; - let public_key_vec = &client.defragment_buffer[public_key_range]; - - // Build signed_data = client_random || server_random || SKE params (without signature) - let mut signed_data = Buf::new(); - client_random.serialize(&mut signed_data); - server_random.serialize(&mut signed_data); - // Manually serialize SKE params - signed_data.push(curve_type.as_u8()); - signed_data.extend_from_slice(&named_group.as_u16().to_be_bytes()); - signed_data.push(public_key_vec.len() as u8); - signed_data.extend_from_slice(public_key_vec); - - let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - // Ensure the server's (hash, signature) pair was offered by the client - let offered = SignatureAndHashAlgorithm::supported().contains(&signature_algorithm); - if !offered { - return Err( - Error::CryptoError(crate::vendor::dimpl::CryptoError::SignatureAlgorithmNotOfferedByClient).into(), - ); - } - - // Ensure the signature algorithm is compatible with the cipher suite - if let Some(expected_sig) = cipher_suite.signature_algorithm() - && signature_algorithm.signature != expected_sig - { - return Err( - Error::CryptoError(crate::vendor::dimpl::CryptoError::SignatureAlgorithmMismatch { - expected: expected_sig, - actual: signature_algorithm.signature, - }) - .into(), - ); - } - - // unwrap: is ok because we verify the order of the flight - let cert_der = client.server_certificates.first().unwrap(); - - // Create a temporary DigitallySigned for verification (we only need the algorithm) - let temp_signed = DigitallySigned { - algorithm: signature_algorithm, - signature_range: 0..signature_bytes.len(), - }; - - client - .engine - .crypto_context_mut() - .verify_signature(&signed_data, &temp_signed, signature_bytes, cert_der) - .map_err(Error::CryptoError)?; - - trace!("ServerKeyExchange signature verified: {:?}", signature_algorithm); - - // Process the server key exchange parameters - // We already have the curve and public key extracted - let kx_buf = client.engine.pop_buffer(); - let shared_secret = client.engine.pop_buffer(); - client - .engine - .crypto_context_mut() - .process_ecdh_params(named_group, public_key_vec, kx_buf, shared_secret) - .map_err(Error::CryptoError)?; - - Ok(Self::AwaitCertificateRequest) - } - - /// PSK ServerKeyExchange carries only an optional identity hint (no signature). - /// Per RFC 4279 §2, ServerKeyExchange is omitted when the server has no hint. - fn await_server_key_exchange_psk(self, client: &mut Client) -> Result { - // If the server skipped ServerKeyExchange (no hint), go straight to ServerHelloDone - let has_done = client.engine.has_complete_handshake(MessageType::ServerHelloDone); - if has_done { - return Ok(Self::AwaitServerHelloDone); - } - - let maybe = client - .engine - .next_handshake(MessageType::ServerKeyExchange, &mut client.defragment_buffer)?; - - let Some(handshake) = maybe else { - return Ok(self); - }; - - let Body::ServerKeyExchange(ske) = &handshake.body else { - unreachable!() - }; - - // PSK ServerKeyExchange contains only an identity hint per RFC 4279 §2 - // (no curve_type or named_group - those are ECDHE-only parameters). - let hint_range = match &ske.params { - ServerKeyExchangeParams::Psk(psk) => psk.hint_range.clone(), - _ => { - return Err(Error::UnexpectedMessage( - crate::vendor::dimpl::UnexpectedMessageError::EcdheServerKeyExchangeInPskPath, - ) - .into()); - } - }; - - drop(handshake); - - let hint = &client.defragment_buffer[hint_range]; - trace!("PSK identity hint ({} bytes)", hint.len()); - // Hint is informational only; we don't use it for PSK lookup currently - - // PSK has no CertificateRequest - Ok(Self::AwaitServerHelloDone) - } - - fn await_certificate_request(self, client: &mut Client) -> Result { - let has_done = client.engine.has_complete_handshake(MessageType::ServerHelloDone); - - if has_done { - return Ok(Self::AwaitServerHelloDone); - } - - let maybe = client - .engine - .next_handshake(MessageType::CertificateRequest, &mut client.defragment_buffer)?; - - let Some(handshake) = maybe else { - // stay in same state - return Ok(self); - }; - - let Body::CertificateRequest(cr) = &handshake.body else { - unreachable!() - }; - - // Check that the hash algorithm that is default fo the PrivateKey in use - // is one of the supported by the CertificateRequest - // unwrap: CertificateRequest only received for certificate-based suites - let hash_algorithm = client - .engine - .crypto_context() - .private_key_default_hash_algorithm() - .unwrap(); - - if !cr.supports_hash_algorithm(hash_algorithm) { - return Err( - Error::CertificateError(crate::vendor::dimpl::CertificateError::UnsupportedHashAlgorithm( - hash_algorithm, - )) - .into(), - ); - } - - debug!("Server supports CertificateVerify hash algorithm: {:?}", hash_algorithm); - - debug!("Received CertificateRequest; enabling client authentication path"); - client.certificate_verify = true; - - Ok(Self::AwaitServerHelloDone) - } - - fn await_server_hello_done(self, client: &mut Client) -> Result { - let maybe = client - .engine - .next_handshake(MessageType::ServerHelloDone, &mut client.defragment_buffer)?; - - let Some(handshake) = maybe else { - // stay in same state - return Ok(self); - }; - - let Body::ServerHelloDone = handshake.body else { - unreachable!() - }; - - trace!("Received ServerHelloDone"); - - let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - if cipher_suite.is_psk() { - // PSK: no certificates involved - return Ok(Self::SendClientKeyExchange); - } - - // Validate the server certificate - if client.server_certificates.is_empty() { - return Err( - (Error::CertificateError(crate::vendor::dimpl::CertificateError::NoServerCertificateReceived)).into(), - ); - } - - // Send the server certificate as an event - if !client.server_certificates.is_empty() { - client.local_events.push_back(LocalEvent::PeerCert); - } - - if client.certificate_verify { - Ok(Self::SendCertificate) - } else { - Ok(Self::SendClientKeyExchange) - } - } - - fn send_certificate(self, client: &mut Client) -> Result { - debug!("Sending Certificate"); - - // Start/restart flight timer for client Flight 5 - client.engine.flight_begin(5); - - // Now use the engine with the stored data - client - .engine - .create_handshake(MessageType::Certificate, handshake_create_certificate)?; - - Ok(Self::SendClientKeyExchange) - } - - fn send_client_key_exchange(self, client: &mut Client) -> Result { - trace!("Sending ClientKeyExchange"); - - // Start/restart flight timer only if this flight did not start with Certificate - if !client.certificate_verify { - client.engine.flight_begin(5); - } - - // Send client key exchange message - client - .engine - .create_handshake(MessageType::ClientKeyExchange, handshake_create_client_key_exchange)?; - - // Capture session hash now for Extended Master Secret (RFC 7627) - // At this point, the session hash includes: ClientHello, ServerHello, Certificate, - // ServerKeyExchange, CertificateRequest, ServerHelloDone, Certificate, ClientKeyExchange - // This is correct per RFC 7627 - session hash should include messages - // up to and including ClientKeyExchange - let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - let suite_hash = cipher_suite.hash_algorithm(); - let mut buf = client.engine.pop_buffer(); - client.engine.transcript_hash(suite_hash, &mut buf); - client.captured_session_hash = Some(buf); - - if client.certificate_verify { - Ok(Self::SendCertificateVerify) - } else { - Ok(Self::SendChangeCipherSpec) - } - } - - fn send_certificate_verify(self, client: &mut Client) -> Result { - debug!("Sending CertificateVerify"); - - // Send the certificate verify message - client - .engine - .create_handshake(MessageType::CertificateVerify, handshake_create_certificate_verify)?; - - Ok(Self::SendChangeCipherSpec) - } - - fn send_change_cipher_spec(self, client: &mut Client) -> Result { - Self::derive_keys(client)?; - - // Send change cipher spec - trace!("Sending ChangeCipherSpec"); - client - .engine - .create_record(ContentType::ChangeCipherSpec, 0, true, |body| { - // Change cipher spec is just a single byte with value 1 - body.push(1); - })?; - - Ok(Self::SendFinished) - } - - fn derive_keys(client: &mut Client) -> Result<(), Error> { - trace!("Deriving keys"); - let Some(cipher_suite) = client.engine.cipher_suite() else { - return Err(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - )); - }; - - trace!("Using cipher suite for key derivation: {:?}", cipher_suite); - - let Some(server_random) = &client.server_random else { - return Err(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoServerRandom, - )); - }; - - // Extract and format the random values for key derivation - let mut client_random_buf_b = Buf::new(); - let mut server_random_buf_b = Buf::new(); - - // Serialize the random values to raw bytes - // unwrap: is ok because we set the random in handle_timeout - client.random.unwrap().serialize(&mut client_random_buf_b); - server_random.serialize(&mut server_random_buf_b); - let client_random_buf = client_random_buf_b; - let server_random_buf = server_random_buf_b; - - // Derive master secret (use EMS if negotiated) - let suite_hash = cipher_suite.hash_algorithm(); - - // Use the captured session hash from when ServerHelloDone was received - let session_hash = client.captured_session_hash.as_ref().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::ExtendedMasterSecretSessionHashMissing, - ))?; - trace!( - "Using captured session hash for Extended Master Secret (length: {})", - session_hash.len() - ); - let mut out = client.engine.pop_buffer(); - let mut scratch = client.engine.pop_buffer(); - client - .engine - .crypto_context_mut() - .derive_extended_master_secret(session_hash, suite_hash, &mut out, &mut scratch) - .map_err(Error::CryptoError)?; - - // Derive the encryption/decryption keys - client - .engine - .crypto_context_mut() - .derive_keys( - cipher_suite, - &client_random_buf, - &server_random_buf, - &mut out, - &mut scratch, - ) - .map_err(Error::CryptoError)?; - - client.engine.push_buffer(out); - client.engine.push_buffer(scratch); - - Ok(()) - } - - fn send_finished(self, client: &mut Client) -> Result { - trace!("Sending Finished message to complete handshake"); - - client.engine.create_handshake(MessageType::Finished, |body, engine| { - // Calculate verify data for Finished message using PRF - let verify_data = engine.generate_verify_data(true)?; - - debug!("Generated verify data for Finished message (12 bytes)"); - - // Directly write the verify data without creating Finished struct - body.extend_from_slice(&verify_data); - Ok(()) - })?; - - Ok(Self::AwaitChangeCipherSpec) - } - - fn await_change_cipher_spec(self, client: &mut Client) -> Result { - let maybe = client.engine.next_record(ContentType::ChangeCipherSpec); - - let Some(_) = maybe else { - // Stay in same state - return Ok(self); - }; - - // Drop any extra CCS resends to avoid being blocked - trace!("Dropping any pending CCS resends from peer"); - client.engine.drop_pending_ccs(); - - // Expect every record to be decrypted from now on. - trace!("Received ChangeCipherSpec; enabling peer encryption"); - client.engine.enable_peer_encryption()?; - - Ok(Self::AwaitNewSessionTicket) - } - - fn await_new_session_ticket(self, client: &mut Client) -> Result { - let has_finished = client.engine.has_complete_handshake(MessageType::Finished); - - if has_finished { - return Ok(Self::AwaitFinished); - } - - let maybe = client - .engine - .next_handshake(MessageType::NewSessionTicket, &mut client.defragment_buffer)?; - - let Some(handshake) = maybe else { - // Stay in same state - return Ok(self); - }; - - let Body::NewSessionTicket(_t) = handshake.body else { - unreachable!() - }; - - // TODO(martin): handle ticket for restart - - trace!("Received NewSessionTicket"); - - Ok(Self::AwaitFinished) - } - - fn await_finished(self, client: &mut Client) -> Result { - // Generate expected verify data based on current transcript. - // This must be done before next_handshake() below since - // it should not include Finished itself. - let expected = client.engine.generate_verify_data(false)?; - - let maybe = client - .engine - .next_handshake(MessageType::Finished, &mut client.defragment_buffer)?; - - if maybe.is_none() { - // stay in same state - return Ok(self); - } - - // Extract the range from the handshake - let verify_data_range = if let Some(ref handshake) = maybe { - if let Body::Finished(finished) = &handshake.body { - finished.verify_data_range.clone() - } else { - panic!("Finished message should have been parsed"); - } - } else { - unreachable!() - }; - - // Drop maybe to release the buffer borrow - drop(maybe); - - // Now we can access the buffer - let verify_data = &client.defragment_buffer[verify_data_range]; - trace!( - "Finished.verify_data received len={}, expected len={}", - verify_data.len(), - expected.len() - ); - // Use constant-time comparison to prevent timing attacks - let is_eq: bool = verify_data.ct_eq(expected.as_slice()).into(); - if !is_eq { - return Err( - (Error::SecurityError(crate::vendor::dimpl::SecurityError::ServerFinishedVerificationFailed)).into(), - ); - } - - // No records from the handshake epochs may survive into application data. - let unexpected_record = client - .engine - .pending_records() - .find(|record| record.record().sequence.epoch != 1); - if let Some(record) = unexpected_record { - debug!( - "Unexpected epoch at handshake completion: record={:?}, handshake={:?}", - record.record(), - record.first_handshake().map(|handshake| &handshake.header), - ); - return Err(Error::UnexpectedMessage(crate::vendor::dimpl::UnexpectedMessageError::UnexpectedEpoch).into()); - } - - trace!("Server Finished verified successfully"); - - // Receiving server Finished implicitly acks our Flight 5; stop resends - client.engine.flight_stop_resend_timers(); - - // Emit Connected event - client.local_events.push_back(LocalEvent::Connected); - - // Extract and emit SRTP keying material if we have a negotiated profile - if let Some(profile) = client.negotiated_srtp_profile { - let suite_hash = client.engine.cipher_suite().unwrap().hash_algorithm(); - - let mut out = client.engine.pop_buffer(); - let mut scratch = client.engine.pop_buffer(); - if let Ok(keying_material) = - client - .engine - .crypto_context() - .extract_srtp_keying_material(profile, suite_hash, &mut out, &mut scratch) - { - client.engine.push_buffer(out); - client.engine.push_buffer(scratch); - // Emit the keying material event with the negotiated profile - debug!( - "SRTP keying material extracted ({} bytes) for profile: {:?}", - keying_material.len(), - profile - ); - // expect should be correct here since we negotiated the profile - let profile = client - .negotiated_srtp_profile - .expect("SRTP profile should be negotiated"); - client - .local_events - .push_back(LocalEvent::KeyingMaterial(keying_material, profile)); - } else { - client.engine.push_buffer(out); - client.engine.push_buffer(scratch); - } - } - - client.engine.release_application_data(); - - debug!("Handshake complete; ready for application data"); - - Ok(Self::AwaitApplicationData) - } - - fn await_application_data(self, client: &mut Client) -> Result { - if client.engine.close_notify_received() { - // RFC 5246 §7.2.1: respond with a reciprocal close_notify and - // close down immediately, discarding any pending writes. - client.engine.discard_pending_writes(); - client.engine.create_record(ContentType::Alert, 1, false, |body| { - body.push(1); // level: warning - body.push(0); // description: close_notify - })?; - return Ok(State::Closed); - } - - if !client.queued_data.is_empty() { - debug!("Sending queued application data: {}", client.queued_data.len()); - for data in client.queued_data.drain(..) { - client - .engine - .create_record(ContentType::ApplicationData, 1, false, |body| { - body.extend_from_slice(&data); - })?; - } - } - - Ok(self) - } -} - -fn handshake_create_client_hello( - body: &mut Buf, - engine: &mut Engine, - cookie: Cookie, - random: Random, - session_id: SessionId, - extension_data: &mut Buf, -) -> Result<(), Error> { - let client_version = ProtocolVersion::DTLS1_2; - - // Get cipher suites from config that are compatible with our key - let cipher_suites: CipherSuiteVec = engine - .config() - .dtls12_cipher_suites() - .map(|cs| cs.suite()) - .filter(|suite| engine.crypto_context().is_cipher_suite_compatible(*suite)) - .take(Dtls12CipherSuite::supported().len()) - .collect(); - - debug!( - "Sending ClientHello: DTLS version={:?}, cookie_len={}, offering {} cipher suites", - client_version, - cookie.len(), - cipher_suites.len() - ); - - let mut compression_methods = ArrayVec::new(); - compression_methods.push(CompressionMethod::Null); - - // Create ClientHello with all required extensions - let client_hello = ClientHello::new( - client_version, - random, - session_id, - cookie, - cipher_suites, - compression_methods, - ) - .with_extensions(extension_data, engine.config()); - - client_hello.serialize(extension_data, body); - Ok(()) -} - -fn handshake_create_certificate(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { - let crypto = engine.crypto_context(); - crypto.serialize_client_certificate(body); - Ok(()) -} - -fn handshake_create_client_key_exchange(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { - // Just check that a cipher suite exists without binding to unused variable - let Some(cipher_suite) = engine.cipher_suite() else { - return Err(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - )); - }; - let key_exchange_algorithm = cipher_suite.as_key_exchange_algorithm(); - - debug!("Using key exchange algorithm: {:?}", key_exchange_algorithm); - - match key_exchange_algorithm { - KeyExchangeAlgorithm::EECDH => { - // Get group info before the mutable borrow - let group_info = engine.crypto_context().get_key_exchange_group_info(); - - // For ECDHE, use the group information we retrieved earlier - let Some((curve_type, named_group)) = group_info else { - unreachable!("No group info available for ECDHE"); - }; - - trace!("Using ECDHE group info: {:?}, {:?}", curve_type, named_group); - - let public_key = engine - .crypto_context_mut() - .maybe_init_key_exchange() - .map_err(Error::CryptoError)?; - - trace!("Generated public key size: {} bytes", public_key.len()); - ClientKeyExchange::serialize_from_bytes(public_key, body); - } - KeyExchangeAlgorithm::PSK => { - let identity = engine - .config() - .psk_identity() - .ok_or(Error::PskError(crate::vendor::dimpl::PskError::NoPskIdentityConfigured))? - .to_vec(); - - // Resolve the PSK via the configured resolver - let psk = engine - .config() - .psk_resolver() - .ok_or(Error::PskError(crate::vendor::dimpl::PskError::NoPskResolverConfigured))? - .resolve(&identity) - .ok_or(Error::PskError(crate::vendor::dimpl::PskError::ResolverReturnedNoKey))?; - - // Set the PSK and compute pre-master secret - let crypto = engine.crypto_context_mut(); - crypto.set_psk(psk); - crypto.compute_psk_pre_master_secret().map_err(Error::CryptoError)?; - - ClientPskKeys::serialize_from_bytes(&identity, body); - } - _ => { - return Err(Error::SecurityError( - crate::vendor::dimpl::SecurityError::UnsupportedKeyExchangeAlgorithm, - )); - } - } - - Ok(()) -} - -fn handshake_create_certificate_verify(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { - // The hash algorithm to use is the default for the private key type, not - // the one negotiated to use with the selected cipher suite. I.e. - // if we negotiate ECDHE_ECDSA_AES256_GCM_SHA384, we are gogin to use - // SHA384 for the signature of the main crypto, but not for CertificateVerify - // where a private key using P256 curve means we use SHA256. - // unwrap: CertificateVerify only sent for certificate-based suites - let hash_alg = engine.crypto_context().private_key_default_hash_algorithm().unwrap(); - debug!("Using hash algorithm for signature: {:?}", hash_alg); - - // Get the signature algorithm type - // unwrap: CertificateVerify only sent for certificate-based suites - let sig_alg = engine.crypto_context().signature_algorithm().unwrap(); - debug!("Using signature algorithm: {:?}", sig_alg); - - // Create the signature algorithm - let algorithm = SignatureAndHashAlgorithm::new(hash_alg, sig_alg); - - let mut signature = engine.pop_buffer(); - - // Sign all handshake messages - let handshake_data = &engine.transcript; - engine - .crypto_context - .sign_data(handshake_data, hash_alg, &mut signature) - .map_err(Error::CryptoError)?; - - debug!("Generated signature size: {} bytes", signature.len()); - - // For sending, directly write the CertificateVerify bytes - body.extend_from_slice(&algorithm.as_u16().to_be_bytes()); - body.extend_from_slice(&(signature.len() as u16).to_be_bytes()); - body.extend_from_slice(&signature); - - engine.push_buffer(signature); - - Ok(()) -} - -impl LocalEvent { - pub fn into_output<'a>(self, buf: &'a mut [u8], peer_certs: &[Buf]) -> Output<'a> { - match self { - LocalEvent::PeerCert => { - let l = peer_certs[0].len(); - assert!(l <= buf.len(), "Output buffer too small for peer certificate"); - buf[..l].copy_from_slice(&peer_certs[0]); - Output::PeerCert(&buf[..l]) - } - LocalEvent::Connected => Output::Connected, - LocalEvent::KeyingMaterial(m, profile) => Output::KeyingMaterial(KeyingMaterial::new(&m), profile), - } - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use super::*; - - fn psk_client() -> Client { - let engine = Engine::new(Arc::new(Config::default()), AuthMode::Psk); - Client::new_with_engine(engine, Instant::now()) - } - - fn epoch0_handshake_packet(msg_type: MessageType, message_seq: u16, body: &[u8]) -> Vec { - let handshake_len = 12 + body.len(); - let mut packet = Vec::new(); - packet.push(ContentType::Handshake.as_u8()); - packet.extend_from_slice(&[0xfe, 0xfd]); - packet.extend_from_slice(&0u16.to_be_bytes()); - packet.extend_from_slice(&0u64.to_be_bytes()[2..]); - packet.extend_from_slice(&(handshake_len as u16).to_be_bytes()); - packet.push(msg_type.as_u8()); - packet.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); - packet.extend_from_slice(&message_seq.to_be_bytes()); - packet.extend_from_slice(&0u32.to_be_bytes()[1..]); - packet.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); - packet.extend_from_slice(body); - packet - } - - #[test] - fn empty_server_certificate_is_certificate_error() { - let mut client = psk_client(); - client - .engine - .parse_packet(&epoch0_handshake_packet(MessageType::Certificate, 0, &[0, 0, 0])) - .expect("queue empty Certificate"); - - let err = State::AwaitCertificate - .await_certificate(&mut client) - .expect_err("empty server Certificate should fail"); - - assert!(matches!( - err, - crate::vendor::dimpl::InternalError::Fatal(Error::CertificateError(_)) - )); - } - - #[test] - fn derive_keys_without_cipher_suite_is_invalid_state() { - let mut client = psk_client(); - - let err = State::derive_keys(&mut client).expect_err("derive_keys requires negotiated cipher suite"); - - assert!(matches!(err, Error::InvalidState(_))); - } - - #[test] - fn derive_keys_without_server_random_is_invalid_state() { - let mut client = psk_client(); - client.engine.set_cipher_suite(Dtls12CipherSuite::PSK_AES128_CCM_8); - - let err = State::derive_keys(&mut client).expect_err("derive_keys requires server random"); - - assert!(matches!(err, Error::InvalidState(_))); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/context.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/context.rs deleted file mode 100644 index 7e8097718dd..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/context.rs +++ /dev/null @@ -1,664 +0,0 @@ -//! DTLS 1.2 cryptographic context for a session. - -use std::sync::Arc; -use tracing::trace; - -use arrayvec::ArrayVec; - -use crate::vendor::dimpl::CryptoError; -use crate::vendor::dimpl::buffer::{Buf, TmpBuf, ToBuf}; -use crate::vendor::dimpl::crypto; -use crate::vendor::dimpl::crypto::SrtpProfile; -use crate::vendor::dimpl::crypto::{Aad, Iv, Nonce}; -use crate::vendor::dimpl::dtls12::message::DigitallySigned; -use crate::vendor::dimpl::dtls12::message::{Asn1Cert, Certificate}; -use crate::vendor::dimpl::dtls12::message::{CurveType, Dtls12CipherSuite, HashAlgorithm}; -use crate::vendor::dimpl::dtls12::message::{NamedGroup, SignatureAlgorithm}; - -/// DTLS 1.2 crypto context holding negotiated keys and ciphers for a session. -pub struct CryptoContext { - /// Configuration (contains crypto provider) - config: Arc, - - /// Key exchange mechanism - key_exchange: Option>, - - /// Our public key from the key exchange (stored for reuse) - key_exchange_public_key: Option>, - - /// Group info from the key exchange (stored for reuse) - key_exchange_group: Option, - - /// Client write key - client_write_key: Option, - - /// Server write key - server_write_key: Option, - - /// Client write IV (4 bytes for AES-GCM, 12 bytes for ChaCha20-Poly1305) - client_write_iv: Option, - - /// Server write IV (4 bytes for AES-GCM, 12 bytes for ChaCha20-Poly1305) - server_write_iv: Option, - - /// Client MAC key (not used for AEAD ciphers) - client_mac_key: Option, - - /// Server MAC key (not used for AEAD ciphers) - server_mac_key: Option, - - /// Master secret - master_secret: Option>, - - /// Pre-master secret (temporary) - pre_master_secret: Option, - - /// Client cipher - client_cipher: Option>, - - /// Server cipher - server_cipher: Option>, - - /// Authentication mode: certificate or PSK. - auth: AuthMode, - - /// Resolved PSK value (set during handshake after identity exchange) - psk: Option>, - - /// Client random (needed for SRTP key export per RFC 5705) - client_random: Option>, - - /// Server random (needed for SRTP key export per RFC 5705) - server_random: Option>, -} - -/// Authentication mode for a DTLS 1.2 session. -pub enum AuthMode { - /// Certificate-based authentication (ECDHE_ECDSA suites). - Certificate { - /// DER-encoded certificate. - certificate: Vec, - /// Parsed signing key for the certificate. - private_key: Box, - }, - /// Pre-shared key authentication (PSK suites). - /// The actual PSK value is resolved during the handshake via [`CryptoContext::set_psk`]. - Psk, -} - -impl CryptoContext { - /// Create a new crypto context with the given authentication mode. - pub fn new(auth: AuthMode, config: Arc) -> Self { - CryptoContext { - config, - key_exchange: None, - key_exchange_public_key: None, - key_exchange_group: None, - client_write_key: None, - server_write_key: None, - client_write_iv: None, - server_write_iv: None, - client_mac_key: None, - server_mac_key: None, - master_secret: None, - pre_master_secret: None, - client_cipher: None, - server_cipher: None, - auth, - psk: None, - client_random: None, - server_random: None, - } - } - - pub fn provider(&self) -> &crypto::CryptoProvider { - self.config.crypto_provider() - } - - /// Generate key exchange public key - pub fn maybe_init_key_exchange(&mut self) -> Result<&[u8], CryptoError> { - // If we already have the public key stored, return it - if let Some(ref pk) = self.key_exchange_public_key { - return Ok(pk); - } - - // Otherwise, get it from the key exchange and store it - match &self.key_exchange { - Some(ke) => { - let pub_key = ke.pub_key().to_vec(); - let group = ke.group(); - self.key_exchange_public_key = Some(pub_key); - self.key_exchange_group = Some(group); - Ok(self.key_exchange_public_key.as_ref().unwrap()) - } - None => Err(CryptoError::KeyExchangeNotInitialized), - } - } - - /// Process peer's public key and compute shared secret - pub fn compute_shared_secret(&mut self, peer_public_key: &[u8], mut buf: Buf) -> Result<(), CryptoError> { - let ke = self.key_exchange.take().ok_or(CryptoError::KeyExchangeNotInitialized)?; - ke.complete(peer_public_key, &mut buf)?; - self.pre_master_secret = Some(buf); - // Note: we keep key_exchange_public_key since it may be needed later - Ok(()) - } - - /// Set the resolved PSK value for this session. - pub fn set_psk(&mut self, psk: Vec) { - self.psk = Some(psk); - } - - /// Compute PSK pre-master secret per RFC 4279 §2. - /// - /// Format: `uint16(N) || zeros(N) || uint16(N) || PSK(N)` - /// where N is the PSK length. - pub fn compute_psk_pre_master_secret(&mut self) -> Result<(), CryptoError> { - let psk = self.psk.as_ref().ok_or(CryptoError::PskNotSet)?; - let n = psk.len(); - // Total: 2 + N + 2 + N = 2N + 4 - // This secret is dropped after deriving the master secret, never pooled. - let mut pms = Buf::new(); - pms.extend_from_slice(&(n as u16).to_be_bytes()); - pms.resize(pms.len() + n, 0); - pms.extend_from_slice(&(n as u16).to_be_bytes()); - pms.extend_from_slice(psk); - self.pre_master_secret = Some(pms); - Ok(()) - } - - /// Initialize ECDHE key exchange (server role) and return our ephemeral public key - pub fn init_ecdh_server(&mut self, named_group: NamedGroup, kx_buf: Buf) -> Result<&[u8], CryptoError> { - // Find the matching key exchange group from the provider - let kx_group = self - .provider() - .supported_kx_groups() - .find(|g| g.name() == named_group) - .ok_or(CryptoError::UnsupportedEcdheNamedGroup(named_group))?; - - self.key_exchange = Some(kx_group.start_exchange(kx_buf)?); - self.maybe_init_key_exchange() - } - - /// Process a ServerKeyExchange message and set up key exchange accordingly - pub fn process_ecdh_params( - &mut self, - group: NamedGroup, - server_public: &[u8], - kx_buf: Buf, - shared_secret: Buf, - ) -> Result<(), CryptoError> { - // Find the matching key exchange group from the provider - let kx_group = self - .provider() - .supported_kx_groups() - .find(|g| g.name() == group) - .ok_or(CryptoError::UnsupportedEcdheNamedGroup(group))?; - - // Create a new ECDH key exchange - self.key_exchange = Some(kx_group.start_exchange(kx_buf)?); - - // Generate our keypair - let _our_public = self.maybe_init_key_exchange()?; - - // Compute shared secret with the server's public key - self.compute_shared_secret(server_public, shared_secret)?; - - Ok(()) - } - - /// Derive master secret using Extended Master Secret (RFC 7627) - pub fn derive_extended_master_secret( - &mut self, - session_hash: &[u8], - hash: HashAlgorithm, - out: &mut Buf, - scratch: &mut Buf, - ) -> Result<(), CryptoError> { - trace!("Deriving extended master secret"); - let Some(pms) = &self.pre_master_secret else { - return Err(CryptoError::PreMasterSecretNotAvailable); - }; - crypto::prf_hkdf::prf_tls12( - self.provider().hmac_provider, - pms, - "extended master secret", - session_hash, - out, - 48, - scratch, - hash, - )?; - let mut master_secret = ArrayVec::new(); - master_secret - .try_extend_from_slice(out) - .map_err(|_| CryptoError::MasterSecretTooLong)?; - self.master_secret = Some(master_secret); - // Clear pre-master secret after use (security measure) - self.pre_master_secret = None; - Ok(()) - } - - /// Derive keys for encryption/decryption - pub fn derive_keys( - &mut self, - cipher_suite: Dtls12CipherSuite, - client_random: &[u8], - server_random: &[u8], - key_block: &mut Buf, - scratch: &mut Buf, - ) -> Result<(), CryptoError> { - let Some(master_secret) = &self.master_secret else { - return Err(CryptoError::MasterSecretNotAvailable); - }; - - // Store the randoms for later SRTP key export (RFC 5705) - let mut client_random_arr = ArrayVec::new(); - client_random_arr - .try_extend_from_slice(client_random) - .expect("client_random too long"); - self.client_random = Some(client_random_arr); - - let mut server_random_arr = ArrayVec::new(); - server_random_arr - .try_extend_from_slice(server_random) - .expect("server_random too long"); - self.server_random = Some(server_random_arr); - - // Find the cipher suite from the provider - let supported_cipher_suite = self - .provider() - .cipher_suites - .iter() - .find(|cs| cs.suite() == cipher_suite) - .ok_or(CryptoError::UnsupportedCipherSuite(cipher_suite))?; - - // Get key sizes from the provider - let (mac_key_len, enc_key_len, fixed_iv_len) = supported_cipher_suite.key_lengths(); - - // Calculate total key material length - let key_material_len = 2 * (mac_key_len + enc_key_len + fixed_iv_len); - - // Compute seed for key expansion: server_random + client_random - let mut seed = [0u8; 64]; - seed[..32].copy_from_slice(server_random); - seed[32..].copy_from_slice(client_random); - - // Generate key material using PRF - crypto::prf_hkdf::prf_tls12( - self.provider().hmac_provider, - master_secret, - "key expansion", - &seed, - key_block, - key_material_len, - scratch, - cipher_suite.hash_algorithm(), - )?; - - // Split key material - let mut offset = 0; - - // Extract MAC keys (if used) - if mac_key_len > 0 { - self.client_mac_key = Some(key_block[offset..offset + mac_key_len].to_buf()); - offset += mac_key_len; - self.server_mac_key = Some(key_block[offset..offset + mac_key_len].to_buf()); - offset += mac_key_len; - } - - // Extract encryption keys - self.client_write_key = Some(key_block[offset..offset + enc_key_len].to_buf()); - offset += enc_key_len; - self.server_write_key = Some(key_block[offset..offset + enc_key_len].to_buf()); - offset += enc_key_len; - - // Extract IVs - self.client_write_iv = Some(Iv::new(&key_block[offset..offset + fixed_iv_len])); - offset += fixed_iv_len; - self.server_write_iv = Some(Iv::new(&key_block[offset..offset + fixed_iv_len])); - - // Initialize ciphers using the provider - self.client_cipher = Some(supported_cipher_suite.create_cipher(self.client_write_key.as_ref().unwrap())?); - - self.server_cipher = Some(supported_cipher_suite.create_cipher(self.server_write_key.as_ref().unwrap())?); - - Ok(()) - } - - /// Encrypt data (client to server) - pub fn encrypt_client_to_server(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - match &mut self.client_cipher { - Some(cipher) => cipher.encrypt(plaintext, aad, nonce), - None => Err(CryptoError::ClientCipherNotInitialized), - } - } - - /// Decrypt data (server to client) - pub fn decrypt_server_to_client( - &mut self, - ciphertext: &mut TmpBuf, - aad: Aad, - nonce: Nonce, - ) -> Result<(), CryptoError> { - match &mut self.server_cipher { - Some(cipher) => cipher.decrypt(ciphertext, aad, nonce), - None => Err(CryptoError::ServerCipherNotInitialized), - } - } - - /// Encrypt data (server to client) - pub fn encrypt_server_to_client(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { - match &mut self.server_cipher { - Some(cipher) => cipher.encrypt(plaintext, aad, nonce), - None => Err(CryptoError::ServerCipherNotInitialized), - } - } - - /// Decrypt data (client to server) - pub fn decrypt_client_to_server( - &mut self, - ciphertext: &mut TmpBuf, - aad: Aad, - nonce: Nonce, - ) -> Result<(), CryptoError> { - match &mut self.client_cipher { - Some(cipher) => cipher.decrypt(ciphertext, aad, nonce), - None => Err(CryptoError::ClientCipherNotInitialized), - } - } - - /// Get client certificate for authentication. - /// - /// Invariant: callers must only invoke this for certificate-based suites. - /// PSK handshakes never send a Certificate message (RFC 4279), and the - /// state machine routes around this path via `cs.is_psk()` checks before - /// reaching Certificate serialization. Violating the invariant is a - /// programmer bug and panics. - pub fn get_client_certificate(&self) -> Certificate { - let AuthMode::Certificate { certificate, .. } = &self.auth else { - panic!("get_client_certificate called in PSK mode"); - }; - let cert = Asn1Cert(0..certificate.len()); - let mut certs = ArrayVec::new(); - certs.push(cert); - Certificate::new(certs) - } - - /// Serialize client certificate for authentication. - /// - /// Same invariant as [`Self::get_client_certificate`]: cert-mode only. - pub fn serialize_client_certificate(&self, output: &mut Buf) { - let cert = self.get_client_certificate(); - let AuthMode::Certificate { certificate, .. } = &self.auth else { - panic!("serialize_client_certificate called in PSK mode"); - }; - cert.serialize(certificate, output); - } - - /// Sign the provided data using the client's private key. - /// Returns an error if no private key is configured (PSK-only mode). - pub fn sign_data(&mut self, data: &[u8], hash_alg: HashAlgorithm, out: &mut Buf) -> Result<(), CryptoError> { - let AuthMode::Certificate { private_key, .. } = &mut self.auth else { - return Err(CryptoError::NoPrivateKeyConfigured); - }; - private_key.sign(data, hash_alg, out) - } - - /// Generate verify data for a Finished message using PRF - pub fn generate_verify_data( - &self, - handshake_hash: &[u8], - is_client: bool, - hash: HashAlgorithm, - out: &mut Buf, - scratch: &mut Buf, - ) -> Result, CryptoError> { - let master_secret = match &self.master_secret { - Some(ms) => ms, - None => return Err(CryptoError::MasterSecretNotAvailable), - }; - - let label = if is_client { - "client finished" - } else { - "server finished" - }; - - // Generate 12 bytes of verify data using PRF - crypto::prf_hkdf::prf_tls12( - self.provider().hmac_provider, - master_secret, - label, - handshake_hash, - out, - 12, - scratch, - hash, - )?; - let mut verify_data = ArrayVec::new(); - verify_data - .try_extend_from_slice(out) - .map_err(|_| CryptoError::VerifyDataTooLong)?; - Ok(verify_data) - } - - /// Extract SRTP keying material from the master secret - /// This is per RFC 5764 (DTLS-SRTP) section 4.2 and RFC 5705 (TLS Exporter) - pub fn extract_srtp_keying_material( - &self, - profile: SrtpProfile, - hash: HashAlgorithm, - out: &mut Buf, - scratch: &mut Buf, - ) -> Result, CryptoError> { - const DTLS_SRTP_KEY_LABEL: &str = "EXTRACTOR-dtls_srtp"; - - let master_secret = match &self.master_secret { - Some(ms) => ms, - None => return Err(CryptoError::MasterSecretNotAvailable), - }; - - let client_random = match &self.client_random { - Some(cr) => cr, - None => return Err(CryptoError::ClientRandomNotAvailable), - }; - - let server_random = match &self.server_random { - Some(sr) => sr, - None => return Err(CryptoError::ServerRandomNotAvailable), - }; - - // Per RFC 5705, the exporter uses: PRF(master_secret, label, client_random + server_random) - // The seed for DTLS-SRTP exporter is client_random + server_random (no additional context) - let mut seed = ArrayVec::::new(); - seed.try_extend_from_slice(client_random) - .expect("client_random too long"); - seed.try_extend_from_slice(server_random) - .expect("server_random too long"); - - crypto::prf_hkdf::prf_tls12( - self.provider().hmac_provider, - master_secret, - DTLS_SRTP_KEY_LABEL, - &seed, - out, - profile.keying_material_len(), - scratch, - hash, - )?; - let mut keying_material = ArrayVec::new(); - keying_material - .try_extend_from_slice(out) - .map_err(|_| CryptoError::KeyingMaterialTooLong)?; - - Ok(keying_material) - } - - /// Signature algorithm for the configured private key. - /// Returns None in PSK-only mode. - pub fn signature_algorithm(&self) -> Option { - match &self.auth { - AuthMode::Certificate { private_key, .. } => Some(private_key.algorithm()), - AuthMode::Psk => None, - } - } - - /// Default hash algorithm for the configured private key. - /// Returns None in PSK-only mode. - pub fn private_key_default_hash_algorithm(&self) -> Option { - match &self.auth { - AuthMode::Certificate { private_key, .. } => Some(private_key.hash_algorithm()), - AuthMode::Psk => None, - } - } - - /// Hash algorithms the configured private key can sign with. - /// Returns an empty slice in PSK-only mode. - pub fn private_key_supported_hash_algorithms(&self) -> &[HashAlgorithm] { - match &self.auth { - AuthMode::Certificate { private_key, .. } => private_key.supported_hash_algorithms(), - AuthMode::Psk => &[], - } - } - - /// Create a hash context for the given algorithm - pub fn create_hash(&self, algorithm: HashAlgorithm) -> Box { - self.provider().hash_provider.create_hash(algorithm) - } - - /// Get the key exchange group info (curve type and named group). - pub fn get_key_exchange_group_info(&self) -> Option<(CurveType, NamedGroup)> { - // Use stored group if available (after key exchange is consumed) - if let Some(group) = self.key_exchange_group { - return Some((CurveType::NamedCurve, group)); - } - - // Otherwise get it from the active key exchange - let Some(ke) = &self.key_exchange else { - return None; - }; - Some((CurveType::NamedCurve, ke.group())) - } - - /// Check if the client's private key is compatible with a given cipher suite. - pub fn is_cipher_suite_compatible(&self, cipher_suite: Dtls12CipherSuite) -> bool { - match (&self.auth, cipher_suite.signature_algorithm()) { - // Certificate-based suite needs a matching private key - (AuthMode::Certificate { private_key, .. }, Some(sig_alg)) => sig_alg == private_key.algorithm(), - // PSK suite is only compatible in PSK mode - (AuthMode::Psk, None) => true, - // Mismatch: cert context + PSK suite, or PSK context + cert suite - _ => false, - } - } - - /// Get the client write IV if derived. - pub fn get_client_write_iv(&self) -> Option { - self.client_write_iv - } - - /// Get the server write IV if derived. - pub fn get_server_write_iv(&self) -> Option { - self.server_write_iv - } - - /// Verify a DigitallySigned structure against a certificate's public key. - pub fn verify_signature( - &self, - data: &Buf, - signature: &DigitallySigned, - signature_buf: &[u8], - cert_der: &[u8], - ) -> Result<(), CryptoError> { - self.provider().signature_verification.verify_signature( - cert_der, - data, - signature.signature(signature_buf), - signature.algorithm.hash, - signature.algorithm.signature, - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::Config; - - fn cert_auth_mode(config: &Config) -> AuthMode { - let cert = crate::vendor::dimpl::certificate::generate_self_signed_certificate().expect("generate cert"); - let private_key = config - .crypto_provider() - .key_provider - .load_private_key(&cert.private_key) - .expect("parse key"); - AuthMode::Certificate { - certificate: cert.certificate, - private_key, - } - } - - #[test] - fn certificate_mode_rejects_psk_suites() { - let config = Arc::new(Config::default()); - let auth = cert_auth_mode(&config); - let ctx = CryptoContext::new(auth, config); - - for suite in Dtls12CipherSuite::supported() { - if suite.is_psk() { - assert!( - !ctx.is_cipher_suite_compatible(*suite), - "Certificate-mode context must reject PSK suite {:?}", - suite - ); - } - } - } - - #[test] - fn certificate_mode_accepts_ecdhe_suites() { - let config = Arc::new(Config::default()); - let auth = cert_auth_mode(&config); - let ctx = CryptoContext::new(auth, config); - - // At least one ECDHE_ECDSA suite should be compatible - assert!( - Dtls12CipherSuite::supported() - .iter() - .filter(|s| !s.is_psk()) - .any(|s| ctx.is_cipher_suite_compatible(*s)), - "Certificate-mode context must accept at least one ECDHE suite" - ); - } - - #[test] - fn psk_mode_rejects_certificate_suites() { - let config = Arc::new(Config::default()); - let ctx = CryptoContext::new(AuthMode::Psk, config); - - for suite in Dtls12CipherSuite::supported() { - if !suite.is_psk() { - assert!( - !ctx.is_cipher_suite_compatible(*suite), - "PSK-mode context must reject certificate suite {:?}", - suite - ); - } - } - } - - #[test] - fn psk_mode_accepts_psk_suites() { - let config = Arc::new(Config::default()); - let ctx = CryptoContext::new(AuthMode::Psk, config); - - assert!( - Dtls12CipherSuite::supported() - .iter() - .filter(|s| s.is_psk()) - .any(|s| ctx.is_cipher_suite_compatible(*s)), - "PSK-mode context must accept at least one PSK suite" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/engine.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/engine.rs deleted file mode 100644 index 6f4ae25b1c7..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/engine.rs +++ /dev/null @@ -1,1610 +0,0 @@ -use std::mem; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::time::Instant; -use tracing::{debug, warn}; - -use super::queue::{QueueRx, QueueTx}; -use crate::vendor::dimpl::buffer::{Buf, BufferPool, TmpBuf}; -use crate::vendor::dimpl::crypto::{Aad, Iv, Nonce}; -use crate::vendor::dimpl::dtls12::context::{AuthMode, CryptoContext}; -use crate::vendor::dimpl::dtls12::incoming::{Incoming, Record, RecordHandler}; -use crate::vendor::dimpl::dtls12::message::{Body, HashAlgorithm, Header, MessageType, ProtocolVersion, Sequence}; -use crate::vendor::dimpl::dtls12::message::{ContentType, DTLSRecord, Dtls12CipherSuite, Handshake}; -use crate::vendor::dimpl::error::bounded_error_len; -use crate::vendor::dimpl::timer::{HandshakeTimers, Timeout, deadline}; -use crate::vendor::dimpl::window::ReplayWindow; -use crate::vendor::dimpl::{Config, Error, InternalError, Output, SeededRng}; - -const MAX_DEFRAGMENT_PACKETS: usize = 50; - -// Using debug_ignore_primary since CryptoContext doesn't implement Debug -pub struct Engine { - config: Arc, - - /// Seedable random number generator for deterministic testing - pub(crate) rng: SeededRng, - - /// Pool of buffers - buffers_free: BufferPool, - - /// Counters for sending DTLSRecord during epoch 0. - /// - /// This is kept separate since resends might force us to - /// "go back" to these sequence number even if we technically - /// progressed to epoch 1. - sequence_epoch_0: Sequence, - - /// Counters for epoch 1 and beyond. - sequence_epoch_n: Sequence, - - /// Queue of incoming packets. - queue_rx: QueueRx, - - /// Queue of outgoing packets. - queue_tx: QueueTx, - - /// The cipher suite in use. Set by ServerHello. - cipher_suite: Option, - - /// Per-record explicit nonce length, cached from the provider suite at - /// `set_cipher_suite` time. 0 for ChaCha20-Poly1305, 8 for AES-GCM. - explicit_nonce_len: usize, - - /// Minimum length of a protected record's encrypted fragment, cached from - /// the provider suite. See - /// [`crate::vendor::dimpl::crypto::SupportedDtls12CipherSuite::min_protected_fragment_len`]. - /// For AEAD suites this is `explicit_nonce + tag`; used both to reject - /// short incoming records and to size outgoing record overhead. - min_protected_fragment_len: usize, - - /// Cryptographic context for handling encryption/decryption - pub(crate) crypto_context: CryptoContext, - - /// Whether the remote peer has enabled encryption - peer_encryption_enabled: bool, - - /// Whether this engine is for a client (true) or server (false) - is_client: bool, - - /// Expected peer handshake sequence number - peer_handshake_seq_no: u16, - - /// Next handshake message sequence number for sending - next_handshake_seq_no: u16, - - /// Handshakes collected for hash computation. - /// - /// NB: pub(crate) because we need to sign it in client.rs - pub(crate) transcript: Buf, - - /// Anti-replay window state (per current epoch) - replay: ReplayWindow, - - /// The records that have been sent in the current flight. - flight_saved_records: Vec, - - timers: HandshakeTimers, - - /// Cooldown for duplicate-triggered resends of the current flight. - /// Disabled allows a resend; Unarmed and Armed suppress it. Expiry only - /// allows another duplicate response, including after periodic retries stop. - flight_dupe_timeout: Timeout, - - /// Whether we are ready to release application data from poll_output. - release_app_data: bool, - - /// Whether we have confirmation that the peer completed the handshake, i.e. - /// that the peer received our final flight. Once set, a stale plaintext - /// handshake (which is unauthenticated and replayable after encryption is - /// enabled) no longer triggers a courtesy flight retransmission. - /// - /// This is set from two signals, each meaningful for one role: - /// - the client stops its resend timer when it completes, which means the - /// server received our final flight (the client confirms at completion); - /// - receiving authenticated application data, which means the peer is past - /// its handshake (the server's only proof the client received flight 6). - peer_handshake_confirmed: bool, - - /// Whether a close_notify alert has been received from the peer. - close_notify_received: bool, - - /// Whether [`Output::CloseNotify`] has already been emitted. - close_notify_reported: bool, -} - -#[derive(Debug)] -struct Entry { - content_type: ContentType, - epoch: u16, - fragment: Buf, -} - -enum PollOutput<'a> { - Data(&'a [u8]), - BufferTooSmall { needed: usize }, - None(&'a mut [u8]), -} - -impl Engine { - pub fn new(config: Arc, auth: AuthMode) -> Self { - let mut rng = SeededRng::new(config.rng_seed()); - - let timers = HandshakeTimers::new(&config, &mut rng); - - let crypto_context = CryptoContext::new(auth, Arc::clone(&config)); - let mut buffers_free = BufferPool::default(); - let transcript = buffers_free.pop(); - - Self { - config, - rng, - buffers_free, - sequence_epoch_0: Sequence::new(0), - sequence_epoch_n: Sequence::new(1), - queue_rx: QueueRx::new(), - queue_tx: QueueTx::new(), - cipher_suite: None, - explicit_nonce_len: 0, - min_protected_fragment_len: 0, - crypto_context, - peer_encryption_enabled: false, - is_client: false, - peer_handshake_seq_no: 0, - next_handshake_seq_no: 0, - transcript, - replay: ReplayWindow::new(), - flight_saved_records: Vec::new(), - timers, - flight_dupe_timeout: Timeout::Disabled, - release_app_data: false, - peer_handshake_confirmed: false, - close_notify_received: false, - close_notify_reported: false, - } - } - - pub fn set_client(&mut self, is_client: bool) { - self.is_client = is_client; - } - - pub fn start_handshake(&mut self, now: Instant) { - self.timers.start_handshake(now); - } - - pub fn config(&self) -> &Config { - &self.config - } - - /// Get a reference to the cipher suite - pub fn cipher_suite(&self) -> Option { - self.cipher_suite - } - - /// Minimum length of a protected record's encrypted fragment for the - /// negotiated suite. See - /// [`crate::vendor::dimpl::crypto::SupportedDtls12CipherSuite::min_protected_fragment_len`]. - pub fn min_protected_fragment_len(&self) -> usize { - self.min_protected_fragment_len - } - - /// Is the given cipher suite allowed by configuration - pub fn is_cipher_suite_allowed(&self, suite: Dtls12CipherSuite) -> bool { - self.config.dtls12_cipher_suites().any(|cs| cs.suite() == suite) - } - - /// Get a reference to the crypto context - pub fn crypto_context(&self) -> &CryptoContext { - &self.crypto_context - } - - /// Get a mutable reference to the crypto context - pub fn crypto_context_mut(&mut self) -> &mut CryptoContext { - &mut self.crypto_context - } - - /// Unconsumed records for protocol-state validation. - pub fn pending_records(&self) -> impl Iterator { - self.queue_rx - .iter() - .flat_map(|incoming| incoming.records().iter()) - .filter(|record| !record.is_handled()) - } - - /// Queue a datagram and report whether it contains the first ClientHello fragment. - pub fn parse_packet(&mut self, packet: &[u8]) -> Result { - let cs = self.cipher_suite; - let incoming = Incoming::parse_packet(packet, self, cs)?; - if let Some(incoming) = incoming { - // A reordered protected flight can be retransmitted once keys are ready. - // A coalesced flight starts with its plaintext key-establishing records. - if !self.peer_encryption_enabled && incoming.first().record().sequence.epoch != 0 { - self.recycle_incoming(incoming); - return Ok(false); - } - let is_client_hello = self.insert_incoming(incoming)?; - return Ok(is_client_hello); - } - - Ok(false) - } - - /// Discard ciphertext still awaiting keys after processing the datagram. - pub fn discard_undecryptable(&mut self) { - if self.peer_encryption_enabled { - return; - } - for incoming in self.queue_rx.iter() { - for record in incoming.records().iter() { - if record.record().sequence.epoch != 0 { - record.set_handled(); - } - } - } - self.purge_handled_queue_rx(); - } - - /// Insert a parsed datagram into the receive queue. - fn insert_incoming(&mut self, incoming: Incoming) -> Result { - // Capacity guard before iterating records. - if self.queue_rx.len() >= self.config.max_queue_rx() { - warn!( - "Receive queue full (max {}): {:?}", - self.config.max_queue_rx(), - self.queue_rx - ); - self.recycle_incoming(incoming); - return Err(Error::ReceiveQueueFull); - } - - // Dispatch to specialized handlers - if incoming.first().first_handshake().is_some() { - self.insert_incoming_handshake(incoming) - } else { - self.insert_incoming_non_handshake(incoming).map(|_| false) - } - } - - fn insert_incoming_handshake(&mut self, incoming: Incoming) -> Result { - let first_record = incoming.first(); - let handshake = first_record.first_handshake().expect("caller ensures handshake"); - - let key_current = (handshake.header.message_seq, handshake.header.fragment_offset); - - let maybe_dupe_seq = incoming - .records() - .iter() - .filter_map(|r| r.first_handshake()) - .filter_map(|h| h.dupe_triggers_resend()) - .next(); - - // Some MessageType when resent, means we must trigger - // an immediate resend of the entire flight. Once the peer is confirmed - // to have completed the handshake, a stale plaintext handshake is just - // unauthenticated noise (or a replay/amplification attempt) and must not - // drive a resend. - if let Some(dupe_seq) = maybe_dupe_seq - && dupe_seq < self.peer_handshake_seq_no - && !self.peer_handshake_confirmed - && let Err(error) = self.flight_resend_on_dupe() - { - self.recycle_incoming(incoming); - return Err(error); - } - - // Drop old duplicates we've already processed - don't let them block newer messages. - if handshake.header.message_seq < self.peer_handshake_seq_no { - self.recycle_incoming(incoming); - return Ok(false); - } - - if self.peer_encryption_enabled && first_record.record().sequence.epoch == 0 { - // Keep old plaintext handshake records available long enough to - // trigger flight resends above, but never queue or process them as - // new messages after peer encryption is enabled. - self.recycle_incoming(incoming); - return Ok(false); - } - - // Reject new handshakes after initial handshake is complete (renegotiation not supported). - if self.release_app_data && handshake.header.message_seq >= self.peer_handshake_seq_no { - self.recycle_incoming(incoming); - return Err(Error::RenegotiationAttempt); - } - - let is_client_hello = first_record.record().sequence.epoch == 0 - && handshake.header.msg_type == MessageType::ClientHello - && handshake.header.message_seq == self.peer_handshake_seq_no; - - let search_result = self.queue_rx.binary_search_by(|item| { - let key_other = item - .first() - .first_handshake() - .as_ref() - .map(|h| (h.header.message_seq, h.header.fragment_offset)) - .unwrap_or((u16::MAX, u32::MAX)); - key_other.cmp(&key_current) - }); - - match search_result { - Err(index) => { - // Insert in order of handshake key - self.queue_rx.insert(index, incoming); - } - Ok(_) => { - // Exact duplicate handshake fragment - self.recycle_incoming(incoming); - } - } - - Ok(is_client_hello) - } - - fn insert_incoming_non_handshake(&mut self, incoming: Incoming) -> Result<(), Error> { - let first = incoming.first(); - let seq_current = first.record().sequence; - - if self.peer_encryption_enabled - && seq_current.epoch == 0 - && first.record().content_type == ContentType::Handshake - { - self.recycle_incoming(incoming); - return Ok(()); - } - - if self.peer_encryption_enabled { - for record in incoming.records().iter() { - if record.record().sequence.epoch == 0 && record.record().content_type == ContentType::Handshake { - if record.handshakes().is_empty() { - record.set_handled(); - } else { - for handshake in record.handshakes() { - handshake.set_handled(); - } - } - } - } - } - - let search_result = self - .queue_rx - .binary_search_by_key(&seq_current, |item| item.first().record().sequence); - - match search_result { - Err(index) => self.queue_rx.insert(index, incoming), - Ok(_) => { - // Exact duplicate. For epoch 0 these come from resends. Before - // peer encryption is enabled, epoch-1 records are queued - // undecrypted and bypass the replay window, so duplicates can - // land here too. After that, Record::parse replay-checks every - // epoch-1 record before it is queued. - assert!(seq_current.epoch == 0 || !self.peer_encryption_enabled); - self.recycle_incoming(incoming); - } - } - - Ok(()) - } - - fn recycle_incoming(&mut self, incoming: Incoming) { - for record in incoming.into_records() { - self.push_buffer(record.into_buffer()); - } - } - - pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { - if let Timeout::Armed(deadline) = self.flight_dupe_timeout - && now >= deadline - { - self.flight_dupe_timeout = Timeout::Disabled; - } - if self.timers.handle_timeout(now, &mut self.rng).map_err(Error::Timeout)? { - self.flight_resend("flight timeout")?; - self.flight_dupe_timeout = Timeout::Unarmed; - } - - Ok(()) - } - - pub fn poll_output<'a>(&mut self, buf: &'a mut [u8], now: Instant) -> Output<'a> { - // Drain incoming queue of processed records. - self.purge_handled_queue_rx(); - - let buf = match self.poll_app_data(buf) { - PollOutput::Data(p) => return Output::ApplicationData(p), - PollOutput::BufferTooSmall { needed } => return Output::BufferTooSmall { needed }, - PollOutput::None(b) => b, - }; - - match self.poll_packet_tx(buf) { - PollOutput::Data(p) => { - if self.is_client { - self.timers.start_handshake(now); - } - self.timers.flight_sent(now); - if self.flight_dupe_timeout == Timeout::Unarmed { - self.flight_dupe_timeout = Timeout::Armed(deadline(now, self.timers.rto())); - } - return Output::Packet(p); - } - PollOutput::BufferTooSmall { needed } => return Output::BufferTooSmall { needed }, - PollOutput::None(_) => {} - } - - if self.close_notify_received && !self.close_notify_reported { - self.close_notify_reported = true; - return Output::CloseNotify; - } - - let next_timeout = self.poll_timeout(now); - - Output::Timeout(next_timeout) - } - - fn poll_app_data<'a>(&mut self, buf: &'a mut [u8]) -> PollOutput<'a> { - if !self.release_app_data { - return PollOutput::None(buf); - } - - let mut unhandled = self - .queue_rx - .iter() - .flat_map(|i| i.records().iter()) - .filter(|r| r.record().content_type == ContentType::ApplicationData) - .skip_while(|r| r.is_handled()); - - let Some(next) = unhandled.next() else { - return PollOutput::None(buf); - }; - - let record_buffer = next.buffer(); - let fragment = next.record().fragment(record_buffer); - let len = fragment.len(); - - if len > buf.len() { - return PollOutput::BufferTooSmall { needed: len }; - } - - buf[..len].copy_from_slice(fragment); - next.set_handled(); - - PollOutput::Data(&buf[..len]) - } - - fn purge_handled_queue_rx(&mut self) { - while let Some(peek) = self.queue_rx.front() { - let fully_handled = peek.records().iter().all(|r| r.is_handled()); - - if fully_handled { - let incoming = self.queue_rx.pop_front().unwrap(); - incoming - .into_records() - .for_each(|r| self.buffers_free.push(r.into_buffer())); - } else { - break; - } - } - } - - fn poll_packet_tx<'a>(&mut self, buf: &'a mut [u8]) -> PollOutput<'a> { - let Some(p) = self.queue_tx.front() else { - return PollOutput::None(buf); - }; - - if p.len() > buf.len() { - return PollOutput::BufferTooSmall { needed: p.len() }; - } - - let p = self.queue_tx.pop_front().expect("queue front checked above"); - let len = p.len(); - buf[..len].copy_from_slice(&p); - - PollOutput::Data(&buf[..len]) - } - - fn poll_timeout(&self, now: Instant) -> Instant { - let timeout = self.timers.poll_timeout(now); - match self.flight_dupe_timeout { - Timeout::Armed(deadline) => timeout.min(deadline), - _ => timeout, - } - } - - pub fn flight_begin(&mut self, flight_no: u8) { - debug!("Begin flight {}", flight_no); - self.timers.begin_flight(&mut self.rng); - self.flight_clear_resends(); - self.flight_dupe_timeout = Timeout::Disabled; - } - - pub fn flight_stop_resend_timers(&mut self) { - debug!("Stop connect and flight timeouts"); - self.timers.stop(); - - // The client stops its resend timer only once it has received the - // server's final flight, which proves the server received the client's - // final flight - so the peer is confirmed. The server, by contrast, - // stops its timer right after sending flight 6, before the client has - // confirmed anything, so it must NOT confirm here (it relies on later - // authenticated application data instead). - if self.is_client { - self.peer_handshake_confirmed = true; - self.flight_dupe_timeout = Timeout::Disabled; - } - } - - fn flight_clear_resends(&mut self) { - for entry in self.flight_saved_records.drain(..) { - self.buffers_free.push(entry.fragment); - } - } - - fn flight_resend_on_dupe(&mut self) -> Result<(), Error> { - // Rate-limit duplicate responses and avoid spending a retry when there - // is no saved flight. - if self.flight_dupe_timeout != Timeout::Disabled || self.flight_saved_records.is_empty() { - return Ok(()); - } - - // Reserve a resend from the same budget used by timed retries, so - // duplicates cannot bypass flight_retries. This also advances backoff, - // but allows final-flight responses after local completion regardless - // of budget (RFC 6347 section 4.2.4). - let resend_requested = self.timers.request_resend(&mut self.rng); - if !resend_requested { - return Ok(()); - } - - self.flight_resend("dupe triggers resend")?; - self.flight_dupe_timeout = Timeout::Unarmed; - Ok(()) - } - - fn flight_resend(&mut self, reason: &str) -> Result<(), Error> { - debug!("Resending flight due to {}", reason); - - let replace_pending_handshake_output = !self.release_app_data; - - if replace_pending_handshake_output { - self.queue_tx.clear(); - } - - // For lifetime issues, we take the entries out of self - let records = mem::take(&mut self.flight_saved_records); - - let mut result = Ok(()); - for (index, entry) in records.iter().enumerate() { - result = self.create_record_inner( - entry.content_type, - entry.epoch, - false, - replace_pending_handshake_output && index == 0, - |fragment| { - fragment.extend_from_slice(&entry.fragment); - }, - ); - if result.is_err() { - break; - } - } - - // Put the entries back into self - self.flight_saved_records = records; - - result - } - - pub fn has_complete_handshake(&mut self, wanted: MessageType) -> bool { - self.has_complete_handshake_with_seq(wanted, self.peer_handshake_seq_no) - } - - fn has_complete_handshake_with_seq(&mut self, wanted: MessageType, expected_seq: u16) -> bool { - let mut skip_handled = self - .queue_rx - .iter() - .flat_map(|i| i.records().iter()) - .skip_while(|r| r.is_handled()) - // Cap to MAX_DEFRAGMENT_PACKETS to avoid misbehaving peers - .take(MAX_DEFRAGMENT_PACKETS) - .flat_map(|r| r.handshakes().iter()) - .skip_while(|h| h.is_handled()) - .peekable(); - - let maybe_first_handshake = skip_handled.peek(); - - let Some(first) = maybe_first_handshake else { - return false; - }; - - if first.header.message_seq != expected_seq { - return false; - } - - if first.header.msg_type != wanted { - return false; - } - - let wanted_seq = first.header.message_seq; - let wanted_length = first.header.length; - let mut last_fragment_end = 0; - - for h in skip_handled { - // A different seq means we're looking at a different handshake - if wanted_seq != h.header.message_seq { - continue; - } - - // Check fragment contiguity - if h.header.fragment_offset != last_fragment_end { - return false; - } - last_fragment_end = h.header.fragment_offset + h.header.fragment_length; - - // Found the last fragment to complete the wanted handshake. - if last_fragment_end == wanted_length { - return true; - } - } - - false - } - - pub fn next_handshake( - &mut self, - wanted: MessageType, - defragment_buffer: &mut Buf, - ) -> Result, InternalError> { - if !self.has_complete_handshake(wanted) { - return Ok(None); - } - - let iter = self - .queue_rx - .iter() - .flat_map(|i| i.records().iter()) - .skip_while(|r| r.is_handled()) - .flat_map(|r| r.handshakes().iter().map(move |h| (h, r.buffer()))) - .skip_while(|(h, _)| h.is_handled()); - - // This sets the handled flag on the handshake. - // Passing Some(&mut self.transcript) to have defragment write to transcript - // before creating the handshake, avoiding borrow conflicts. - let handshake = Handshake::defragment(iter, defragment_buffer, self.cipher_suite, Some(&mut self.transcript))?; - - // Move the expected seq_no along - self.peer_handshake_seq_no = handshake.header.message_seq + 1; - - Ok(Some(handshake)) - } - - pub(crate) fn next_record(&mut self, ctype: ContentType) -> Option<&Record> { - let record = self - .queue_rx - .iter() - .flat_map(|i| i.records().iter()) - .find(|r| !r.is_handled())?; - - if record.record().content_type != ctype { - return None; - } - - record.set_handled(); - - Some(record) - } - - /// Mark any pending ChangeCipherSpec records as handled and purge them. - /// We can accumulate multiple ChangeCipherSpec due to resends. Since they - /// don't have any Handshake message_seq and each resend gives a new DTLSRecord - /// sequence number, we might have multiple. - pub fn drop_pending_ccs(&mut self) { - for incoming in self.queue_rx.iter() { - for record in incoming.records().iter() { - if record.record().content_type == ContentType::ChangeCipherSpec { - record.set_handled(); - } - } - } - } - - /// Create a DTLS record and serialize it into a buffer - pub fn create_record( - &mut self, - content_type: ContentType, - epoch: u16, - save_fragment: bool, - f: F, - ) -> Result<(), Error> - where - F: FnOnce(&mut Buf), - { - self.create_record_inner(content_type, epoch, save_fragment, false, f) - } - - fn create_record_inner( - &mut self, - content_type: ContentType, - epoch: u16, - save_fragment: bool, - force_new_datagram: bool, - f: F, - ) -> Result<(), Error> - where - F: FnOnce(&mut Buf), - { - let maybe_suite = if epoch >= 1 { - Some(self.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?) - } else { - None - }; - - // Prepare the plaintext fragment - let mut fragment = self.buffers_free.pop(); - - // Let the caller fill the fragment (plaintext) - f(&mut fragment); - - // Use this as a marker to know whether we are to record fragments for resends. - if save_fragment { - let mut clone = self.buffers_free.pop(); - clone.extend_from_slice(&fragment); - self.flight_saved_records.push(Entry { - content_type, - epoch, - fragment: clone, - }); - } - - // Compute wire length of the record if serialized into a datagram. - // Record header (13) + handshake/change/app data bytes + per-suite - // protection overhead (if epoch >= 1). For AEAD suites the protection - // overhead equals the min-protected-fragment-len. - let overhead = if maybe_suite.is_some() { - self.min_protected_fragment_len() - } else { - 0 - }; - let record_wire_len = DTLSRecord::HEADER_LEN + fragment.len() + overhead; - - // Decide whether to append to the existing last datagram or create a new one - let can_append = self - .queue_tx - .back() - .map(|b| !force_new_datagram && b.len() + record_wire_len <= self.config.mtu()) - .unwrap_or(false); - - // If we cannot append, ensure we have space for a new datagram - if !can_append && self.queue_tx.len() >= self.config.max_queue_tx() { - warn!( - "Transmit queue full (max {}): {:?}", - self.config.max_queue_tx(), - self.queue_tx - ); - return Err(Error::TransmitQueueFull); - } - - // Sequence number to use for this record - let sequence = if epoch == 0 { - self.sequence_epoch_0 - } else { - self.sequence_epoch_n - }; - let length = fragment.len() as u16; - - // Handle encryption for epochs >= 1 - if epoch >= 1 { - let suite = maybe_suite.expect("cipher suite must be set for encrypted epochs"); - - // Get the fixed part of the IV - let iv = if self.is_client { - self.crypto_context.get_client_write_iv() - } else { - self.crypto_context.get_server_write_iv() - }; - - let Some(iv) = iv else { - return Err(Error::CryptoError( - crate::vendor::dimpl::CryptoError::WriteIvNotAvailable { - is_client: self.is_client, - }, - )); - }; - - let explicit_nonce_len = self.explicit_nonce_len; - let mut explicit_nonce = [0u8; DTLSRecord::EXPLICIT_NONCE_LEN]; - let seq64 = ((sequence.epoch as u64) << 48) | sequence.sequence_number; - let nonce = match explicit_nonce_len { - 0 => Nonce::xor(iv.as_12_bytes(), seq64), - DTLSRecord::EXPLICIT_NONCE_LEN => { - explicit_nonce = self.rng.random(); - Nonce::new(iv, &explicit_nonce) - } - _ => { - return Err(Error::CryptoError( - crate::vendor::dimpl::CryptoError::UnsupportedDtls12RecordIvLen { - len: bounded_error_len(explicit_nonce_len), - suite, - }, - )); - } - }; - - // DTLS 1.2 AEAD: AAD uses the plaintext length (DTLSCompressed.length). - let aad = Aad::new_dtls12(content_type, sequence, length); - - // Encrypt the fragment in-place - self.encrypt_data(&mut fragment, aad, nonce)?; - let ctext_len = fragment.len(); - - // For suites with a per-record nonce (e.g. AES-GCM), prefix it on the wire. - if explicit_nonce_len > 0 { - fragment.resize(explicit_nonce_len + ctext_len, 0); - fragment.copy_within(0..ctext_len, explicit_nonce_len); - fragment[..explicit_nonce_len].copy_from_slice(&explicit_nonce[..explicit_nonce_len]); - } - } - - // Build the record structure referencing the (possibly encrypted) fragment - let record = DTLSRecord { - content_type, - version: ProtocolVersion::DTLS1_2, - sequence, - length: fragment.len() as u16, - fragment_range: 0..fragment.len(), - }; - - // Increment the sequence number for the next transmission - if epoch == 0 { - self.sequence_epoch_0.sequence_number += 1; - } else { - self.sequence_epoch_n.sequence_number += 1; - } - - // Serialize the record into the chosen datagram buffer - if can_append { - let last = self.queue_tx.back_mut().unwrap(); - record.serialize(&fragment, last); - } else { - let mut buffer = self.buffers_free.pop(); - buffer.clear(); - record.serialize(&fragment, &mut buffer); - self.queue_tx.push_back(buffer); - } - - // Return the fragment buffer to the pool - self.buffers_free.push(fragment); - - Ok(()) - } - - /// Create a handshake message and wrap it in a DTLS record - pub fn create_handshake(&mut self, msg_type: MessageType, f: F) -> Result<(), Error> - where - F: FnOnce(&mut Buf, &mut Self) -> Result<(), Error>, - { - // Get a buffer for the handshake body - let mut body_buffer = self.buffers_free.pop(); - - // Let the callback fill the handshake body - f(&mut body_buffer, self)?; - - // Create the handshake header with the next sequence number - let handshake_header = Header { - msg_type, - length: body_buffer.len() as u32, - message_seq: self.next_handshake_seq_no, - fragment_offset: 0, - fragment_length: body_buffer.len() as u32, - }; - - let mut buffer_full = self.buffers_free.pop(); - { - let handshake = Handshake { - header: handshake_header, - body: Body::Fragment(0..body_buffer.len()), - handled: AtomicBool::new(false), - }; - // Serialize with body_buffer as source - handshake.serialize(&body_buffer, &mut buffer_full); - } - self.transcript.extend_from_slice(&buffer_full); - self.buffers_free.push(buffer_full); - - // Increment the sequence number for the next handshake message - self.next_handshake_seq_no += 1; - - // We want to pack as much as possible into the outgoing datagram and - // remain within the MTU. Fragment the handshake across records as needed. - - let epoch = msg_type.epoch(); - let total_len = body_buffer.len(); - let mut offset: usize = 0; - - // Handshake header is 12 bytes - let handshake_header_len = 12usize; - // Per-record protection overhead on the wire (for AEAD suites this is - // explicit_nonce + tag). Used to size fragments to fit the MTU. - let protection_overhead = if epoch >= 1 { - self.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - self.min_protected_fragment_len() - } else { - 0 - }; - - // At least one record must be created even if total_len == 0 - while offset < total_len || (total_len == 0 && offset == 0) { - // How many bytes are already used in the current datagram (if any)? - let already_used_in_current = self.queue_tx.back().map(|b| b.len()).unwrap_or(0); - let available_in_current = self.config.mtu().saturating_sub(already_used_in_current); - - // Fixed overhead per handshake record on the wire: - // DTLS record header + handshake header + protection overhead (if epoch >= 1) - let fixed_overhead = DTLSRecord::HEADER_LEN + handshake_header_len + protection_overhead; - - // Prefer to pack into the current datagram. If the current one cannot fit even - // the fixed overhead, we will start a fresh datagram and compute space again. - let available_for_body = if available_in_current > fixed_overhead { - // There is room for at least 1 byte of handshake body in the current datagram - available_in_current - fixed_overhead - } else { - // Not enough space in the current datagram for any body bytes; start a fresh datagram - self.config.mtu().saturating_sub(fixed_overhead) - }; - - // Remaining bytes from the handshake body we still need to send. - let remaining_body_bytes = total_len.saturating_sub(offset); - - // For empty-body handshakes (e.g., ServerHelloDone), we still send a header-only record. - let chunk_len = if total_len == 0 { - 0 - } else { - remaining_body_bytes.min(available_for_body) - }; - - let frag_range = if chunk_len == 0 { - 0..0 - } else { - offset..offset + chunk_len - }; - - let frag_handshake = Handshake { - header: Header { - msg_type, - length: handshake_header.length, - message_seq: handshake_header.message_seq, - fragment_offset: offset as u32, - fragment_length: chunk_len as u32, - }, - body: Body::Fragment(frag_range), - handled: AtomicBool::new(false), - }; - - // Emit the record; packing into current datagram happens inside create_record - self.create_record(ContentType::Handshake, epoch, true, |fragment| { - // Serialize with body_buffer as source - frag_handshake.serialize(&body_buffer, fragment); - })?; - - if total_len == 0 { - // Nothing more to send for empty-body handshake - break; - } - - offset += chunk_len; - } - - // Return the buffer - self.buffers_free.push(body_buffer); - - Ok(()) - } - - /// Release application data from the incoming queue - pub fn release_application_data(&mut self) { - self.release_app_data = true; - } - - /// Whether a close_notify alert has been received from the peer. - pub fn close_notify_received(&self) -> bool { - self.close_notify_received - } - - /// Whether a received close_notify still needs to be surfaced. - pub fn close_notify_pending(&self) -> bool { - self.close_notify_received && !self.close_notify_reported - } - - /// Whether close-related output remains to be polled. - pub fn has_pending_close_output(&self) -> bool { - !self.queue_tx.is_empty() || self.close_notify_pending() - } - - /// Discard all pending outgoing data. - /// - /// RFC 5246 §7.2.1: on receiving close_notify, discard any pending writes. - pub fn discard_pending_writes(&mut self) { - self.queue_tx.clear(); - } - - /// Abort the connection: flush all queued output, retransmission state, and - /// disable timers so that no further packets are emitted. - pub fn abort(&mut self) { - self.queue_tx.clear(); - self.flight_saved_records.clear(); - self.flight_dupe_timeout = Timeout::Disabled; - self.timers.stop(); - } - - /// Pop a buffer from the buffer pool for temporary use - pub(crate) fn pop_buffer(&mut self) -> Buf { - self.buffers_free.pop() - } - - /// Return a buffer to the buffer pool - pub(crate) fn push_buffer(&mut self, buf: Buf) { - self.buffers_free.push(buf); - } - - /// Encrypt data appropriate for the role (client or server) - fn encrypt_data(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), Error> { - if self.is_client { - self.crypto_context - .encrypt_client_to_server(plaintext, aad, nonce) - .map_err(Error::CryptoError) - } else { - self.crypto_context - .encrypt_server_to_client(plaintext, aad, nonce) - .map_err(Error::CryptoError) - } - } - - /// Decrypt data appropriate for the role (client or server) - pub fn decrypt_data(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), Error> { - if self.is_client { - self.crypto_context - .decrypt_server_to_client(ciphertext, aad, nonce) - .map_err(Error::CryptoError) - } else { - self.crypto_context - .decrypt_client_to_server(ciphertext, aad, nonce) - .map_err(Error::CryptoError) - } - } - - /// Reset server handshake state after sending HelloVerifyRequest. - /// - /// Per RFC 6347 §4.2.2, the HelloVerifyRequest exchange is stateless. After sending - /// HVR, the server expects a fresh ClientHello containing the cookie with message_seq=1. - /// - /// The message flow per RFC 6347 §4.2.2: - /// ClientHello (seq=0) ------> - /// <------ HelloVerifyRequest (seq=0) - /// ClientHello (seq=1) ------> (with cookie) - /// <------ ServerHello (seq=1) - pub fn reset_server_for_hello_verify_request(&mut self) { - self.transcript.clear(); - // Per RFC 6347 §4.2.2, the next ClientHello (with cookie) has message_seq=1. - // We keep peer_handshake_seq_no at 1 (already incremented after first ClientHello). - // Clear queued incoming handshakes so the next ClientHello (with cookie) - // isn't rejected as a duplicate of the first ClientHello (without cookie). - self.queue_rx.clear(); - // Note: Don't clear flight_saved_records here - the HelloVerifyRequest should - // still be resendable via timeout until we receive the valid ClientHello with cookie. - // The flight_begin(4) call when processing the cookie-bearing ClientHello will - // clear the old records. - } - - /// Reset client handshake state after receiving HelloVerifyRequest. - /// - /// Per RFC 6347 §4.2.2, the client sends the next ClientHello (with cookie) using - /// message_seq=1. The transcript is cleared because the initial ClientHello and - /// HelloVerifyRequest are not part of the handshake transcript per RFC 6347 §4.2.1. - /// - /// Note: next_handshake_seq_no is already 1 after sending the first ClientHello, - /// so we don't reset it - the next ClientHello will correctly have message_seq=1. - pub fn reset_client_for_hello_verify_request(&mut self) { - self.transcript.clear(); - // Note: next_handshake_seq_no stays at 1 - the next ClientHello (with cookie) - // will have message_seq=1 per RFC 6347 §4.2.2. - // Note: peer_handshake_seq_no stays at 1 - the next message from server - // (ServerHello) will have message_seq=1 per RFC 6347 §4.2.2. - } - - pub fn transcript_hash(&self, algorithm: HashAlgorithm, out: &mut Buf) { - let mut hash = self.crypto_context.create_hash(algorithm); - hash.update(&self.transcript); - hash.clone_and_finalize(out); - } - - pub fn transcript(&self) -> &[u8] { - &self.transcript - } - - pub fn set_cipher_suite(&mut self, cipher_suite: Dtls12CipherSuite) { - // Cache AEAD record parameters from the provider suite. The formula - // (explicit_nonce + tag) lives on the suite trait; Engine just stores - // the resolved values for hot-path access. - let provider_suite = self - .crypto_context - .provider() - .cipher_suites - .iter() - .find(|cs| cs.suite() == cipher_suite) - .expect("cipher suite must be in provider"); - self.explicit_nonce_len = provider_suite.explicit_nonce_len(); - self.min_protected_fragment_len = provider_suite.min_protected_fragment_len(); - self.cipher_suite = Some(cipher_suite); - } - - pub fn enable_peer_encryption(&mut self) -> Result<(), InternalError> { - debug!("Peer encryption enabled"); - self.peer_encryption_enabled = true; - - let maybe_index_epoch1 = self - .queue_rx - .iter() - .position(|i| i.records().iter().any(|r| r.record().sequence.epoch == 1)); - - let Some(index_epoch1) = maybe_index_epoch1 else { - return Ok(()); - }; - - // Now decrypt all entries remaining. - let all = self.queue_rx.split_off(index_epoch1); - - for incoming in all { - let unhandled = incoming.into_records().filter(|r| !r.is_handled()); - - for record in unhandled { - let buf = record.into_buffer(); - self.parse_packet(&buf)?; - self.buffers_free.push(buf); - } - } - - Ok(()) - } - - fn peer_iv(&self) -> Iv { - if self.is_client { - self.crypto_context - .get_server_write_iv() - .expect("Server write IV not available - keys not derived yet") - } else { - self.crypto_context - .get_client_write_iv() - .expect("Client write IV not available - keys not derived yet") - } - } - - pub fn decryption_aad_and_nonce(&self, dtls: &DTLSRecord, buf: &[u8]) -> (Aad, Nonce) { - // DTLS 1.2 AEAD: AAD uses the plaintext length. Recover plaintext length - // from the record header by subtracting this suite's wire overhead. - let plaintext_len = dtls.length.saturating_sub(self.min_protected_fragment_len() as u16); - let aad = Aad::new_dtls12(dtls.content_type, dtls.sequence, plaintext_len); - let iv = self.peer_iv(); - let seq64 = ((dtls.sequence.epoch as u64) << 48) | dtls.sequence.sequence_number; - let nonce = match self.explicit_nonce_len { - 0 => Nonce::xor(iv.as_12_bytes(), seq64), - DTLSRecord::EXPLICIT_NONCE_LEN => Nonce::new(iv, dtls.nonce(buf)), - len => Nonce::new(iv, dtls.nonce_with_len(buf, len)), - }; - (aad, nonce) - } - - pub fn generate_verify_data(&mut self, is_client: bool) -> Result<[u8; 12], Error> { - let Some(suite) = self.cipher_suite() else { - return Err(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - )); - }; - let algorithm = suite.hash_algorithm(); - let mut handshake_hash = self.buffers_free.pop(); - self.transcript_hash(algorithm, &mut handshake_hash); - - let suite_hash = suite.hash_algorithm(); - let mut out = self.buffers_free.pop(); - let mut scratch = self.buffers_free.pop(); - let verify_data_vec = self - .crypto_context() - .generate_verify_data(&handshake_hash, is_client, suite_hash, &mut out, &mut scratch) - .map_err(Error::CryptoError)?; - - if verify_data_vec.len() != 12 { - return Err(Error::CryptoError( - crate::vendor::dimpl::CryptoError::InvalidVerifyDataLength, - )); - } - - let mut verify_data = [0u8; 12]; - verify_data.copy_from_slice(&verify_data_vec); - - self.buffers_free.push(handshake_hash); - self.buffers_free.push(out); - self.buffers_free.push(scratch); - - Ok(verify_data) - } -} - -impl RecordHandler for Engine { - fn pop_buffer(&mut self) -> Buf { - Engine::pop_buffer(self) - } - - fn push_buffer(&mut self, buffer: Buf) { - Engine::push_buffer(self, buffer); - } - - fn classify_record(&mut self, record: Record) -> Result, Error> { - let epoch = record.record().sequence.epoch; - - if record.record().content_type == ContentType::ChangeCipherSpec && epoch == 0 && self.peer_encryption_enabled { - // DTLS 1.2 peers may retransmit their last handshake flight after - // we have already enabled peer encryption. A late plaintext CCS is - // no longer actionable; queuing it would leave an unhandled control - // record in queue_rx and prevent handled app-data records behind it - // from being purged. - self.push_buffer(record.into_buffer()); - return Ok(None); - } - - if record.record().content_type == ContentType::Handshake && epoch == 0 && self.peer_encryption_enabled { - // A stale plaintext handshake can request our previous flight, but - // must not discard authenticated records alongside it in this datagram. - let dupe_seq = record - .first_handshake() - .and_then(|handshake| handshake.dupe_triggers_resend()); - self.push_buffer(record.into_buffer()); - if dupe_seq.is_some_and(|seq| seq < self.peer_handshake_seq_no) && !self.peer_handshake_confirmed { - self.flight_resend_on_dupe()?; - } - return Ok(None); - } - - if record.record().content_type == ContentType::Alert { - if epoch == 0 { - if self.peer_encryption_enabled { - // Post-handshake: epoch 0 alerts are unauthenticated, discard. - self.push_buffer(record.into_buffer()); - return Ok(None); - } - - let fatal_description = { - let fragment = record.record().fragment(record.buffer()); - (fragment.len() >= 2 && fragment[0] == 2).then(|| fragment[1]) - }; - self.push_buffer(record.into_buffer()); - - if let Some(description) = fatal_description { - return Err(Error::SecurityError(crate::vendor::dimpl::SecurityError::FatalAlert { - description, - })); - } - - return Ok(None); - } - - if !self.peer_encryption_enabled { - // A CCS earlier in this datagram may enable authentication. - // Otherwise discard_undecryptable() will discard this record. - return Ok(Some(record)); - } - - let alert = { - let fragment = record.record().fragment(record.buffer()); - (fragment.len() >= 2).then(|| (fragment[0], fragment[1])) - }; - self.push_buffer(record.into_buffer()); - - if let Some((level, description)) = alert { - if description == 0 { - self.close_notify_received = true; - return Ok(None); - } - - if level == 2 { - return Err(Error::SecurityError(crate::vendor::dimpl::SecurityError::FatalAlert { - description, - })); - } - } - - return Ok(None); - } - - if self.close_notify_received && record.record().content_type == ContentType::ApplicationData { - self.push_buffer(record.into_buffer()); - return Ok(None); - } - - Ok(Some(record)) - } - - fn is_peer_encryption_enabled(&self) -> bool { - self.peer_encryption_enabled - } - - fn replay_check(&self, seq: Sequence) -> bool { - // Only epoch 1 (encrypted) records reach here; epoch 0 records are - // returned early by the DTLS 1.2 incoming parser. - self.replay.check(seq.sequence_number) - } - - fn replay_update(&mut self, seq: Sequence) { - self.replay.update(seq.sequence_number); - } - - fn note_decrypted_record(&mut self, content_type: ContentType) { - // A decrypted (so authenticated) application-data record proves the peer - // is past its handshake, which means it received our final flight. Once - // that's known, a stale plaintext handshake (unauthenticated, replayable) - // must no longer drive a courtesy flight retransmission. The client - // confirms separately at its own completion (flight_stop_resend_timers). - if content_type == ContentType::ApplicationData { - self.peer_handshake_confirmed = true; - self.flight_dupe_timeout = Timeout::Disabled; - } - } - - fn decryption_aad_and_nonce(&self, dtls: &DTLSRecord, buf: &[u8]) -> (Aad, Nonce) { - Engine::decryption_aad_and_nonce(self, dtls, buf) - } - - fn explicit_nonce_len(&self) -> usize { - self.explicit_nonce_len - } - - fn min_protected_fragment_len(&self) -> usize { - self.min_protected_fragment_len - } - - fn decrypt_data(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), Error> { - Engine::decrypt_data(self, ciphertext, aad, nonce) - } - - fn can_discard_bad_protected_record(&self) -> bool { - self.release_app_data - } -} - -#[cfg(test)] -mod tests { - use std::time::Duration; - - use super::*; - - fn poll_packets(engine: &mut Engine, now: Instant) -> (usize, Instant) { - let mut packets = 0; - let mut output = [0; 2048]; - loop { - match engine.poll_output(&mut output, now) { - Output::Packet(_) => packets += 1, - Output::Timeout(deadline) => return (packets, deadline), - _ => panic!("unexpected engine output"), - } - } - } - - fn duplicate_handshake(seq: u16) -> Vec { - let mut packet = vec![22, 0xFE, 0xFD, 0, 0, 0, 0, 0, 0, 0, 1, 0, 12, 14, 0, 0, 0]; - packet.extend_from_slice(&seq.to_be_bytes()); - packet.extend_from_slice(&[0; 6]); - packet - } - - fn resend_engine(now: Instant) -> Engine { - let config = Config::builder() - .dangerously_set_rng_seed(42) - .build() - .expect("valid config"); - let mut engine = Engine::new(Arc::new(config), AuthMode::Psk); - engine.peer_handshake_seq_no = 3; - engine.flight_begin(4); - engine - .create_record(ContentType::ChangeCipherSpec, 0, true, |buf| buf.push(1)) - .expect("save a flight"); - assert_eq!(poll_packets(&mut engine, now).0, 1); - engine.handle_timeout(now).expect("arm flight timer"); - assert_eq!(poll_packets(&mut engine, now).0, 0); - engine - } - - #[test] - fn ordered_datagrams_can_arrive_out_of_order() { - let now = Instant::now(); - let mut engine = Engine::new(Arc::new(Config::default()), AuthMode::Psk); - engine.peer_handshake_seq_no = 2; - let later = [duplicate_handshake(3), duplicate_handshake(4)].concat(); - engine.parse_packet(&later).expect("queue sequences 3 and 4 first"); - assert_eq!(poll_packets(&mut engine, now).0, 0); - assert!(!engine.has_complete_handshake(MessageType::ServerHelloDone)); - engine - .parse_packet(&duplicate_handshake(2)) - .expect("queue sequence 2 later"); - assert_eq!(poll_packets(&mut engine, now).0, 0); - - let mut buffer = engine.pop_buffer(); - for seq in 2..=4 { - let handshake = engine - .next_handshake(MessageType::ServerHelloDone, &mut buffer) - .expect("reassemble in message order") - .expect("expected sequence is now available"); - assert_eq!(handshake.header.message_seq, seq); - assert_eq!(poll_packets(&mut engine, now).0, 0); - } - engine.push_buffer(buffer); - } - - #[test] - fn duplicate_resend_restarts_backoff_and_suppresses_other_old_messages() { - let now = Instant::now(); - let mut engine = resend_engine(now); - let initial_deadline = poll_packets(&mut engine, now).1; - let resend_at = initial_deadline - Duration::from_millis(1); - engine.handle_timeout(resend_at).expect("advance time"); - assert_eq!(poll_packets(&mut engine, resend_at).0, 0); - - engine.parse_packet(&duplicate_handshake(1)).expect("first duplicate"); - let (packets, deadline) = poll_packets(&mut engine, resend_at); - assert_eq!(packets, 1); - assert_eq!(deadline, resend_at + engine.timers.rto()); - engine.handle_timeout(resend_at).expect("resend backoff remains armed"); - assert_eq!(poll_packets(&mut engine, resend_at), (0, deadline)); - assert!(deadline > initial_deadline + Duration::from_secs(1)); - - for seq in [1, 2, 1, 2] { - engine - .parse_packet(&duplicate_handshake(seq)) - .expect("further duplicate"); - assert_eq!(poll_packets(&mut engine, resend_at), (0, deadline)); - } - engine - .handle_timeout(initial_deadline) - .expect("old deadline is cancelled"); - assert_eq!(poll_packets(&mut engine, initial_deadline), (0, deadline)); - engine.handle_timeout(deadline).expect("retry at new deadline"); - let (packets, next_deadline) = poll_packets(&mut engine, deadline); - assert_eq!(packets, 1); - assert!(next_deadline - deadline > deadline - resend_at); - engine - .parse_packet(&duplicate_handshake(2)) - .expect("duplicate after timer resend"); - assert_eq!(poll_packets(&mut engine, deadline), (0, next_deadline)); - - engine.flight_begin(6); - engine - .create_record(ContentType::ChangeCipherSpec, 0, true, |buf| buf.push(1)) - .expect("save new flight"); - assert_eq!(poll_packets(&mut engine, deadline).0, 1); - engine - .parse_packet(&duplicate_handshake(2)) - .expect("new flight duplicate"); - assert_eq!(poll_packets(&mut engine, deadline).0, 1); - } - - #[test] - fn final_flight_duplicates_back_off_without_periodic_retransmissions() { - let now = Instant::now(); - let mut engine = resend_engine(now); - engine.flight_stop_resend_timers(); - poll_packets(&mut engine, now); - - engine - .parse_packet(&duplicate_handshake(1)) - .expect("first final-flight duplicate"); - let (packets, deadline) = poll_packets(&mut engine, now); - assert_eq!(packets, 1); - assert_eq!(deadline, now + engine.timers.rto()); - engine.handle_timeout(now).expect("final-flight cooldown remains armed"); - assert_eq!(poll_packets(&mut engine, now), (0, deadline)); - assert!(deadline < now + Duration::from_secs(10)); - engine - .parse_packet(&duplicate_handshake(2)) - .expect("further final-flight duplicate"); - assert_eq!(poll_packets(&mut engine, now), (0, deadline)); - - engine.handle_timeout(deadline).expect("expire cooldown"); - assert_eq!(poll_packets(&mut engine, deadline).0, 0); - engine - .parse_packet(&duplicate_handshake(2)) - .expect("retry after cooldown"); - let (packets, next_deadline) = poll_packets(&mut engine, deadline); - assert_eq!(packets, 1); - assert_eq!(next_deadline, deadline + engine.timers.rto()); - engine.handle_timeout(deadline).expect("longer cooldown remains armed"); - assert_eq!(poll_packets(&mut engine, deadline), (0, next_deadline)); - assert!(next_deadline - deadline > deadline - now); - } - - #[test] - fn duplicate_cooldown_starts_when_resend_is_emitted() { - let now = Instant::now(); - let mut engine = resend_engine(now); - engine.flight_stop_resend_timers(); - engine - .parse_packet(&duplicate_handshake(1)) - .expect("queue final-flight resend"); - assert!(matches!( - engine.poll_output(&mut [], now), - Output::BufferTooSmall { .. } - )); - - let emitted_at = now + Duration::from_secs(10); - engine - .handle_timeout(emitted_at) - .expect("unsent resend has no cooldown"); - assert_eq!(engine.flight_dupe_timeout, Timeout::Unarmed); - let (packets, deadline) = poll_packets(&mut engine, emitted_at); - assert_eq!(packets, 1); - assert_eq!(deadline, emitted_at + engine.timers.rto()); - engine - .parse_packet(&duplicate_handshake(2)) - .expect("suppress duplicate during cooldown"); - assert_eq!(poll_packets(&mut engine, emitted_at), (0, deadline)); - } - - #[test] - fn duplicate_datagram_recycles_its_pooled_buffer() { - let mut engine = Engine::new(Arc::new(Config::default()), AuthMode::Psk); - let packet = [ - 0x14, 0xFE, 0xFD, // ChangeCipherSpec, DTLS 1.2. - 0, 0, // Epoch 0. - 0, 0, 0, 0, 0, 1, // Record sequence 1. - 0, 1, 1, // Fragment length 1 and ChangeCipherSpec body. - ]; - engine.parse_packet(&packet).expect("queue first datagram"); - let mut output = [0u8; 2048]; - assert!(matches!( - engine.poll_output(&mut output, Instant::now()), - Output::Timeout(_) - )); - - let mut buffer = engine.pop_buffer(); - buffer.resize(2048, 0xAA); - engine.push_buffer(buffer); - - engine.parse_packet(&packet).expect("discard duplicate datagram"); - assert!(matches!( - engine.poll_output(&mut output, Instant::now()), - Output::Timeout(_) - )); - assert_eq!(engine.queue_rx.len(), 1); - assert!( - engine.pop_buffer().into_vec().capacity() >= 2048, - "discarding a duplicate must preserve its reusable receive allocation" - ); - } - - #[test] - fn timing_resend_queue_failure_is_fatal() { - let now = Instant::now(); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .build() - .expect("valid config"), - ); - let mut engine = Engine::new(config, AuthMode::Psk); - engine.flight_begin(1); - engine - .create_record(ContentType::Handshake, 0, true, |fragment| fragment.push(1)) - .expect("queue original flight"); - let mut buffer = [0; 64]; - assert!(matches!(engine.poll_output(&mut buffer, now), Output::Packet(_))); - let Output::Timeout(retry_at) = engine.poll_output(&mut buffer, now) else { - panic!("expected flight timer"); - }; - engine.config = Arc::new( - Config::builder() - .max_queue_tx(0) - .build() - .expect("inject exhausted transmit capacity"), - ); - assert_eq!(engine.handle_timeout(retry_at), Err(Error::TransmitQueueFull)); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/incoming.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/incoming.rs deleted file mode 100644 index 6cd4f30a478..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/incoming.rs +++ /dev/null @@ -1,734 +0,0 @@ -use std::fmt; -use std::ops::Deref; -use std::sync::atomic::{AtomicBool, Ordering}; -use tracing::trace; - -use arrayvec::ArrayVec; -use nom::error::ErrorKind; - -use crate::vendor::dimpl::buffer::{Buf, TmpBuf}; -use crate::vendor::dimpl::crypto::{Aad, Nonce}; -use crate::vendor::dimpl::dtls12::message::{ContentType, DTLSRecord, Dtls12CipherSuite, Handshake, Sequence}; -use crate::vendor::dimpl::{Error, InternalError}; - -/// Holds both the UDP packet and the parsed result of that packet. -pub struct Incoming { - // Box is here to reduce the size of the Incoming struct - // to be passed in register instead of using memmove. - records: Box, -} - -impl Incoming { - pub fn records(&self) -> &Records { - &self.records - } - - pub fn first(&self) -> &Record { - // Invariant: Every Incoming must have at least one Record - // or the parser of Incoming returns None. - &self.records()[0] - } - - pub fn into_records(self) -> impl Iterator { - self.records.records.into_iter() - } -} - -impl Incoming { - /// Parse an incoming UDP packet - /// - /// * `packet` is the data from the UDP socket. - /// * `decrypt` provides the decryption operations for encrypted records. - /// * `cs` is the negotiated cipher suite, if any. - /// - /// Will surface parser errors. - pub fn parse_packet( - packet: &[u8], - decrypt: &mut dyn RecordHandler, - cs: Option, - ) -> Result, InternalError> { - // Parse records directly from packet, copying each record ONCE into its own buffer - let records = Records::parse(packet, decrypt, cs)?; - - // We need at least one Record to be valid. For replayed frames, we discard - // the records, hence this might be None - if records.records.is_empty() { - return Ok(None); - } - - let records = Box::new(records); - - Ok(Some(Incoming { records })) - } -} - -/// A number of records parsed from a single UDP packet. -#[derive(Debug)] -pub struct Records { - pub records: ArrayVec, -} - -impl Records { - pub fn parse( - packet: &[u8], - decrypt: &mut dyn RecordHandler, - cs: Option, - ) -> Result { - let mut parsed_records: ArrayVec = ArrayVec::new(); - if let Err(error) = Self::parse_records(packet, decrypt, cs, &mut parsed_records) { - for record in parsed_records { - decrypt.push_buffer(record.into_buffer()); - } - return Err(error); - } - - let mut records = ArrayVec::new(); - for record in parsed_records { - if let Some(record) = decrypt.classify_record(record)? { - records - .try_push(record) - .expect("filtered records cannot exceed parsed records"); - } - } - - Ok(Records { records }) - } - - fn parse_records( - mut packet: &[u8], - decrypt: &mut dyn RecordHandler, - cs: Option, - parsed_records: &mut ArrayVec, - ) -> Result<(), InternalError> { - // Find record boundaries and copy each record ONCE from the packet - while !packet.is_empty() { - if packet.len() < DTLSRecord::HEADER_LEN { - return Err(InternalError::parse_incomplete()); - } - - let length_bytes: [u8; 2] = packet[DTLSRecord::LENGTH_OFFSET].try_into().unwrap(); - let length = u16::from_be_bytes(length_bytes) as usize; - let record_end = DTLSRecord::HEADER_LEN + length; - - if packet.len() < record_end { - return Err(InternalError::parse_incomplete()); - } - - // This is the ONLY copy: packet -> record buffer - let record_slice = &packet[..record_end]; - let record = Record::parse(record_slice, decrypt, cs)?; - if let Some(record) = record { - if let Err(error) = parsed_records.try_push(record) { - decrypt.push_buffer(error.element().into_buffer()); - return Err(InternalError::too_many_records()); - } - } else { - trace!("Discarding replayed rec"); - } - - packet = &packet[record_end..]; - } - - // The receive queue preserves each datagram's internal order. Reject an - // unordered datagram before classifying controls or retaining any of it, - // so a subsequent clean retransmission can recover. The caller recycles - // all parsed records through the normal parser-error cleanup path. - if !Self::is_ordered(parsed_records, decrypt.is_peer_encryption_enabled()) { - return Err(InternalError::parse(ErrorKind::Verify)); - } - - Ok(()) - } - - fn is_ordered(records: &[Record], peer_encryption_enabled: bool) -> bool { - let mut previous_epoch = 0; - let mut previous_seq = None; - let mut seen_ccs = false; - - for record in records { - let header = record.record(); - let epoch = header.sequence.epoch; - // After peer encryption is enabled, late plaintext records are - // discarded separately and may trail authenticated application data. - if !peer_encryption_enabled && epoch < previous_epoch { - return false; - } - previous_epoch = epoch; - - if header.content_type == ContentType::ChangeCipherSpec { - seen_ccs = true; - } - if header.content_type != ContentType::Handshake { - continue; - } - if !peer_encryption_enabled && seen_ccs && epoch == 0 { - return false; - } - // A queued future-epoch Finished is still ciphertext until CCS has - // enabled decryption; its bytes cannot be treated as message_seq. - if epoch > 0 && !peer_encryption_enabled { - continue; - } - - // Check the full payload, including messages beyond the bounded - // parsed handshake list. Match its handling of malformed tails. - let mut fragment = header.fragment(record.buffer()); - while !fragment.is_empty() { - let Ok((body, handshake)) = Handshake::parse_header(fragment) else { - break; - }; - let Some(remaining) = body.get(handshake.fragment_length as usize..) else { - break; - }; - let seq = handshake.message_seq; - if previous_seq.is_some_and(|previous| seq < previous) { - return false; - } - // Equal sequences are normal for fragments of one message. - previous_seq = Some(seq); - fragment = remaining; - } - } - true - } -} - -impl Deref for Records { - type Target = [Record]; - - fn deref(&self) -> &Self::Target { - &self.records - } -} - -pub struct Record { - buffer: Buf, - // Box is here to reduce the size of the Record struct - // to be passed in register instead of using memmove. - parsed: Box, -} - -impl Record { - /// The first parse pass only parses the DTLSRecord header which is unencrypted. - /// Copies record data from UDP packet ONCE into a pooled buffer. - pub fn parse( - record_slice: &[u8], - decrypt: &mut dyn RecordHandler, - cs: Option, - ) -> Result, InternalError> { - // ONLY COPY: UDP packet slice -> pooled buffer - let mut buffer = decrypt.pop_buffer(); - buffer.extend_from_slice(record_slice); - - match Self::parse_buffer(&mut buffer, decrypt, cs) { - Ok(Some(parsed)) => Ok(Some(Record { buffer, parsed })), - result => { - decrypt.push_buffer(buffer); - result.map(|_| None) - } - } - } - - fn parse_buffer( - buffer: &mut Buf, - decrypt: &mut dyn RecordHandler, - cs: Option, - ) -> Result>, InternalError> { - let parsed = match ParsedRecord::parse(buffer, cs, 0, false) { - Ok(p) => p, - Err(e) => { - // RFC 6347 §4.1.2.7: Invalid records SHOULD be silently discarded. - // This includes epoch 0 records with invalid ContentType. - trace!("Discarding record: parse failed: {}", e); - return Ok(None); - } - }; - // There is no cipher state beyond epoch 1 (renegotiation is unsupported). - // CCS belongs to epoch 0, never to the protected epoch it enables. - if parsed.record.sequence.epoch > 1 - || (parsed.record.sequence.epoch != 0 && parsed.record.content_type == ContentType::ChangeCipherSpec) - { - return Ok(None); - } - let parsed = Box::new(parsed); - - // A coalesced datagram may contain CCS followed by protected Finished. - // Stage ciphertext opaquely until the state machine processes that CCS; - // anything still undecryptable afterward is discarded. - let is_epoch_0 = parsed.record.sequence.epoch == 0; - if is_epoch_0 || !decrypt.is_peer_encryption_enabled() { - return Ok(Some(parsed)); - } - - // We need to decrypt the record and redo the parsing. - let dtls = &parsed.record; - let sequence = dtls.sequence; - let content_type = dtls.content_type; - - // Anti-replay check (read-only, does not update window) - if !decrypt.replay_check(sequence) { - return Ok(None); - } - - let explicit_nonce_len = decrypt.explicit_nonce_len(); - if (dtls.length as usize) < decrypt.min_protected_fragment_len() { - return Ok(None); - } - - // Get a reference to the buffer - let (aad, nonce) = decrypt.decryption_aad_and_nonce(dtls, buffer); - - // Local shorthand for where the encrypted ciphertext starts - let ciph = DTLSRecord::HEADER_LEN + explicit_nonce_len; - - // The encrypted part is after the DTLS header and optional explicit nonce. - // The entire buffer is only the single record, since we chunk - // records up in Records::parse() - let ciphertext = &mut buffer[ciph..]; - - let new_len = { - let mut buffer = TmpBuf::new(ciphertext); - - // This decrypts in place. - if let Err(e) = decrypt.decrypt_data(&mut buffer, aad, nonce) { - if !decrypt.can_discard_bad_protected_record() { - return Err(e.into()); - } - - trace!("Discarding record: decrypt failed: {}", e); - return Ok(None); - } - - buffer.len() - }; - - // Decryption succeeded - now commit the replay window update. - // RFC 6347 §4.1.2.6: "The receive window is updated only if the - // MAC verification succeeds." - decrypt.replay_update(sequence); - - // The record is now authenticated. Tell the handler so it can act on a - // confirmed-genuine record (e.g. mark the peer past its handshake). - decrypt.note_decrypted_record(content_type); - - // Update the length of the record. - buffer[11] = (new_len >> 8) as u8; - buffer[12] = new_len as u8; - - let parsed = ParsedRecord::parse(buffer, cs, explicit_nonce_len, true)?; - let parsed = Box::new(parsed); - - Ok(Some(parsed)) - } - - pub fn record(&self) -> &DTLSRecord { - &self.parsed.record - } - - pub fn handshakes(&self) -> &[Handshake] { - &self.parsed.handshakes - } - - pub fn first_handshake(&self) -> Option<&Handshake> { - self.parsed.handshakes.first() - } - - pub fn is_handled(&self) -> bool { - if self.parsed.handshakes.is_empty() { - self.parsed.handled.load(Ordering::Relaxed) - } else { - self.parsed.handshakes.iter().all(|h| h.is_handled()) - } - } - - pub fn set_handled(&self) { - // Handshakes should be empty because we set_handled() on them individually - // during defragmentation. set_handled() on the record is only for non-handshakes. - assert!(self.parsed.handshakes.is_empty()); - self.parsed.handled.store(true, Ordering::Relaxed); - } - - pub fn buffer(&self) -> &[u8] { - &self.buffer - } - - pub(crate) fn into_buffer(self) -> Buf { - self.buffer - } -} - -pub struct ParsedRecord { - record: DTLSRecord, - handshakes: ArrayVec, - handled: AtomicBool, -} - -impl ParsedRecord { - pub fn parse( - input: &[u8], - cipher_suite: Option, - offset: usize, - authenticated: bool, - ) -> Result { - let (_, record) = DTLSRecord::parse(input, 0, offset)?; - - // Protected bytes must remain opaque until authentication succeeds. - let handshakes = - if record.content_type == ContentType::Handshake && (record.sequence.epoch == 0 || authenticated) { - let fragment_offset = record.fragment_range.start; - parse_handshakes(record.fragment(input), fragment_offset, cipher_suite) - } else { - ArrayVec::new() - }; - - Ok(ParsedRecord { - record, - handshakes, - handled: AtomicBool::new(false), - }) - } -} - -/// Trait abstracting record parsing-time handling for incoming records. -/// -/// This decouples the record parser from the full `Engine`, allowing the parse loop -/// to acquire buffers, decrypt records, classify control records, and queue only the records that -/// should survive into `Incoming`. -pub trait RecordHandler { - /// Acquire an empty buffer whose allocation can be reused for a record. - fn pop_buffer(&mut self) -> Buf; - /// Recycle a buffer when parsing fails or silently discards a record. - fn push_buffer(&mut self, buffer: Buf); - fn classify_record(&mut self, record: Record) -> Result, Error>; - fn is_peer_encryption_enabled(&self) -> bool; - fn replay_check(&self, seq: Sequence) -> bool; - fn replay_update(&mut self, seq: Sequence); - fn decryption_aad_and_nonce(&self, dtls: &DTLSRecord, buf: &[u8]) -> (Aad, Nonce); - fn explicit_nonce_len(&self) -> usize; - fn min_protected_fragment_len(&self) -> usize; - fn decrypt_data(&mut self, ciphertext: &mut TmpBuf, aad: Aad, nonce: Nonce) -> Result<(), Error>; - - fn can_discard_bad_protected_record(&self) -> bool { - false - } - - /// Called once a record has been successfully decrypted, i.e. authenticated. - /// Lets the handler react to a confirmed-genuine record (e.g. note that the - /// peer is past its handshake). The default does nothing. - fn note_decrypted_record(&mut self, _content_type: ContentType) {} -} - -fn parse_handshakes( - mut input: &[u8], - mut base_offset: usize, - cipher_suite: Option, -) -> ArrayVec { - let mut handshakes = ArrayVec::new(); - while !input.is_empty() { - if let Ok((remaining, handshake)) = Handshake::parse(input, base_offset, cipher_suite, true) { - let len = input.len() - remaining.len(); - base_offset += len; - input = remaining; - if handshakes.try_push(handshake).is_err() { - break; - } - } else { - break; - } - } - handshakes -} - -impl fmt::Debug for Incoming { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Incoming").field("records", &self.records()).finish() - } -} - -impl fmt::Debug for Record { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Record") - .field("record", &self.parsed.record) - .field("handshakes", &self.parsed.handshakes) - .finish() - } -} - -/* -Why it is sound to assert UnwindSafe for Incoming - -- No internal unwind boundaries: this crate does not use catch_unwind. We do not - cross panic boundaries internally while mutating state. This marker exists to - document that external callers can wrap our APIs in catch_unwind without - observing broken invariants from this type. - -- Read-only builders: our dependent builders (e.g., ParsedRecord::parse) take - only a &[u8] to the buffer and do not mutate the buffer during construction. - An unwind during builder execution therefore cannot leave the buffer partially - mutated across a boundary. - -- Decrypt-and-reparse is publish-after-complete: when decrypting we first extract - the buffer, mutate it (length update, in-place decrypt), and only then construct - a fresh Record from the fully transformed bytes. If a panic occurs mid-transformation, - the new Record is not built and the previously-built Record is dropped; no - consumer can observe a half-transformed record across an unwind boundary. - -- Interior mutability is benign across unwind: the only interior mutability is - AtomicBool "handled" flags. They are monotonic (false -> true). If an external - caller catches a panic and continues, the worst effect is conservatively - skipping work already done. This does not introduce memory unsafety or aliasing - violations, and no invariants rely on "handled implies delivery". - -Given the above, an unwind cannot leave Incoming in a state where broken -invariants are later observed across a catch_unwind boundary. Marking Incoming -as UnwindSafe is a sound assertion and clarifies behavior for callers. -*/ -impl std::panic::UnwindSafe for Incoming {} - -#[cfg(test)] -mod tests { - use crate::vendor::dimpl::buffer::BufferPool; - - use super::*; - - #[derive(Default)] - struct TestHandler { - buffers: BufferPool, - buffers_acquired: usize, - buffers_returned: usize, - classify_calls: usize, - dropped_alerts: usize, - } - - impl RecordHandler for TestHandler { - fn pop_buffer(&mut self) -> Buf { - self.buffers_acquired += 1; - self.buffers.pop() - } - - fn push_buffer(&mut self, buffer: Buf) { - self.buffers_returned += 1; - self.buffers.push(buffer); - } - - fn classify_record(&mut self, record: Record) -> Result, Error> { - self.classify_calls += 1; - if record.record().content_type == ContentType::Alert { - self.dropped_alerts += 1; - self.push_buffer(record.into_buffer()); - return Ok(None); - } - Ok(Some(record)) - } - - fn is_peer_encryption_enabled(&self) -> bool { - false - } - - fn replay_check(&self, _seq: Sequence) -> bool { - panic!("replay_check should not be called for plaintext tests"); - } - - fn replay_update(&mut self, _seq: Sequence) { - panic!("replay_update should not be called for plaintext tests"); - } - - fn decryption_aad_and_nonce(&self, _dtls: &DTLSRecord, _buf: &[u8]) -> (Aad, Nonce) { - panic!("decryption_aad_and_nonce should not be called for plaintext tests"); - } - - fn explicit_nonce_len(&self) -> usize { - panic!("explicit_nonce_len should not be called for plaintext tests"); - } - - fn min_protected_fragment_len(&self) -> usize { - panic!("min_protected_fragment_len should not be called for plaintext tests"); - } - - fn decrypt_data(&mut self, _ciphertext: &mut TmpBuf, _aad: Aad, _nonce: Nonce) -> Result<(), Error> { - panic!("decrypt_data should not be called for plaintext tests"); - } - } - - fn build_record(content_type: ContentType, epoch: u16, seq: u64, fragment: &[u8]) -> Vec { - let mut out = Vec::new(); - out.push(content_type.as_u8()); - out.extend_from_slice(&[0xFE, 0xFD]); - out.extend_from_slice(&epoch.to_be_bytes()); - out.extend_from_slice(&seq.to_be_bytes()[2..]); - out.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); - out.extend_from_slice(fragment); - out - } - - fn build_handshake(seq: u16, offset: u32, body: &[u8]) -> Vec { - let mut out = vec![14]; // ServerHelloDone; only the fragment header is parsed here. - out.extend_from_slice(&4u32.to_be_bytes()[1..]); - out.extend_from_slice(&seq.to_be_bytes()); - out.extend_from_slice(&offset.to_be_bytes()[1..]); - out.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); - out.extend_from_slice(body); - out - } - - #[test] - fn unordered_handshakes_discard_the_whole_datagram_before_classification() { - for separate_records in [false, true] { - let mut packet = build_record(ContentType::Alert, 0, 0, &[2, 40]); - let mut handshakes = Vec::new(); - for seq in [3, 1, 2] { - let handshake = build_handshake(seq, 0, &[0; 4]); - if separate_records { - packet.extend_from_slice(&build_record(ContentType::Handshake, 0, u64::from(seq), &handshake)); - } else { - handshakes.extend_from_slice(&handshake); - } - } - if !separate_records { - packet.extend_from_slice(&build_record(ContentType::Handshake, 0, 1, &handshakes)); - } - - let mut handler = TestHandler::default(); - let error = Incoming::parse_packet(&packet, &mut handler, None) - .expect_err("unordered datagrams produce an internal parse error"); - assert!(error.into_public_error().is_none()); - assert_eq!(handler.classify_calls, 0); - assert_eq!(handler.buffers_returned, handler.buffers_acquired); - } - } - - #[test] - fn unordered_handshakes_beyond_the_parsed_capacity_are_discarded() { - let mut handshakes = Vec::new(); - for seq in 0..8 { - handshakes.extend_from_slice(&build_handshake(seq, 0, &[0; 4])); - } - handshakes.extend_from_slice(&build_handshake(0, 0, &[0; 4])); - let packet = build_record(ContentType::Handshake, 0, 0, &handshakes); - let mut handler = TestHandler::default(); - let error = Incoming::parse_packet(&packet, &mut handler, None) - .expect_err("unordered datagrams produce an internal parse error"); - assert!(error.into_public_error().is_none()); - assert_eq!(handler.classify_calls, 0); - assert_eq!(handler.buffers_returned, handler.buffers_acquired); - } - - #[test] - fn ordered_datagrams_allow_fragments_and_arbitrary_starting_sequences() { - let mut packet = Vec::new(); - for (seq, offset, body) in [(4, 0, &[0; 2][..]), (4, 2, &[0; 2][..]), (5, 0, &[0; 4][..])] { - packet.extend_from_slice(&build_record( - ContentType::Handshake, - 0, - u64::from(seq), - &build_handshake(seq, offset, body), - )); - } - let mut handler = TestHandler::default(); - let incoming = Incoming::parse_packet(&packet, &mut handler, None) - .expect("parse ordered fragments") - .expect("ordered fragments must remain available"); - assert_eq!(incoming.records().len(), 3); - } - - #[test] - fn unordered_ccs_and_epochs_discard_the_whole_datagram() { - let ccs = build_record(ContentType::ChangeCipherSpec, 0, 1, &[1]); - let finished = build_record(ContentType::Handshake, 1, 0, &[0; 16]); - let handshake = build_record(ContentType::Handshake, 0, 0, &build_handshake(4, 0, &[0; 4])); - for packet in [[finished, ccs.clone()].concat(), [ccs, handshake].concat()] { - let mut handler = TestHandler::default(); - let error = Incoming::parse_packet(&packet, &mut handler, None) - .expect_err("unordered datagrams produce an internal parse error"); - assert!(error.into_public_error().is_none()); - assert_eq!(handler.classify_calls, 0); - assert_eq!(handler.buffers_returned, handler.buffers_acquired); - } - } - - #[test] - fn parse_packet_filters_control_records_after_packet_validation() { - let mut packet = Vec::new(); - packet.extend_from_slice(&build_record(ContentType::Alert, 0, 1, &[0x01, 0x00])); - packet.extend_from_slice(&build_record(ContentType::ApplicationData, 1, 2, &[0xAA, 0xBB])); - - let mut handler = TestHandler::default(); - let incoming = Incoming::parse_packet(&packet, &mut handler, None) - .unwrap() - .expect("application data record should remain"); - - assert_eq!(handler.classify_calls, 2); - assert_eq!(handler.dropped_alerts, 1); - assert_eq!(incoming.records().len(), 1); - assert_eq!(incoming.first().record().content_type, ContentType::ApplicationData); - assert_eq!(incoming.first().record().sequence.epoch, 1); - } - - #[test] - fn receive_records_reuse_pooled_buffers() { - let mut handler = TestHandler::default(); - let mut buffer = handler.pop_buffer(); - buffer.resize(2048, 0xAA); - let allocation = buffer.as_ptr(); - handler.push_buffer(buffer); - - let packet = build_record(ContentType::ApplicationData, 1, 1, &[0x11; 1500]); - for _ in 0..10_000 { - let incoming = Incoming::parse_packet(&packet, &mut handler, None) - .expect("parse application data") - .expect("packet contains a record"); - assert_eq!(incoming.first().buffer().as_ptr(), allocation); - assert_eq!(incoming.first().buffer(), packet); - for record in incoming.into_records() { - handler.push_buffer(record.into_buffer()); - } - } - } - - #[test] - fn discarded_records_return_pooled_buffers() { - let mut handler = TestHandler::default(); - let mut buffer = handler.pop_buffer(); - buffer.resize(2048, 0xAA); - let allocation = buffer.as_ptr(); - handler.push_buffer(buffer); - - let packet = build_record(ContentType::ApplicationData, 0, 1, &[0x11; 1500]); - let incoming = Incoming::parse_packet(&packet, &mut handler, None) - .expect("invalid plaintext application data is discarded"); - assert!(incoming.is_none()); - let reused = handler.pop_buffer(); - assert!(reused.is_empty()); - assert_eq!(reused.as_ptr(), allocation); - } - - #[test] - fn truncated_datagram_recycles_all_pooled_records() { - let mut handler = TestHandler::default(); - let mut packet = build_record(ContentType::ApplicationData, 1, 1, &[0x11; 1500]); - packet.push(0xFF); - - assert!(Incoming::parse_packet(&packet, &mut handler, None).is_err()); - assert_eq!(handler.classify_calls, 0); - assert_eq!( - handler.buffers_returned, handler.buffers_acquired, - "discarding a malformed datagram must recycle its accepted records" - ); - } - - #[test] - fn oversized_datagram_recycles_all_pooled_records() { - let mut handler = TestHandler::default(); - let mut packet = Vec::new(); - for sequence in 0..9 { - packet.extend_from_slice(&build_record(ContentType::ApplicationData, 1, sequence, &[0x11; 32])); - } - - assert!(Incoming::parse_packet(&packet, &mut handler, None).is_err()); - assert_eq!(handler.classify_calls, 0); - assert_eq!( - handler.buffers_returned, handler.buffers_acquired, - "discarding a datagram with too many records must recycle every record" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate.rs deleted file mode 100644 index bb7534ff5bb..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate.rs +++ /dev/null @@ -1,102 +0,0 @@ -use super::Asn1Cert; -use crate::vendor::dimpl::buffer::Buf; -use arrayvec::ArrayVec; -use nom::Err; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::{IResult, number::complete::be_u24}; - -#[derive(Debug, PartialEq, Eq)] -pub struct Certificate { - pub certificate_list: ArrayVec, -} - -impl Certificate { - pub fn new(certificate_list: ArrayVec) -> Self { - Certificate { certificate_list } - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Certificate> { - let original_input = input; - let (input, total_len) = be_u24(input)?; - let (input, certs_data) = take(total_len)(input)?; - - // Calculate base offset for certs_data within the root buffer - let certs_base_offset = base_offset + (certs_data.as_ptr() as usize - original_input.as_ptr() as usize); - - // Parse certificates manually with dynamic base_offset - let mut certificate_list = ArrayVec::new(); - let mut rest = certs_data; - while !rest.is_empty() { - let offset = certs_base_offset + (rest.as_ptr() as usize - certs_data.as_ptr() as usize); - let (new_rest, cert) = Asn1Cert::parse(rest, offset)?; - certificate_list - .try_push(cert) - .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; - rest = new_rest; - } - - Ok((input, Certificate { certificate_list })) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - let total_len: usize = self - .certificate_list - .iter() - .map(|cert| 3 + cert.as_slice(buf).len()) - .sum(); - output.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]); - - for cert in &self.certificate_list { - let cert_data = cert.as_slice(buf); - output.extend_from_slice(&(cert_data.len() as u32).to_be_bytes()[1..]); - output.extend_from_slice(cert_data); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0x00, 0x00, 0x0C, // Total length - 0x00, 0x00, 0x04, // Certificate 1 length - 0x01, 0x02, 0x03, 0x04, // Certificate 1 data - 0x00, 0x00, 0x02, // Certificate 2 length - 0x05, 0x06, // Certificate 2 data - ]; - - #[test] - fn roundtrip() { - // Parse the message with base_offset 0 - let (rest, parsed) = Certificate::parse(MESSAGE, 0).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - parsed.serialize(MESSAGE, &mut serialized); - assert_eq!(&*serialized, MESSAGE); - } - - #[test] - fn rejects_too_many_certificates() { - let mut message = Vec::new(); - let total_len = 33 * 4; - message.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]); - for _ in 0..33 { - message.extend_from_slice(&[0x00, 0x00, 0x01, 0xAA]); - } - - let result = Certificate::parse(&message, 0); - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "oversized certificate list should fail with LengthValue" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate_request.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate_request.rs deleted file mode 100644 index 3dbd0a4061d..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate_request.rs +++ /dev/null @@ -1,221 +0,0 @@ -use super::{CertificateTypeVec, ClientCertificateType, DistinguishedName}; -use super::{SignatureAndHashAlgorithm, SignatureAndHashAlgorithmVec}; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::util::{many0, many1}; -use arrayvec::ArrayVec; -use nom::Err; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::{be_u8, be_u16}; -use nom::{IResult, bytes::complete::take}; - -#[derive(Debug, PartialEq, Eq)] -pub struct CertificateRequest { - pub certificate_types: CertificateTypeVec, - pub supported_signature_algorithms: SignatureAndHashAlgorithmVec, - pub certificate_authorities: ArrayVec, -} - -impl CertificateRequest { - pub fn new( - certificate_types: CertificateTypeVec, - supported_signature_algorithms: SignatureAndHashAlgorithmVec, - certificate_authorities: ArrayVec, - ) -> Self { - CertificateRequest { - certificate_types, - supported_signature_algorithms, - certificate_authorities, - } - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateRequest> { - let original_input = input; - let (input, cert_types_len) = be_u8(input)?; - let (input, input_type) = take(cert_types_len)(input)?; - let (rest, certificate_types) = - many1(ClientCertificateType::parse, ClientCertificateType::is_supported)(input_type)?; - if !rest.is_empty() { - return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); - } - - let (input, sig_algs_len) = be_u16(input)?; - let (input, input_sigs) = take(sig_algs_len)(input)?; - let (rest, supported_signature_algorithms) = many0( - SignatureAndHashAlgorithm::parse, - SignatureAndHashAlgorithm::is_supported, - )(input_sigs)?; - if !rest.is_empty() { - return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); - } - - let (input, cert_auths_len) = be_u16(input)?; - let (input, input_auths) = take(cert_auths_len)(input)?; - - // Calculate base offset for input_auths within the root buffer - let auths_base_offset = base_offset + (input_auths.as_ptr() as usize - original_input.as_ptr() as usize); - - // Parse certificate authorities manually with dynamic base_offset - let mut certificate_authorities = ArrayVec::new(); - let mut rest = input_auths; - while !rest.is_empty() { - let offset = auths_base_offset + (rest.as_ptr() as usize - input_auths.as_ptr() as usize); - let (new_rest, auth) = DistinguishedName::parse(rest, offset)?; - certificate_authorities - .try_push(auth) - .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; - rest = new_rest; - } - - Ok(( - input, - CertificateRequest { - certificate_types, - supported_signature_algorithms, - certificate_authorities, - }, - )) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - output.push(self.certificate_types.len() as u8); - for cert_type in &self.certificate_types { - output.push(cert_type.as_u8()); - } - - let sig_algs_len = (self.supported_signature_algorithms.len() * 2) as u16; - output.extend_from_slice(&sig_algs_len.to_be_bytes()); - for sig_alg in &self.supported_signature_algorithms { - output.extend_from_slice(&sig_alg.as_u16().to_be_bytes()); - } - - let cert_auths_len: usize = self - .certificate_authorities - .iter() - .map(|name| 2 + name.as_slice(buf).len()) - .sum(); - output.extend_from_slice(&(cert_auths_len as u16).to_be_bytes()); - for name in &self.certificate_authorities { - let name_data = name.as_slice(buf); - output.extend_from_slice(&(name_data.len() as u16).to_be_bytes()); - output.extend_from_slice(name_data); - } - } - - /// Checks if the CertificateRequest supports a specific hash algorithm - pub fn supports_hash_algorithm(&self, hash_algorithm: super::HashAlgorithm) -> bool { - self.supported_signature_algorithms - .iter() - .any(|algo| algo.hash == hash_algorithm) - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - // Test message with recognized values: - // - Certificate type: 0x40 (ECDSA_SIGN) - // - Signature algorithms: SHA256/ECDSA (0x04, 0x03), SHA256/RSA (0x04, 0x01) - const MESSAGE: &[u8] = &[ - 0x01, // Certificate types length (1 byte) - 0x40, // Certificate type: ECDSA_SIGN - 0x00, 0x04, // Signature algorithms length (4 bytes = 2 algorithms) - 0x04, 0x03, // SHA256/ECDSA - 0x04, 0x01, // SHA256/RSA - 0x00, 0x0C, // Certificate authorities length - 0x00, 0x04, // Distinguished name 1 length - 0x01, 0x02, 0x03, 0x04, // Distinguished name 1 data - 0x00, 0x04, // Distinguished name 2 length - 0x05, 0x06, 0x07, 0x08, // Distinguished name 2 data - ]; - - #[test] - fn filters_unsupported_rsa_signature_algorithm() { - // Parse the message with base_offset 0 - let (rest, parsed) = CertificateRequest::parse(MESSAGE, 0).unwrap(); - assert!(rest.is_empty()); - assert_eq!(parsed.supported_signature_algorithms.len(), 1); - assert_eq!( - parsed.supported_signature_algorithms[0], - SignatureAndHashAlgorithm::new( - super::super::HashAlgorithm::SHA256, - super::super::SignatureAlgorithm::ECDSA, - ) - ); - - // Serialization must not re-advertise the filtered RSA algorithm. - let mut serialized = Buf::new(); - parsed.serialize(MESSAGE, &mut serialized); - let expected = [ - 0x01, // Certificate types length (1 byte) - 0x40, // Certificate type: ECDSA_SIGN - 0x00, 0x02, // Signature algorithms length (2 bytes = 1 algorithm) - 0x04, 0x03, // SHA256/ECDSA - 0x00, 0x0C, // Certificate authorities length - 0x00, 0x04, // Distinguished name 1 length - 0x01, 0x02, 0x03, 0x04, // Distinguished name 1 data - 0x00, 0x04, // Distinguished name 2 length - 0x05, 0x06, 0x07, 0x08, // Distinguished name 2 data - ]; - assert_eq!(&*serialized, expected); - } - - #[test] - fn filters_unsupported_types() { - // Message with unsupported certificate types and signature algorithms - let message_with_unsupported: &[u8] = &[ - 0x03, // Certificate types length (3 bytes) - 0x01, // RSA_SIGN (unsupported, filtered) - 0x40, // ECDSA_SIGN (supported) - 0x02, // DSS_SIGN (unsupported, filtered) - 0x00, 0x06, // Signature algorithms length (6 bytes = 3 algorithms) - 0x05, 0x02, // SHA384/DSA (unsupported) - 0x04, 0x03, // SHA256/ECDSA (supported) - 0x01, 0x01, // MD5/RSA (unsupported) - 0x00, 0x00, // Certificate authorities length (0) - ]; - - let (rest, parsed) = CertificateRequest::parse(message_with_unsupported, 0).unwrap(); - assert!(rest.is_empty()); - - // Only supported types should remain - assert_eq!(parsed.certificate_types.len(), 1); - assert_eq!(parsed.certificate_types[0], ClientCertificateType::ECDSA_SIGN); - - assert_eq!(parsed.supported_signature_algorithms.len(), 1); - assert_eq!( - parsed.supported_signature_algorithms[0], - SignatureAndHashAlgorithm::new( - super::super::HashAlgorithm::SHA256, - super::super::SignatureAlgorithm::ECDSA - ) - ); - } - - #[test] - fn too_many_certificate_authorities_are_rejected() { - let mut message = Vec::new(); - message.push(1); // Certificate types length - message.push(ClientCertificateType::ECDSA_SIGN.as_u8()); - message.extend_from_slice(&0u16.to_be_bytes()); // Signature algorithms length - - let count = 33; - let cert_auths_len = count * 3; - message.extend_from_slice(&(cert_auths_len as u16).to_be_bytes()); - for _ in 0..count { - message.extend_from_slice(&1u16.to_be_bytes()); - message.push(0xAA); - } - - let result = CertificateRequest::parse(&message, 0); - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "too many certificate authorities should fail with LengthValue" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate_verify.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate_verify.rs deleted file mode 100644 index 707ed139eec..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/certificate_verify.rs +++ /dev/null @@ -1,43 +0,0 @@ -use super::DigitallySigned; -use crate::vendor::dimpl::buffer::Buf; -use nom::IResult; - -#[derive(Debug, PartialEq, Eq)] -pub struct CertificateVerify { - pub signed: DigitallySigned, -} - -impl CertificateVerify { - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateVerify> { - let (input, signed) = DigitallySigned::parse(input, base_offset)?; - Ok((input, CertificateVerify { signed })) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - self.signed.serialize(buf, output); - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0x04, 0x01, // SignatureAndHashAlgorithm (SHA256 + RSA) - 0x00, 0x04, // Signature length - 0x01, 0x02, 0x03, 0x04, // Signature data - ]; - - #[test] - fn roundtrip() { - // Parse the message with base_offset 0 - let (rest, parsed) = CertificateVerify::parse(MESSAGE, 0).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - parsed.serialize(MESSAGE, &mut serialized); - assert_eq!(&*serialized, MESSAGE); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/client_hello.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/client_hello.rs deleted file mode 100644 index eb65d84094a..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/client_hello.rs +++ /dev/null @@ -1,396 +0,0 @@ -use super::{CipherSuiteVec, CompressionMethod, CompressionMethodVec, Dtls12CipherSuite}; -use super::{Cookie, Extension, ExtensionType, ProtocolVersion, Random, SessionId}; -use super::{ECPointFormatsExtension, SignatureAlgorithmsExtension}; -use super::{NamedGroupVec, SignatureAndHashAlgorithmVec, SrtpProfileVec}; -use super::{SupportedGroupsExtension, UseSrtpExtension}; -use arrayvec::ArrayVec; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::{be_u8, be_u16}; -use nom::{Err, IResult}; - -use super::extension::ExtensionVec; -use crate::vendor::dimpl::Config; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::util::many1; - -#[derive(Debug, PartialEq, Eq)] -pub struct ClientHello { - pub client_version: ProtocolVersion, - pub random: Random, - pub session_id: SessionId, - pub cookie: Cookie, - pub cipher_suites: CipherSuiteVec, - pub compression_methods: CompressionMethodVec, - pub extensions: ExtensionVec, - // Receive-side values; outbound serialization uses the raw extensions above. - parsed_extensions: ParsedExtensions, -} - -#[derive(Debug, Default, PartialEq, Eq)] -struct ParsedExtensions { - supported_groups: Option, - signature_algorithms: Option, - srtp_profiles: Option, -} - -impl ClientHello { - pub fn new( - client_version: ProtocolVersion, - random: Random, - session_id: SessionId, - cookie: Cookie, - cipher_suites: CipherSuiteVec, - compression_methods: CompressionMethodVec, - ) -> Self { - ClientHello { - client_version, - random, - session_id, - cookie, - cipher_suites, - compression_methods, - extensions: ArrayVec::new(), - parsed_extensions: ParsedExtensions::default(), - } - } - - /// Add all required extensions for DTLS handshake - pub fn with_extensions(mut self, buf: &mut Buf, config: &Config) -> Self { - // Clear the extension data buffer - buf.clear(); - - // First write all extension data - let mut ranges = ArrayVec::<(ExtensionType, usize, usize), 8>::new(); - - // Check if provider has ECDH support - let has_ecdh = config.crypto_provider().has_ecdh(); - - // Add supported groups and EC point formats if using ECDH - if has_ecdh { - // Add supported groups extension from config - let mut groups = super::NamedGroupVec::new(); - for kx_group in config.kx_groups() { - groups.push(kx_group.name()); - } - let supported_groups = SupportedGroupsExtension { groups }; - let start_pos = buf.len(); - supported_groups.serialize(buf); - ranges.push((ExtensionType::SupportedGroups, start_pos, buf.len())); - - // Add EC point formats extension - let ec_point_formats = ECPointFormatsExtension::default(); - let start_pos = buf.len(); - ec_point_formats.serialize(buf); - ranges.push((ExtensionType::EcPointFormats, start_pos, buf.len())); - } - - // Add signature algorithms extension (required for TLS 1.2+) - let signature_algorithms = SignatureAlgorithmsExtension::default(); - let start_pos = buf.len(); - signature_algorithms.serialize(buf); - ranges.push((ExtensionType::SignatureAlgorithms, start_pos, buf.len())); - - // Add use_srtp extension for DTLS-SRTP support - let use_srtp = UseSrtpExtension::default(); - let start_pos = buf.len(); - use_srtp.serialize(buf); - ranges.push((ExtensionType::UseSrtp, start_pos, buf.len())); - - // // Add session_ticket extension (empty) - // let start_pos = buf.len(); - // buf.extend_from_slice(&[0x00]); // Empty extension data - // ranges.push((ExtensionType::SessionTicket, start_pos, buf.len())); - - let need_etm = self.cipher_suites.iter().any(|suite| suite.need_encrypt_then_mac()); - if need_etm { - // Add encrypt_then_mac extension (empty) - let start_pos = buf.len(); - buf.extend_from_slice(&[0x00]); // Empty extension data - ranges.push((ExtensionType::EncryptThenMac, start_pos, buf.len())); - } - - let start_pos = buf.len(); - ranges.push(( - ExtensionType::ExtendedMasterSecret, - start_pos, - start_pos, // No data at all - )); - - // Now create all extensions using ranges - for (extension_type, start, end) in ranges { - self.extensions.push(Extension { - extension_type, - extension_data_range: start..end, - }); - } - - self - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientHello> { - let original_input = input; - let (input, client_version) = ProtocolVersion::parse(input)?; - let (input, random) = Random::parse(input)?; - let (input, session_id) = SessionId::parse(input)?; - let (input, cookie) = Cookie::parse(input)?; - let (input, cipher_suites_len) = be_u16(input)?; - let (input, input_cipher) = take(cipher_suites_len)(input)?; - let (rest, cipher_suites) = many1(Dtls12CipherSuite::parse, Dtls12CipherSuite::is_supported)(input_cipher)?; - if !rest.is_empty() { - return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); - } - let (input, compression_methods_len) = be_u8(input)?; - let (input, input_compression) = take(compression_methods_len)(input)?; - let (rest, compression_methods) = - many1(CompressionMethod::parse, CompressionMethod::is_supported)(input_compression)?; - if !rest.is_empty() { - return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); - } - - // Calculate base_offset for extensions parsing - let consumed = input.as_ptr() as usize - original_input.as_ptr() as usize; - let extensions_base_offset = base_offset + consumed; - - // Parse extensions if there are any left - let mut parsed_extensions = ParsedExtensions::default(); - let (remaining_input, extensions) = - Self::parse_extensions(input, extensions_base_offset, &mut parsed_extensions)?; - - Ok(( - remaining_input, - ClientHello { - client_version, - random, - session_id, - cookie, - cipher_suites, - compression_methods, - extensions, - parsed_extensions, - }, - )) - } - - /// Parse extensions from the input, filtering to only known extension types - fn parse_extensions<'a>( - input: &'a [u8], - base_offset: usize, - parsed: &mut ParsedExtensions, - ) -> IResult<&'a [u8], ExtensionVec> { - let mut extensions = ArrayVec::new(); - - // Early return if input is empty - if input.is_empty() { - return Ok((input, extensions)); - } - - let original_input = input; - - // Parse extensions length - let (remaining, extensions_len) = be_u16(input)?; - - // Early return if extensions length is 0 - if extensions_len == 0 { - return Ok((remaining, extensions)); - } - - // Take the extensions data - let (remaining, extensions_data) = take(extensions_len)(remaining)?; - - // Calculate base_offset for extension data - let consumed = extensions_data.as_ptr() as usize - original_input.as_ptr() as usize; - let data_base_offset = base_offset + consumed; - - // Parse individual extensions, filtering to only known types - let mut extensions_rest = extensions_data; - let mut current_offset = data_base_offset; - while !extensions_rest.is_empty() { - let before_len = extensions_rest.len(); - let (rest, extension) = Extension::parse(extensions_rest, current_offset)?; - let parsed_len = before_len - rest.len(); - current_offset += parsed_len; - - // Only keep supported extension types - if extension.extension_type.is_supported() { - if extensions - .iter() - .any(|existing| existing.extension_type == extension.extension_type) - { - return Err(Err::Failure(Error::new(extensions_rest, ErrorKind::LengthValue))); - } - // Parse payloads once, retaining the values used by the server. - // Ranges are absolute, while this input starts at base_offset. - let range = &extension.extension_data_range; - let data = &original_input[range.start - base_offset..range.end - base_offset]; - match extension.extension_type { - ExtensionType::SupportedGroups => { - parsed.supported_groups = Some(SupportedGroupsExtension::parse(data)?.1.groups); - } - ExtensionType::SignatureAlgorithms => { - parsed.signature_algorithms = Some( - SignatureAlgorithmsExtension::parse(data)? - .1 - .supported_signature_algorithms, - ); - } - ExtensionType::UseSrtp => { - parsed.srtp_profiles = Some(UseSrtpExtension::parse(data)?.1.profiles); - } - ExtensionType::EcPointFormats => { - ECPointFormatsExtension::parse(data)?; - } - _ => {} - } - extensions - .try_push(extension) - .map_err(|_| Err::Failure(Error::new(extensions_rest, ErrorKind::LengthValue)))?; - } - extensions_rest = rest; - } - - Ok((remaining, extensions)) - } - - pub fn supported_groups(&self) -> Option<&NamedGroupVec> { - self.parsed_extensions.supported_groups.as_ref() - } - - pub fn signature_algorithms(&self) -> Option<&SignatureAndHashAlgorithmVec> { - self.parsed_extensions.signature_algorithms.as_ref() - } - - pub fn srtp_profiles(&self) -> Option<&SrtpProfileVec> { - self.parsed_extensions.srtp_profiles.as_ref() - } - - pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { - output.extend_from_slice(&self.client_version.as_u16().to_be_bytes()); - self.random.serialize(output); - output.push(self.session_id.len() as u8); - output.extend_from_slice(&self.session_id); - output.push(self.cookie.len() as u8); - output.extend_from_slice(&self.cookie); - output.extend_from_slice(&(self.cipher_suites.len() as u16 * 2).to_be_bytes()); - for suite in &self.cipher_suites { - output.extend_from_slice(&suite.as_u16().to_be_bytes()); - } - output.push(self.compression_methods.len() as u8); - for method in &self.compression_methods { - output.push(method.as_u8()); - } - - // Add extensions if any - if !self.extensions.is_empty() { - // First calculate total extensions length - let mut extensions_len = 0; - for ext in &self.extensions { - // Extension type (2) + Extension length (2) + Extension data - let ext_data = ext.extension_data(source_buf); - extensions_len += 4 + ext_data.len(); - } - - // Write extensions length - output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); - - // Write each extension - for ext in &self.extensions { - ext.serialize(source_buf, output); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 - // Random - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, // - 0x01, // SessionId length - 0xAA, // SessionId - 0x01, // Cookie length - 0xBB, // Cookie - 0x00, 0x04, // Dtls12CipherSuites length - 0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - 0xC0, 0x2C, // Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - 0x01, // CompressionMethods length - 0x00, // CompressionMethod::Null - ]; - - #[test] - fn roundtrip() { - let random = Random::parse(&MESSAGE[2..34]).unwrap().1; - let session_id = SessionId::try_new(&[0xAA]).unwrap(); - let cookie = Cookie::try_new(&[0xBB]).unwrap(); - let mut cipher_suites = ArrayVec::new(); - cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256); - cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384); - let mut compression_methods = ArrayVec::new(); - compression_methods.push(CompressionMethod::Null); - - let client_hello = ClientHello::new( - ProtocolVersion::DTLS1_2, - random, - session_id, - cookie, - cipher_suites, - compression_methods, - ); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - client_hello.serialize(&[], &mut serialized); - assert_eq!(&*serialized, MESSAGE); - - // Parse and compare with original - let (rest, parsed) = ClientHello::parse(&serialized, 0).unwrap(); - assert_eq!(parsed, client_hello); - - assert!(rest.is_empty()); - } - - #[test] - fn session_id_too_long() { - let mut message = MESSAGE.to_vec(); - message[34] = 0x21; // SessionId length (33, which is too long) - - let result = ClientHello::parse(&message, 0); - assert!(result.is_err()); - } - - #[test] - fn cookie_too_long() { - let mut message = MESSAGE.to_vec(); - message[36] = 0xFF; // Cookie length (255, which is too long) - - let result = ClientHello::parse(&message, 0); - assert!(result.is_err()); - } - - #[test] - fn duplicate_supported_extensions_are_rejected() { - for count in [2, 9] { - let mut message = MESSAGE.to_vec(); - message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); - for _ in 0..count { - message.extend_from_slice(&ExtensionType::ExtendedMasterSecret.as_u16().to_be_bytes()); - message.extend_from_slice(&0u16.to_be_bytes()); - } - - let result = ClientHello::parse(&message, 0); - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "duplicate supported extensions should fail with LengthValue" - ); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/client_key_exchange.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/client_key_exchange.rs deleted file mode 100644 index 021576dbc3b..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/client_key_exchange.rs +++ /dev/null @@ -1,209 +0,0 @@ -use super::KeyExchangeAlgorithm; -use super::{CurveType, NamedGroup}; -use crate::vendor::dimpl::buffer::Buf; -use nom::bytes::complete::take; -use nom::error::Error; -use nom::number::complete::be_u8; -use nom::{Err, IResult}; -use std::ops::Range; - -#[derive(Debug, PartialEq, Eq)] -pub struct ClientKeyExchange { - pub exchange_keys: ExchangeKeys, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum ExchangeKeys { - Ecdh(ClientEcdhKeys), - Psk(ClientPskKeys), -} - -/// ECDHE key exchange parameters -#[derive(Debug, PartialEq, Eq)] -pub struct ClientEcdhKeys { - pub curve_type: CurveType, - pub named_group: NamedGroup, - pub public_key_range: Range, -} - -impl ClientEcdhKeys { - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientEcdhKeys> { - let original_input = input; - let (input, public_key_length) = be_u8(input)?; - let (input, public_key_slice) = take(public_key_length)(input)?; - - // Calculate absolute range in root buffer - let relative_offset = public_key_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + public_key_slice.len(); - - Ok(( - input, - ClientEcdhKeys { - // In ClientKeyExchange, we don't include curve_type and named_group - // since they're already established during ServerKeyExchange - curve_type: CurveType::NamedCurve, // Default - named_group: NamedGroup::Secp256r1, // Default - public_key_range: start..end, - }, - )) - } - - pub fn public_key<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.public_key_range.clone()] - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - // For client key exchange, we only need to include the public key length and value - // The curve_type and named_group are already established during ServerKeyExchange - let public_key = self.public_key(buf); - output.push(public_key.len() as u8); - output.extend_from_slice(public_key); - } -} - -impl ClientKeyExchange { - pub fn parse( - input: &[u8], - base_offset: usize, - key_exchange_algorithm: KeyExchangeAlgorithm, - ) -> IResult<&[u8], ClientKeyExchange> { - let (input, exchange_keys) = match key_exchange_algorithm { - KeyExchangeAlgorithm::EECDH => { - let (input, ecdh_keys) = ClientEcdhKeys::parse(input, base_offset)?; - (input, ExchangeKeys::Ecdh(ecdh_keys)) - } - KeyExchangeAlgorithm::PSK => { - let (input, psk_keys) = ClientPskKeys::parse(input, base_offset)?; - (input, ExchangeKeys::Psk(psk_keys)) - } - _ => return Err(Err::Failure(Error::new(input, nom::error::ErrorKind::Tag))), - }; - - Ok((input, ClientKeyExchange { exchange_keys })) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - match &self.exchange_keys { - ExchangeKeys::Ecdh(ecdh_keys) => ecdh_keys.serialize(buf, output), - ExchangeKeys::Psk(psk_keys) => psk_keys.serialize(buf, output), - } - } - - /// Helper to serialize directly from public key bytes (for sending) - pub fn serialize_from_bytes(public_key: &[u8], output: &mut Buf) { - output.push(public_key.len() as u8); - output.extend_from_slice(public_key); - } -} - -/// PSK identity sent by the client (RFC 4279 §2). -/// -/// Wire format: `uint16 identity_length + identity` -#[derive(Debug, PartialEq, Eq)] -pub struct ClientPskKeys { - pub identity_range: Range, -} - -impl ClientPskKeys { - pub fn identity<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.identity_range.clone()] - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientPskKeys> { - let original_input = input; - let (input, identity_len) = nom::number::complete::be_u16(input)?; - let (input, identity_slice) = take(identity_len as usize)(input)?; - - let relative_offset = identity_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + identity_slice.len(); - - Ok(( - input, - ClientPskKeys { - identity_range: start..end, - }, - )) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - let identity = self.identity(buf); - output.extend_from_slice(&(identity.len() as u16).to_be_bytes()); - output.extend_from_slice(identity); - } - - /// Serialize directly from identity bytes (for sending). - pub fn serialize_from_bytes(identity: &[u8], output: &mut Buf) { - output.extend_from_slice(&(identity.len() as u16).to_be_bytes()); - output.extend_from_slice(identity); - } -} - -#[cfg(test)] -mod test { - use super::super::KeyExchangeAlgorithm; - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const ECDH_MESSAGE: &[u8] = &[ - 0x04, // Public key length - 0x01, 0x02, 0x03, 0x04, // Public key data - ]; - - #[test] - fn roundtrip_ecdh() { - // Parse the message with base_offset 0 - let (rest, parsed) = ClientKeyExchange::parse(ECDH_MESSAGE, 0, KeyExchangeAlgorithm::EECDH).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to ECDH_MESSAGE - let mut serialized = Buf::new(); - parsed.serialize(ECDH_MESSAGE, &mut serialized); - assert_eq!(&*serialized, ECDH_MESSAGE); - } - - #[test] - fn psk_roundtrip() { - const PSK_MESSAGE: &[u8] = &[ - 0x00, 0x05, // identity length = 5 - b'h', b'e', b'l', b'l', b'o', - ]; - let (rest, parsed) = ClientKeyExchange::parse(PSK_MESSAGE, 0, KeyExchangeAlgorithm::PSK).unwrap(); - assert!(rest.is_empty()); - - let ExchangeKeys::Psk(psk) = &parsed.exchange_keys else { - panic!("expected Psk variant"); - }; - assert_eq!(&PSK_MESSAGE[psk.identity_range.clone()], b"hello"); - - let mut serialized = Buf::new(); - parsed.serialize(PSK_MESSAGE, &mut serialized); - assert_eq!(&*serialized, PSK_MESSAGE); - } - - #[test] - fn psk_rejects_oversized_length() { - // identity_length=0x0064 (100) but only 3 bytes follow - parser must fail - let bad: &[u8] = &[0x00, 0x64, b'a', b'b', b'c']; - let result = ClientKeyExchange::parse(bad, 0, KeyExchangeAlgorithm::PSK); - assert!( - result.is_err(), - "parser must reject PSK identity shorter than advertised length" - ); - } - - #[test] - fn psk_empty_identity() { - // identity_length=0 is wire-legal; parser should accept an empty range. - // (RFC 4279 §5.1 says server MAY reject this - that's an application - // policy decision, not a parse error.) - let empty: &[u8] = &[0x00, 0x00]; - let (rest, parsed) = ClientKeyExchange::parse(empty, 0, KeyExchangeAlgorithm::PSK).unwrap(); - assert!(rest.is_empty()); - let ExchangeKeys::Psk(psk) = &parsed.exchange_keys else { - panic!("expected Psk variant"); - }; - assert!(psk.identity_range.is_empty()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/digitally_signed.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/digitally_signed.rs deleted file mode 100644 index 1d8cfa2ac68..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/digitally_signed.rs +++ /dev/null @@ -1,68 +0,0 @@ -use super::SignatureAndHashAlgorithm; -use crate::vendor::dimpl::buffer::Buf; -use nom::number::complete::be_u16; -use nom::{IResult, bytes::complete::take}; -use std::ops::Range; - -#[derive(Debug, PartialEq, Eq)] -pub struct DigitallySigned { - pub algorithm: SignatureAndHashAlgorithm, - pub signature_range: Range, -} - -impl DigitallySigned { - pub fn signature<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.signature_range.clone()] - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], DigitallySigned> { - let original_input = input; - let (rest, algorithm) = SignatureAndHashAlgorithm::parse(input)?; - let (rest, signature_len) = be_u16(rest)?; - let (rest, signature_slice) = take(signature_len)(rest)?; - - // Calculate absolute range in root buffer - let relative_offset = signature_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + signature_slice.len(); - - Ok(( - rest, - DigitallySigned { - algorithm, - signature_range: start..end, - }, - )) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - output.extend_from_slice(&self.algorithm.as_u16().to_be_bytes()); - let signature = self.signature(buf); - output.extend_from_slice(&(signature.len() as u16).to_be_bytes()); - output.extend_from_slice(signature); - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0x04, 0x01, // SignatureAndHashAlgorithm (SHA256 + RSA) - 0x00, 0x04, // Signature length - 0x01, 0x02, 0x03, 0x04, // Signature data - ]; - - #[test] - fn roundtrip() { - // Parse the message with base_offset 0 - let (rest, parsed) = DigitallySigned::parse(MESSAGE, 0).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - parsed.serialize(MESSAGE, &mut serialized); - assert_eq!(&*serialized, MESSAGE); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extension.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extension.rs deleted file mode 100644 index f3cd24fcad2..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extension.rs +++ /dev/null @@ -1,237 +0,0 @@ -use crate::vendor::dimpl::buffer::Buf; -use arrayvec::ArrayVec; -use nom::{IResult, bytes::complete::take, number::complete::be_u16}; -use std::{fmt, ops::Range}; - -pub type ExtensionVec = ArrayVec; - -#[derive(Debug, PartialEq, Eq, Default)] -pub struct Extension { - pub extension_type: ExtensionType, - pub extension_data_range: Range, -} - -impl Extension { - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Extension> { - let original_input = input; - let (input, extension_type) = ExtensionType::parse(input)?; - let (input, extension_length) = be_u16(input)?; - let (input, extension_data_slice) = if extension_length > 0 { - take(extension_length)(input)? - } else { - (input, &input[0..0]) - }; - - // Calculate absolute range in root buffer - let relative_offset = extension_data_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + extension_data_slice.len(); - - Ok(( - input, - Extension { - extension_type, - extension_data_range: start..end, - }, - )) - } - - pub fn extension_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.extension_data_range.clone()] - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - let extension_data = self.extension_data(buf); - output.extend_from_slice(&self.extension_type.as_u16().to_be_bytes()); - output.extend_from_slice(&(extension_data.len() as u16).to_be_bytes()); - if !extension_data.is_empty() { - output.extend_from_slice(extension_data); - } - } -} - -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct ExtensionType(u16); - -#[allow(non_upper_case_globals)] -impl ExtensionType { - pub const ServerName: Self = Self(0x0000); - pub const MaxFragmentLength: Self = Self(0x0001); - pub const ClientCertificateUrl: Self = Self(0x0002); - pub const TrustedCaKeys: Self = Self(0x0003); - pub const TruncatedHmac: Self = Self(0x0004); - pub const StatusRequest: Self = Self(0x0005); - pub const UserMapping: Self = Self(0x0006); - pub const ClientAuthz: Self = Self(0x0007); - pub const ServerAuthz: Self = Self(0x0008); - pub const CertType: Self = Self(0x0009); - pub const SupportedGroups: Self = Self(0x000A); - pub const EcPointFormats: Self = Self(0x000B); - pub const Srp: Self = Self(0x000C); - pub const SignatureAlgorithms: Self = Self(0x000D); - pub const UseSrtp: Self = Self(0x000E); - pub const Heartbeat: Self = Self(0x000F); - pub const ApplicationLayerProtocolNegotiation: Self = Self(0x0010); - pub const StatusRequestV2: Self = Self(0x0011); - pub const SignedCertificateTimestamp: Self = Self(0x0012); - pub const ClientCertificateType: Self = Self(0x0013); - pub const ServerCertificateType: Self = Self(0x0014); - pub const Padding: Self = Self(0x0015); - pub const EncryptThenMac: Self = Self(0x0016); - pub const ExtendedMasterSecret: Self = Self(0x0017); - pub const TokenBinding: Self = Self(0x0018); - pub const CachedInfo: Self = Self(0x0019); - pub const SessionTicket: Self = Self(0x0023); - pub const PreSharedKey: Self = Self(0x0029); - pub const EarlyData: Self = Self(0x002A); - pub const SupportedVersions: Self = Self(0x002B); - pub const Cookie: Self = Self(0x002C); - pub const PskKeyExchangeModes: Self = Self(0x002D); - pub const CertificateAuthorities: Self = Self(0x002F); - pub const OidFilters: Self = Self(0x0030); - pub const PostHandshakeAuth: Self = Self(0x0031); - pub const SignatureAlgorithmsCert: Self = Self(0x0032); - pub const KeyShare: Self = Self(0x0033); - pub const RenegotiationInfo: Self = Self(0xFF01); - - pub const fn from_u16(value: u16) -> Self { - Self(value) - } - - pub const fn as_u16(&self) -> u16 { - self.0 - } - - const fn is_unknown(&self) -> bool { - !matches!( - *self, - Self(0x0000..=0x0019 | 0x0023 | 0x0029..=0x002D | 0x002F..=0x0033 | 0xFF01) - ) - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], ExtensionType> { - let (input, value) = be_u16(input)?; - Ok((input, ExtensionType::from_u16(value))) - } - - /// Returns true if this extension type is supported by this implementation. - pub fn is_supported(&self) -> bool { - Self::supported().contains(self) - } - - /// Supported extension types that this implementation handles. - pub const fn supported() -> &'static [ExtensionType; 8] { - &[ - ExtensionType::SupportedGroups, - ExtensionType::EcPointFormats, - ExtensionType::SignatureAlgorithms, - ExtensionType::UseSrtp, - ExtensionType::EncryptThenMac, - ExtensionType::ExtendedMasterSecret, - ExtensionType::RenegotiationInfo, - ExtensionType::SessionTicket, - ] - } -} - -impl fmt::Debug for ExtensionType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.is_unknown() { - return f.debug_tuple("Unknown").field(&self.0).finish(); - } - - let name = match *self { - ExtensionType::ServerName => "ServerName", - ExtensionType::MaxFragmentLength => "MaxFragmentLength", - ExtensionType::ClientCertificateUrl => "ClientCertificateUrl", - ExtensionType::TrustedCaKeys => "TrustedCaKeys", - ExtensionType::TruncatedHmac => "TruncatedHmac", - ExtensionType::StatusRequest => "StatusRequest", - ExtensionType::UserMapping => "UserMapping", - ExtensionType::ClientAuthz => "ClientAuthz", - ExtensionType::ServerAuthz => "ServerAuthz", - ExtensionType::CertType => "CertType", - ExtensionType::SupportedGroups => "SupportedGroups", - ExtensionType::EcPointFormats => "EcPointFormats", - ExtensionType::Srp => "Srp", - ExtensionType::SignatureAlgorithms => "SignatureAlgorithms", - ExtensionType::UseSrtp => "UseSrtp", - ExtensionType::Heartbeat => "Heartbeat", - ExtensionType::ApplicationLayerProtocolNegotiation => "ApplicationLayerProtocolNegotiation", - ExtensionType::StatusRequestV2 => "StatusRequestV2", - ExtensionType::SignedCertificateTimestamp => "SignedCertificateTimestamp", - ExtensionType::ClientCertificateType => "ClientCertificateType", - ExtensionType::ServerCertificateType => "ServerCertificateType", - ExtensionType::Padding => "Padding", - ExtensionType::EncryptThenMac => "EncryptThenMac", - ExtensionType::ExtendedMasterSecret => "ExtendedMasterSecret", - ExtensionType::TokenBinding => "TokenBinding", - ExtensionType::CachedInfo => "CachedInfo", - ExtensionType::SessionTicket => "SessionTicket", - ExtensionType::PreSharedKey => "PreSharedKey", - ExtensionType::EarlyData => "EarlyData", - ExtensionType::SupportedVersions => "SupportedVersions", - ExtensionType::Cookie => "Cookie", - ExtensionType::PskKeyExchangeModes => "PskKeyExchangeModes", - ExtensionType::CertificateAuthorities => "CertificateAuthorities", - ExtensionType::OidFilters => "OidFilters", - ExtensionType::PostHandshakeAuth => "PostHandshakeAuth", - ExtensionType::SignatureAlgorithmsCert => "SignatureAlgorithmsCert", - ExtensionType::KeyShare => "KeyShare", - ExtensionType::RenegotiationInfo => "RenegotiationInfo", - _ => unreachable!("known DTLS 1.2 extension type missing Debug label"), - }; - - f.write_str(name) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0x00, 0x0A, // ExtensionType::SupportedGroups - 0x00, 0x08, // Extension length - 0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, // Extension data - ]; - - #[test] - fn extension_type_newtype_shape() { - assert_eq!(std::mem::size_of::(), 2); - assert_eq!(ExtensionType::default().as_u16(), 0); - assert_eq!(ExtensionType::default(), ExtensionType::ServerName); - } - - #[test] - fn extension_type_wire_roundtrip() { - for extension_type in ExtensionType::supported() { - assert_eq!(ExtensionType::from_u16(extension_type.as_u16()), *extension_type); - assert!(!extension_type.is_unknown()); - } - - let unknown = ExtensionType::from_u16(0xFFFF); - assert_eq!(unknown.as_u16(), 0xFFFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn extension_type_debug_stays_enum_like() { - assert_eq!(format!("{:?}", ExtensionType::SupportedGroups), "SupportedGroups"); - assert_eq!(format!("{:?}", ExtensionType::from_u16(0xFFFF)), "Unknown(65535)"); - } - - #[test] - fn roundtrip() { - // Parse the message with base_offset 0 - let (rest, parsed) = Extension::parse(MESSAGE, 0).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - parsed.serialize(MESSAGE, &mut serialized); - assert_eq!(&*serialized, MESSAGE); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/ec_point_formats.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/ec_point_formats.rs deleted file mode 100644 index e6efb368391..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/ec_point_formats.rs +++ /dev/null @@ -1,186 +0,0 @@ -use crate::vendor::dimpl::buffer::Buf; -use arrayvec::ArrayVec; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::{Err, IResult, number::complete::be_u8}; - -/// EC Point Format as defined in RFC 4492 Section 5.1.2 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[allow(unused)] -pub enum ECPointFormat { - #[default] - Uncompressed = 0x00, - AnsiX962CompressedPrime = 0x01, - AnsiX962CompressedChar2 = 0x02, -} - -impl ECPointFormat { - #[allow(unused)] - pub fn parse(input: &[u8]) -> IResult<&[u8], ECPointFormat> { - let (input, value) = be_u8(input)?; - let format = match value { - 0x00 => ECPointFormat::Uncompressed, - 0x01 => ECPointFormat::AnsiX962CompressedPrime, - 0x02 => ECPointFormat::AnsiX962CompressedChar2, - _ => { - return Err(nom::Err::Error(nom::error::Error::new( - input, - nom::error::ErrorKind::Switch, - ))); - } - }; - Ok((input, format)) - } - - pub fn as_u8(&self) -> u8 { - *self as u8 - } -} - -/// ECPointFormats extension as defined in RFC 4492 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ECPointFormatsExtension { - pub formats: ArrayVec, -} - -impl ECPointFormatsExtension { - /// Create a default ECPointFormatsExtension with standard formats - pub fn default() -> Self { - let mut formats = ArrayVec::new(); - // Most implementations only support uncompressed format - formats.push(ECPointFormat::Uncompressed); - - ECPointFormatsExtension { formats } - } - - #[allow(unused)] - pub fn parse(input: &[u8]) -> IResult<&[u8], ECPointFormatsExtension> { - let (input, list_len) = be_u8(input)?; - if list_len == 0 { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - let (input, formats_data) = take(list_len)(input)?; - if !input.is_empty() { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - let mut formats = ArrayVec::new(); - let mut current_input = formats_data; - - while !current_input.is_empty() { - let format_input = current_input; - let (rest, format) = be_u8(current_input)?; - let Some(format) = (match format { - 0x00 => Some(ECPointFormat::Uncompressed), - 0x01 => Some(ECPointFormat::AnsiX962CompressedPrime), - 0x02 => Some(ECPointFormat::AnsiX962CompressedChar2), - _ => None, - }) else { - current_input = rest; - continue; - }; - - formats - .try_push(format) - .map_err(|_| Err::Failure(Error::new(format_input, ErrorKind::LengthValue)))?; - current_input = rest; - } - - Ok((current_input, ECPointFormatsExtension { formats })) - } - - pub fn serialize(&self, output: &mut Buf) { - // Write the number of formats - output.push(self.formats.len() as u8); - - // Write each format - for format in &self.formats { - output.push(format.as_u8()); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - #[test] - fn test_ec_point_formats_extension() { - let mut formats = ArrayVec::new(); - formats.push(ECPointFormat::Uncompressed); - formats.push(ECPointFormat::AnsiX962CompressedPrime); - - let ext = ECPointFormatsExtension { formats }; - - let mut serialized = Buf::new(); - ext.serialize(&mut serialized); - - let expected = [ - 0x02, // Number of formats (2) - 0x00, // Uncompressed (0x00) - 0x01, // ANSI X9.62 compressed prime (0x01) - ]; - - assert_eq!(&*serialized, expected); - - let (_, parsed) = ECPointFormatsExtension::parse(&serialized).unwrap(); - - assert_eq!(parsed.formats.as_slice(), ext.formats.as_slice()); - } - - #[test] - fn too_many_ec_point_formats_are_rejected() { - let bytes = [ - 0x04, // Four point formats. - 0x00, // Uncompressed. - 0x00, // Uncompressed. - 0x00, // Uncompressed. - 0x00, // Uncompressed. - ]; - - let err = ECPointFormatsExtension::parse(&bytes).unwrap_err(); - - assert!(matches!( - err, - Err::Failure(Error { - code: ErrorKind::LengthValue, - .. - }) - )); - } - - #[test] - fn unknown_ec_point_formats_are_ignored() { - let (rest, parsed) = ECPointFormatsExtension::parse(&[ - 0x03, // Three point formats. - 0x02, // ANSI X9.62 compressed char2. - 0x00, // Uncompressed. - 0xFF, // Unknown/private point format. - ]) - .unwrap(); - - assert!(rest.is_empty()); - assert_eq!( - parsed.formats.as_slice(), - &[ECPointFormat::AnsiX962CompressedChar2, ECPointFormat::Uncompressed,] - ); - } - - #[test] - fn trailing_ec_point_format_bytes_are_rejected() { - let result = ECPointFormatsExtension::parse(&[ - 0x01, // One point format. - 0x00, // Uncompressed. - 0xFF, // Extension body has a trailing byte beyond the vector. - ]); - - assert!(matches!( - result, - Err(Err::Failure(Error { - code: ErrorKind::LengthValue, - .. - })) - )); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/mod.rs deleted file mode 100644 index 7c6ec7c0fc2..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod ec_point_formats; -pub mod signature_algorithms; -pub mod supported_groups; -pub mod use_srtp; - -pub use ec_point_formats::ECPointFormatsExtension; -pub use signature_algorithms::SignatureAlgorithmsExtension; -pub use supported_groups::SupportedGroupsExtension; -pub use use_srtp::UseSrtpExtension; diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/signature_algorithms.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/signature_algorithms.rs deleted file mode 100644 index b560e8f45ea..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/signature_algorithms.rs +++ /dev/null @@ -1,206 +0,0 @@ -use super::super::{SignatureAndHashAlgorithm, SignatureAndHashAlgorithmVec}; -use crate::vendor::dimpl::buffer::Buf; -use nom::Err; -use nom::IResult; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; - -/// SignatureAlgorithms extension as defined in RFC 5246 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SignatureAlgorithmsExtension { - pub supported_signature_algorithms: SignatureAndHashAlgorithmVec, -} - -impl SignatureAlgorithmsExtension { - /// Create a default SignatureAlgorithmsExtension with standard algorithms - pub fn default() -> Self { - SignatureAlgorithmsExtension { - supported_signature_algorithms: SignatureAndHashAlgorithmVec::from(*SignatureAndHashAlgorithm::supported()), - } - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAlgorithmsExtension> { - let (input, list_len) = nom::number::complete::be_u16(input)?; - if list_len == 0 || list_len % 2 != 0 { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - let mut algorithms = SignatureAndHashAlgorithmVec::new(); - let (input, mut current_input) = take(list_len)(input)?; - if !input.is_empty() { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - // Parse algorithms, filtering to only keep supported ones - while !current_input.is_empty() { - let (rest, alg) = SignatureAndHashAlgorithm::parse(current_input)?; - // Only keep supported signature+hash combinations - if alg.is_supported() { - algorithms - .try_push(alg) - .map_err(|_| Err::Failure(Error::new(current_input, ErrorKind::LengthValue)))?; - } - current_input = rest; - } - - Ok(( - input, - SignatureAlgorithmsExtension { - supported_signature_algorithms: algorithms, - }, - )) - } - - pub fn serialize(&self, output: &mut Buf) { - // Write the total length of all algorithms (2 bytes per algorithm) - output.extend_from_slice(&((self.supported_signature_algorithms.len() * 2) as u16).to_be_bytes()); - - // Write each algorithm - for alg in &self.supported_signature_algorithms { - output.extend_from_slice(&alg.as_u16().to_be_bytes()); - } - } -} - -#[cfg(test)] -mod tests { - use super::super::super::{HashAlgorithm, SignatureAlgorithm}; - - use super::*; - - #[test] - fn test_signature_algorithms_extension() { - let mut algorithms = SignatureAndHashAlgorithmVec::new(); - algorithms.push(SignatureAndHashAlgorithm::new( - HashAlgorithm::SHA256, - SignatureAlgorithm::ECDSA, - )); - algorithms.push(SignatureAndHashAlgorithm::new( - HashAlgorithm::SHA256, - SignatureAlgorithm::RSA, - )); - - let ext = SignatureAlgorithmsExtension { - supported_signature_algorithms: algorithms.clone(), - }; - - let mut serialized = Buf::new(); - ext.serialize(&mut serialized); - - let expected = [ - 0x00, 0x04, // Length (4 bytes) - 0x04, 0x03, // SHA256/ECDSA - 0x04, 0x01, // SHA256/RSA - ]; - - assert_eq!(&*serialized, expected); - - let (_, parsed) = SignatureAlgorithmsExtension::parse(&serialized).unwrap(); - - assert_eq!(parsed.supported_signature_algorithms.len(), 1); - assert_eq!( - parsed.supported_signature_algorithms[0], - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA,) - ); - } - - #[test] - fn default_does_not_advertise_rsa() { - let extension = SignatureAlgorithmsExtension::default(); - - assert!( - extension - .supported_signature_algorithms - .iter() - .all(|algorithm| algorithm.signature != SignatureAlgorithm::RSA) - ); - } - - #[test] - fn capacity_matches_supported() { - let extension = SignatureAlgorithmsExtension::default(); - - assert_eq!( - extension.supported_signature_algorithms.capacity(), - SignatureAndHashAlgorithm::supported().len() - ); - } - - #[test] - fn too_many_supported_signature_algorithms_are_rejected() { - let mut bytes = Vec::new(); - let count = SignatureAndHashAlgorithm::supported().len() + 1; - bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes()); - for _ in 0..count { - bytes.extend_from_slice( - &SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA) - .as_u16() - .to_be_bytes(), - ); - } - - let result = SignatureAlgorithmsExtension::parse(&bytes); - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "too many supported signature algorithms should fail with LengthValue" - ); - } - - #[test] - fn odd_length_signature_algorithms_are_rejected_without_panic() { - let result = std::panic::catch_unwind(|| { - SignatureAlgorithmsExtension::parse(&[ - 0x00, 0x01, // Declared list length is not divisible by 2. - 0x04, 0x03, // Extra byte proves the parser must reject before looping. - ]) - }); - - assert!(result.is_ok(), "odd signature_algorithms length must not panic"); - assert!( - matches!( - result.unwrap(), - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "odd signature_algorithms length should fail with LengthValue" - ); - } - - #[test] - fn empty_signature_algorithms_are_rejected() { - let result = SignatureAlgorithmsExtension::parse(&[ - 0x00, 0x00, // Empty signature_algorithms vector is invalid. - ]); - - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "empty signature_algorithms vector should fail with LengthValue" - ); - } - - #[test] - fn trailing_signature_algorithms_bytes_are_rejected() { - let result = SignatureAlgorithmsExtension::parse(&[ - 0x00, 0x02, // One algorithm follows. - 0x04, 0x03, // SHA256/ECDSA - 0xff, // Extension body has a trailing byte beyond the vector. - ]); - - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "trailing signature_algorithms bytes should fail with LengthValue" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/supported_groups.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/supported_groups.rs deleted file mode 100644 index 1963ce427da..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/supported_groups.rs +++ /dev/null @@ -1,156 +0,0 @@ -use super::super::{NamedGroup, NamedGroupVec}; -use crate::vendor::dimpl::buffer::Buf; -use nom::Err; -use nom::IResult; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; - -/// SupportedGroups extension as defined in RFC 8422 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SupportedGroupsExtension { - pub groups: NamedGroupVec, -} - -impl SupportedGroupsExtension { - pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedGroupsExtension> { - let (input, list_len) = nom::number::complete::be_u16(input)?; - if list_len == 0 || list_len % 2 != 0 { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - let (input, mut current_input) = take(list_len)(input)?; - if !input.is_empty() { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - let mut groups = NamedGroupVec::new(); - - // Parse groups; only include supported groups (skip Unknown and unsupported) - while !current_input.is_empty() { - let group_input = current_input; - let (rest, group) = NamedGroup::parse(group_input)?; - current_input = rest; - // Only add supported groups - if group.is_supported() { - groups - .try_push(group) - .map_err(|_| Err::Failure(Error::new(group_input, ErrorKind::LengthValue)))?; - } - } - - Ok((input, SupportedGroupsExtension { groups })) - } - - pub fn serialize(&self, output: &mut Buf) { - // Write the total length of all groups (2 bytes per group) - output.extend_from_slice(&((self.groups.len() * 2) as u16).to_be_bytes()); - - // Write each group - for group in &self.groups { - output.extend_from_slice(&group.as_u16().to_be_bytes()); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - #[test] - fn test_supported_groups_extension() { - let mut groups = NamedGroupVec::new(); - groups.push(NamedGroup::X25519); - groups.push(NamedGroup::Secp256r1); - - let ext = SupportedGroupsExtension { groups }; - - let mut serialized = Buf::new(); - ext.serialize(&mut serialized); - - let expected = [ - 0x00, 0x04, // Groups length (4 bytes) - 0x00, 0x1D, // X25519 (0x001D) - 0x00, 0x17, // secp256r1 (0x0017) - ]; - - assert_eq!(&*serialized, expected); - - let (_, parsed) = SupportedGroupsExtension::parse(&serialized).unwrap(); - - assert_eq!(parsed.groups.as_slice(), ext.groups.as_slice()); - } - - #[test] - fn test_supported_groups_parse_provided_bytes() { - // Provided bytes: [0,10,0,29,0,23,0,24,1,0,1,1] - // Meaning: - // 0x000A -> list length = 10 bytes (5 groups) - // groups: 0x001D (X25519), 0x0017 (P-256), 0x0018 (P-384), 0x0100 (unknown), 0x0101 (unknown) - let bytes = [0, 10, 0, 29, 0, 23, 0, 24, 1, 0, 1, 1]; - - let (rest, parsed) = SupportedGroupsExtension::parse(&bytes).expect("parse SupportedGroups"); - assert!(rest.is_empty()); - - // Expect only the supported groups in order as they appear - assert_eq!( - parsed.groups.as_slice(), - &[NamedGroup::X25519, NamedGroup::Secp256r1, NamedGroup::Secp384r1] - ); - } - - #[test] - fn too_many_supported_groups_are_rejected() { - let mut bytes = Vec::new(); - let count = NamedGroup::supported().len() + 1; - bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes()); - for _ in 0..count { - bytes.extend_from_slice(&NamedGroup::X25519.as_u16().to_be_bytes()); - } - - let result = SupportedGroupsExtension::parse(&bytes); - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "too many supported groups should fail with LengthValue" - ); - } - - #[test] - fn odd_supported_groups_vector_is_rejected() { - let result = SupportedGroupsExtension::parse(&[ - 0x00, 0x03, // Declared vector length is not divisible by 2. - 0x00, 0x1D, 0xFF, - ]); - - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "odd supported_groups vector should fail with LengthValue" - ); - } - - #[test] - fn trailing_supported_groups_bytes_are_rejected() { - let result = SupportedGroupsExtension::parse(&[ - 0x00, 0x02, // One named group. - 0x00, 0x1D, // X25519. - 0xFF, // Extension body has a trailing byte beyond the vector. - ]); - - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "trailing supported_groups bytes should fail with LengthValue" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/use_srtp.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/use_srtp.rs deleted file mode 100644 index 036d4954acf..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/extensions/use_srtp.rs +++ /dev/null @@ -1,293 +0,0 @@ -use crate::vendor::dimpl::SrtpProfile; -use crate::vendor::dimpl::buffer::Buf; -use arrayvec::ArrayVec; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::{be_u8, be_u16}; -use nom::{Err, IResult}; - -pub type SrtpProfileVec = ArrayVec; - -/// DTLS-SRTP protection profile identifiers -/// From RFC 5764 Section 4.1.2 -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[allow(non_camel_case_types)] -pub enum SrtpProfileId { - #[default] - SRTP_AES128_CM_SHA1_80 = 0x0001, - SRTP_AEAD_AES_128_GCM = 0x0007, - SRTP_AEAD_AES_256_GCM = 0x0008, -} - -impl SrtpProfileId { - pub fn parse(input: &[u8]) -> IResult<&[u8], SrtpProfileId> { - let (input, value) = be_u16(input)?; - let profile = match value { - 0x0001 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, - 0x0007 => SrtpProfileId::SRTP_AEAD_AES_128_GCM, - 0x0008 => SrtpProfileId::SRTP_AEAD_AES_256_GCM, - _ => { - return Err(nom::Err::Error(nom::error::Error::new( - input, - nom::error::ErrorKind::Switch, - ))); - } - }; - Ok((input, profile)) - } - - pub fn as_u16(&self) -> u16 { - *self as u16 - } - - /// All recognized SRTP profile IDs (every non-`Unknown` variant). - pub const fn all() -> &'static [SrtpProfileId; 3] { - &[ - SrtpProfileId::SRTP_AES128_CM_SHA1_80, - SrtpProfileId::SRTP_AEAD_AES_128_GCM, - SrtpProfileId::SRTP_AEAD_AES_256_GCM, - ] - } - - /// Supported SRTP profile IDs. - pub const fn supported() -> &'static [SrtpProfileId; 3] { - Self::all() - } -} - -impl From for SrtpProfileId { - fn from(profile: SrtpProfile) -> Self { - match profile { - SrtpProfile::AES128_CM_SHA1_80 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, - SrtpProfile::AEAD_AES_128_GCM => SrtpProfileId::SRTP_AEAD_AES_128_GCM, - SrtpProfile::AEAD_AES_256_GCM => SrtpProfileId::SRTP_AEAD_AES_256_GCM, - } - } -} - -impl From for SrtpProfile { - fn from(profile: SrtpProfileId) -> Self { - match profile { - SrtpProfileId::SRTP_AES128_CM_SHA1_80 => SrtpProfile::AES128_CM_SHA1_80, - SrtpProfileId::SRTP_AEAD_AES_128_GCM => SrtpProfile::AEAD_AES_128_GCM, - SrtpProfileId::SRTP_AEAD_AES_256_GCM => SrtpProfile::AEAD_AES_256_GCM, - } - } -} - -/// UseSrtp extension as defined in RFC 5764 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct UseSrtpExtension { - pub profiles: SrtpProfileVec, - pub mki: ArrayVec, // MKI value (usually empty) -} - -impl UseSrtpExtension { - pub fn new(profiles: SrtpProfileVec, mki: ArrayVec) -> Self { - UseSrtpExtension { profiles, mki } - } - - /// Create a default UseSrtpExtension with standard profiles - pub fn default() -> Self { - let mut profiles = SrtpProfileVec::new(); - // Add profiles in order of preference (most secure first) - profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM); - profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM); - profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80); - - // MKI is typically empty as per RFC 5764 - UseSrtpExtension { - profiles, - mki: ArrayVec::new(), - } - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], UseSrtpExtension> { - let (input, profiles_length) = be_u16(input)?; - if profiles_length == 0 { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - let (input, profiles_data) = take(profiles_length)(input)?; - - // Parse the profiles (ignore unknown profile IDs instead of failing) - let mut profiles = SrtpProfileVec::new(); - let mut profiles_rest = profiles_data; - - while profiles_rest.len() >= 2 { - let profile_input = profiles_rest; - let (rest, value) = be_u16(profile_input)?; - profiles_rest = rest; - match value { - 0x0001 => profiles - .try_push(SrtpProfileId::SRTP_AES128_CM_SHA1_80) - .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, - 0x0007 => profiles - .try_push(SrtpProfileId::SRTP_AEAD_AES_128_GCM) - .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, - 0x0008 => profiles - .try_push(SrtpProfileId::SRTP_AEAD_AES_256_GCM) - .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, - _ => { - // Unknown SRTP profile: skip - } - } - } - if !profiles_rest.is_empty() { - return Err(Err::Failure(Error::new(profiles_rest, ErrorKind::LengthValue))); - } - - // Parse MKI - let (input, mki_length) = be_u8(input)?; - let (input, mki) = take(mki_length)(input)?; - if !input.is_empty() { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - Ok(( - input, - UseSrtpExtension { - profiles, - mki: ArrayVec::try_from(mki).unwrap_or_default(), - }, - )) - } - - pub fn serialize(&self, output: &mut Buf) { - // Length of all profiles (2 bytes per profile) - output.extend_from_slice(&((self.profiles.len() * 2) as u16).to_be_bytes()); - - // Write each profile - for profile in &self.profiles { - output.extend_from_slice(&profile.as_u16().to_be_bytes()); - } - - // MKI length and data - output.push(self.mki.len() as u8); - output.extend_from_slice(&self.mki); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - #[test] - fn test_use_srtp_extension() { - let mut profiles = SrtpProfileVec::new(); - profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM); - profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM); - profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80); - - let mut mki = ArrayVec::new(); - mki.push(1); - mki.push(2); - mki.push(3); - - let ext = UseSrtpExtension::new(profiles, mki.clone()); - - let mut serialized = Buf::new(); - ext.serialize(&mut serialized); - - let expected = [ - 0x00, 0x06, // Profiles length (6 bytes) - 0x00, 0x08, // SRTP_AEAD_AES_256_GCM (0x0008) - 0x00, 0x07, // SRTP_AEAD_AES_128_GCM (0x0007) - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80 (0x0001) - 0x03, // MKI length (3 bytes) - 0x01, 0x02, 0x03, // MKI - ]; - - assert_eq!(&*serialized, expected); - - let (_, parsed) = UseSrtpExtension::parse(&serialized).unwrap(); - - assert_eq!(parsed.profiles.as_slice(), ext.profiles.as_slice()); - assert_eq!(parsed.mki, mki); - } - - #[test] - fn test_use_srtp_parse_provided_bytes() { - // Provided bytes: [0,8,0,7,0,8,0,1,0,2,0] - // Meaning: - // 0x0008 -> profiles length = 8 bytes (4 profile IDs) - // profiles: 0x0007, 0x0008, 0x0001, 0x0002 (0x0002 is unknown and should be ignored) - // MKI length = 0 - let bytes = [0, 8, 0, 7, 0, 8, 0, 1, 0, 2, 0]; - - let (_, parsed) = UseSrtpExtension::parse(&bytes).expect("parse UseSrtpExtension"); - - // Expect only the three known profiles, in the same order as offered - assert_eq!( - parsed.profiles.as_slice(), - &[ - SrtpProfileId::SRTP_AEAD_AES_128_GCM, - SrtpProfileId::SRTP_AEAD_AES_256_GCM, - SrtpProfileId::SRTP_AES128_CM_SHA1_80 - ] - ); - assert_eq!(parsed.mki, ArrayVec::::new()); - } - - #[test] - fn too_many_supported_srtp_profiles_are_rejected() { - let bytes = [ - 0x00, 0x08, // Four profile IDs. - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. - 0x00, // Empty MKI. - ]; - - let err = UseSrtpExtension::parse(&bytes).unwrap_err(); - - assert!(matches!( - err, - Err::Failure(Error { - code: ErrorKind::LengthValue, - .. - }) - )); - } - - #[test] - fn odd_srtp_profile_vector_is_rejected() { - let bytes = [ - 0x00, 0x03, // Odd profile vector length. - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. - 0x00, // Dangling byte in profile vector. - 0x00, // Empty MKI. - ]; - - let err = UseSrtpExtension::parse(&bytes).unwrap_err(); - - assert!(matches!( - err, - Err::Failure(Error { - code: ErrorKind::LengthValue, - .. - }) - )); - } - - #[test] - fn trailing_mki_bytes_are_rejected() { - let bytes = [ - 0x00, 0x02, // One profile ID. - 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. - 0x00, // Empty MKI. - 0xFF, // Trailing extension-body byte. - ]; - - let err = UseSrtpExtension::parse(&bytes).unwrap_err(); - - assert!(matches!( - err, - Err::Failure(Error { - code: ErrorKind::LengthValue, - .. - }) - )); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/finished.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/finished.rs deleted file mode 100644 index a0059d56ecc..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/finished.rs +++ /dev/null @@ -1,58 +0,0 @@ -use super::Dtls12CipherSuite; -use crate::vendor::dimpl::buffer::Buf; -use nom::IResult; -use nom::bytes::complete::take; -use std::ops::Range; - -#[derive(Debug, PartialEq, Eq)] -pub struct Finished { - pub verify_data_range: Range, -} - -impl Finished { - pub fn verify_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.verify_data_range.clone()] - } - - pub fn parse(input: &[u8], cipher_suite: Dtls12CipherSuite) -> IResult<&[u8], Finished> { - let verify_data_length = cipher_suite.verify_data_length(); - let (rest, verify_data_slice) = take(verify_data_length)(input)?; - - // Calculate range relative to input buffer without unsafe code - // verify_data_slice is a sub-slice of input from nom's take combinator - let start = verify_data_slice.as_ptr() as usize - input.as_ptr() as usize; - let end = start + verify_data_slice.len(); - - Ok(( - rest, - Finished { - verify_data_range: start..end, - }, - )) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - output.extend_from_slice(self.verify_data(buf)); - } -} - -#[cfg(test)] -mod test { - use super::Dtls12CipherSuite; - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - #[test] - fn roundtrip() { - let verify_data = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C]; - - // Parse the data - let (rest, parsed) = Finished::parse(&verify_data, Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to original - let mut serialized = Buf::new(); - parsed.serialize(&verify_data, &mut serialized); - assert_eq!(&*serialized, &verify_data[..]); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/handshake.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/handshake.rs deleted file mode 100644 index 23821c071dd..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/handshake.rs +++ /dev/null @@ -1,1030 +0,0 @@ -use std::fmt; -use std::ops::Range; -use std::sync::atomic::{AtomicBool, Ordering}; -use tracing::debug; - -use super::Certificate; -use super::CertificateRequest; -use super::CertificateVerify; -use super::ClientHello; -use super::ClientKeyExchange; -use super::Dtls12CipherSuite; -use super::Finished; -use super::HelloVerifyRequest; -use super::ServerHello; -use super::ServerKeyExchange; -use crate::vendor::dimpl::buffer::Buf; -use arrayvec::ArrayVec; -use nom::Err; -use nom::IResult; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::be_u8; -use nom::number::complete::{be_u16, be_u24, be_u32}; - -// Defensive stack cap over flattened handshake fragments selected for one -// defragmentation attempt. This intentionally does not mirror the receive -// queue's record-count cap; exceeding 50 fragments for one handshake implies -// pathologically tiny records and is treated as invalid input. -const MAX_DEFRAGMENT_HANDSHAKES: usize = 50; - -#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)] -pub struct Header { - pub msg_type: MessageType, - pub length: u32, - pub message_seq: u16, - pub fragment_offset: u32, - pub fragment_length: u32, -} - -#[derive(Debug, Default)] -pub struct Handshake { - pub header: Header, - pub body: Body, - pub handled: AtomicBool, -} - -impl PartialEq for Handshake { - fn eq(&self, other: &Self) -> bool { - self.header == other.header - && self.body == other.body - && self.handled.load(Ordering::Relaxed) == other.handled.load(Ordering::Relaxed) - } -} - -impl Eq for Handshake {} - -impl Handshake { - #[cfg(test)] - pub fn new( - msg_type: MessageType, - length: u32, - message_seq: u16, - fragment_offset: u32, - fragment_length: u32, - body: Body, - ) -> Self { - Handshake { - header: Header { - msg_type, - length, - message_seq, - fragment_offset, - fragment_length, - }, - body, - handled: AtomicBool::new(false), - } - } - - pub fn parse_header(input: &[u8]) -> IResult<&[u8], Header> { - let (input, msg_type) = MessageType::parse(input)?; - let (input, length) = be_u24(input)?; - let (input, message_seq) = be_u16(input)?; - let (input, fragment_offset) = be_u24(input)?; - let (input, fragment_length) = be_u24(input)?; - - Ok(( - input, - Header { - msg_type, - length, - message_seq, - fragment_offset, - fragment_length, - }, - )) - } - - pub fn parse( - input: &[u8], - base_offset: usize, - c: Option, - as_fragment: bool, - ) -> IResult<&[u8], Handshake> { - let original_input = input; - let (input, header) = Self::parse_header(input)?; - - let fragment_end = header.fragment_offset + header.fragment_length; - let fragment_out_of_bounds = fragment_end > header.length; - let empty_client_hello_fragment = header.msg_type == MessageType::ClientHello && header.fragment_length == 0; - - if fragment_out_of_bounds || empty_client_hello_fragment { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - let is_fragment = header.fragment_offset > 0 || header.fragment_length < header.length; - - if !as_fragment && is_fragment { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - let (input, body) = if as_fragment { - let (input, fragment_slice) = take(header.fragment_length as usize)(input)?; - // Calculate range relative to original input - let relative_offset = fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + fragment_slice.len(); - (input, Body::Fragment(start..end)) - } else { - let (input, body_bytes) = take(header.length as usize)(input)?; - // Calculate base_offset for body parsing - let consumed = body_bytes.as_ptr() as usize - original_input.as_ptr() as usize; - let body_base_offset = base_offset + consumed; - let (_, body) = Body::parse(body_bytes, body_base_offset, header.msg_type, c)?; - (input, body) - }; - - Ok(( - input, - Handshake { - header, - body, - handled: AtomicBool::new(false), - }, - )) - } - - pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { - output.push(self.header.msg_type.as_u8()); - output.extend_from_slice(&self.header.length.to_be_bytes()[1..]); - output.extend_from_slice(&self.header.message_seq.to_be_bytes()); - output.extend_from_slice(&self.header.fragment_offset.to_be_bytes()[1..]); - output.extend_from_slice(&self.header.fragment_length.to_be_bytes()[1..]); - self.body.serialize(source_buf, output); - } - - #[allow(private_interfaces)] - pub fn defragment<'b>( - mut iter: impl Iterator, - buffer: &mut Buf, - cipher_suite: Option, - transcript: Option<&mut Buf>, - ) -> Result { - buffer.clear(); - - // Invariant is upheld by the caller. - let (first_handshake, first_buffer) = iter.next().unwrap(); - - let Body::Fragment(range) = &first_handshake.body else { - unreachable!("Non-Fragment body in defragment()") - }; - let mut handled = ArrayVec::<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>::new(); - handled - .try_push(first_handshake) - .map_err(|_| crate::vendor::dimpl::InternalError::too_many_records())?; - buffer.extend_from_slice(&first_buffer[range.clone()]); - - for (handshake, source_buf) in iter { - if handshake.header.msg_type != first_handshake.header.msg_type - || handshake.header.message_seq != first_handshake.header.message_seq - { - break; - } - - let Body::Fragment(range) = &handshake.body else { - unreachable!("Non-Fragment body in defragment()") - }; - - handled - .try_push(handshake) - .map_err(|_| crate::vendor::dimpl::InternalError::too_many_records())?; - - buffer.extend_from_slice(&source_buf[range.clone()]); - } - - if buffer.len() != first_handshake.header.length as usize { - debug!("Defragmentation failed. Fragment length mismatch"); - return Err(crate::vendor::dimpl::InternalError::parse_incomplete()); - } - - let (rest, body) = match Body::parse(buffer, 0, first_handshake.header.msg_type, cipher_suite) { - Ok(parsed) => parsed, - Err(err) => { - mark_handled(handled); - return Err(err.into()); - } - }; - - if !rest.is_empty() && first_handshake.header.msg_type.rejects_trailing_body_bytes() { - debug!("Defragmentation failed. Body::parse() did not consume the entire buffer"); - mark_handled(handled); - return Err(crate::vendor::dimpl::InternalError::parse_incomplete()); - } - - // Parsing boundary: Body::parse and its callees must perform all - // structural validation, including extension payloads, before returning - // success. Below we consume the message and append it to the transcript; - // deferring parsing-level checks to state handlers would commit malformed - // input and poison the transcript for a corrected retransmission. - // Negotiation and cryptographic verification belong in the state handlers. - mark_handled(handled); - - // If transcript is provided, write the handshake header + body after parsing succeeds. - if let Some(transcript) = transcript { - transcript.push(first_handshake.header.msg_type.as_u8()); - transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]); - transcript.extend_from_slice(&first_handshake.header.message_seq.to_be_bytes()); - // Defragmented handshake has fragment_offset=0 and fragment_length=length - transcript.extend_from_slice(&0u32.to_be_bytes()[1..]); - transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]); - transcript.extend_from_slice(&buffer[..first_handshake.header.length as usize]); - } - - let handshake = Handshake { - header: Header { - msg_type: first_handshake.header.msg_type, - length: first_handshake.header.length, - message_seq: first_handshake.header.message_seq, - fragment_offset: 0, - fragment_length: first_handshake.header.length, - }, - body, - handled: AtomicBool::new(false), - }; - - // Create a new Handshake with the merged body - Ok(handshake) - } - - #[cfg(test)] - fn do_clone(&self) -> Handshake { - Handshake { - header: Header { - msg_type: self.header.msg_type, - length: self.header.length, - message_seq: self.header.message_seq, - fragment_offset: self.header.fragment_offset, - fragment_length: self.header.fragment_length, - }, - body: Body::HelloRequest, // Placeholder - handled: AtomicBool::new(false), - } - } - - #[cfg(test)] - pub fn fragment<'b>(&self, max: usize, buffer: &'b mut Buf) -> impl Iterator + 'b { - // Must be called with an empty buffer. - assert!(buffer.is_empty()); - - // Note: For fragmentize, self is already serialized data in Body::Fragment - // which doesn't need source_buf, so we pass an empty slice - self.body.serialize(&[], buffer); - - // If this is wrong, the serialize has not produced the same output as we parsed. - assert_eq!(buffer.len(), self.header.length as usize); - - let to_clone = self.do_clone(); - - buffer.chunks(max).enumerate().map(move |(i, chunk)| { - let fragment_length = chunk.len() as u32; - let offset = i * max; - let fragment_range = offset..(offset + chunk.len()); - - let mut fragment = to_clone.do_clone(); - fragment.header.fragment_offset = offset as u32; - fragment.header.fragment_length = fragment_length; - fragment.header.message_seq = to_clone.header.message_seq; - fragment.body = Body::Fragment(fragment_range); - - fragment - }) - } - - // These are (unencrypted) handshakes that, when detected as - // duplicates, trigger a resend of the entire flight. - pub fn dupe_triggers_resend(&self) -> Option { - // Only trigger on the first fragment of a handshake message to avoid - // multiple resends caused by fragmented duplicates of the same message. - if self.header.fragment_offset != 0 { - return None; - } - - let qualifies = matches!( - self.header.msg_type, - MessageType::ClientHello | // flight 1 and 3 - MessageType::HelloVerifyRequest | // flight 2 - MessageType::ServerHelloDone | // flight 4 - MessageType::ClientKeyExchange // flight 5 - ); - - qualifies.then_some(self.header.message_seq) - } - - pub fn is_handled(&self) -> bool { - self.handled.load(Ordering::Relaxed) - } - - pub fn set_handled(&self) { - self.handled.store(true, Ordering::Relaxed); - } -} - -fn mark_handled(handled: ArrayVec<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>) { - for handshake in handled { - handshake.set_handled(); - } -} - -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct MessageType(u8); - -#[allow(non_upper_case_globals)] -impl MessageType { - pub const HelloRequest: Self = Self(0); - pub const ClientHello: Self = Self(1); - pub const ServerHello: Self = Self(2); - pub const HelloVerifyRequest: Self = Self(3); - pub const NewSessionTicket: Self = Self(4); - pub const Certificate: Self = Self(11); - pub const ServerKeyExchange: Self = Self(12); - pub const CertificateRequest: Self = Self(13); - pub const ServerHelloDone: Self = Self(14); - pub const CertificateVerify: Self = Self(15); - pub const ClientKeyExchange: Self = Self(16); - pub const Finished: Self = Self(20); - - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - pub const fn as_u8(&self) -> u8 { - self.0 - } - - const fn is_unknown(&self) -> bool { - !matches!(*self, Self(0..=4 | 11..=16 | 20)) - } - - const fn rejects_trailing_body_bytes(&self) -> bool { - !self.is_unknown() - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], MessageType> { - let (input, byte) = be_u8(input)?; - Ok((input, Self::from_u8(byte))) - } - - pub fn epoch(&self) -> u16 { - if matches!(*self, MessageType::NewSessionTicket | MessageType::Finished) { - 1 - } else { - 0 - } - } -} - -impl fmt::Debug for MessageType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.is_unknown() { - return f.debug_tuple("Unknown").field(&self.0).finish(); - } - - let name = match *self { - MessageType::HelloRequest => "HelloRequest", - MessageType::ClientHello => "ClientHello", - MessageType::HelloVerifyRequest => "HelloVerifyRequest", - MessageType::ServerHello => "ServerHello", - MessageType::Certificate => "Certificate", - MessageType::ServerKeyExchange => "ServerKeyExchange", - MessageType::CertificateRequest => "CertificateRequest", - MessageType::ServerHelloDone => "ServerHelloDone", - MessageType::CertificateVerify => "CertificateVerify", - MessageType::ClientKeyExchange => "ClientKeyExchange", - MessageType::NewSessionTicket => "NewSessionTicket", - MessageType::Finished => "Finished", - _ => unreachable!("known DTLS 1.2 handshake message type missing Debug label"), - }; - - f.write_str(name) - } -} - -#[derive(Debug, PartialEq, Eq)] -#[allow(clippy::large_enum_variant)] -pub enum Body { - HelloRequest, // empty - ClientHello(ClientHello), - HelloVerifyRequest(HelloVerifyRequest), - ServerHello(ServerHello), - Certificate(Certificate), - ServerKeyExchange(ServerKeyExchange), - CertificateRequest(CertificateRequest), - ServerHelloDone, // empty - CertificateVerify(CertificateVerify), - ClientKeyExchange(ClientKeyExchange), - NewSessionTicket(Range), - Finished(Finished), - Unknown(u8), - Fragment(Range), -} - -impl Default for Body { - fn default() -> Self { - Self::Unknown(0) - } -} - -impl Body { - pub fn parse( - input: &[u8], - base_offset: usize, - m: MessageType, - c: Option, - ) -> IResult<&[u8], Body> { - match m { - MessageType::HelloRequest => Ok((input, Body::HelloRequest)), - MessageType::ClientHello => { - let (input, client_hello) = ClientHello::parse(input, base_offset)?; - Ok((input, Body::ClientHello(client_hello))) - } - MessageType::HelloVerifyRequest => { - let (input, hello_verify_request) = HelloVerifyRequest::parse(input)?; - Ok((input, Body::HelloVerifyRequest(hello_verify_request))) - } - MessageType::ServerHello => { - let (input, server_hello) = ServerHello::parse(input, base_offset)?; - Ok((input, Body::ServerHello(server_hello))) - } - MessageType::Certificate => { - let (input, certificate) = Certificate::parse(input, base_offset)?; - Ok((input, Body::Certificate(certificate))) - } - MessageType::ServerKeyExchange => { - let cipher_suite = c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; - let algo = cipher_suite.as_key_exchange_algorithm(); - let (input, server_key_exchange) = ServerKeyExchange::parse(input, base_offset, algo)?; - Ok((input, Body::ServerKeyExchange(server_key_exchange))) - } - MessageType::CertificateRequest => { - let (input, certificate_request) = CertificateRequest::parse(input, base_offset)?; - Ok((input, Body::CertificateRequest(certificate_request))) - } - MessageType::ServerHelloDone => Ok((input, Body::ServerHelloDone)), - MessageType::CertificateVerify => { - let (input, certificate_verify) = CertificateVerify::parse(input, base_offset)?; - Ok((input, Body::CertificateVerify(certificate_verify))) - } - MessageType::ClientKeyExchange => { - let cipher_suite = c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; - let algo = cipher_suite.as_key_exchange_algorithm(); - let (input, client_key_exchange) = ClientKeyExchange::parse(input, base_offset, algo)?; - Ok((input, Body::ClientKeyExchange(client_key_exchange))) - } - MessageType::NewSessionTicket => { - let range = base_offset..(base_offset + input.len()); - let (input, _lifetime_hint) = be_u32(input)?; - let (input, ticket_len) = be_u16(input)?; - let (input, _ticket) = take(ticket_len)(input)?; - if !input.is_empty() { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - Ok((input, Body::NewSessionTicket(range))) - } - MessageType::Finished => { - let cipher_suite = c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; - let (input, finished) = Finished::parse(input, cipher_suite)?; - Ok((input, Body::Finished(finished))) - } - _ => Ok((input, Body::Unknown(m.as_u8()))), - } - } - - pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { - match self { - Body::HelloRequest => { - // Serialize HelloRequest (empty) - } - Body::ClientHello(client_hello) => { - client_hello.serialize(source_buf, output); - } - Body::HelloVerifyRequest(hello_verify_request) => { - hello_verify_request.serialize(output); - } - Body::ServerHello(server_hello) => { - server_hello.serialize(source_buf, output); - } - Body::Certificate(certificate) => { - certificate.serialize(source_buf, output); - } - Body::ServerKeyExchange(server_key_exchange) => { - server_key_exchange.serialize(source_buf, output, true); - } - Body::CertificateRequest(certificate_request) => { - certificate_request.serialize(source_buf, output); - } - Body::ServerHelloDone => { - // Serialize ServerHelloDone (empty) - } - Body::CertificateVerify(certificate_verify) => { - certificate_verify.serialize(source_buf, output); - } - Body::ClientKeyExchange(client_key_exchange) => { - client_key_exchange.serialize(source_buf, output); - } - Body::NewSessionTicket(range) => { - output.extend_from_slice(&source_buf[range.clone()]); - } - Body::Finished(finished) => { - finished.serialize(source_buf, output); - } - Body::Unknown(value) => { - output.push(*value); - } - Body::Fragment(range) => { - output.extend_from_slice(&source_buf[range.clone()]); - } - } - } -} - -#[cfg(test)] -mod tests { - use arrayvec::ArrayVec; - use std::collections::VecDeque; - - use super::*; - - use crate::vendor::dimpl::buffer::Buf; - use crate::vendor::dimpl::dtls12::message::CompressionMethod; - use crate::vendor::dimpl::dtls12::message::Cookie; - use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; - use crate::vendor::dimpl::dtls12::message::ProtocolVersion; - use crate::vendor::dimpl::dtls12::message::Random; - use crate::vendor::dimpl::dtls12::message::SessionId; - - const MESSAGE: &[u8] = &[ - 0x01, // MessageType::ClientHello - 0x00, 0x00, 0x2E, // length - 0x00, 0x00, // message_seq - 0x00, 0x00, 0x00, // fragment_offset - 0x00, 0x00, 0x2E, // fragment_length - // ClientHello - 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 - // Random - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, // - 0x01, // SessionId length - 0xAA, // SessionId - 0x01, // Cookie length - 0xBB, // Cookie - 0x00, 0x04, // Dtls12CipherSuites length - 0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - 0xC0, 0x2C, // Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - 0x01, // CompressionMethods length - 0x00, // CompressionMethod::Null - ]; - - fn check_body_before_commit(kind: MessageType, body: &[u8], accepted: bool) { - let mut source = vec![0; 7]; - source.extend_from_slice(body); - let parsed = Body::parse(&source[7..], 7, kind, None); - assert_eq!(parsed.is_ok(), accepted, "{kind:?}: {body:02x?}"); - if let Ok((rest, parsed)) = parsed { - assert!(rest.is_empty()); - let mut serialized = Buf::new(); - parsed.serialize(&source, &mut serialized); - assert_eq!(&*serialized, body); - } - for fragmented in [false, true] { - let split = if fragmented { body.len() / 2 } else { body.len() }; - let mut fragments = vec![Handshake::new( - kind, - body.len() as u32, - 0, - 0, - split as u32, - Body::Fragment(0..split), - )]; - if fragmented { - fragments.push(Handshake::new( - kind, - body.len() as u32, - 0, - split as u32, - (body.len() - split) as u32, - Body::Fragment(split..body.len()), - )); - } - let mut buffer = Buf::new(); - let mut transcript = Buf::new(); - transcript.extend_from_slice(b"prior transcript"); - let result = Handshake::defragment( - fragments.iter().map(|h| (h, body)), - &mut buffer, - None, - Some(&mut transcript), - ); - assert_eq!(result.is_ok(), accepted, "{kind:?}: {body:02x?}"); - if !accepted { - assert_eq!(&*transcript, b"prior transcript"); - } - } - } - - #[test] - fn empty_groups_rejected_before_commit() { - let mut body = MESSAGE[12..].to_vec(); - append_extension(&mut body, 10, &[0, 0]); - check_body_before_commit(MessageType::ClientHello, &body, false); - } - - #[test] - fn empty_srtp_rejected_before_commit() { - let mut body = MESSAGE[12..].to_vec(); - append_extension(&mut body, 14, &[0, 0, 0]); - check_body_before_commit(MessageType::ClientHello, &body, false); - } - - #[test] - fn empty_point_formats_rejected_before_commit() { - let mut body = MESSAGE[12..].to_vec(); - append_extension(&mut body, 11, &[0]); - check_body_before_commit(MessageType::ClientHello, &body, false); - } - - #[test] - fn nonempty_unknown_extension_vectors_remain_structurally_valid() { - for (kind, payload) in [(10, &[0, 2, 0xff, 0xff][..]), (14, &[0, 2, 0xff, 0xff, 0])] { - let mut body = MESSAGE[12..].to_vec(); - append_extension(&mut body, kind, payload); - check_body_before_commit(MessageType::ClientHello, &body, true); - } - } - - fn append_extension(body: &mut Vec, kind: u16, payload: &[u8]) { - body.extend_from_slice(&((4 + payload.len()) as u16).to_be_bytes()); - body.extend_from_slice(&kind.to_be_bytes()); - body.extend_from_slice(&(payload.len() as u16).to_be_bytes()); - body.extend_from_slice(payload); - } - - #[test] - fn server_hello_and_ticket_parse_before_commit() { - let valid_srtp = [0, 2, 0, 1, 0]; - for len in 0..=valid_srtp.len() { - let mut hello = vec![0xfe, 0xfd]; - hello.extend_from_slice(&[0; 32]); - hello.extend_from_slice(&[0, 0xc0, 0x2b, 0]); - append_extension(&mut hello, 14, &valid_srtp[..len]); - check_body_before_commit(MessageType::ServerHello, &hello, len == valid_srtp.len()); - } - let ticket = [0, 0, 0, 1, 0, 1, 7]; - for len in 0..=ticket.len() { - check_body_before_commit(MessageType::NewSessionTicket, &ticket[..len], len == ticket.len()); - } - let mut trailing = ticket.to_vec(); - trailing.push(0); - check_body_before_commit(MessageType::NewSessionTicket, &trailing, false); - check_body_before_commit(MessageType::NewSessionTicket, &[0; 6], true); - } - - #[test] - fn message_type_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - assert_eq!(MessageType::default().as_u8(), 0); - assert_eq!(MessageType::default(), MessageType::HelloRequest); - } - - #[test] - fn message_type_wire_roundtrip() { - for message_type in [ - MessageType::HelloRequest, - MessageType::ClientHello, - MessageType::ServerHello, - MessageType::HelloVerifyRequest, - MessageType::NewSessionTicket, - MessageType::Certificate, - MessageType::ServerKeyExchange, - MessageType::CertificateRequest, - MessageType::ServerHelloDone, - MessageType::CertificateVerify, - MessageType::ClientKeyExchange, - MessageType::Finished, - ] { - assert_eq!(MessageType::from_u8(message_type.as_u8()), message_type); - assert!(!message_type.is_unknown()); - } - - let unknown = MessageType::from_u8(0xFF); - assert_eq!(unknown.as_u8(), 0xFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn message_type_debug_stays_enum_like() { - assert_eq!(format!("{:?}", MessageType::ClientHello), "ClientHello"); - assert_eq!(format!("{:?}", MessageType::from_u8(0xFF)), "Unknown(255)"); - } - - #[test] - fn handshake_size() { - let h = Handshake::new( - // ServerHelloDone has a 0 sized body. - MessageType::ServerHelloDone, - 0, - 0, - 0, - 0, - Body::ServerHelloDone, - ); - - let mut v = Buf::new(); - h.serialize(&[], &mut v); - - assert_eq!(v.len(), 12); - } - - #[test] - fn roundtrip() { - let mut serialized = Buf::new(); - - let random = Random::parse(&MESSAGE[14..46]).unwrap().1; - let session_id = SessionId::try_new(&[0xAA]).unwrap(); - let cookie = Cookie::try_new(&[0xBB]).unwrap(); - let mut cipher_suites = ArrayVec::new(); - cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256); - cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384); - let mut compression_methods = ArrayVec::new(); - compression_methods.push(CompressionMethod::Null); - - let client_hello = ClientHello::new( - ProtocolVersion::DTLS1_2, - random, - session_id, - cookie, - cipher_suites, - compression_methods, - ); - - let handshake = Handshake::new( - MessageType::ClientHello, - 0x2E, - 0, - 0, - 0x2E, - Body::ClientHello(client_hello), - ); - - // Serialize and compare to MESSAGE - handshake.serialize(&[], &mut serialized); - assert_eq!(&*serialized, MESSAGE); - - // Parse and compare with original - let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap(); - assert_eq!(parsed, handshake); - - assert!(rest.is_empty()); - } - - #[test] - fn roundtrip_fragment() { - let mut serialized = Buf::new(); - let mut buffer = Buf::new(); - - let random = Random::parse(&MESSAGE[14..46]).unwrap().1; - let session_id = SessionId::try_new(&[0xAA]).unwrap(); - let cookie = Cookie::try_new(&[0xBB]).unwrap(); - let mut cipher_suites = ArrayVec::new(); - cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256); - cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384); - let mut compression_methods = ArrayVec::new(); - compression_methods.push(CompressionMethod::Null); - - let client_hello = ClientHello::new( - ProtocolVersion::DTLS1_2, - random, - session_id, - cookie, - cipher_suites, - compression_methods, - ); - - let handshake = Handshake::new(MessageType::ClientHello, 46, 0, 0, 46, Body::ClientHello(client_hello)); - - // Fragment the handshake with size 10 - let fragments: VecDeque<_> = handshake.fragment(10, &mut buffer).collect(); - - // Defragment the fragments - let mut defragmented_buffer = Buf::new(); - let defragmented_handshake = Handshake::defragment( - fragments.iter().map(|h| (h, &buffer[..])), - &mut defragmented_buffer, - None, - None, - ) - .unwrap(); - - // Serialize and compare to MESSAGE - // Save header info and drop handshake to release buffer borrow - let header = defragmented_handshake.header; - drop(defragmented_handshake); - - serialized.push(header.msg_type.as_u8()); - serialized.extend_from_slice(&header.length.to_be_bytes()[1..]); - serialized.extend_from_slice(&header.message_seq.to_be_bytes()); - serialized.extend_from_slice(&header.fragment_offset.to_be_bytes()[1..]); - serialized.extend_from_slice(&header.fragment_length.to_be_bytes()[1..]); - serialized.extend_from_slice(&defragmented_buffer[..header.length as usize]); - assert_eq!(&*serialized, MESSAGE); - - // Parse and compare with original - let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap(); - assert_eq!(parsed, handshake); - - assert!(rest.is_empty()); - } - - #[test] - fn failed_defragment_parse_discards_candidate_without_writing_transcript() { - let mut body = MESSAGE[12..].to_vec(); - body[38] = 0; - body[39] = 3; - - let handshake = Handshake::new( - MessageType::ClientHello, - body.len() as u32, - 0, - 0, - body.len() as u32, - Body::Fragment(0..body.len()), - ); - - let mut defragmented_buffer = Buf::new(); - let mut transcript = Buf::new(); - let result = Handshake::defragment( - std::iter::once((&handshake, body.as_slice())), - &mut defragmented_buffer, - None, - Some(&mut transcript), - ); - - assert!(result.is_err()); - assert!(handshake.is_handled()); - assert!(transcript.is_empty()); - } - - #[test] - fn client_hello_payload_validation_precedes_transcript_commit() { - let cases: &[(u16, &[u8])] = &[ - (10, &[0, 2, 0, 23]), // supported_groups - (13, &[0, 2, 4, 3]), // signature_algorithms - (14, &[0, 2, 0, 1, 0]), // use_srtp - (11, &[1, 0]), // ec_point_formats - (0xffff, &[0xff]), // unknown extensions remain opaque - ]; - for &(kind, valid) in cases { - for malformed in [false, true] { - let mut payload = valid.to_vec(); - if malformed { - payload[0] = 0xff; // Internal length exceeds the extension envelope. - } - let mut body = MESSAGE[12..].to_vec(); - body.extend_from_slice(&((4 + payload.len()) as u16).to_be_bytes()); - body.extend_from_slice(&kind.to_be_bytes()); - body.extend_from_slice(&(payload.len() as u16).to_be_bytes()); - body.extend_from_slice(&payload); - // The parse path must also work with a nonzero root-buffer offset. - let mut source = vec![0; 7]; - source.extend_from_slice(&body); - let accepted = !malformed || kind == 0xffff; - assert_eq!( - Body::parse(&source[7..], 7, MessageType::ClientHello, None).is_ok(), - accepted, - "extension {kind}, malformed={malformed}" - ); - for fragmented in [false, true] { - let split = if fragmented { body.len() - 1 } else { body.len() }; - let mut fragments = vec![Handshake::new( - MessageType::ClientHello, - body.len() as u32, - 0, - 0, - split as u32, - Body::Fragment(0..split), - )]; - if fragmented { - fragments.push(Handshake::new( - MessageType::ClientHello, - body.len() as u32, - 0, - split as u32, - (body.len() - split) as u32, - Body::Fragment(split..body.len()), - )); - } - let mut buffer = Buf::new(); - let mut transcript = Buf::new(); - transcript.extend_from_slice(b"prior transcript"); - let result = Handshake::defragment( - fragments.iter().map(|h| (h, body.as_slice())), - &mut buffer, - None, - Some(&mut transcript), - ); - assert_eq!(result.is_ok(), accepted, "extension {kind}"); - assert!(fragments.iter().all(Handshake::is_handled)); - if !accepted { - assert_eq!(&*transcript, b"prior transcript"); - } - } - } - } - } - - #[test] - fn defragment_stops_at_cross_sequence_fragment() { - let body = &MESSAGE[12..]; - let mut source = body.to_vec(); - source.push(0); - - let handshake = Handshake::new( - MessageType::ClientHello, - body.len() as u32, - 0, - 0, - body.len() as u32, - Body::Fragment(0..body.len()), - ); - let decoy = Handshake::new( - MessageType::ClientHello, - body.len() as u32 + 1, - 1, - body.len() as u32, - 1, - Body::Fragment(body.len()..body.len() + 1), - ); - - let mut defragmented_buffer = Buf::new(); - let defragmented_handshake = Handshake::defragment( - [(&handshake, source.as_slice()), (&decoy, source.as_slice())].into_iter(), - &mut defragmented_buffer, - None, - None, - ) - .unwrap(); - - assert_eq!(defragmented_handshake.header.message_seq, 0); - assert_eq!(&defragmented_buffer[..body.len()], body); - assert!(handshake.is_handled()); - assert!(!decoy.is_handled()); - } - - #[test] - fn known_body_rejects_trailing_bytes() { - let body = [0]; - let handshake = Handshake::new( - MessageType::HelloRequest, - body.len() as u32, - 0, - 0, - body.len() as u32, - Body::Fragment(0..body.len()), - ); - - let mut defragmented_buffer = Buf::new(); - let mut transcript = Buf::new(); - let result = Handshake::defragment( - std::iter::once((&handshake, body.as_slice())), - &mut defragmented_buffer, - None, - Some(&mut transcript), - ); - - assert!(result.is_err()); - assert!(handshake.is_handled()); - assert!(transcript.is_empty()); - } - - #[test] - fn parse_rejects_invalid_client_hello_fragments() { - for (length, offset, fragment_length, valid) in [ - (4u32, 3u32, 2u32, false), // extends past the message - (4, 0, 0, false), // empty fragment - (0, 0, 0, false), // empty ClientHello - (4, 2, 2, true), // later fragment can arrive first - (1, 0, 1, true), // body validity is decided after reassembly - ] { - let mut packet = vec![MessageType::ClientHello.as_u8()]; - packet.extend_from_slice(&length.to_be_bytes()[1..]); - packet.extend_from_slice(&0u16.to_be_bytes()); - packet.extend_from_slice(&offset.to_be_bytes()[1..]); - packet.extend_from_slice(&fragment_length.to_be_bytes()[1..]); - packet.resize(packet.len() + fragment_length as usize, 0); - assert_eq!( - Handshake::parse(&packet, 0, None, true).is_ok(), - valid, - "length={length}, offset={offset}, fragment_length={fragment_length}" - ); - } - } - - #[test] - fn parse_accepts_empty_server_hello_done() { - let mut packet = vec![0; 12]; - packet[0] = MessageType::ServerHelloDone.as_u8(); - assert!(Handshake::parse(&packet, 0, None, true).is_ok()); - assert!(Handshake::parse(&packet, 0, None, false).is_ok()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/hello_verify.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/hello_verify.rs deleted file mode 100644 index 20b07749e79..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/hello_verify.rs +++ /dev/null @@ -1,84 +0,0 @@ -use super::ProtocolVersion; -use super::id::Cookie; -use crate::vendor::dimpl::buffer::Buf; -use nom::IResult; -use nom::error::{Error, ErrorKind}; - -#[derive(Debug, PartialEq, Eq)] -pub struct HelloVerifyRequest { - pub server_version: ProtocolVersion, - pub cookie: Cookie, -} - -impl HelloVerifyRequest { - pub fn new(server_version: ProtocolVersion, cookie: Cookie) -> Self { - HelloVerifyRequest { server_version, cookie } - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], HelloVerifyRequest> { - let (input, server_version) = ProtocolVersion::parse(input)?; - let (input, cookie) = Cookie::parse(input)?; - - if cookie.is_empty() { - return Err(nom::Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - - Ok((input, HelloVerifyRequest { server_version, cookie })) - } - - pub fn serialize(&self, output: &mut Buf) { - output.extend_from_slice(&self.server_version.as_u16().to_be_bytes()); - output.push(self.cookie.len() as u8); - output.extend_from_slice(&self.cookie); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 - 0x01, // Cookie length - 0xBB, // Cookie - ]; - - #[test] - fn roundtrip() { - let cookie = Cookie::try_new(&[0xBB]).unwrap(); - - let hello_verify_request = HelloVerifyRequest::new(ProtocolVersion::DTLS1_2, cookie); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - hello_verify_request.serialize(&mut serialized); - assert_eq!(&*serialized, MESSAGE); - - // Parse and compare with original - let (rest, parsed) = HelloVerifyRequest::parse(&serialized).unwrap(); - assert_eq!(parsed, hello_verify_request); - - assert!(rest.is_empty()); - } - - #[test] - fn empty_cookie() { - let message: &[u8] = &[ - 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 - 0x00, // Cookie length (0, which is empty) - ]; - - let result = HelloVerifyRequest::parse(message); - assert!(result.is_err()); - } - - #[test] - fn cookie_too_long() { - let mut message = MESSAGE.to_vec(); - message[2] = 0xFF; // Cookie length (255, which is too long) - - let result = HelloVerifyRequest::parse(&message); - assert!(result.is_err()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/id.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/id.rs deleted file mode 100644 index 14586a91bdb..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/id.rs +++ /dev/null @@ -1,128 +0,0 @@ -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::be_u8; -use nom::{Err, IResult}; -use std::fmt; -use std::ops::Deref; - -pub struct InvalidLength(&'static str, IdType, usize); - -impl fmt::Debug for InvalidLength { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self) - } -} - -impl std::error::Error for InvalidLength {} - -impl fmt::Display for InvalidLength { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self.1 { - IdType::Fixed(len) => write!( - f, - "Incorrect fixed ID ({}) length: {} should be {}", - self.0, self.2, len - ), - IdType::Variable(min, max) => write!( - f, - "Incorrect variable ID ({}) length: {} <= {} <= {}", - self.0, min, self.2, max, - ), - } - } -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum IdType { - #[allow(unused)] - Fixed(usize), - Variable(usize, usize), -} - -macro_rules! var_array { - ($name:ident, $min:expr, $max:expr) => { - #[derive(Clone, Copy)] - pub struct $name([u8; $max], usize); - - impl $name { - pub fn try_new(data: &[u8]) -> Result { - #[allow(unused_comparisons)] - if data.len() < $min || data.len() > $max { - return Err(InvalidLength( - stringify!($name), - IdType::Variable($min, $max), - data.len(), - )); - } - let mut array = [0; $max]; - array[..data.len()].copy_from_slice(data); - Ok($name(array, data.len())) - } - - pub fn empty() -> Self { - if $min > 0 { - panic!("{}::empty() is not valid", stringify!($name)); - } - Self([0; $max], 0) - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], Self> { - let (input, len) = be_u8(input)?; - if len < $min as u8 || len > $max as u8 { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - let (input, data) = take(len as usize)(input)?; - // unwrap() is ok because we check the size above. - let instance = Self::try_new(data).unwrap(); - Ok((input, instance)) - } - } - - impl fmt::Debug for $name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self) - } - } - - impl fmt::Display for $name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}({:02x?})", stringify!($name), &self.0[..self.1]) - } - } - - impl PartialEq for $name { - fn eq(&self, other: &Self) -> bool { - self.deref() == other.deref() - } - } - - impl Eq for $name {} - - impl Deref for $name { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0[..self.1] - } - } - - impl<'a> TryFrom<&'a [u8]> for $name { - type Error = InvalidLength; - - fn try_from(value: &'a [u8]) -> Result { - Self::try_new(value) - } - } - - impl<'a> TryFrom<&'a str> for $name { - type Error = InvalidLength; - - fn try_from(value: &'a str) -> Result { - Self::try_new(value.as_bytes()) - } - } - }; -} - -var_array!(SessionId, 0, 32); -var_array!(Cookie, 0, 255); diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/mod.rs deleted file mode 100644 index 9570b08e840..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/mod.rs +++ /dev/null @@ -1,440 +0,0 @@ -//! Low-level DTLS message parsing and serialization types. -//! -//! This module exposes enums and helpers used by the public API for negotiating -//! cipher suites and signature algorithms, as well as parsing wire formats. -//! Only the public items are documented here; the rest are internal helpers. - -mod certificate; -mod certificate_request; -mod certificate_verify; -mod client_hello; -mod client_key_exchange; -mod digitally_signed; -mod extension; -mod extensions; -mod finished; -mod handshake; -mod hello_verify; -mod id; -mod named_group; -mod record; -mod server_hello; -mod server_key_exchange; -mod wrapped; - -use std::fmt; - -use arrayvec::ArrayVec; -pub use certificate::Certificate; -pub use certificate_request::CertificateRequest; -pub use certificate_verify::CertificateVerify; -pub use client_hello::ClientHello; -pub use client_key_exchange::{ClientKeyExchange, ClientPskKeys, ExchangeKeys}; -pub use digitally_signed::DigitallySigned; -pub use extension::{Extension, ExtensionType}; -pub use extensions::ECPointFormatsExtension; -pub use extensions::SignatureAlgorithmsExtension; -pub use extensions::SupportedGroupsExtension; -pub use extensions::UseSrtpExtension; -pub use extensions::use_srtp::{SrtpProfileId, SrtpProfileVec}; -pub use finished::Finished; -pub use handshake::{Body, Handshake, Header, MessageType}; -pub use hello_verify::HelloVerifyRequest; -pub use id::{Cookie, SessionId}; -pub use named_group::CurveType; -pub use record::DTLSRecord; - -// Re-export shared types for backwards compatibility -pub use crate::vendor::dimpl::types::{ - CompressionMethod, ContentType, HashAlgorithm, NamedGroup, NamedGroupVec, ProtocolVersion, Random, Sequence, - SignatureAlgorithm, -}; -pub use server_hello::ServerHello; -pub use server_key_exchange::{PskParams, ServerKeyExchange, ServerKeyExchangeParams}; -pub use wrapped::{Asn1Cert, DistinguishedName}; - -use nom::IResult; -use nom::number::complete::{be_u8, be_u16}; - -pub type CipherSuiteVec = ArrayVec; - -/// Supported TLS 1.2 cipher suites for DTLS. -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct Dtls12CipherSuite(u16); - -impl Dtls12CipherSuite { - /// ECDHE with ECDSA authentication, AES-256-GCM, SHA-384. - pub const ECDHE_ECDSA_AES256_GCM_SHA384: Self = Self(0xC02C); - /// ECDHE with ECDSA authentication, AES-128-GCM, SHA-256. - pub const ECDHE_ECDSA_AES128_GCM_SHA256: Self = Self(0xC02B); - /// ECDHE with ECDSA authentication, ChaCha20-Poly1305, SHA-256. - pub const ECDHE_ECDSA_CHACHA20_POLY1305_SHA256: Self = Self(0xCCA9); - /// PSK with AES-128-CCM-8 (8-byte tag), SHA-256. - pub const PSK_AES128_CCM_8: Self = Self(0xC0A8); - - /// Convert the 16-bit IANA value to a `Dtls12CipherSuite`. - pub const fn from_u16(value: u16) -> Self { - Self(value) - } - - /// Return the 16-bit IANA value for this cipher suite. - pub const fn as_u16(&self) -> u16 { - self.0 - } - - /// Returns true if this is not a known DTLS 1.2 cipher suite wire value. - pub const fn is_unknown(&self) -> bool { - !matches!(*self, Self(0xC02B..=0xC02C | 0xC0A8 | 0xCCA9)) - } - - /// Parse a `Dtls12CipherSuite` from network byte order. - pub fn parse(input: &[u8]) -> IResult<&[u8], Dtls12CipherSuite> { - let (input, value) = be_u16(input)?; - Ok((input, Dtls12CipherSuite::from_u16(value))) - } - - /// Length in bytes of verify_data for Finished MACs. - pub fn verify_data_length(&self) -> usize { - match *self { - // AES-GCM suites - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 - | Dtls12CipherSuite::PSK_AES128_CCM_8 => 12, - - _ => 12, // Default length for unknown cipher suites - } - } - - /// The key exchange algorithm family for this cipher suite. - pub fn as_key_exchange_algorithm(&self) -> KeyExchangeAlgorithm { - match *self { - // All ECDHE ciphers - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => KeyExchangeAlgorithm::EECDH, - - Dtls12CipherSuite::PSK_AES128_CCM_8 => KeyExchangeAlgorithm::PSK, - - _ => KeyExchangeAlgorithm::Unknown, - } - } - - /// Whether this cipher suite uses ECC-based key exchange. - pub fn has_ecc(&self) -> bool { - matches!( - *self, - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 - ) - } - - /// Whether this cipher suite uses PSK (Pre-Shared Key) key exchange. - pub fn is_psk(&self) -> bool { - matches!(*self, Dtls12CipherSuite::PSK_AES128_CCM_8) - } - - /// All supported cipher suites in server preference order. - pub const fn all() -> &'static [Dtls12CipherSuite] { - &[ - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384, - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, - Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, - Dtls12CipherSuite::PSK_AES128_CCM_8, - ] - } - - /// Cipher suites compatible with a given certificate's signature algorithm. - pub fn compatible_with_certificate(cert_type: SignatureAlgorithm) -> &'static [Dtls12CipherSuite] { - match cert_type { - SignatureAlgorithm::ECDSA => &[ - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384, - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, - Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, - ], - _ => panic!("Need either RSA or ECDSA certificate"), - } - } - - fn need_encrypt_then_mac(&self) -> bool { - // We do not support and ciphers such as: - // ECDHE-RSA-AES128-SHA - // ECDHE-RSA-AES256-SHA - // DHE-RSA-AES128-SHA256 - false - } - - /// The hash algorithm used by this cipher suite. - pub fn hash_algorithm(&self) -> HashAlgorithm { - match *self { - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 => HashAlgorithm::SHA384, - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 - | Dtls12CipherSuite::PSK_AES128_CCM_8 => HashAlgorithm::SHA256, - _ => HashAlgorithm::UNKNOWN_DERIVED, - } - } - - /// The signature algorithm associated with the suite's key exchange. - /// - /// Returns `None` for PSK cipher suites (no signature authentication). - pub fn signature_algorithm(&self) -> Option { - match *self { - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 - | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => Some(SignatureAlgorithm::ECDSA), - Dtls12CipherSuite::PSK_AES128_CCM_8 => None, - _ => Some(SignatureAlgorithm::UNKNOWN_DERIVED), - } - } - - /// Returns true if this cipher suite is supported by this implementation. - pub fn is_supported(&self) -> bool { - Self::supported().contains(self) - } - - /// Supported DTLS 1.2 cipher suites in server preference order. - pub const fn supported() -> &'static [Dtls12CipherSuite] { - Self::all() - } -} - -impl fmt::Debug for Dtls12CipherSuite { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 => f.write_str("ECDHE_ECDSA_AES256_GCM_SHA384"), - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 => f.write_str("ECDHE_ECDSA_AES128_GCM_SHA256"), - Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => { - f.write_str("ECDHE_ECDSA_CHACHA20_POLY1305_SHA256") - } - Dtls12CipherSuite::PSK_AES128_CCM_8 => f.write_str("PSK_AES128_CCM_8"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -pub type CompressionMethodVec = ArrayVec; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[allow(non_camel_case_types)] -#[allow(clippy::upper_case_acronyms)] -pub enum KeyExchangeAlgorithm { - EECDH, - PSK, - Unknown, -} - -pub type CertificateTypeVec = ArrayVec; - -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct ClientCertificateType(u8); - -impl ClientCertificateType { - pub const RSA_SIGN: Self = Self(1); - pub const DSS_SIGN: Self = Self(2); - pub const RSA_FIXED_DH: Self = Self(3); - pub const DSS_FIXED_DH: Self = Self(4); - pub const RSA_EPHEMERAL_DH: Self = Self(5); - pub const DSS_EPHEMERAL_DH: Self = Self(6); - pub const FORTEZZA_DMS: Self = Self(20); - pub const ECDSA_SIGN: Self = Self(64); - - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - /// Returns true if this certificate type is supported by this implementation. - /// Currently only ECDSA_SIGN is supported. - pub fn is_supported(&self) -> bool { - Self::supported().contains(self) - } - - /// Supported client certificate types. - pub const fn supported() -> &'static [ClientCertificateType; 1] { - &[ClientCertificateType::ECDSA_SIGN] - } - - pub const fn as_u8(&self) -> u8 { - self.0 - } - - const fn is_unknown(&self) -> bool { - !matches!(*self, Self(1..=6 | 20 | 64)) - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], ClientCertificateType> { - let (input, value) = be_u8(input)?; - Ok((input, ClientCertificateType::from_u8(value))) - } -} - -impl fmt::Debug for ClientCertificateType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.is_unknown() { - return f.debug_tuple("Unknown").field(&self.0).finish(); - } - - let name = match *self { - ClientCertificateType::RSA_SIGN => "RSA_SIGN", - ClientCertificateType::DSS_SIGN => "DSS_SIGN", - ClientCertificateType::RSA_FIXED_DH => "RSA_FIXED_DH", - ClientCertificateType::DSS_FIXED_DH => "DSS_FIXED_DH", - ClientCertificateType::RSA_EPHEMERAL_DH => "RSA_EPHEMERAL_DH", - ClientCertificateType::DSS_EPHEMERAL_DH => "DSS_EPHEMERAL_DH", - ClientCertificateType::FORTEZZA_DMS => "FORTEZZA_DMS", - ClientCertificateType::ECDSA_SIGN => "ECDSA_SIGN", - _ => unreachable!("known DTLS 1.2 client certificate type missing Debug label"), - }; - - f.write_str(name) - } -} - -// SignatureAlgorithm and HashAlgorithm are now in crate::vendor::dimpl::types - -pub type SignatureAndHashAlgorithmVec = - ArrayVec; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct SignatureAndHashAlgorithm { - pub hash: HashAlgorithm, - pub signature: SignatureAlgorithm, -} - -impl SignatureAndHashAlgorithm { - pub const fn new(hash: HashAlgorithm, signature: SignatureAlgorithm) -> Self { - SignatureAndHashAlgorithm { hash, signature } - } - - pub fn from_u16(value: u16) -> Self { - let hash = HashAlgorithm::from_u8((value >> 8) as u8); - let signature = SignatureAlgorithm::from_u8(value as u8); - SignatureAndHashAlgorithm { hash, signature } - } - - pub fn as_u16(&self) -> u16 { - ((self.hash.as_u8() as u16) << 8) | (self.signature.as_u8() as u16) - } - - pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAndHashAlgorithm> { - let (input, value) = be_u16(input)?; - Ok((input, SignatureAndHashAlgorithm::from_u16(value))) - } - - /// All recognized signature+hash combinations. - #[allow(dead_code)] - pub const fn all() -> &'static [SignatureAndHashAlgorithm; 4] { - const ALL: &[SignatureAndHashAlgorithm; 4] = &[ - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA), - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA), - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA), - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::RSA), - ]; - - ALL - } - - /// Supported signature+hash combinations. - pub const fn supported() -> &'static [SignatureAndHashAlgorithm; 2] { - const SUPPORTED: &[SignatureAndHashAlgorithm; 2] = &[ - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA), - SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA), - ]; - - SUPPORTED - } - - /// Returns true if this signature+hash combination is supported. - pub fn is_supported(&self) -> bool { - Self::supported().contains(self) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rsa_signature_algorithms_are_recognized_but_not_supported() { - let rsa_sha256 = SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA); - - assert!(SignatureAndHashAlgorithm::all().contains(&rsa_sha256)); - assert!(!rsa_sha256.is_supported()); - assert_eq!(SignatureAndHashAlgorithm::supported().len(), 2); - } - - #[test] - fn dtls12_cipher_suite_newtype_shape() { - assert_eq!(std::mem::size_of::(), 2); - assert_eq!(Dtls12CipherSuite::default().as_u16(), 0); - assert!(Dtls12CipherSuite::default().is_unknown()); - } - - #[test] - fn dtls12_cipher_suite_wire_roundtrip() { - for suite in Dtls12CipherSuite::all() { - assert_eq!(Dtls12CipherSuite::from_u16(suite.as_u16()), *suite); - assert!(!suite.is_unknown()); - } - - let unknown = Dtls12CipherSuite::from_u16(0xFFFF); - assert_eq!(unknown.as_u16(), 0xFFFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn dtls12_cipher_suite_debug_stays_enum_like() { - assert_eq!( - format!("{:?}", Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256), - "ECDHE_ECDSA_AES128_GCM_SHA256" - ); - assert_eq!(format!("{:?}", Dtls12CipherSuite::from_u16(0xFFFF)), "Unknown(65535)"); - } - - #[test] - fn client_certificate_type_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - assert_eq!(ClientCertificateType::default().as_u8(), 0); - assert!(ClientCertificateType::default().is_unknown()); - } - - #[test] - fn client_certificate_type_wire_roundtrip() { - for certificate_type in [ - ClientCertificateType::RSA_SIGN, - ClientCertificateType::DSS_SIGN, - ClientCertificateType::RSA_FIXED_DH, - ClientCertificateType::DSS_FIXED_DH, - ClientCertificateType::RSA_EPHEMERAL_DH, - ClientCertificateType::DSS_EPHEMERAL_DH, - ClientCertificateType::FORTEZZA_DMS, - ClientCertificateType::ECDSA_SIGN, - ] { - assert_eq!( - ClientCertificateType::from_u8(certificate_type.as_u8()), - certificate_type - ); - assert!(!certificate_type.is_unknown()); - } - - let unknown = ClientCertificateType::from_u8(0xFF); - assert_eq!(unknown.as_u8(), 0xFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn client_certificate_type_debug_stays_enum_like() { - assert_eq!(format!("{:?}", ClientCertificateType::ECDSA_SIGN), "ECDSA_SIGN"); - assert_eq!(format!("{:?}", ClientCertificateType::from_u8(0xFF)), "Unknown(255)"); - } - - #[test] - fn unknown_dtls12_cipher_suite_uses_internal_derived_markers() { - let unknown = Dtls12CipherSuite::from_u16(0xFFFF); - assert!(unknown.hash_algorithm().is_unknown()); - assert!(unknown.signature_algorithm().is_some_and(|s| s.is_unknown())); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/named_group.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/named_group.rs deleted file mode 100644 index 6b3238f364c..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/named_group.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! DTLS 1.2 curve type definitions. -//! -//! NamedGroup is now in crate::vendor::dimpl::types as it's shared between DTLS versions. -//! CurveType is DTLS 1.2 specific (used in ServerKeyExchange). - -use nom::IResult; -use nom::number::complete::be_u8; -use std::fmt; - -/// Curve type for ECDH parameters in DTLS 1.2. -/// -/// This is specific to DTLS 1.2's ServerKeyExchange message format. -#[repr(transparent)] -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct CurveType(u8); - -#[allow(non_upper_case_globals)] -impl CurveType { - /// Explicit prime curve parameters. - pub const ExplicitPrime: Self = Self(1); - /// Explicit characteristic-2 curve parameters. - pub const ExplicitChar2: Self = Self(2); - /// Named curve (the common case). - pub const NamedCurve: Self = Self(3); - - /// Convert a u8 value to a `CurveType`. - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - /// Convert this `CurveType` to its u8 value. - pub const fn as_u8(&self) -> u8 { - self.0 - } - - const fn is_unknown(&self) -> bool { - !matches!(*self, Self(1..=3)) - } - - /// Parse a `CurveType` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], CurveType> { - let (input, value) = be_u8(input)?; - Ok((input, CurveType::from_u8(value))) - } -} - -impl fmt::Debug for CurveType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.is_unknown() { - return f.debug_tuple("Unknown").field(&self.0).finish(); - } - - let name = match *self { - CurveType::ExplicitPrime => "ExplicitPrime", - CurveType::ExplicitChar2 => "ExplicitChar2", - CurveType::NamedCurve => "NamedCurve", - _ => unreachable!("known DTLS 1.2 curve type missing Debug label"), - }; - - f.write_str(name) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn curve_type_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - } - - #[test] - fn curve_type_wire_roundtrip() { - for curve_type in [ - CurveType::ExplicitPrime, - CurveType::ExplicitChar2, - CurveType::NamedCurve, - ] { - assert_eq!(CurveType::from_u8(curve_type.as_u8()), curve_type); - assert!(!curve_type.is_unknown()); - } - - let unknown = CurveType::from_u8(0xFF); - assert_eq!(unknown.as_u8(), 0xFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn curve_type_debug_stays_enum_like() { - assert_eq!(format!("{:?}", CurveType::NamedCurve), "NamedCurve"); - assert_eq!(format!("{:?}", CurveType::from_u8(0xFF)), "Unknown(255)"); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/record.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/record.rs deleted file mode 100644 index b05df1d6619..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/record.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! DTLS 1.2 record layer types. -//! -//! ContentType and Sequence are now in crate::vendor::dimpl::types as they're shared between DTLS versions. - -use std::fmt; -use std::ops::Range; - -use super::ProtocolVersion; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::types::{ContentType, Sequence}; -use crate::vendor::dimpl::util::be_u48; -use nom::bytes::complete::take; -use nom::number::complete::be_u16; -use nom::{Err, IResult}; - -/// DTLS 1.2 record structure. -#[derive(PartialEq, Eq, Default)] -pub struct DTLSRecord { - /// The content type of this record. - pub content_type: ContentType, - /// The protocol version. - pub version: ProtocolVersion, - /// The epoch and sequence number. - pub sequence: Sequence, - /// The length of the fragment. - pub length: u16, - /// The range of the fragment in the source buffer. - pub fragment_range: Range, -} - -impl DTLSRecord { - /// DTLS record header length: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) - pub const HEADER_LEN: usize = 13; - - /// Length of the explicit nonce prefix in DTLS 1.2 AES-GCM records. - pub const EXPLICIT_NONCE_LEN: usize = 8; - - /// Byte offset in the record header where the 2-byte length field is - pub const LENGTH_OFFSET: Range = 11..13; - - /// Parse a DTLS record from the input buffer. - pub fn parse(input: &[u8], base_offset: usize, skip_offset: usize) -> IResult<&[u8], DTLSRecord> { - let original_input = input; - let (input, content_type) = ContentType::parse(input)?; // u8 - let (input, version) = ProtocolVersion::parse(input)?; // u16 - - // Accept DTLS 1.0 or 1.2 in record layer per RFC 6347 - // DTLS 1.0 (0xFEFF) is often used in record layer during handshake for compatibility - // The actual protocol version is negotiated in the handshake messages - match version { - ProtocolVersion::DTLS1_0 | ProtocolVersion::DTLS1_2 => { - // Valid DTLS versions for record layer - } - _ => { - return Err(Err::Failure(nom::error::Error::new(input, nom::error::ErrorKind::Tag))); - } - } - - let (input, epoch) = be_u16(input)?; // u16 - - // Epoch 0 records are plaintext in DTLS 1.2. Reject plaintext - // ApplicationData before record protection is active, and only accept - // the epoch-0 content types this implementation supports. - if epoch == 0 { - match content_type { - ContentType::ChangeCipherSpec | ContentType::Alert | ContentType::Handshake => {} - _ => { - return Err(Err::Failure(nom::error::Error::new(input, nom::error::ErrorKind::Tag))); - } - } - } - let (input, sequence_number) = be_u48(input)?; // u48 - let (input, length) = be_u16(input)?; // u16 - - // When encrypted, skip_offset is 0 and this has the explicit nonce. - // When decrypted, skip_offset is > 0 to skip the explicit nonce. - let input = &input[skip_offset..]; - - let (rest, fragment_slice) = take(length as usize)(input)?; - - // Calculate absolute range in root buffer - // fragment_slice is already offset from original_input by all the header bytes and skip_offset - let relative_offset = fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + fragment_slice.len(); - - let sequence = Sequence { epoch, sequence_number }; - - Ok(( - rest, - DTLSRecord { - content_type, - version, - sequence, - length, - fragment_range: start..end, - }, - )) - } - - /// Get the fragment data from the source buffer. - pub fn fragment<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.fragment_range.clone()] - } - - /// Serialize this record to the output buffer. - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - output.push(self.content_type.as_u8()); - self.version.serialize(output); - output.extend_from_slice(&self.sequence.epoch.to_be_bytes()); - output.extend_from_slice(&self.sequence.sequence_number.to_be_bytes()[2..]); - output.extend_from_slice(&self.length.to_be_bytes()); - output.extend_from_slice(self.fragment(buf)); - } - - /// Get the explicit nonce from the fragment using the requested length. - pub fn nonce_with_len<'a>(&self, buf: &'a [u8], len: usize) -> &'a [u8] { - let fragment = self.fragment(buf); - &fragment[..len] - } - - /// Get the explicit nonce from the fragment (AES-GCM default). - pub fn nonce<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - self.nonce_with_len(buf, Self::EXPLICIT_NONCE_LEN) - } -} - -impl fmt::Debug for DTLSRecord { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DTLSRecord") - .field("content_type", &self.content_type) - .field("version", &self.version) - .field("sequence", &self.sequence) - .field("length", &self.length) - .field("fragment_range", &self.fragment_range) - .finish() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const RECORD: &[u8] = &[ - 0x16, // ContentType::Handshake - 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 - 0x00, 0x01, // epoch - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // sequence_number - 0x00, 0x10, // length - // fragment - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, - ]; - - #[test] - fn roundtrip() { - // Parse the record with base_offset 0, skip_offset 0 - let (rest, parsed) = DTLSRecord::parse(RECORD, 0, 0).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to RECORD - let mut serialized = Buf::new(); - parsed.serialize(RECORD, &mut serialized); - assert_eq!(&*serialized, RECORD); - } - - #[test] - fn epoch_0_content_type_whitelist() { - // Epoch 0 is plaintext (RFC 6347 §4.1: epoch starts at 0, incremented by each CCS). - // Only ChangeCipherSpec(20), Alert(21), and Handshake(22) can legitimately - // appear unencrypted. ApplicationData in epoch 0 is rejected at parse time. - - fn build_epoch_0_record(content_type: u8) -> Vec { - vec![ - content_type, // ContentType - 0xFE, - 0xFD, // version: DTLS 1.2 - 0x00, - 0x00, // epoch: 0 (plaintext) - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x01, // sequence_number - 0x00, - 0x02, // length: 2 - 0xAA, - 0xBB, // fragment payload - ] - } - - // ALLOWED: ChangeCipherSpec (20) - let ccs = build_epoch_0_record(0x14); - assert!( - DTLSRecord::parse(&ccs, 0, 0).is_ok(), - "ChangeCipherSpec should be allowed in epoch 0" - ); - - // ALLOWED: Alert (21) - let alert = build_epoch_0_record(0x15); - assert!( - DTLSRecord::parse(&alert, 0, 0).is_ok(), - "Alert should be allowed in epoch 0" - ); - - // ALLOWED: Handshake (22) - let handshake = build_epoch_0_record(0x16); - assert!( - DTLSRecord::parse(&handshake, 0, 0).is_ok(), - "Handshake should be allowed in epoch 0" - ); - - // REJECTED: ApplicationData (23) - let app_data = build_epoch_0_record(0x17); - assert!( - DTLSRecord::parse(&app_data, 0, 0).is_err(), - "ApplicationData must be rejected in epoch 0" - ); - - // REJECTED: Ack (26) - valid in DTLS 1.3 but not DTLS 1.2 - let ack = build_epoch_0_record(0x1A); - assert!( - DTLSRecord::parse(&ack, 0, 0).is_err(), - "Ack must be rejected in DTLS 1.2 epoch 0" - ); - - // REJECTED: Unknown ContentType (0x99) - let unknown = build_epoch_0_record(0x99); - assert!( - DTLSRecord::parse(&unknown, 0, 0).is_err(), - "Unknown ContentType must be rejected in epoch 0" - ); - - // Verify that epoch 1+ allows ApplicationData (no whitelist restriction) - let mut epoch_1_app_data = build_epoch_0_record(0x17); - epoch_1_app_data[3] = 0x00; // epoch high byte - epoch_1_app_data[4] = 0x01; // epoch low byte = 1 - assert!( - DTLSRecord::parse(&epoch_1_app_data, 0, 0).is_ok(), - "ApplicationData should be allowed in epoch 1+" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/server_hello.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/server_hello.rs deleted file mode 100644 index 820989aac72..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/server_hello.rs +++ /dev/null @@ -1,262 +0,0 @@ -use super::SrtpProfileVec; -use super::extension::ExtensionVec; -use super::extensions::use_srtp::{SrtpProfileId, UseSrtpExtension}; -use super::{CompressionMethod, Dtls12CipherSuite, Extension, ExtensionType}; -use super::{ProtocolVersion, Random, SessionId}; -use crate::vendor::dimpl::buffer::Buf; -use arrayvec::ArrayVec; -use nom::Err; -use nom::error::{Error, ErrorKind}; -use nom::{IResult, bytes::complete::take, number::complete::be_u16}; - -#[derive(Debug, PartialEq, Eq)] -pub struct ServerHello { - pub server_version: ProtocolVersion, - pub random: Random, - pub session_id: SessionId, - pub cipher_suite: Dtls12CipherSuite, - pub compression_method: CompressionMethod, - pub extensions: Option, - // Receive-side values; outbound serialization uses the raw extensions above. - srtp_profiles: Option, -} - -impl ServerHello { - pub fn new( - server_version: ProtocolVersion, - random: Random, - session_id: SessionId, - cipher_suite: Dtls12CipherSuite, - compression_method: CompressionMethod, - extensions: Option, - ) -> Self { - ServerHello { - server_version, - random, - session_id, - cipher_suite, - compression_method, - extensions, - srtp_profiles: None, - } - } - - /// Add extensions to ServerHello using a builder-style API, mirroring ClientHello::with_extensions - /// - /// - Uses the provided buffer to stage extension bytes and then stores Range references - /// - Includes UseSRTP if a profile is provided - /// - Includes Extended Master Secret if the flag is set - pub fn with_extensions(mut self, buf: &mut Buf, srtp_profile: Option) -> Self { - // Clear the buffer and collect extension byte ranges - buf.clear(); - - let mut ranges: ArrayVec<(ExtensionType, usize, usize), { ExtensionType::supported().len() }> = ArrayVec::new(); - - // UseSRTP (if negotiated) - if let Some(pid) = srtp_profile { - let start = buf.len(); - let mut profiles = ArrayVec::new(); - profiles.push(pid); - let ext = UseSrtpExtension::new(profiles, ArrayVec::new()); - ext.serialize(buf); - ranges.push((ExtensionType::UseSrtp, start, buf.len())); - } - - // Extended Master Secret (mandatory) - let start = buf.len(); - ranges.push((ExtensionType::ExtendedMasterSecret, start, start)); - - // Renegotiation Info (RFC 5746) - empty for initial handshake - let start = buf.len(); - buf.push(0); // renegotiated_connection length = 0 - ranges.push((ExtensionType::RenegotiationInfo, start, buf.len())); - - let mut extensions = ExtensionVec::new(); - for (t, s, e) in ranges { - extensions.push(Extension { - extension_type: t, - extension_data_range: s..e, - }); - } - self.extensions = Some(extensions); - - self - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ServerHello> { - let original_input = input; - let mut srtp_profiles = None; - let (input, server_version) = ProtocolVersion::parse(input)?; - let (input, random) = Random::parse(input)?; - let (input, session_id) = SessionId::parse(input)?; - let (input, cipher_suite) = Dtls12CipherSuite::parse(input)?; - let (input, compression_method) = CompressionMethod::parse(input)?; - - // Parse extensions if there are any bytes left - let (input, extensions) = if !input.is_empty() { - // Check if we have enough bytes to read the extensions length (2 bytes) - if input.len() < 2 { - return Err(Err::Failure(Error::new(input, ErrorKind::Eof))); - } - let (input, extensions_len) = be_u16(input)?; - - // Check if we have enough bytes to read the extensions data - if input.len() < extensions_len as usize { - return Err(Err::Failure(Error::new(input, ErrorKind::Eof))); - } - - if extensions_len > 0 { - let (rest, input_ext) = take(extensions_len)(input)?; - if !rest.is_empty() { - return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); - } - let consumed_to_ext_data = input_ext.as_ptr() as usize - original_input.as_ptr() as usize; - let ext_base_offset = base_offset + consumed_to_ext_data; - - // Parse extensions manually to pass base_offset, filtering unknown types - let mut extensions_vec = ExtensionVec::new(); - let mut current_input = input_ext; - let mut current_offset = ext_base_offset; - while !current_input.is_empty() { - let before_len = current_input.len(); - let (new_rest, ext) = Extension::parse(current_input, current_offset)?; - let parsed_len = before_len - new_rest.len(); - current_offset += parsed_len; - // Only keep supported extension types - if ext.extension_type.is_supported() { - if extensions_vec - .iter() - .any(|existing| existing.extension_type == ext.extension_type) - { - return Err(Err::Failure(Error::new(current_input, ErrorKind::LengthValue))); - } - if ext.extension_type == ExtensionType::UseSrtp { - let range = &ext.extension_data_range; - let data = &original_input[range.start - base_offset..range.end - base_offset]; - srtp_profiles = Some(UseSrtpExtension::parse(data)?.1.profiles); - } - extensions_vec - .try_push(ext) - .map_err(|_| Err::Failure(Error::new(current_input, ErrorKind::LengthValue)))?; - } - current_input = new_rest; - } - (rest, Some(extensions_vec)) - } else { - (input, None) - } - } else { - (input, None) - }; - - Ok(( - input, - ServerHello { - server_version, - random, - session_id, - cipher_suite, - compression_method, - extensions, - srtp_profiles, - }, - )) - } - - pub fn srtp_profiles(&self) -> Option<&SrtpProfileVec> { - self.srtp_profiles.as_ref() - } - - pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { - output.extend_from_slice(&self.server_version.as_u16().to_be_bytes()); - self.random.serialize(output); - output.push(self.session_id.len() as u8); - output.extend_from_slice(&self.session_id); - output.extend_from_slice(&self.cipher_suite.as_u16().to_be_bytes()); - output.push(self.compression_method.as_u8()); - if let Some(extensions) = &self.extensions { - // Calculate total extensions length according to spec: - // For each extension: type (2) + length (2) + data - let mut extensions_len = 0; - for ext in extensions.iter() { - let ext_data = ext.extension_data(source_buf); - extensions_len += 2 + 2 + ext_data.len(); - } - - // Write extensions length - output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); - - // Write each extension - for ext in extensions { - ext.serialize(source_buf, output); - } - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE: &[u8] = &[ - 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 - // Random - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, // - 0x01, // SessionId length - 0xAA, // SessionId - 0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 - 0x00, // CompressionMethod::Null - 0x00, 0x0C, // Extensions length (12 bytes total: 2 type + 2 length + 8 data) - 0x00, 0x0A, // ExtensionType::SupportedGroups - 0x00, 0x08, // Extension data length (8 bytes) - 0x00, 0x06, // Extension data - 0x00, 0x17, // NamedGroup::Secp256r1 - 0x00, 0x18, // NamedGroup::Secp384r1 - 0x00, 0x19, // NamedGroup::Secp521r1 - ]; - - #[test] - fn roundtrip() { - // Parse the message first to get the Extension with proper ranges - let (rest, parsed) = ServerHello::parse(MESSAGE, 0).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to MESSAGE - let mut serialized = Buf::new(); - parsed.serialize(MESSAGE, &mut serialized); - assert_eq!(&*serialized, MESSAGE); - } - - #[test] - fn session_id_too_long() { - let mut message = MESSAGE.to_vec(); - message[34] = 0x21; // SessionId length (33, which is too long) - - let result = ServerHello::parse(&message, 0); - assert!(result.is_err()); - } - - #[test] - fn duplicate_supported_extensions_are_rejected() { - for count in [2, 9] { - let mut message = MESSAGE[..39].to_vec(); - message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); - for _ in 0..count { - message.extend_from_slice(&ExtensionType::ExtendedMasterSecret.as_u16().to_be_bytes()); - message.extend_from_slice(&0u16.to_be_bytes()); - } - - let result = ServerHello::parse(&message, 0); - assert!( - matches!( - result, - Err(nom::Err::Failure(error)) - if error.code == nom::error::ErrorKind::LengthValue - ), - "duplicate supported extensions should fail with LengthValue" - ); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/server_key_exchange.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/server_key_exchange.rs deleted file mode 100644 index 8e07ac09078..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/server_key_exchange.rs +++ /dev/null @@ -1,234 +0,0 @@ -use super::{CurveType, DigitallySigned, KeyExchangeAlgorithm, NamedGroup}; -use crate::vendor::dimpl::buffer::Buf; -use nom::Err; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::be_u8; -use nom::{IResult, bytes::complete::take}; -use std::ops::Range; - -#[derive(Debug, PartialEq, Eq)] -pub struct ServerKeyExchange { - pub params: ServerKeyExchangeParams, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum ServerKeyExchangeParams { - Ecdh(EcdhParams), - Psk(PskParams), -} - -impl ServerKeyExchange { - pub fn parse( - input: &[u8], - base_offset: usize, - key_exchange_algorithm: KeyExchangeAlgorithm, - ) -> IResult<&[u8], ServerKeyExchange> { - let (input, params) = match key_exchange_algorithm { - KeyExchangeAlgorithm::EECDH => { - let (input, ecdh_params) = EcdhParams::parse(input, base_offset)?; - (input, ServerKeyExchangeParams::Ecdh(ecdh_params)) - } - KeyExchangeAlgorithm::PSK => { - let (input, psk_params) = PskParams::parse(input, base_offset)?; - (input, ServerKeyExchangeParams::Psk(psk_params)) - } - _ => return Err(Err::Failure(Error::new(input, ErrorKind::Tag))), - }; - - Ok((input, ServerKeyExchange { params })) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf, with_signature: bool) { - match &self.params { - ServerKeyExchangeParams::Ecdh(ecdh_params) => ecdh_params.serialize(buf, output, with_signature), - ServerKeyExchangeParams::Psk(psk_params) => psk_params.serialize(buf, output), - } - } - - pub fn signature(&self) -> Option<&DigitallySigned> { - match &self.params { - ServerKeyExchangeParams::Ecdh(ecdh_params) => ecdh_params.signature.as_ref(), - ServerKeyExchangeParams::Psk(_) => None, - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct EcdhParams { - pub curve_type: CurveType, - pub named_group: NamedGroup, - pub public_key_range: Range, - pub signature: Option, -} - -impl EcdhParams { - pub fn public_key<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.public_key_range.clone()] - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], EcdhParams> { - let original_input = input; - let (input, curve_type) = CurveType::parse(input)?; - let (input, named_group) = NamedGroup::parse(input)?; - - // First byte is the length of the public key - let (input, public_key_len) = be_u8(input)?; - let (input, public_key_slice) = take(public_key_len as usize)(input)?; - - // Calculate absolute range for public key - let relative_offset = public_key_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + public_key_slice.len(); - let public_key_range = start..end; - - // Optionally parse a trailing DigitallySigned structure - let (input, signature) = if !input.is_empty() { - // Calculate absolute offset for the signature part - let sig_offset = base_offset + (input.as_ptr() as usize - original_input.as_ptr() as usize); - let (rest, signed) = DigitallySigned::parse(input, sig_offset)?; - (rest, Some(signed)) - } else { - (input, None) - }; - - Ok(( - input, - EcdhParams { - curve_type, - named_group, - public_key_range, - signature, - }, - )) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf, with_signature: bool) { - let public_key = self.public_key(buf); - output.push(self.curve_type.as_u8()); - output.extend_from_slice(&self.named_group.as_u16().to_be_bytes()); - output.push(public_key.len() as u8); - output.extend_from_slice(public_key); - - if with_signature && let Some(signed) = &self.signature { - signed.serialize(buf, output); - } - } -} - -/// PSK identity hint (RFC 4279 §2). -/// -/// Wire format: `uint16 hint_length + hint` -#[derive(Debug, PartialEq, Eq)] -pub struct PskParams { - pub hint_range: Range, -} - -impl PskParams { - pub fn hint<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.hint_range.clone()] - } - - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], PskParams> { - let original_input = input; - let (input, hint_len) = nom::number::complete::be_u16(input)?; - let (input, hint_slice) = take(hint_len as usize)(input)?; - - let relative_offset = hint_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + hint_slice.len(); - - Ok((input, PskParams { hint_range: start..end })) - } - - pub fn serialize(&self, buf: &[u8], output: &mut Buf) { - let hint = self.hint(buf); - output.extend_from_slice(&(hint.len() as u16).to_be_bytes()); - output.extend_from_slice(hint); - } - - /// Serialize directly from hint bytes (for sending). - pub fn serialize_from_bytes(hint: &[u8], output: &mut Buf) { - output.extend_from_slice(&(hint.len() as u16).to_be_bytes()); - output.extend_from_slice(hint); - } -} - -#[cfg(test)] -mod test { - use super::super::{HashAlgorithm, SignatureAlgorithm, SignatureAndHashAlgorithm}; - use super::*; - use crate::vendor::dimpl::buffer::Buf; - - const MESSAGE_ECDH_PUBKEY: &[u8] = &[ - 0x03, // curve_type - 0x00, 0x17, // named_group - 0x04, // public_key length - 0x01, 0x02, 0x03, 0x04, // public_key - ]; - - #[test] - fn roundtrip_ecdh() { - // Build expected message - let algorithm = SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA); - let signature_bytes: &[u8] = &[0x05, 0x06, 0x07, 0x08]; - - let mut expected = Buf::new(); - expected.extend_from_slice(MESSAGE_ECDH_PUBKEY); - expected.extend_from_slice(&algorithm.as_u16().to_be_bytes()); - expected.extend_from_slice(&(signature_bytes.len() as u16).to_be_bytes()); - expected.extend_from_slice(signature_bytes); - - // Parse the message with base_offset 0 - let (rest, parsed) = ServerKeyExchange::parse(&expected, 0, KeyExchangeAlgorithm::EECDH).unwrap(); - assert!(rest.is_empty()); - - // Serialize and compare to expected bytes - let mut serialized = Buf::new(); - parsed.serialize(&expected, &mut serialized, true); - assert_eq!(&*serialized, &*expected); - } - - #[test] - fn psk_roundtrip() { - // PSK ServerKeyExchange: just hint_length + hint - const PSK_MESSAGE: &[u8] = &[ - 0x00, 0x04, // hint length = 4 - b'h', b'i', b'n', b't', - ]; - let (rest, parsed) = ServerKeyExchange::parse(PSK_MESSAGE, 0, KeyExchangeAlgorithm::PSK).unwrap(); - assert!(rest.is_empty()); - - let ServerKeyExchangeParams::Psk(psk) = &parsed.params else { - panic!("expected Psk variant"); - }; - assert_eq!(&PSK_MESSAGE[psk.hint_range.clone()], b"hint"); - assert!(parsed.signature().is_none(), "PSK SKE must have no signature"); - - let mut serialized = Buf::new(); - parsed.serialize(PSK_MESSAGE, &mut serialized, true); - assert_eq!(&*serialized, PSK_MESSAGE); - } - - #[test] - fn psk_rejects_oversized_hint_length() { - // hint_length=0x00FF (255) but only 2 bytes follow - parser must fail - let bad: &[u8] = &[0x00, 0xFF, b'a', b'b']; - let result = ServerKeyExchange::parse(bad, 0, KeyExchangeAlgorithm::PSK); - assert!( - result.is_err(), - "parser must reject PSK hint shorter than advertised length" - ); - } - - #[test] - fn psk_empty_hint() { - // Zero-length hint is wire-legal (RFC 4279 §2). - let empty: &[u8] = &[0x00, 0x00]; - let (rest, parsed) = ServerKeyExchange::parse(empty, 0, KeyExchangeAlgorithm::PSK).unwrap(); - assert!(rest.is_empty()); - let ServerKeyExchangeParams::Psk(psk) = &parsed.params else { - panic!("expected Psk variant"); - }; - assert!(psk.hint_range.is_empty()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/wrapped.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/wrapped.rs deleted file mode 100644 index 1ede363e33f..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/message/wrapped.rs +++ /dev/null @@ -1,39 +0,0 @@ -use nom::Err; -use nom::IResult; -use nom::bytes::complete::take; -use nom::error::{Error, ErrorKind}; -use nom::number::complete::{be_u16, be_u24}; -use std::ops::Range; - -macro_rules! wrapped_slice { - ($name:ident, $length_parser:path, $min:expr) => { - #[derive(Debug, Clone, PartialEq, Eq, Default)] - pub struct $name(pub Range); - - impl $name { - pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Self> { - let original_input = input; - let (input, len) = $length_parser(input)?; - #[allow(unused_comparisons)] - if len < $min { - return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); - } - let (input, data_slice) = take(len)(input)?; - - // Calculate absolute range in root buffer - let relative_offset = data_slice.as_ptr() as usize - original_input.as_ptr() as usize; - let start = base_offset + relative_offset; - let end = start + data_slice.len(); - - Ok((input, $name(start..end))) - } - - pub fn as_slice<'a>(&self, buf: &'a [u8]) -> &'a [u8] { - &buf[self.0.clone()] - } - } - }; -} - -wrapped_slice!(Asn1Cert, be_u24, 0); -wrapped_slice!(DistinguishedName, be_u16, 1); diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/mod.rs deleted file mode 100644 index aee21900e75..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/mod.rs +++ /dev/null @@ -1,38 +0,0 @@ -//! DTLS 1.2 protocol implementation. -//! - -// This is the full DTLS 1.2 handshake flow -// -// Client Server -// -// 1 ClientHello --------> -// -// 2 <-------- HelloVerifyRequest -// (contains cookie) -// -// 3 ClientHello --------> -// (with cookie) -// 4 ServerHello -// Certificate* -// ServerKeyExchange* -// CertificateRequest* -// <-------- ServerHelloDone -// 5 Certificate* -// ClientKeyExchange -// CertificateVerify* -// [ChangeCipherSpec] -// Finished --------> -// 6 [ChangeCipherSpec] -// <-------- Finished -// Application Data <-------> Application Data - -mod client; -mod context; -mod engine; -pub mod incoming; -pub mod message; -mod queue; -mod server; - -pub use client::Client; -pub use server::Server; diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/queue.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/queue.rs deleted file mode 100644 index 74eff5a27a5..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/queue.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! Queue wrapper types with safe Debug implementations. -//! -//! These wrappers ensure that debug output only shows metadata, -//! not potentially sensitive payload data. - -use std::collections::VecDeque; -use std::fmt; -use std::ops::{Deref, DerefMut}; - -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::dtls12::incoming::Incoming; -use crate::vendor::dimpl::types::ContentType; - -/// Wrapper around the receive queue that provides safe Debug output. -/// -/// The Debug implementation only shows metadata (counts by content type), -/// not potentially sensitive payload data. -pub(crate) struct QueueRx(VecDeque); - -impl QueueRx { - pub fn new() -> Self { - Self(VecDeque::new()) - } -} - -impl Deref for QueueRx { - type Target = VecDeque; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for QueueRx { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -impl fmt::Debug for QueueRx { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut handshake = 0; - let mut app_data = 0; - let mut alert = 0; - let mut ccs = 0; - let mut other = 0; - let mut min_seq: Option<(u16, u64)> = None; - let mut max_seq: Option<(u16, u64)> = None; - - for item in &self.0 { - let record = item.first().record(); - match record.content_type { - ContentType::Handshake => handshake += 1, - ContentType::ApplicationData => app_data += 1, - ContentType::Alert => alert += 1, - ContentType::ChangeCipherSpec => ccs += 1, - _ => other += 1, - } - - let seq = (record.sequence.epoch, record.sequence.sequence_number); - min_seq = Some(min_seq.map_or(seq, |m| m.min(seq))); - max_seq = Some(max_seq.map_or(seq, |m| m.max(seq))); - } - - let mut s = f.debug_struct("QueueRx"); - s.field("len", &self.0.len()) - .field("handshake", &handshake) - .field("app_data", &app_data) - .field("alert", &alert) - .field("ccs", &ccs) - .field("other", &other); - - if let (Some(min), Some(max)) = (min_seq, max_seq) { - s.field("seq_range", &format_args!("{}:{} - {}:{}", min.0, min.1, max.0, max.1)); - } - - s.finish() - } -} - -/// Wrapper around the transmit queue that provides safe Debug output. -/// -/// The Debug implementation only shows metadata (datagram count and total bytes), -/// not potentially sensitive payload data. -pub(crate) struct QueueTx(VecDeque); - -impl QueueTx { - pub fn new() -> Self { - Self(VecDeque::new()) - } -} - -impl Deref for QueueTx { - type Target = VecDeque; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for QueueTx { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -impl fmt::Debug for QueueTx { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let total_bytes: usize = self.0.iter().map(|b| b.len()).sum(); - f.debug_struct("QueueTx") - .field("datagrams", &self.0.len()) - .field("total_bytes", &total_bytes) - .finish() - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/dtls12/server.rs b/rs/moq-webrtc/src/vendor/dimpl/dtls12/server.rs deleted file mode 100644 index dee6997c719..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/dtls12/server.rs +++ /dev/null @@ -1,1394 +0,0 @@ -// DTLS Server Handshake Flow: -// -// 1. Client sends ClientHello (maybe without cookie) -// 2. If cookie missing/invalid, Server sends HelloVerifyRequest (stateless cookie) -// - Client resends ClientHello with cookie -// 3. Server sends ServerHello, Certificate, ServerKeyExchange, -// CertificateRequest (required), ServerHelloDone -// 4. Client sends Certificate (required when requested), ClientKeyExchange, -// CertificateVerify (if client cert), ChangeCipherSpec, Finished -// 5. Server verifies Finished, then sends ChangeCipherSpec, Finished -// 6. Handshake complete, application data can flow -// -// This implementation mirrors the client structure and ordering for a DTLS server. - -use std::collections::VecDeque; -use std::sync::Arc; -use std::time::Instant; -use tracing::{debug, trace}; - -use arrayvec::ArrayVec; -use subtle::ConstantTimeEq; - -use crate::vendor::dimpl::buffer::{Buf, ToBuf}; -use crate::vendor::dimpl::crypto::SrtpProfile; -use crate::vendor::dimpl::dtls12::Client; -use crate::vendor::dimpl::dtls12::client::LocalEvent; -use crate::vendor::dimpl::dtls12::context::AuthMode; -use crate::vendor::dimpl::dtls12::engine::Engine; -use crate::vendor::dimpl::dtls12::message::PskParams; -use crate::vendor::dimpl::dtls12::message::SignatureAndHashAlgorithm; -use crate::vendor::dimpl::dtls12::message::{Body, CertificateRequest, CertificateTypeVec, Dtls12CipherSuite}; -use crate::vendor::dimpl::dtls12::message::{ClientCertificateType, CompressionMethod, ContentType}; -use crate::vendor::dimpl::dtls12::message::{Cookie, CurveType, DistinguishedName, ExchangeKeys, ExtensionType}; -use crate::vendor::dimpl::dtls12::message::{HashAlgorithm, HelloVerifyRequest, KeyExchangeAlgorithm}; -use crate::vendor::dimpl::dtls12::message::{MessageType, NamedGroup, NamedGroupVec, ProtocolVersion, Random}; -use crate::vendor::dimpl::dtls12::message::{ServerHello, SessionId, SignatureAlgorithm}; -use crate::vendor::dimpl::dtls12::message::{SignatureAndHashAlgorithmVec, SrtpProfileId}; -use crate::vendor::dimpl::timer::Timeout; -use crate::vendor::dimpl::{Config, Error, InternalError, Output}; - -/// Length of the random dummy PSK used when identity resolution fails. -/// Fixed so handshake timing does not leak the failure, and long enough -/// that a coincidental match with a real 32-byte PSK is cryptographically -/// impossible. -const DUMMY_PSK_LEN: usize = 32; - -/// DTLS server -pub struct Server { - /// Current server state. - state: State, - - /// Engine in common between server and client. - engine: Engine, - - /// Random unique data (with gmt timestamp). Used for signature checks. - random: Option, - - /// SessionId we provide to the client (unused/resumption not implemented). - session_id: Option, - - /// Cookie secret for HMAC, generated per-server instance - cookie_secret: [u8; 32], - - /// Storage for extension data - extension_data: Buf, - - /// The negotiated SRTP profile (if any) - negotiated_srtp_profile: Option, - - /// Client's offered supported_groups (if any) - client_supported_groups: Option, - - /// Client's offered signature_algorithms (if any) - client_signature_algorithms: Option, - - /// Client random. Set by ClientHello. - client_random: Option, - - /// Client certificates - client_certificates: Vec, - - /// Buffer for defragmenting handshakes - defragment_buffer: Buf, - - /// Captured session hash for Extended Master Secret (RFC 7627) - captured_session_hash: Option, - - /// Whether the PSK identity resolved to a real key. - /// - /// `None` until the PSK ClientKeyExchange is processed. Non-PSK handshakes - /// leave this `None` and the Finished check skips the PSK branch entirely. - /// Defaulting to `None` (rather than `true`) means a future refactor that - /// forgets to set it in the PSK path fails closed instead of silently - /// bypassing identity validation. - psk_valid: Option, - - /// The last now we seen - last_now: Instant, - - /// Events we are to emit from this Server. - local_events: VecDeque, - - /// Data that is sent before we are connected. - queued_data: Vec, -} - -/// Current state of the server. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum State { - AwaitClientHello, - SendServerHello, - SendCertificate, - SendServerKeyExchange, - SendCertificateRequest, - SendServerHelloDone, - AwaitCertificate, - AwaitClientKeyExchange, - AwaitCertificateVerify, - AwaitChangeCipherSpec, - AwaitFinished, - SendChangeCipherSpec, - SendFinished, - AwaitApplicationData, - Closed, -} - -impl Server { - /// Create a new DTLS server - pub fn new(config: Arc, certificate: crate::vendor::dimpl::DtlsCertificate, now: Instant) -> Server { - assert!( - !certificate.certificate.is_empty(), - "Server certificate cannot be empty" - ); - // unwrap: malformed private_key bytes are a programmer error from the - // caller who constructed DtlsCertificate; panic matches the prior - // CryptoContext::new behavior which also panicked on empty/invalid - // key material. - let private_key = config - .crypto_provider() - .key_provider - .load_private_key(&certificate.private_key) - .expect("Failed to parse server private key"); - let auth = AuthMode::Certificate { - certificate: certificate.certificate, - private_key, - }; - let engine = Engine::new(config, auth); - Self::new_with_engine(engine, now) - } - - /// Create a new PSK-only DTLS server (no certificate). - pub fn new_psk(config: Arc, now: Instant) -> Server { - let engine = Engine::new(config, AuthMode::Psk); - Self::new_with_engine(engine, now) - } - - pub(crate) fn new_with_engine(mut engine: Engine, now: Instant) -> Server { - engine.set_client(false); - - let cookie_secret: [u8; 32] = engine.rng.random(); - let extension_data = engine.pop_buffer(); - let defragment_buffer = engine.pop_buffer(); - - Server { - state: State::AwaitClientHello, - engine, - random: None, - session_id: None, - cookie_secret, - extension_data, - negotiated_srtp_profile: None, - client_supported_groups: None, - client_signature_algorithms: None, - client_random: None, - client_certificates: Vec::with_capacity(3), - defragment_buffer, - captured_session_hash: None, - psk_valid: None, - last_now: now, - local_events: VecDeque::new(), - queued_data: Vec::new(), - } - } - - pub fn into_client(self) -> Client { - Client::new_with_engine(self.engine, self.last_now) - } - - pub(crate) fn state_name(&self) -> &'static str { - self.state.name() - } - - pub fn is_closing(&self) -> bool { - self.state == State::Closed && !self.is_closed() - } - - pub fn is_closed(&self) -> bool { - self.state == State::Closed && self.local_events.is_empty() && !self.engine.has_pending_close_output() - } - - pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { - match self.engine.parse_packet(packet).and_then(|is_client_hello| { - if is_client_hello { - self.engine.start_handshake(self.last_now); - } - let result = self.make_progress(); - self.engine.discard_undecryptable(); - result - }) { - Ok(()) => Ok(()), - Err(e) => e.into_public_error().map_or(Ok(()), Err), - } - } - - pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { - if let Some(event) = self.local_events.pop_front() { - return event.into_output(buf, &self.client_certificates); - } - self.engine.poll_output(buf, self.last_now) - } - - pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { - self.last_now = now; - if self.random.is_none() { - self.random = Some(Random::new_with_time(now, &mut self.engine.rng)); - } - self.engine.handle_timeout(now)?; - match self.make_progress() { - Ok(()) => Ok(()), - Err(e) => e.into_public_error().map_or(Ok(()), Err), - } - } - - /// Send application data when the server is in the Running state - pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { - if self.state == State::Closed { - return Err(Error::ConnectionClosed); - } - - if self.state != State::AwaitApplicationData { - self.queued_data.push(data.to_buf()); - return Ok(()); - } - - // Use the engine's create_record to send application data - // The encryption is now handled in the engine - self.engine - .create_record(ContentType::ApplicationData, 1, false, |body| { - body.extend_from_slice(data); - })?; - - Ok(()) - } - - /// Initiate graceful shutdown by sending a `close_notify` alert. - pub fn close(&mut self) -> Result<(), Error> { - if self.state == State::Closed { - return Ok(()); - } - if self.state != State::AwaitApplicationData { - self.engine.abort(); - self.state = State::Closed; - return Ok(()); - } - self.engine.create_record(ContentType::Alert, 1, false, |body| { - body.push(1); // level: warning - body.push(0); // description: close_notify - })?; - self.state = State::Closed; - Ok(()) - } - - fn make_progress(&mut self) -> Result<(), InternalError> { - loop { - let prev_state = self.state; - - let new_state = prev_state.make_progress(self)?; - if prev_state != new_state { - self.state = new_state; - trace!("{:?} -> {:?}", prev_state, new_state); - } else { - break; - } - } - Ok(()) - } -} - -impl State { - fn name(&self) -> &'static str { - match self { - State::AwaitClientHello => "AwaitClientHello", - State::SendServerHello => "SendServerHello", - State::SendCertificate => "SendCertificate", - State::SendServerKeyExchange => "SendServerKeyExchange", - State::SendCertificateRequest => "SendCertificateRequest", - State::SendServerHelloDone => "SendServerHelloDone", - State::AwaitCertificate => "AwaitCertificate", - State::AwaitClientKeyExchange => "AwaitClientKeyExchange", - State::AwaitCertificateVerify => "AwaitCertificateVerify", - State::AwaitChangeCipherSpec => "AwaitChangeCipherSpec", - State::AwaitFinished => "AwaitFinished", - State::SendChangeCipherSpec => "SendChangeCipherSpec", - State::SendFinished => "SendFinished", - State::AwaitApplicationData => "AwaitApplicationData", - State::Closed => "Closed", - } - } - - fn make_progress(self, server: &mut Server) -> Result { - match self { - State::AwaitClientHello => self.await_client_hello(server), - State::SendServerHello => self.send_server_hello(server), - State::SendCertificate => self.send_certificate(server), - State::SendServerKeyExchange => self.send_server_key_exchange(server), - State::SendCertificateRequest => self.send_certificate_request(server), - State::SendServerHelloDone => self.send_server_hello_done(server), - State::AwaitCertificate => self.await_certificate(server), - State::AwaitClientKeyExchange => self.await_client_key_exchange(server), - State::AwaitCertificateVerify => self.await_certificate_verify(server), - State::AwaitChangeCipherSpec => self.await_change_cipher_spec(server), - State::AwaitFinished => self.await_finished(server), - State::SendChangeCipherSpec => self.send_change_cipher_spec(server), - State::SendFinished => self.send_finished(server), - State::AwaitApplicationData => self.await_application_data(server), - State::Closed => Ok(self), - } - } - - fn await_client_hello(self, server: &mut Server) -> Result { - let maybe = server - .engine - .next_handshake(MessageType::ClientHello, &mut server.defragment_buffer)?; - - let Some(handshake) = maybe else { - // Stay in same state - return Ok(self); - }; - - let Body::ClientHello(ch) = handshake.body else { - unreachable!() - }; - - // Enforce DTLS1.2 - if ch.client_version != ProtocolVersion::DTLS1_2 { - return Err( - Error::SecurityError(crate::vendor::dimpl::SecurityError::UnsupportedClientVersion( - ch.client_version, - )) - .into(), - ); - } - - // Enforce Null compression only (client must offer it) - let has_null = ch.compression_methods.contains(&CompressionMethod::Null); - if !has_null { - return Err(Error::SecurityError(crate::vendor::dimpl::SecurityError::UnsupportedClientCompression).into()); - } - - trace!( - "ClientHello: cookie_len={}, offered_suites={}", - ch.cookie.len(), - ch.cipher_suites.len() - ); - - // Stateless cookie: require 32-byte cookie matching HMAC(secret, client_random) - let client_random = ch.random; - let hmac_provider = server.engine.config().crypto_provider().hmac_provider; - let need_cookie = server.engine.config().use_server_cookie(); - let cookie_valid = - !need_cookie || verify_cookie(hmac_provider, &server.cookie_secret, client_random, ch.cookie); - if !cookie_valid { - debug!("Invalid/missing cookie; sending HelloVerifyRequest"); - - let cookie = compute_cookie(hmac_provider, &server.cookie_secret, client_random)?; - // Start/restart flight timer for server Flight 2 (HelloVerifyRequest) - server.engine.flight_begin(2); - server - .engine - .create_handshake(MessageType::HelloVerifyRequest, |body, _engine| { - // RFC 6347 4.2.1: The server_version field in the HelloVerifyRequest - // message MUST be set to DTLS 1.0 - let hvr = HelloVerifyRequest::new(ProtocolVersion::DTLS1_0, cookie); - hvr.serialize(body); - Ok(()) - })?; - - // The HelloVerifyRequest exchange is stateless per RFC 6347. - // Reset all handshake state so the next ClientHello (with cookie) is processed fresh. - server.engine.reset_server_for_hello_verify_request(); - return Ok(self); - } - - trace!("Accepted ClientHello cookie; proceeding with handshake"); - - // Client offered suites; we pick per client order intersecting allowed and server key compatibility - let mut selected: Option = None; - for s in ch.cipher_suites.iter() { - let is_allowed = server.engine.is_cipher_suite_allowed(*s); - let is_compatible = server.engine.crypto_context().is_cipher_suite_compatible(*s); - if is_allowed && is_compatible { - selected = Some(*s); - break; - } - } - - let Some(cs) = selected else { - return Err( - (Error::SecurityError(crate::vendor::dimpl::SecurityError::NoMutuallyAcceptableCipherSuite)).into(), - ); - }; - - server.engine.set_cipher_suite(cs); - server.client_random = Some(client_random); - - debug!("Selected cipher suite: {:?}", cs); - - let client_offers_ems = ch - .extensions - .iter() - .any(|ext| ext.extension_type == ExtensionType::ExtendedMasterSecret); - let client_srtp_profiles = ch.srtp_profiles(); - let client_supported_groups = ch.supported_groups().cloned(); - let client_signature_algorithms = ch.signature_algorithms().cloned(); - - // EMS is mandatory - if !client_offers_ems { - return Err( - Error::SecurityError(crate::vendor::dimpl::SecurityError::ExtendedMasterSecretNotNegotiated).into(), - ); - } - - // Select SRTP profile according to server priority: AES256GCM, AES128GCM, then SHA1 - if let Some(profiles) = client_srtp_profiles { - // Map client profile ids to SrtpProfile, then pick our preferred - let mut selected_profile: Option = None; - for preferred in [ - SrtpProfile::AEAD_AES_256_GCM, - SrtpProfile::AEAD_AES_128_GCM, - SrtpProfile::AES128_CM_SHA1_80, - ] { - if profiles.iter().any(|pid| preferred == (*pid).into()) { - selected_profile = Some(preferred); - break; - } - } - server.negotiated_srtp_profile = selected_profile; - if let Some(profile) = server.negotiated_srtp_profile { - debug!("Negotiated SRTP profile: {:?}", profile); - } - } - - // Store client's offers for later selection - server.client_supported_groups = client_supported_groups; - server.client_signature_algorithms = client_signature_algorithms; - - // Proceed to send the server flight - trace!("Extended Master Secret enabled"); - Ok(Self::SendServerHello) - } - - fn send_server_hello(self, server: &mut Server) -> Result { - trace!("Sending ServerHello"); - - // Start/restart flight timer for server Flight 4 - server.engine.flight_begin(4); - - let session_id = server.session_id.unwrap_or_else(SessionId::empty); - // unwrap: is ok because we set the random in handle_timeout - let random = server.random.unwrap(); - let negotiated_srtp_profile = server.negotiated_srtp_profile; - let extension_data = &mut server.extension_data; - - // Send ServerHello - server - .engine - .create_handshake(MessageType::ServerHello, move |body, engine| { - handshake_create_server_hello( - body, - engine, - random, - session_id, - negotiated_srtp_profile, - extension_data, - ) - })?; - - let cs = server.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - // PSK suites skip Certificate - if cs.is_psk() { - Ok(Self::SendServerKeyExchange) - } else { - Ok(Self::SendCertificate) - } - } - - fn send_certificate(self, server: &mut Server) -> Result { - trace!("Sending Certificate"); - - server - .engine - .create_handshake(MessageType::Certificate, handshake_create_certificate)?; - - Ok(Self::SendServerKeyExchange) - } - - fn send_server_key_exchange(self, server: &mut Server) -> Result { - trace!("Sending ServerKeyExchange"); - - let cs = server.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - if cs.is_psk() { - return self.send_server_key_exchange_psk(server); - } - - let client_random = server.client_random.ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoClientRandom, - ))?; - // unwrap: is ok because we set the random in handle_timeout - let server_random = server.random.unwrap(); - - // Select ECDHE group from the intersection of: - // - client offers, and - // - server-allowed DTLS 1.2 groups (provider + config filter) - // Preference follows Config::kx_groups() order. - let allowed_named_groups: Vec = server.engine.config().kx_groups().map(|g| g.name()).collect(); - let selected_named_group = select_named_group(server.client_supported_groups.as_ref(), &allowed_named_groups) - .ok_or_else(|| { - if server.client_supported_groups.is_some() { - Error::SecurityError(crate::vendor::dimpl::SecurityError::NoCommonKeyExchangeGroup) - } else { - Error::CryptoError(crate::vendor::dimpl::CryptoError::NoDtls12KeyExchangeGroupsConfigured) - } - })?; - - // Select signature/hash for SKE by intersecting client's list - // with our key type, preferring the key's native hash algorithm. - // unwrap: ServerKeyExchange signature only needed for certificate-based suites - let selected_signature = select_ske_signature_algorithm( - server.client_signature_algorithms.as_ref(), - server.engine.crypto_context().signature_algorithm().unwrap(), - server - .engine - .crypto_context() - .private_key_default_hash_algorithm() - .unwrap(), - server.engine.crypto_context().private_key_supported_hash_algorithms(), - ); - - debug!( - "ServerKeyExchange params: group={:?}, signature_alg={:?}", - selected_named_group, selected_signature - ); - - server - .engine - .create_handshake(MessageType::ServerKeyExchange, |body, engine| { - handshake_create_server_key_exchange( - body, - engine, - client_random, - server_random, - selected_named_group, - selected_signature, - ) - })?; - - if server.engine.config().require_client_certificate() { - Ok(Self::SendCertificateRequest) - } else { - Ok(Self::SendServerHelloDone) - } - } - - /// PSK ServerKeyExchange: send identity hint only (no ECDHE, no signature). - /// Per RFC 4279 §2, the message is omitted entirely when no hint is configured. - fn send_server_key_exchange_psk(self, server: &mut Server) -> Result { - let Some(hint) = server.engine.config().psk_identity_hint().map(<[u8]>::to_vec) else { - return Ok(Self::SendServerHelloDone); - }; - - server - .engine - .create_handshake(MessageType::ServerKeyExchange, move |body, _engine| { - PskParams::serialize_from_bytes(&hint, body); - Ok(()) - })?; - - // PSK never sends CertificateRequest - Ok(Self::SendServerHelloDone) - } - - fn send_certificate_request(self, server: &mut Server) -> Result { - debug!("Sending CertificateRequest"); - // Select CertificateRequest.signature_algorithms as intersection of client's list and our supported - let sig_algs = select_certificate_request_sig_algs(server.client_signature_algorithms.as_ref()); - debug!( - "CertificateRequest will advertise {} signature algorithms", - sig_algs.len() - ); - - server - .engine - .create_handshake(MessageType::CertificateRequest, move |body, _| { - handshake_serialize_certificate_request(body, &sig_algs) - })?; - - Ok(Self::SendServerHelloDone) - } - - fn send_server_hello_done(self, server: &mut Server) -> Result { - trace!("Sending ServerHelloDone"); - - server - .engine - .create_handshake(MessageType::ServerHelloDone, |_, _| Ok(()))?; - - let cs = server.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - // PSK: no client certificates - if cs.is_psk() { - return Ok(Self::AwaitClientKeyExchange); - } - - if server.engine.config().require_client_certificate() { - Ok(Self::AwaitCertificate) - } else { - Ok(Self::AwaitClientKeyExchange) - } - } - - fn await_certificate(self, server: &mut Server) -> Result { - let maybe = server - .engine - .next_handshake(MessageType::Certificate, &mut server.defragment_buffer)?; - - let Some(ref handshake) = maybe else { - // Stay in same state - return Ok(self); - }; - - let Body::Certificate(certificate) = &handshake.body else { - unreachable!() - }; - - // Extract certificate ranges before dropping handshake - let cert_ranges: ArrayVec<_, 32> = certificate.certificate_list.iter().map(|cert| cert.0.clone()).collect(); - - drop(maybe); - - if cert_ranges.is_empty() { - // The handshake has no key material yet, so send a fatal alert in epoch 0. - server.engine.abort(); - server.engine.create_record(ContentType::Alert, 0, false, |body| { - body.push(2); // fatal - body.push(40); // handshake_failure - })?; - server.state = State::Closed; - return Err( - Error::CertificateError(crate::vendor::dimpl::CertificateError::NoClientCertificateReceived).into(), - ); - } else { - // Store and verify via callback - debug!( - "Received client certificate chain with {} certificate(s)", - cert_ranges.len() - ); - for (i, range) in cert_ranges.iter().enumerate() { - let cert_data = &server.defragment_buffer[range.clone()]; - trace!("Client Certificate #{} size: {} bytes", i + 1, cert_data.len()); - server.client_certificates.push(cert_data.to_buf()); - } - - server.local_events.push_back(LocalEvent::PeerCert); - } - - Ok(Self::AwaitClientKeyExchange) - } - - fn await_client_key_exchange(self, server: &mut Server) -> Result { - let maybe = server - .engine - .next_handshake(MessageType::ClientKeyExchange, &mut server.defragment_buffer)?; - - let Some(ref handshake) = maybe else { - // Stay in same state - return Ok(self); - }; - - let Body::ClientKeyExchange(ckx) = &handshake.body else { - unreachable!() - }; - - let suite = server.engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - ))?; - - if suite.is_psk() { - // Extract PSK identity range before dropping handshake - let identity_range = match &ckx.exchange_keys { - ExchangeKeys::Psk(keys) => keys.identity_range.clone(), - _ => { - return Err(Error::UnexpectedMessage( - crate::vendor::dimpl::UnexpectedMessageError::EcdheClientKeyExchangeInPskPath, - ) - .into()); - } - }; - - drop(maybe); - - let identity = &server.defragment_buffer[identity_range]; - trace!("PSK identity ({} bytes)", identity.len()); - - // Resolve PSK via the configured resolver. On failure we derive a - // random dummy of fixed length so the handshake proceeds identically - // to a valid-identity flow (no timing oracle) and the Finished MAC - // is guaranteed to mismatch - not merely likely to. - let resolved = server - .engine - .config() - .psk_resolver() - .ok_or(Error::PskError(crate::vendor::dimpl::PskError::NoPskResolverConfigured))? - .resolve(identity); - - let (psk, psk_valid) = match resolved { - Some(key) => (key, true), - None => { - let dummy: [u8; DUMMY_PSK_LEN] = server.engine.rng.random(); - (dummy.to_vec(), false) - } - }; - - server.psk_valid = Some(psk_valid); - - let crypto = server.engine.crypto_context_mut(); - crypto.set_psk(psk); - crypto.compute_psk_pre_master_secret().map_err(Error::CryptoError)?; - } else { - // Extract client's public key range before dropping handshake - let public_key_range = match &ckx.exchange_keys { - ExchangeKeys::Ecdh(keys) => keys.public_key_range.clone(), - ExchangeKeys::Psk(_) => { - return Err(Error::UnexpectedMessage( - crate::vendor::dimpl::UnexpectedMessageError::PskClientKeyExchangeInEcdhePath, - ) - .into()); - } - }; - - drop(maybe); - - // Get the actual public key data from defragment_buffer - let client_pub = &server.defragment_buffer[public_key_range]; - - // Compute shared secret - let buf = server.engine.pop_buffer(); - server - .engine - .crypto_context_mut() - .compute_shared_secret(client_pub, buf) - .map_err(Error::CryptoError)?; - } - - // Capture session hash for EMS now (up to ClientKeyExchange) - let suite_hash = suite.hash_algorithm(); - let mut buf = server.engine.pop_buffer(); - server.engine.transcript_hash(suite_hash, &mut buf); - server.captured_session_hash = Some(buf); - - // Derive master secret and keys (needed to decrypt client's Finished) - let client_random_buf = { - let mut b = Buf::new(); - server.client_random.unwrap().serialize(&mut b); - b - }; - let server_random_buf = { - let mut b = Buf::new(); - // unwrap: is ok because we set the random in handle_timeout - server.random.unwrap().serialize(&mut b); - b - }; - - let session_hash = server.captured_session_hash.as_ref().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::ExtendedMasterSecretSessionHashMissing, - ))?; - - let mut out = server.engine.pop_buffer(); - let mut scratch = server.engine.pop_buffer(); - server - .engine - .crypto_context_mut() - .derive_extended_master_secret(session_hash, suite_hash, &mut out, &mut scratch) - .map_err(Error::CryptoError)?; - - server - .engine - .crypto_context_mut() - .derive_keys(suite, &client_random_buf, &server_random_buf, &mut out, &mut scratch) - .map_err(Error::CryptoError)?; - - server.engine.push_buffer(out); - server.engine.push_buffer(scratch); - - trace!("Captured session hash length for EMS: {}", session_hash.len()); - trace!("Derived session keys (EMS) and ready to verify Finished"); - - if !server.client_certificates.is_empty() { - Ok(Self::AwaitCertificateVerify) - } else { - Ok(Self::AwaitChangeCipherSpec) - } - } - - fn await_certificate_verify(self, server: &mut Server) -> Result { - // Get handshake data BEFORE processing CertificateVerify message - // According to TLS spec, signature is over all handshake messages - // up to but not including CertificateVerify - let data = server.engine.transcript().to_buf(); - - let maybe = server - .engine - .next_handshake(MessageType::CertificateVerify, &mut server.defragment_buffer)?; - - if maybe.is_none() { - // Stay in same state - return Ok(self); - }; - - // Extract signature data before accessing buffer - let (signature_range, signature_algorithm) = { - let handshake = maybe.as_ref().unwrap(); - let Body::CertificateVerify(cv) = &handshake.body else { - unreachable!() - }; - - (cv.signed.signature_range.clone(), cv.signed.algorithm) - }; - - // Drop maybe to release buffer borrow - drop(maybe); - - // Now access the buffer - let signature_bytes = &server.defragment_buffer[signature_range]; - - if server.client_certificates.is_empty() { - return Err(Error::CertificateError( - crate::vendor::dimpl::CertificateError::NoClientCertificateForVerification, - ) - .into()); - } - - // Create temp DigitallySigned for verification - let temp_signed = crate::vendor::dimpl::dtls12::message::DigitallySigned { - algorithm: signature_algorithm, - signature_range: 0..signature_bytes.len(), - }; - - server - .engine - .crypto_context() - .verify_signature(&data, &temp_signed, signature_bytes, &server.client_certificates[0]) - .map_err(Error::CryptoError)?; - - debug!("Client CertificateVerify verified successfully"); - - Ok(Self::AwaitChangeCipherSpec) - } - - fn await_change_cipher_spec(self, server: &mut Server) -> Result { - let maybe = server.engine.next_record(ContentType::ChangeCipherSpec); - - let Some(_) = maybe else { - // Stay in same state - return Ok(self); - }; - - // Drop any extra CCS resends to avoid being blocked - trace!("Dropping any pending CCS resends from peer"); - server.engine.drop_pending_ccs(); - - // Expect every record to be decrypted from now on. - trace!("Received ChangeCipherSpec; enabling peer encryption"); - server.engine.enable_peer_encryption()?; - - Ok(Self::AwaitFinished) - } - - fn await_finished(self, server: &mut Server) -> Result { - // Generate expected verify data based on current transcript. - // This must be done before next_handshake() below since - // it should not include Finished itself. - let expected = server.engine.generate_verify_data(true /* client */)?; - - let maybe = server - .engine - .next_handshake(MessageType::Finished, &mut server.defragment_buffer)?; - - if maybe.is_none() { - // stay in same state - return Ok(self); - } - - // Extract the range from the handshake - let verify_data_range = if let Some(ref handshake) = maybe { - if let Body::Finished(finished) = &handshake.body { - finished.verify_data_range.clone() - } else { - panic!("Finished message should have been parsed"); - } - } else { - unreachable!() - }; - - // Drop maybe to release the buffer borrow - drop(maybe); - - // Now we can access the buffer - let verify_data = &server.defragment_buffer[verify_data_range]; - // Use constant-time comparison to prevent timing attacks - let is_eq: bool = verify_data.ct_eq(expected.as_slice()).into(); - if !is_eq { - return Err( - (Error::SecurityError(crate::vendor::dimpl::SecurityError::ClientFinishedVerificationFailed)).into(), - ); - } - - // Invariant: full PSK handshakes always set psk_valid in - // await_client_key_exchange before reaching Finished. A violation is a - // state-machine bug, not network input - `assert!` (not debug_assert!) - // because a silent bypass could let a forged-PSK Finished through. - // Loosen when dtls-conn-id lands and abbreviated handshakes legitimately - // skip ClientKeyExchange (reusing a cached master secret). - if server.engine.cipher_suite().is_some_and(|cs| cs.is_psk()) { - assert!( - server.psk_valid.is_some(), - "PSK handshake reached Finished without processing ClientKeyExchange" - ); - } - - // Defense-in-depth for PSK: the random dummy key should already make - // the MAC above fail when the identity was unknown. We additionally - // reject `Some(false)` explicitly so a future refactor that lets the - // dummy path survive the MAC check still fails closed here. - // - // `None` is legitimate for abbreviated (resumption) handshakes, which - // skip ClientKeyExchange and therefore never set psk_valid - those - // paths reuse a cached master_secret and don't consult the resolver. - if server.psk_valid == Some(false) { - return Err( - (Error::SecurityError(crate::vendor::dimpl::SecurityError::ClientFinishedVerificationFailed)).into(), - ); - } - - trace!("Client Finished verified successfully"); - - Ok(Self::SendChangeCipherSpec) - } - - fn send_change_cipher_spec(self, server: &mut Server) -> Result { - trace!("Sending ChangeCipherSpec"); - - // Start/restart flight timer for server Flight 6 (CCS+Finished) - server.engine.flight_begin(6); - - // Send ChangeCipherSpec - server - .engine - .create_record(ContentType::ChangeCipherSpec, 0, true, |body| { - body.push(1); - })?; - - Ok(Self::SendFinished) - } - - fn send_finished(self, server: &mut Server) -> Result { - trace!("Sending Finished message to complete handshake"); - - // No records from the handshake epochs may survive into application data. - let unexpected_record = server - .engine - .pending_records() - .find(|record| record.record().sequence.epoch != 1); - if let Some(record) = unexpected_record { - debug!( - "Unexpected epoch at handshake completion: record={:?}, handshake={:?}", - record.record(), - record.first_handshake().map(|handshake| &handshake.header), - ); - return Err(Error::UnexpectedMessage(crate::vendor::dimpl::UnexpectedMessageError::UnexpectedEpoch).into()); - } - - server.engine.create_handshake(MessageType::Finished, |body, engine| { - let verify_data = engine.generate_verify_data(false /* server */)?; - trace!("Finished.verify_data length: {}", verify_data.len()); - // Directly write the verify data without creating Finished struct - body.extend_from_slice(&verify_data); - Ok(()) - })?; - - // Final flight sent; stop periodic retransmission timers per RFC 6347 FINISHED state. - // If this flight need resending, it relies on the client to resend its last flight. - server.engine.flight_stop_resend_timers(); - - // Handshake complete - debug!("Handshake complete; ready for application data"); - server.local_events.push_back(LocalEvent::Connected); - - // Emit SRTP keying material if negotiated - if let Some(profile) = server.negotiated_srtp_profile { - let suite_hash = server.engine.cipher_suite().unwrap().hash_algorithm(); - let mut out = server.engine.pop_buffer(); - let mut scratch = server.engine.pop_buffer(); - if let Ok(keying_material) = - server - .engine - .crypto_context() - .extract_srtp_keying_material(profile, suite_hash, &mut out, &mut scratch) - { - server.engine.push_buffer(out); - server.engine.push_buffer(scratch); - debug!( - "SRTP keying material extracted ({} bytes) for profile: {:?}", - keying_material.len(), - profile - ); - // expect should be correct here since we negotiated the profile - let profile = server - .negotiated_srtp_profile - .expect("SRTP profile should be negotiated"); - server - .local_events - .push_back(LocalEvent::KeyingMaterial(keying_material, profile)); - } else { - server.engine.push_buffer(out); - server.engine.push_buffer(scratch); - } - } - - server.engine.release_application_data(); - - Ok(Self::AwaitApplicationData) - } - - fn await_application_data(self, server: &mut Server) -> Result { - if server.engine.close_notify_received() { - // RFC 5246 §7.2.1: respond with a reciprocal close_notify and - // close down immediately, discarding any pending writes. - server.engine.discard_pending_writes(); - server.engine.create_record(ContentType::Alert, 1, false, |body| { - body.push(1); // level: warning - body.push(0); // description: close_notify - })?; - return Ok(State::Closed); - } - - // Now send any application data that was queued before we were connected. - if !server.queued_data.is_empty() { - debug!("Sending queued application data: {}", server.queued_data.len()); - for data in server.queued_data.drain(..) { - server - .engine - .create_record(ContentType::ApplicationData, 1, false, |body| { - body.extend_from_slice(&data); - })?; - } - } - - Ok(self) - } -} - -fn compute_cookie( - hmac_provider: &dyn crate::vendor::dimpl::crypto::HmacProvider, - secret: &[u8], - client_random: Random, -) -> Result { - // cookie = trunc_32(HMAC(secret, client_random)) - let mut buf = Buf::new(); - client_random.serialize(&mut buf); - let tag = hmac_provider.hmac_sha256(secret, &buf).map_err(Error::CryptoError)?; - let cookie = Cookie::try_new(&tag).map_err(|_| { - Error::CryptoError(crate::vendor::dimpl::CryptoError::OperationFailed( - crate::vendor::dimpl::CryptoOperation::ComputeCookie, - )) - })?; - Ok(cookie) -} - -fn verify_cookie( - hmac_provider: &dyn crate::vendor::dimpl::crypto::HmacProvider, - secret: &[u8], - client_random: Random, - cookie: Cookie, -) -> bool { - if cookie.len() != 32 { - return false; - } - match compute_cookie(hmac_provider, secret, client_random) { - // Use constant-time comparison to prevent timing attacks - Ok(expected) => expected[..].ct_eq(&cookie[..]).into(), - Err(_) => false, - } -} - -fn handshake_create_certificate(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { - let crypto = engine.crypto_context(); - crypto.serialize_client_certificate(body); - Ok(()) -} - -fn handshake_create_server_hello( - body: &mut Buf, - engine: &mut Engine, - random: Random, - session_id: SessionId, - negotiated_srtp_profile: Option, - extension_data: &mut Buf, -) -> Result<(), Error> { - let server_version = ProtocolVersion::DTLS1_2; - - let cs = engine.cipher_suite().ok_or(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuite, - ))?; - - let srtp_pid = negotiated_srtp_profile.map(|p| match p { - SrtpProfile::AEAD_AES_256_GCM => SrtpProfileId::SRTP_AEAD_AES_256_GCM, - SrtpProfile::AEAD_AES_128_GCM => SrtpProfileId::SRTP_AEAD_AES_128_GCM, - SrtpProfile::AES128_CM_SHA1_80 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, - }); - - let sh = ServerHello::new(server_version, random, session_id, cs, CompressionMethod::Null, None) - .with_extensions(extension_data, srtp_pid); - - sh.serialize(extension_data, body); - Ok(()) -} - -fn handshake_create_server_key_exchange( - body: &mut Buf, - engine: &mut Engine, - client_random: Random, - server_random: Random, - named_group: NamedGroup, - algorithm: SignatureAndHashAlgorithm, -) -> Result<(), Error> { - let Some(cipher_suite) = engine.cipher_suite() else { - return Err(Error::InvalidState( - crate::vendor::dimpl::InvalidStateError::NoCipherSuiteSelected, - )); - }; - - let key_exchange_algorithm = cipher_suite.as_key_exchange_algorithm(); - debug!("Using key exchange algorithm: {:?}", key_exchange_algorithm); - - // Use hash part from selected algorithm - let hash_alg = algorithm.hash; - - match key_exchange_algorithm { - KeyExchangeAlgorithm::EECDH => { - let (curve_type, named_group) = (CurveType::NamedCurve, named_group); - let kx_buf = engine.pop_buffer(); - let pubkey = engine - .crypto_context_mut() - .init_ecdh_server(named_group, kx_buf) - .map_err(Error::CryptoError)?; - - trace!("SKE ECDHE: group={:?}, pubkey_len={}", named_group, pubkey.len()); - - // Build signed_data = client_random || server_random || params(without signature) - let mut signed_data = Buf::new(); - client_random.serialize(&mut signed_data); - server_random.serialize(&mut signed_data); - // Write params directly for signing - signed_data.push(curve_type.as_u8()); - signed_data.extend_from_slice(&named_group.as_u16().to_be_bytes()); - signed_data.push(pubkey.len() as u8); - signed_data.extend_from_slice(pubkey); - - let mut signature = engine.pop_buffer(); - - trace!("SKE signature hash: {:?}", hash_alg); - engine - .crypto_context - .sign_data(&signed_data, hash_alg, &mut signature) - .map_err(Error::CryptoError)?; - - // unwrap: safe because init_ecdh_server() above sets key_exchange = Some(...). - // If that failed, we returned Err earlier and never reach this point. - let pubkey = engine.crypto_context_mut().maybe_init_key_exchange().unwrap(); - - // For sending, we don't use DigitallySigned struct, just write the params and signature directly - body.push(curve_type.as_u8()); - body.extend_from_slice(&named_group.as_u16().to_be_bytes()); - body.push(pubkey.len() as u8); - body.extend_from_slice(pubkey); - - // Write signature - body.extend_from_slice(&algorithm.as_u16().to_be_bytes()); - body.extend_from_slice(&(signature.len() as u16).to_be_bytes()); - body.extend_from_slice(&signature); - - engine.push_buffer(signature); - - Ok(()) - } - _ => Err(Error::SecurityError( - crate::vendor::dimpl::SecurityError::UnsupportedKeyExchangeAlgorithm, - )), - } -} - -fn handshake_serialize_certificate_request( - body: &mut Buf, - sig_algs: &SignatureAndHashAlgorithmVec, -) -> Result<(), Error> { - // Only advertise ECDSA_SIGN (the only supported client cert type) - let mut cert_types = CertificateTypeVec::new(); - cert_types.push(ClientCertificateType::ECDSA_SIGN); - - // If intersection is empty (e.g., client didn't advertise), fall back to our supported set - // Build the selected list with the capacity expected by CertificateRequest - let mut selected = SignatureAndHashAlgorithmVec::new(); - if sig_algs.is_empty() { - let fallback = SignatureAndHashAlgorithm::supported(); - for alg in fallback.iter() { - selected.push(*alg); - } - } else { - for alg in sig_algs.iter() { - selected.push(*alg); - } - } - - let cert_auths: ArrayVec = ArrayVec::new(); - - let cr = CertificateRequest::new(cert_types, selected, cert_auths); - cr.serialize(&[], body); - Ok(()) -} - -fn select_named_group(client_groups: Option<&NamedGroupVec>, server_groups: &[NamedGroup]) -> Option { - if let Some(groups) = client_groups { - // Server preference order from Config::kx_groups() - for sg in server_groups { - if groups.iter().any(|g| g == sg) { - return Some(*sg); - } - } - // Client advertised supported_groups, but there is no overlap. - return None; - } - - // Fallback only when client did not advertise supported_groups: - // pick the first server-configured group. - server_groups.first().copied() -} - -fn select_ske_signature_algorithm( - client_algs: Option<&SignatureAndHashAlgorithmVec>, - our_sig: SignatureAlgorithm, - our_hash: HashAlgorithm, - supported_hashes: &[HashAlgorithm], -) -> SignatureAndHashAlgorithm { - // Prefer the key's native hash first, then fall back to the other - let hash_pref = match our_hash { - HashAlgorithm::SHA384 => [HashAlgorithm::SHA384, HashAlgorithm::SHA256], - _ => [HashAlgorithm::SHA256, HashAlgorithm::SHA384], - }; - - if let Some(list) = client_algs { - for h in hash_pref.iter() { - // Only consider hash algorithms the backend can actually sign with - if !supported_hashes.contains(h) { - continue; - } - if let Some(chosen) = list.iter().find(|alg| alg.signature == our_sig && alg.hash == *h) { - return *chosen; - } - } - } - - // Fallback: use the key's native hash - SignatureAndHashAlgorithm::new(our_hash, our_sig) -} - -fn select_certificate_request_sig_algs( - client_algs: Option<&SignatureAndHashAlgorithmVec>, -) -> SignatureAndHashAlgorithmVec { - // Only select algorithms supported by dimpl's signature verifiers. - let ours = SignatureAndHashAlgorithm::supported(); - - // Build intersection preserving client preference order - let mut out = ArrayVec::new(); - if let Some(list) = client_algs { - for alg in list.iter() { - if ours.iter().any(|a| a.hash == alg.hash && a.signature == alg.signature) { - out.push(*alg); - } - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn named_group_vec(groups: &[NamedGroup]) -> NamedGroupVec { - let mut out = NamedGroupVec::new(); - for g in groups { - out.push(*g); - } - out - } - - #[test] - fn select_named_group_prefers_x25519_when_available() { - let client = named_group_vec(&[NamedGroup::Secp256r1, NamedGroup::X25519, NamedGroup::Secp384r1]); - let provider = [NamedGroup::X25519, NamedGroup::Secp256r1]; - - let selected = select_named_group(Some(&client), &provider); - - assert_eq!(selected, Some(NamedGroup::X25519)); - } - - #[test] - fn select_named_group_respects_provider_capabilities() { - let client = named_group_vec(&[NamedGroup::X25519, NamedGroup::Secp256r1]); - let provider = [NamedGroup::Secp256r1]; - - let selected = select_named_group(Some(&client), &provider); - - assert_eq!(selected, Some(NamedGroup::Secp256r1)); - } - - #[test] - fn select_named_group_falls_back_to_provider_when_client_missing() { - let provider = [NamedGroup::Secp384r1]; - - let selected = select_named_group(None, &provider); - - assert_eq!(selected, Some(NamedGroup::Secp384r1)); - } - - #[test] - fn select_named_group_rejects_when_client_has_no_overlap() { - let client = named_group_vec(&[NamedGroup::X25519]); - let provider = [NamedGroup::Secp256r1]; - - let selected = select_named_group(Some(&client), &provider); - - assert_eq!(selected, None); - } - - #[test] - fn certificate_request_does_not_select_rsa_signatures() { - let mut client = SignatureAndHashAlgorithmVec::new(); - client.push(SignatureAndHashAlgorithm::new( - HashAlgorithm::SHA256, - SignatureAlgorithm::ECDSA, - )); - client.push(SignatureAndHashAlgorithm::new( - HashAlgorithm::SHA256, - SignatureAlgorithm::RSA, - )); - - let selected = select_certificate_request_sig_algs(Some(&client)); - - assert_eq!(selected.len(), 1); - assert_eq!(selected[0].signature, SignatureAlgorithm::ECDSA); - assert_eq!(selected[0].hash, HashAlgorithm::SHA256); - } - - #[test] - fn certificate_request_rejects_rsa_only_signatures() { - let mut client = SignatureAndHashAlgorithmVec::new(); - client.push(SignatureAndHashAlgorithm::new( - HashAlgorithm::SHA256, - SignatureAlgorithm::RSA, - )); - - let selected = select_certificate_request_sig_algs(Some(&client)); - - assert!(selected.is_empty()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/error.rs b/rs/moq-webrtc/src/vendor/dimpl/error.rs deleted file mode 100644 index d3fe5ba8403..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/error.rs +++ /dev/null @@ -1,877 +0,0 @@ -//! Public error type returned by the high-level DTLS API. - -use std::fmt; -use tracing::debug; - -use crate::vendor::dimpl::dtls12::message::Dtls12CipherSuite; -use crate::vendor::dimpl::types::CompressionMethod; -use crate::vendor::dimpl::types::HashAlgorithm; -use crate::vendor::dimpl::types::NamedGroup; -use crate::vendor::dimpl::types::ProtocolVersion; -use crate::vendor::dimpl::types::SignatureAlgorithm; - -pub(crate) fn bounded_error_len(len: usize) -> u16 { - len.min(u16::MAX as usize) as u16 -} - -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -/// Errors returned by DTLS processing functions. -pub enum Error { - /// Unexpected DTLS message. - UnexpectedMessage(UnexpectedMessageError), - /// Local state was missing data required for the requested operation. - InvalidState(InvalidStateError), - /// Cryptographic operation failed. - CryptoError(CryptoError), - /// Certificate validation failed. - CertificateError(CertificateError), - /// Security policy violation. - SecurityError(SecurityError), - /// PSK (Pre-Shared Key) error. - PskError(PskError), - /// Incoming queue exceeded capacity. - ReceiveQueueFull, - /// Outgoing queue exceeded capacity. - TransmitQueueFull, - /// Missing fields when parsing ServerHello. - IncompleteServerHello, - /// Something timed out. - Timeout(TimeoutError), - /// Configuration error (e.g., invalid crypto provider). - ConfigError(ConfigError), - /// Peer attempted renegotiation (not supported). - RenegotiationAttempt, - /// The connection has been closed (close_notify sent or received). - ConnectionClosed, -} - -/// Fine-grained reason for an [`Error::UnexpectedMessage`]. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum UnexpectedMessageError { - /// A record from a handshake epoch remained when entering application data. - UnexpectedEpoch, - /// A DTLS 1.2 `ServerKeyExchange` omitted its required signature. - ServerKeyExchangeWithoutSignature, - /// A PSK `ServerKeyExchange` was received while processing an ECDHE suite. - PskServerKeyExchangeInEcdhePath, - /// An ECDHE `ServerKeyExchange` was received while processing a PSK suite. - EcdheServerKeyExchangeInPskPath, - /// A PSK `ClientKeyExchange` was received while processing an ECDHE suite. - PskClientKeyExchangeInEcdhePath, - /// An ECDHE `ClientKeyExchange` was received while processing a PSK suite. - EcdheClientKeyExchangeInPskPath, -} - -/// Fine-grained reason for an [`Error::InvalidState`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum InvalidStateError { - /// No cipher suite has been selected for the connection. - NoCipherSuiteSelected, - /// A cipher suite was required but not available. - NoCipherSuite, - /// The client random was required but not available. - NoClientRandom, - /// The server random was required but not available. - NoServerRandom, - /// Extended master secret was negotiated, but the session hash was not captured. - ExtendedMasterSecretSessionHashMissing, -} - -/// Fine-grained reason for an [`Error::CryptoError`]. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum CryptoError { - /// DTLS 1.2 needs a key exchange group but none is configured. - NoDtls12KeyExchangeGroupsConfigured, - /// A key exchange operation was requested before initialization. - KeyExchangeNotInitialized, - /// The requested key exchange group is unsupported. - UnsupportedKeyExchangeGroup(NamedGroup), - /// The requested ECDHE group is unsupported. - UnsupportedEcdheNamedGroup(NamedGroup), - /// The requested DTLS 1.2 cipher suite is unsupported. - UnsupportedCipherSuite(Dtls12CipherSuite), - /// The requested HMAC hash algorithm is unsupported. - UnsupportedHmacHash(HashAlgorithm), - /// The requested signature algorithm is unsupported. - UnsupportedSignatureAlgorithm(SignatureAlgorithm), - /// No locally supported signature algorithm was offered by the peer. - SignatureAlgorithmNotOfferedByClient, - /// The signature algorithm did not match the expected algorithm. - SignatureAlgorithmMismatch { - /// The signature algorithm expected for this operation. - expected: SignatureAlgorithm, - /// The signature algorithm actually present. - actual: SignatureAlgorithm, - }, - /// The signature, hash, and key group combination is unsupported for verification. - UnsupportedSignatureVerification { - /// The requested signature algorithm. - signature: SignatureAlgorithm, - /// The requested hash algorithm. - hash: HashAlgorithm, - /// The public key group used for verification. - group: NamedGroup, - }, - /// Signature verification failed for a supported signature/hash/group combination. - SignatureVerificationFailed { - /// The requested signature algorithm. - signature: SignatureAlgorithm, - /// The requested hash algorithm. - hash: HashAlgorithm, - /// The public key group used for verification. - group: NamedGroup, - }, - /// The public key algorithm is unsupported. - UnsupportedPublicKeyAlgorithm, - /// A certificate or key references an unsupported EC curve. - UnsupportedEcCurve, - /// Certificate parsing failed during a crypto operation. - CertificateParseFailed, - /// A certificate omitted its required EC curve parameter. - MissingEcCurveParameter, - /// A certificate had an invalid EC curve parameter. - InvalidEcCurveParameter, - /// A certificate had an invalid subject public key. - InvalidSubjectPublicKey, - /// A public key could not be parsed for the given group. - InvalidPublicKey(NamedGroup), - /// A private key could not be parsed in any supported format. - InvalidPrivateKey, - /// A signing key was used with a hash other than the one it is bound to. - SigningKeyHashMismatch { - /// The hash algorithm bound to the signing key. - key_hash: HashAlgorithm, - /// The hash algorithm requested by the caller. - requested: HashAlgorithm, - }, - /// An AES-GCM key had the wrong length. - InvalidAesGcmKeySize { - /// The actual key length in bytes. - /// - /// Values greater than `u16::MAX` are reported as `u16::MAX`. - actual: u16, - }, - /// A ChaCha20-Poly1305 key had the wrong length. - InvalidChacha20Poly1305KeySize { - /// The actual key length in bytes. - /// - /// Values greater than `u16::MAX` are reported as `u16::MAX`. - actual: u16, - }, - /// An AES-128-CCM-8 key had the wrong length. - InvalidAes128Ccm8KeySize { - /// The actual key length in bytes. - /// - /// Values greater than `u16::MAX` are reported as `u16::MAX`. - actual: u16, - }, - /// A nonce was invalid for the selected cipher. - InvalidNonce, - /// A ciphertext was shorter than the selected AEAD permits. - CiphertextTooShort { - /// The minimum accepted ciphertext length in bytes. - minimum: u8, - /// The actual ciphertext length in bytes. - actual: u8, - }, - /// The `Finished` verify-data length was invalid. - InvalidVerifyDataLength, - /// The `Finished` verify-data is too long to encode. - VerifyDataTooLong, - /// The TLS 1.2 master secret is too long to encode. - MasterSecretTooLong, - /// The requested exported keying material is too long. - KeyingMaterialTooLong, - /// The TLS 1.2 pre-master secret is not available. - PreMasterSecretNotAvailable, - /// The TLS 1.2 master secret is not available. - MasterSecretNotAvailable, - /// The client random is not available. - ClientRandomNotAvailable, - /// The server random is not available. - ServerRandomNotAvailable, - /// The client cipher has not been initialized. - ClientCipherNotInitialized, - /// The server cipher has not been initialized. - ServerCipherNotInitialized, - /// A write IV is not available for the requested side. - WriteIvNotAvailable { - /// Whether the missing write IV is for the client side. - is_client: bool, - }, - /// The DTLS 1.2 record IV length is unsupported for the selected suite. - UnsupportedDtls12RecordIvLen { - /// The unsupported record IV length. - /// - /// Values greater than `u16::MAX` are reported as `u16::MAX`. - len: u16, - /// The selected DTLS 1.2 cipher suite. - suite: Dtls12CipherSuite, - }, - /// No private key is configured. - NoPrivateKeyConfigured, - /// A PSK operation was requested before a PSK was set. - PskNotSet, - /// A provider operation failed without a more specific reason. - OperationFailed(CryptoOperation), -} - -/// A cryptographic operation that can fail. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum CryptoOperation { - /// Create an AEAD cipher instance. - CreateCipher, - /// Encrypt plaintext. - Encrypt, - /// Decrypt ciphertext. - Decrypt, - /// Sign a transcript or payload. - Sign, - /// Generate an ephemeral key. - GenerateEphemeralKey, - /// Compute a public key. - ComputePublicKey, - /// Fill a buffer with random bytes. - FillRandom, - /// Compute a DTLS cookie. - ComputeCookie, - /// Encode a key. - EncodeKey, - /// Compute an HMAC. - ComputeHmac, -} - -/// Fine-grained reason for an [`Error::CertificateError`]. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum CertificateError { - /// The peer did not send a server certificate. - NoServerCertificateReceived, - /// The client sent an empty certificate list when a certificate was required. - NoClientCertificateReceived, - /// Client certificate verification was requested with no client certificate. - NoClientCertificateForVerification, - /// The certificate operation needs an unsupported hash algorithm. - UnsupportedHashAlgorithm(HashAlgorithm), - /// A certificate omitted its EC curve parameter. - MissingEcCurveParameter, - /// A certificate had an invalid EC curve parameter. - InvalidEcCurveParameter, - /// A certificate references an unsupported EC curve. - UnsupportedEcCurve, - /// A certificate had an invalid subject public key. - InvalidSubjectPublicKey, -} - -/// Fine-grained reason for an [`Error::SecurityError`]. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum SecurityError { - /// `HelloVerifyRequest` used an unsupported protocol version. - UnsupportedHelloVerifyRequestVersion(ProtocolVersion), - /// A server selected an unsupported protocol version. - UnsupportedServerVersion(ProtocolVersion), - /// A client offered an unsupported protocol version. - UnsupportedClientVersion(ProtocolVersion), - /// A server selected an unsupported DTLS 1.2 compression method. - UnsupportedServerCompression(CompressionMethod), - /// A client did not offer null compression. - UnsupportedClientCompression, - /// The selected key exchange algorithm is unsupported. - UnsupportedKeyExchangeAlgorithm, - /// The server selected a cipher suite that was not offered or recognized. - ServerSelectedUnknownCipherSuite, - /// The server selected a DTLS 1.2 cipher suite incompatible with local mode. - ServerSelectedIncompatibleCipherSuite(Dtls12CipherSuite), - /// The server selected a DTLS 1.2 cipher suite disallowed by configuration. - ServerSelectedDisallowedCipherSuite(Dtls12CipherSuite), - /// DTLS 1.2 extended master secret was required but not negotiated. - ExtendedMasterSecretNotNegotiated, - /// No mutually acceptable cipher suite was found. - NoMutuallyAcceptableCipherSuite, - /// No common key exchange group was found. - NoCommonKeyExchangeGroup, - /// A signature algorithm did not match the expected algorithm. - SignatureAlgorithmMismatch { - /// The expected signature algorithm. - expected: SignatureAlgorithm, - /// The actual signature algorithm. - actual: SignatureAlgorithm, - }, - /// Server Finished verification failed. - ServerFinishedVerificationFailed, - /// Client Finished verification failed. - ClientFinishedVerificationFailed, - /// A fatal DTLS alert was received. - FatalAlert { - /// The DTLS alert description. - description: u8, - }, -} - -/// Fine-grained reason for an [`Error::PskError`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum PskError { - /// No PSK resolver is configured. - NoPskResolverConfigured, - /// No PSK identity is configured. - NoPskIdentityConfigured, - /// The configured PSK resolver did not return a key. - ResolverReturnedNoKey, -} - -/// Fine-grained reason for an [`Error::Timeout`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum TimeoutError { - /// Timeout while connecting. - Connect, - /// Timeout while handshaking. - Handshake, -} - -/// Fine-grained reason for an [`Error::ConfigError`]. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum ConfigError { - /// The configured MTU is smaller than dimpl permits. - MtuTooSmall { - /// The configured MTU. - mtu: u16, - /// The minimum accepted MTU. - minimum: u16, - }, - /// The handshake timeout is zero or greater than 3650 days. - InvalidHandshakeTimeout, - /// The initial flight RTO is zero or greater than 3650 days. - InvalidFlightStartRto, - /// Cipher-suite filtering removed every available suite. - NoCipherSuitesAfterFiltering, - /// A PSK resolver is configured but no PSK cipher suite remains enabled. - PskConfiguredWithoutPskCipherSuite, - /// DTLS 1.2 suites are enabled but no compatible key exchange group remains enabled. - NoDtls12KeyExchangeGroupsAfterFiltering, - /// Crypto provider validation failed. - CryptoProvider(CryptoProviderValidationError), - /// No provider was given, and rind's default refuses this CPU. - UnsupportedCpu(rind::cpu::MissingFeature), -} - -/// Fine-grained reason for crypto provider validation failure. -#[derive(Debug, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum CryptoProviderValidationError { - /// The provider has no cipher suites supported by dimpl. - NoCipherSuites, - /// The provider has ECDH cipher suites but no key exchange groups. - EcdhCipherSuitesWithoutKeyExchangeGroups, - /// No hash test vector exists for the hash algorithm. - MissingHashTestVector(HashAlgorithm), - /// The provider hash implementation returned an unexpected value. - HashProviderIncorrect(HashAlgorithm), - /// The provider PRF operation failed. - PrfFailed { - /// The hash algorithm used by the PRF. - hash: HashAlgorithm, - /// The underlying crypto failure. - source: CryptoError, - }, - /// No PRF test vector exists for the hash algorithm. - MissingPrfTestVector(HashAlgorithm), - /// The provider PRF returned incorrect output. - PrfIncorrect(HashAlgorithm), - /// No signature-validation vector exists for the algorithm pair. - NoSignatureValidationVector { - /// The hash algorithm used by the vector. - hash: HashAlgorithm, - /// The signature algorithm used by the vector. - signature: SignatureAlgorithm, - }, - /// Provider signature verification failed. - SignatureVerificationFailed { - /// The hash algorithm used for verification. - hash: HashAlgorithm, - /// The signature algorithm used for verification. - signature: SignatureAlgorithm, - /// The underlying crypto failure. - source: CryptoError, - }, - /// Starting key exchange failed. - KeyExchangeStartFailed { - /// The key exchange group under validation. - group: NamedGroup, - /// The underlying crypto failure. - source: CryptoError, - }, - /// Completing key exchange failed. - KeyExchangeCompleteFailed { - /// The key exchange group under validation. - group: NamedGroup, - /// The underlying crypto failure. - source: CryptoError, - }, - /// Two sides of a validation key exchange produced different shared secrets. - KeyExchangeMismatchedSharedSecret(NamedGroup), - /// HMAC validation failed. - HmacFailed(CryptoError), - /// HMAC validation returned incorrect output. - HmacIncorrect, -} - -#[derive(Debug)] -pub(crate) enum InternalError { - Transient(TransientError), - Fatal(Error), -} - -#[derive(Debug)] -pub(crate) enum TransientError { - ParseIncomplete, - Parse(nom::error::ErrorKind), - TooManyRecords, -} - -impl InternalError { - pub(crate) fn parse_incomplete() -> Self { - Self::Transient(TransientError::ParseIncomplete) - } - - pub(crate) fn parse(kind: nom::error::ErrorKind) -> Self { - Self::Transient(TransientError::Parse(kind)) - } - - pub(crate) fn too_many_records() -> Self { - Self::Transient(TransientError::TooManyRecords) - } - - pub(crate) fn into_public_error(self) -> Option { - match self { - Self::Transient(err) => { - debug!("Discarding packet: {err}"); - None - } - Self::Fatal(err) => Some(err), - } - } -} - -impl From for InternalError { - fn from(value: Error) -> Self { - Self::Fatal(value) - } -} - -impl<'a> From>> for InternalError { - fn from(value: nom::Err>) -> Self { - match value { - nom::Err::Incomplete(_) => InternalError::parse_incomplete(), - nom::Err::Error(x) => InternalError::parse(x.code), - nom::Err::Failure(x) => InternalError::parse(x.code), - } - } -} - -impl From for Error { - fn from(value: CryptoError) -> Self { - Self::CryptoError(value) - } -} - -impl From for Error { - fn from(value: CertificateError) -> Self { - Self::CertificateError(value) - } -} - -impl From for Error { - fn from(value: SecurityError) -> Self { - Self::SecurityError(value) - } -} - -impl From for Error { - fn from(value: PskError) -> Self { - Self::PskError(value) - } -} - -impl From for Error { - fn from(value: ConfigError) -> Self { - Self::ConfigError(value) - } -} - -impl std::error::Error for Error {} - -impl fmt::Display for InternalError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - InternalError::Transient(err) => err.fmt(f), - InternalError::Fatal(err) => err.fmt(f), - } - } -} - -impl fmt::Display for TransientError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - TransientError::ParseIncomplete => write!(f, "parse incomplete"), - TransientError::Parse(kind) => write!(f, "parse error: {:?}", kind), - TransientError::TooManyRecords => write!(f, "too many records in packet"), - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::UnexpectedMessage(err) => write!(f, "unexpected message: {err}"), - Error::InvalidState(err) => write!(f, "invalid state: {err}"), - Error::CryptoError(err) => write!(f, "crypto error: {err}"), - Error::CertificateError(err) => write!(f, "certificate error: {err}"), - Error::SecurityError(err) => write!(f, "security error: {err}"), - Error::PskError(err) => write!(f, "psk error: {err}"), - Error::ReceiveQueueFull => write!(f, "receive queue full"), - Error::TransmitQueueFull => write!(f, "transmit queue full"), - Error::IncompleteServerHello => write!(f, "incomplete ServerHello"), - Error::Timeout(err) => write!(f, "timeout: {err}"), - Error::ConfigError(err) => write!(f, "config error: {err}"), - Error::RenegotiationAttempt => write!(f, "peer attempted renegotiation"), - Error::ConnectionClosed => write!(f, "connection closed"), - } - } -} - -impl fmt::Display for UnexpectedMessageError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::UnexpectedEpoch => { - write!(f, "pending record in unexpected epoch at handshake completion") - } - Self::ServerKeyExchangeWithoutSignature => { - write!(f, "ServerKeyExchange without signature") - } - Self::PskServerKeyExchangeInEcdhePath => { - write!(f, "PSK ServerKeyExchange in ECDHE path") - } - Self::EcdheServerKeyExchangeInPskPath => { - write!(f, "ECDHE ServerKeyExchange in PSK path") - } - Self::PskClientKeyExchangeInEcdhePath => { - write!(f, "PSK ClientKeyExchange in ECDHE path") - } - Self::EcdheClientKeyExchangeInPskPath => { - write!(f, "ECDHE ClientKeyExchange in PSK path") - } - } - } -} - -impl fmt::Display for InvalidStateError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoCipherSuiteSelected => write!(f, "no cipher suite selected"), - Self::NoCipherSuite => write!(f, "no cipher suite"), - Self::NoClientRandom => write!(f, "no client random"), - Self::NoServerRandom => write!(f, "no server random"), - Self::ExtendedMasterSecretSessionHashMissing => { - write!(f, "extended master secret negotiated but session hash not captured") - } - } - } -} - -impl fmt::Display for CryptoError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoDtls12KeyExchangeGroupsConfigured => { - write!(f, "no DTLS 1.2 key exchange groups configured") - } - Self::KeyExchangeNotInitialized => write!(f, "key exchange not initialized"), - Self::UnsupportedKeyExchangeGroup(group) => { - write!(f, "unsupported key exchange group: {group:?}") - } - Self::UnsupportedEcdheNamedGroup(group) => { - write!(f, "unsupported ECDHE named group: {group:?}") - } - Self::UnsupportedCipherSuite(suite) => { - write!(f, "unsupported cipher suite: {suite:?}") - } - Self::UnsupportedHmacHash(hash) => { - write!(f, "unsupported HMAC hash algorithm: {hash:?}") - } - Self::UnsupportedSignatureAlgorithm(sig) => { - write!(f, "unsupported signature algorithm: {sig:?}") - } - Self::SignatureAlgorithmNotOfferedByClient => { - write!(f, "signature algorithm not offered by client") - } - Self::SignatureAlgorithmMismatch { expected, actual } => { - write!(f, "signature algorithm mismatch: {actual:?} != {expected:?}") - } - Self::UnsupportedSignatureVerification { signature, hash, group } => write!( - f, - "unsupported signature verification: {signature:?} + {hash:?} + {group:?}" - ), - Self::SignatureVerificationFailed { signature, hash, group } => { - write!(f, "signature verification failed: {signature:?} + {hash:?} + {group:?}") - } - Self::UnsupportedPublicKeyAlgorithm => write!(f, "unsupported public key algorithm"), - Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"), - Self::CertificateParseFailed => write!(f, "failed to parse certificate"), - Self::MissingEcCurveParameter => { - write!(f, "missing EC curve parameter in certificate") - } - Self::InvalidEcCurveParameter => { - write!(f, "invalid EC curve parameter in certificate") - } - Self::InvalidSubjectPublicKey => { - write!(f, "invalid EC subject_public_key bitstring") - } - Self::InvalidPublicKey(group) => write!(f, "invalid {group:?} public key"), - Self::InvalidPrivateKey => { - write!(f, "failed to parse private key in any supported format") - } - Self::SigningKeyHashMismatch { key_hash, requested } => write!( - f, - "signing key is locked to {key_hash:?} but {requested:?} was requested" - ), - Self::InvalidAesGcmKeySize { actual } => { - write!(f, "invalid key size for AES-GCM: {actual}") - } - Self::InvalidChacha20Poly1305KeySize { actual } => { - write!(f, "invalid key size for CHACHA20-POLY1305: {actual}") - } - Self::InvalidAes128Ccm8KeySize { actual } => { - write!(f, "invalid key size for AES-128-CCM-8: {actual}") - } - Self::InvalidNonce => write!(f, "invalid nonce"), - Self::CiphertextTooShort { minimum, actual } => { - write!(f, "ciphertext too short: got {actual}, minimum {minimum}") - } - Self::InvalidVerifyDataLength => write!(f, "invalid verify data length"), - Self::VerifyDataTooLong => write!(f, "verify data too long"), - Self::MasterSecretTooLong => write!(f, "master secret too long"), - Self::KeyingMaterialTooLong => write!(f, "keying material too long"), - Self::PreMasterSecretNotAvailable => write!(f, "pre-master secret not available"), - Self::MasterSecretNotAvailable => write!(f, "master secret not available"), - Self::ClientRandomNotAvailable => write!(f, "client random not available"), - Self::ServerRandomNotAvailable => write!(f, "server random not available"), - Self::ClientCipherNotInitialized => write!(f, "client cipher not initialized"), - Self::ServerCipherNotInitialized => write!(f, "server cipher not initialized"), - Self::WriteIvNotAvailable { is_client } => { - let side = if *is_client { "client" } else { "server" }; - write!(f, "{side} write IV not available") - } - Self::UnsupportedDtls12RecordIvLen { len, suite } => { - write!(f, "unsupported DTLS 1.2 record_iv_len={len} for {suite:?}") - } - Self::NoPrivateKeyConfigured => write!(f, "no private key configured"), - Self::PskNotSet => write!(f, "PSK not set"), - Self::OperationFailed(op) => write!(f, "{op} failed"), - } - } -} - -impl fmt::Display for CryptoOperation { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let text = match self { - Self::CreateCipher => "cipher creation", - Self::Encrypt => "encryption", - Self::Decrypt => "decryption", - Self::Sign => "signing", - Self::GenerateEphemeralKey => "ephemeral key generation", - Self::ComputePublicKey => "public key computation", - Self::FillRandom => "random generation", - Self::ComputeCookie => "cookie computation", - Self::EncodeKey => "key encoding", - Self::ComputeHmac => "HMAC computation", - }; - write!(f, "{text}") - } -} - -impl fmt::Display for CertificateError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoServerCertificateReceived => write!(f, "no server certificate received"), - Self::NoClientCertificateReceived => write!(f, "no client certificate received"), - Self::NoClientCertificateForVerification => { - write!(f, "no client certificate for verification") - } - Self::UnsupportedHashAlgorithm(hash) => { - write!(f, "unsupported hash algorithm: {hash:?}") - } - Self::MissingEcCurveParameter => { - write!(f, "missing EC curve parameter in certificate") - } - Self::InvalidEcCurveParameter => { - write!(f, "invalid EC curve parameter in certificate") - } - Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"), - Self::InvalidSubjectPublicKey => { - write!(f, "invalid EC subject_public_key bitstring") - } - } - } -} - -impl fmt::Display for SecurityError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::UnsupportedHelloVerifyRequestVersion(version) => { - write!(f, "unsupported DTLS version in HelloVerifyRequest: {version:?}") - } - Self::UnsupportedServerVersion(version) => { - write!(f, "unsupported DTLS version from server: {version:?}") - } - Self::UnsupportedClientVersion(version) => { - write!(f, "unsupported DTLS version from client: {version:?}") - } - Self::UnsupportedServerCompression(compression) => { - write!(f, "unsupported compression method from server: {compression:?}") - } - Self::UnsupportedClientCompression => { - write!(f, "client did not offer null compression") - } - Self::UnsupportedKeyExchangeAlgorithm => { - write!(f, "unsupported key exchange algorithm") - } - Self::ServerSelectedUnknownCipherSuite => { - write!(f, "server selected unknown cipher suite") - } - Self::ServerSelectedIncompatibleCipherSuite(suite) => { - write!(f, "server selected incompatible cipher suite: {suite:?}") - } - Self::ServerSelectedDisallowedCipherSuite(suite) => { - write!(f, "server selected disallowed cipher suite: {suite:?}") - } - Self::ExtendedMasterSecretNotNegotiated => { - write!(f, "extended master secret not negotiated") - } - Self::NoMutuallyAcceptableCipherSuite => { - write!(f, "no mutually acceptable cipher suite") - } - Self::NoCommonKeyExchangeGroup => write!(f, "no common key exchange group"), - Self::SignatureAlgorithmMismatch { expected, actual } => { - write!(f, "signature algorithm mismatch: expected {expected:?}, got {actual:?}") - } - Self::ServerFinishedVerificationFailed => { - write!(f, "server Finished verification failed") - } - Self::ClientFinishedVerificationFailed => { - write!(f, "client Finished verification failed") - } - Self::FatalAlert { description } => { - write!(f, "received fatal alert: description={description}") - } - } - } -} - -impl fmt::Display for PskError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoPskResolverConfigured => write!(f, "no PSK resolver configured"), - Self::NoPskIdentityConfigured => write!(f, "no PSK identity configured"), - Self::ResolverReturnedNoKey => write!(f, "PSK resolver returned no key"), - } - } -} - -impl fmt::Display for TimeoutError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Connect => write!(f, "connect"), - Self::Handshake => write!(f, "handshake"), - } - } -} - -impl fmt::Display for ConfigError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MtuTooSmall { mtu, minimum } => { - write!(f, "MTU {mtu} is too small (minimum {minimum})") - } - Self::InvalidHandshakeTimeout => { - write!(f, "handshake_timeout must be nonzero and at most 3650 days") - } - Self::InvalidFlightStartRto => { - write!(f, "flight_start_rto must be nonzero and at most 3650 days") - } - Self::NoCipherSuitesAfterFiltering => write!( - f, - "no cipher suites remain after filtering; at least one DTLS 1.2 cipher suite must be available" - ), - Self::PskConfiguredWithoutPskCipherSuite => write!( - f, - "PSK is configured but no PSK cipher suite remains after filtering DTLS 1.2 suites" - ), - Self::NoDtls12KeyExchangeGroupsAfterFiltering => write!( - f, - concat!( - "DTLS 1.2 cipher suites are enabled but no compatible key exchange ", - "groups remain after filtering" - ) - ), - Self::CryptoProvider(err) => write!(f, "crypto provider validation failed: {err}"), - Self::UnsupportedCpu(missing) => write!(f, "unsupported CPU: {missing}"), - } - } -} - -impl fmt::Display for CryptoProviderValidationError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoCipherSuites => { - write!(f, "CryptoProvider has no cipher suites supported by dimpl") - } - Self::EcdhCipherSuitesWithoutKeyExchangeGroups => write!( - f, - "CryptoProvider has ECDH cipher suites but no supported key exchange groups" - ), - Self::MissingHashTestVector(hash) => { - write!(f, "no expected hash data for hash algorithm: {hash:?}") - } - Self::HashProviderIncorrect(hash) => { - write!(f, "hash provider {hash:?} produced incorrect result") - } - Self::PrfFailed { hash, source } => write!(f, "PRF failed for {hash:?}: {source}"), - Self::MissingPrfTestVector(hash) => { - write!(f, "no expected PRF data for hash algorithm: {hash:?}") - } - Self::PrfIncorrect(hash) => write!(f, "PRF {hash:?} produced incorrect result"), - Self::NoSignatureValidationVector { hash, signature } => { - write!(f, "no validation test vectors for {hash:?} + {signature:?}") - } - Self::SignatureVerificationFailed { - hash, - signature, - source, - } => write!( - f, - "signature verification failed for {hash:?} + {signature:?}: {source}" - ), - Self::KeyExchangeStartFailed { group, source } => { - write!(f, "key exchange start failed for {group:?}: {source}") - } - Self::KeyExchangeCompleteFailed { group, source } => { - write!(f, "key exchange complete failed for {group:?}: {source}") - } - Self::KeyExchangeMismatchedSharedSecret(group) => { - write!(f, "key exchange produced different secrets for {group:?}") - } - Self::HmacFailed(source) => write!(f, "HMAC provider failed: {source}"), - Self::HmacIncorrect => { - write!(f, "HMAC provider produced incorrect result for HMAC-SHA256") - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/lib.rs b/rs/moq-webrtc/src/vendor/dimpl/lib.rs deleted file mode 100644 index 03aba1dbc05..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/lib.rs +++ /dev/null @@ -1,703 +0,0 @@ -//! dimpl - DTLS 1.2 implementation (Sans‑IO, Sync) -//! -//! dimpl is a DTLS 1.2 implementation aimed at WebRTC. It is a Sans‑IO -//! state machine you embed into your own UDP/RTC event loop: you feed incoming -//! datagrams, poll for outgoing records or timers, and wire up certificate -//! verification and SRTP key export yourself. -//! -//! # Goals -//! - **DTLS 1.2**: Implements the DTLS handshake and record layer used by WebRTC. -//! - **Safety**: `forbid(unsafe_code)` throughout the crate. -//! - **Minimal Rust‑only deps**: Uses small, well‑maintained Rust crypto crates. -//! - **Low overhead**: Tight control over allocations and buffers; Sans‑IO integration. -//! -//! ## Non‑goals -//! - **DTLS 1.0** -//! - **Async** (the crate is Sans‑IO and event‑loop agnostic) -//! - **no_std** (at least not without allocation) -//! - **RSA** -//! - **DHE** -//! -//! ## Constructors -//! -//! - [`Dtls::new_12`][new_12] - certificate‑based -//! - [`Dtls::new_12_psk`][new_12_psk] - PSK, no certificates -//! -//! # Cryptography surface -//! - **Cipher suites (TLS 1.2 over DTLS)** -//! - `ECDHE_ECDSA_AES256_GCM_SHA384` -//! - `ECDHE_ECDSA_AES128_GCM_SHA256` -//! - `ECDHE_ECDSA_CHACHA20_POLY1305_SHA256` -//! - **PSK cipher suites (TLS 1.2 over DTLS)** -//! - `PSK_AES128_CCM_8` -//! - **AEAD**: AES‑GCM 128/256, ChaCha20‑Poly1305 (no CBC/EtM modes). -//! - **Key exchange**: ECDHE (P‑256/P‑384), X25519 -//! - **Signatures**: ECDSA P‑256/SHA‑256, ECDSA P‑384/SHA‑384 -//! - **DTLS‑SRTP**: Exports keying material for `SRTP_AEAD_AES_256_GCM`, -//! `SRTP_AEAD_AES_128_GCM`, and `SRTP_AES128_CM_SHA1_80` ([RFC 5764], [RFC 7714]). -//! - **Extended Master Secret** ([RFC 7627]) is negotiated and enforced. -//! -//! ## Certificate model -//! During the handshake the engine emits -//! [`Output::PeerCert`][peer_cert] with the peer's leaf -//! certificate (DER). The crate uses that certificate to verify DTLS -//! handshake messages, but it does not perform any PKI validation. Your -//! application is responsible for validating the peer certificate according to -//! your policy (fingerprint, chain building, name/EKU checks, pinning, etc.). -//! -//! ## Sans‑IO integration model -//! Drive the engine with three calls: -//! - [`Dtls::handle_packet`][handle_packet] - feed an entire -//! received UDP datagram. -//! - [`Dtls::poll_output`][poll_output] - drain pending output: -//! DTLS records, timers, events. -//! - [`Dtls::handle_timeout`][handle_timeout] - trigger -//! retransmissions/time‑based progress. -//! -//! The output is an [`Output`][output] enum with borrowed -//! references into your provided buffer: -//! - `Packet(&[u8])`: send on your UDP socket -//! - `BufferTooSmall { needed }`: resize the poll buffer and retry -//! - `Timeout(Instant)`: schedule a timer and call `handle_timeout` at/after it -//! - `Connected`: handshake complete -//! - `PeerCert(&[u8])`: peer leaf certificate (DER) - validate in your app -//! - `KeyingMaterial(KeyingMaterial, SrtpProfile)`: DTLS‑SRTP export -//! - `ApplicationData(&[u8])`: plaintext received from peer -//! - `CloseNotify`: peer sent a `close_notify` alert (graceful shutdown) -//! -//! # Error handling -//! -//! Every `Error` returned by the public API -//! ([`handle_packet`][handle_packet], [`handle_timeout`][handle_timeout], -//! `send_application_data`, and `close`) is **fatal**: the connection is no -//! longer usable and must be thrown away. The engine has no recoverable -//! error states, so the correct response is always to drop the `Dtls` -//! instance - and start a fresh handshake if you still need a connection. -//! -//! Transient, non‑fatal conditions inherent to running over an unreliable -//! transport - malformed datagrams, replayed or out‑of‑window records, and -//! other parser noise - are handled internally and never surface as an -//! `Error`. Such packets are discarded (logged at `debug!`) while the -//! connection keeps running. You therefore never need to distinguish -//! "retry" from "give up": a returned `Error` always means give up on this -//! connection. -//! -//! # Example (Sans‑IO loop) -//! -//! ```ignore -//! # #[cfg(all())] -//! # { -//! use std::sync::Arc; -//! use std::time::Instant; -//! -//! use crate::vendor::dimpl::{certificate, Config, Dtls, Output}; -//! -//! // Stub I/O to keep the example focused on the state machine -//! enum Event { Udp(Vec, Instant), Timer(Instant) } -//! fn wait_next_event(_next_wake: Option) -> Event { Event::Udp(Vec::new(), Instant::now()) } -//! fn send_udp(_bytes: &[u8]) {} -//! -//! fn example_event_loop(mut dtls: Dtls) -> Result<(), crate::vendor::dimpl::Error> { -//! let mut next_wake: Option = None; -//! let mut received_packet: Option> = None; -//! loop { -//! // Drain engine output until we have to wait for I/O or a timer -//! let mut out_buf = vec![0u8; 2048]; -//! loop { -//! match dtls.poll_output(&mut out_buf) { -//! Output::Packet(p) => send_udp(p), -//! Output::BufferTooSmall { needed } => { -//! out_buf.resize(needed, 0); -//! } -//! Output::Timeout(t) => { next_wake = Some(t); break; } -//! Output::Connected => { -//! // DTLS established - application may start sending -//! } -//! Output::PeerCert(_der) => { -//! // Inspect peer leaf certificate if desired -//! } -//! Output::KeyingMaterial(_km, _profile) => { -//! // Provide to SRTP stack -//! } -//! Output::ApplicationData(_data) => { -//! // Deliver plaintext to application -//! } -//! Output::CloseNotify => { -//! // Peer initiated graceful shutdown - leave the event loop -//! return Ok(()); -//! } -//! _ => {} -//! } -//! } -//! -//! if let Some(packet) = received_packet.take() { -//! dtls.handle_packet(&packet)?; -//! continue; -//! } -//! -//! // Block waiting for either UDP input or the scheduled timeout -//! match wait_next_event(next_wake) { -//! Event::Udp(pkt, now) => { -//! dtls.handle_timeout(now)?; -//! received_packet = Some(pkt); -//! } -//! Event::Timer(now) => dtls.handle_timeout(now)?, -//! } -//! } -//! } -//! -//! fn mk_dtls_client() -> Dtls { -//! let cert = certificate::generate_self_signed_certificate().unwrap(); -//! let cfg = Arc::new(Config::default()); -//! let mut dtls = Dtls::new_12(cfg, cert, Instant::now()); -//! dtls.set_active(true); // client role -//! dtls -//! } -//! -//! // Putting it together -//! let dtls = mk_dtls_client(); -//! let _ = example_event_loop(dtls); -//! # } -//! ``` -//! -//! # Example (PSK client) -//! -//! ```ignore -//! use std::sync::Arc; -//! use std::time::Instant; -//! -//! use crate::vendor::dimpl::{Config, Dtls, PskResolver}; -//! -//! struct MyPsk; -//! -//! impl PskResolver for MyPsk { -//! fn resolve(&self, identity: &[u8]) -> Option> { -//! if identity == b"device-01" { -//! Some(b"shared-secret-key".to_vec()) -//! } else { -//! None -//! } -//! } -//! } -//! -//! let config = Arc::new( -//! Config::builder() -//! .with_psk_client(b"device-01".to_vec(), Arc::new(MyPsk)) -//! .build() -//! .unwrap(), -//! ); -//! -//! let mut dtls = Dtls::new_12_psk(config, Instant::now()); -//! dtls.set_active(true); // client role -//! ``` -//! -//! ### MSRV -//! Rust 1.85.0 -//! -//! ### Status -//! - Session resumption is not implemented (WebRTC does a full handshake on ICE restart). -//! - Renegotiation is not implemented (WebRTC does full restart). -//! -//! [new_12]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_12 -//! [new_12_psk]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_12_psk -//! [peer_cert]: https://docs.rs/dimpl/latest/dimpl/enum.Output.html#variant.PeerCert -//! [handle_packet]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.handle_packet -//! [poll_output]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.poll_output -//! [handle_timeout]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.handle_timeout -//! [output]: https://docs.rs/dimpl/latest/dimpl/enum.Output.html -//! [RFC 5764]: https://www.rfc-editor.org/rfc/rfc5764 -//! [RFC 7714]: https://www.rfc-editor.org/rfc/rfc7714 -//! [RFC 7627]: https://www.rfc-editor.org/rfc/rfc7627 -//! -#![forbid(unsafe_code)] -#![allow(unknown_lints)] -#![deny(missing_docs)] -#![deny(missing_debug_implementations)] - -use std::fmt; -use std::sync::Arc; -use std::time::Instant; -use tracing::debug; - -mod types; -pub use types::{ - CompressionMethod, ContentType, HashAlgorithm, NamedGroup, ProtocolVersion, Sequence, SignatureAlgorithm, -}; - -mod dtls12; - -use dtls12::{Client as Client12, Server as Server12}; - -mod time_tricks; - -pub(crate) mod buffer; -mod window; - -mod util; - -mod error; -pub(crate) use error::InternalError; -pub use error::{ - CertificateError, ConfigError, CryptoError, CryptoOperation, CryptoProviderValidationError, Error, - InvalidStateError, PskError, SecurityError, TimeoutError, UnexpectedMessageError, -}; - -mod config; -pub use config::{Config, ConfigBuilder, Psk, PskResolver}; - -pub mod certificate; - -pub mod crypto; - -pub use crypto::{KeyingMaterial, SrtpProfile}; - -mod timer; - -mod rng; -pub(crate) use rng::SeededRng; - -/// Certificate and private key pair. -#[derive(Clone)] -pub struct DtlsCertificate { - /// Certificate in DER format. - pub certificate: Vec, - /// Private key in DER format. - pub private_key: Vec, -} - -impl fmt::Debug for DtlsCertificate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("DtlsCertificate") - .field("certificate", &self.certificate.len()) - .field("private_key", &self.private_key.len()) - .finish() - } -} - -/// Sans-IO DTLS endpoint (client or server). -/// -/// New instances start in the **server role**. Call -/// [`set_active(true)`](Self::set_active) to switch to client before -/// the handshake begins. -/// -/// Drive the state machine with [`handle_packet`](Self::handle_packet), -/// [`poll_output`](Self::poll_output), and -/// [`handle_timeout`](Self::handle_timeout). -pub struct Dtls { - inner: Option, -} - -enum Inner { - Client12(Client12), - Server12(Server12), -} - -impl Dtls { - /// Create a new DTLS 1.2 instance in the server role. - /// - /// Call [`set_active(true)`](Self::set_active) to switch to client - /// before the handshake begins. The `now` parameter seeds the internal - /// time tracking for timeouts and retransmissions. - /// - /// During the handshake, the peer's leaf certificate is surfaced via - /// [`Output::PeerCert`]. It is up to the application to validate that - /// certificate according to its security policy. - pub fn new_12(config: Arc, certificate: DtlsCertificate, now: Instant) -> Self { - let inner = Inner::Server12(Server12::new(config, certificate, now)); - Dtls { inner: Some(inner) } - } - - /// Create a new DTLS 1.2 PSK-only instance (no certificate). - /// - /// Call [`set_active(true)`](Self::set_active) to switch to client - /// before the handshake begins. The `config` must have a - /// [`PskResolver`] configured, and for clients a PSK identity - /// via [`ConfigBuilder::with_psk_client`](ConfigBuilder). - /// - /// Panics if `config` has no PSK configured. Without PSK data the - /// PSK suite filter would leave zero negotiable suites, so failing - /// fast at construction is preferable to a late handshake error. - pub fn new_12_psk(config: Arc, now: Instant) -> Self { - assert!( - config.psk().is_some(), - "Dtls::new_12_psk requires a PSK configuration; \ - set one via ConfigBuilder::with_psk_client or with_psk_server" - ); - let inner = Inner::Server12(Server12::new_psk(config, now)); - Dtls { inner: Some(inner) } - } - - /// Returns the negotiated DTLS protocol version. - pub fn protocol_version(&self) -> Option { - Some(ProtocolVersion::DTLS1_2) - } - - /// Return true while DTLS shutdown is in progress. - /// - /// This becomes true after local shutdown starts, or while a received - /// `close_notify` still needs to be reported by - /// [`poll_output`](Self::poll_output). Callers should continue polling - /// until this returns false or [`is_closed`](Self::is_closed) returns true. - pub fn is_closing(&self) -> bool { - match self.inner.as_ref() { - Some(Inner::Client12(client)) => client.is_closing(), - Some(Inner::Server12(server)) => server.is_closing(), - None => false, - } - } - - /// Return true once DTLS shutdown is terminal for the embedder. - /// - /// This only becomes true after no application data can be sent and no - /// close-related packets or events remain to be drained through - /// [`poll_output`](Self::poll_output). In particular, DTLS 1.2 can enter - /// its internal closed state before the queued `close_notify` packet has - /// been polled out; this method remains false until that output is drained. - pub fn is_closed(&self) -> bool { - match self.inner.as_ref() { - Some(Inner::Client12(client)) => client.is_closed(), - Some(Inner::Server12(server)) => server.is_closed(), - None => false, - } - } - - /// Return true if the instance is operating in the client role. - pub fn is_active(&self) -> bool { - matches!(self.inner, Some(Inner::Client12(_))) - } - - /// Switch between server and client roles. - /// - /// Set `active` to true for client role, false for server role. - pub fn set_active(&mut self, active: bool) { - // unwrap is ok: the inner is only taken to convert it in place. - self.inner = Some(match (self.inner.take().unwrap(), active) { - (Inner::Client12(c), false) => Inner::Server12(c.into_server()), - (Inner::Server12(s), true) => Inner::Client12(s.into_client()), - (inner, _) => inner, - }); - } - - /// Process an incoming DTLS datagram. - /// - /// Refresh the logical clock with [`Self::handle_timeout`] before receiving - /// packets at a new instant, even if no advertised timer is due. A server's - /// overall handshake deadline starts at that time when the first structurally - /// valid ClientHello fragment is accepted. Later body validation failures do - /// not reset this peer's deadline. Unrelated input does not start the deadline. - /// Poll until [`Output::Timeout`] after each mutation. - pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { - match self.inner.as_mut().unwrap() { - Inner::Client12(client) => client.handle_packet(packet), - Inner::Server12(server) => server.handle_packet(packet), - } - } - - /// Poll for pending output from the DTLS engine. - /// - /// Emitting the first ClientHello fragment starts the client's handshake - /// deadline; queuing output or returning [`Output::BufferTooSmall`] does not. - /// Uses the logical time from [`Self::handle_timeout`]; refresh it first if - /// time has advanced. Caller-side transport delays are outside dimpl. - /// Continue polling until [`Output::Timeout`]. - pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { - match self.inner.as_mut().unwrap() { - Inner::Client12(client) => client.poll_output(buf), - Inner::Server12(server) => server.poll_output(buf), - } - } - - /// Handle time-based events such as retransmission timers. - /// - /// Advances the logical clock for subsequent operations, even when no timer - /// is due. Time alone does not start handshake or unsent-flight timers. - /// Supply monotonically increasing instants and poll until [`Output::Timeout`] - /// after each mutation. See [`ConfigBuilder::handshake_timeout`] for the - /// overall deadline and retry policy. - pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { - match self.inner.as_mut().unwrap() { - Inner::Client12(client) => client.handle_timeout(now), - Inner::Server12(server) => server.handle_timeout(now), - } - } - - /// Send application data over the established DTLS session. - /// - /// Returns the number of bytes accepted for buffering or transmission, not - /// delivery. Currently accepts the entire slice or none of it. - /// - /// Data sent before handshake completion is buffered internally and returns - /// `Ok(data.len())`. An empty slice returns `Ok(0)` on success; this does not - /// indicate handshake readiness. - pub fn send_application_data(&mut self, data: &[u8]) -> Result { - match self.inner.as_mut().unwrap() { - Inner::Client12(client) => client.send_application_data(data), - Inner::Server12(server) => server.send_application_data(data), - } - .map(|()| data.len()) - } - - /// Initiate graceful shutdown by sending a `close_notify` alert. - /// - /// **Connected** (`AwaitApplicationData`): queues a `close_notify` alert; - /// the next [`poll_output`](Self::poll_output) cycle yields it as - /// [`Output::Packet`]. - /// - /// **Handshake in progress**: aborts immediately without sending an - /// alert (no authenticated channel exists). Subsequent calls to - /// [`send_application_data`](Self::send_application_data) will return - /// an error. - /// - /// The alert is not retransmitted (per RFC 6347 §4.2.7). - pub fn close(&mut self) -> Result<(), Error> { - match self.inner.as_mut().unwrap() { - Inner::Client12(client) => client.close(), - Inner::Server12(server) => server.close(), - } - } -} - -impl fmt::Debug for Dtls { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let (role, state) = match &self.inner { - Some(Inner::Client12(c)) => ("Client12", c.state_name()), - Some(Inner::Server12(s)) => ("Server12", s.state_name()), - None => ("None", ""), - }; - f.debug_struct("Dtls") - .field("role", &role) - .field("state", &state) - .finish() - } -} - -/// Output events produced by the DTLS engine when polled. -#[non_exhaustive] -pub enum Output<'a> { - /// A DTLS record to transmit on the wire. - Packet(&'a [u8]), - /// The provided output buffer is too small for the next pending output. - /// - /// Retry [`Dtls::poll_output`] with a buffer of at least `needed` bytes. - /// The pending output is retained until it can be emitted. - BufferTooSmall { - /// Minimum buffer length required to emit the pending output. - needed: usize, - }, - /// Schedule a timer and call [`Dtls::handle_timeout`] at this instant. - /// - /// This is always the last variant returned by a poll cycle. - /// Internal state is only consistent after reaching `Timeout`. - Timeout(Instant), - /// The handshake completed and the connection is established. - Connected, - /// The peer's leaf certificate in DER encoding. - /// - /// Applications must validate this certificate independently (chain, - /// name/EKU checks, pinning, etc.). - PeerCert(&'a [u8]), - /// Extracted DTLS-SRTP keying material and selected SRTP profile. - KeyingMaterial(KeyingMaterial, SrtpProfile), - /// Received application data plaintext. - ApplicationData(&'a [u8]), - /// The peer sent a `close_notify` alert, indicating graceful connection closure. - CloseNotify, -} - -impl fmt::Debug for Output<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Packet(v) => write!(f, "Packet({})", v.len()), - Self::BufferTooSmall { needed } => write!(f, "BufferTooSmall({needed})"), - Self::Timeout(v) => write!(f, "Timeout({:?})", v), - Self::Connected => write!(f, "Connected"), - Self::PeerCert(v) => write!(f, "PeerCert({})", v.len()), - Self::KeyingMaterial(v, p) => write!(f, "KeyingMaterial({}, {:?})", v.len(), p), - Self::ApplicationData(v) => write!(f, "ApplicationData({})", v.len()), - Self::CloseNotify => write!(f, "CloseNotify"), - } - } -} - -#[cfg(test)] -mod test { - use std::panic::UnwindSafe; - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - use super::*; - - fn new_instance() -> Dtls { - let client_cert = generate_self_signed_certificate().expect("Failed to generate client cert"); - let config = Arc::new(Config::default()); - Dtls::new_12(config, client_cert, Instant::now()) - } - - fn new_instance_12_no_cookie() -> Dtls { - let cert = generate_self_signed_certificate().expect("Failed to generate cert"); - let config = Arc::new(Config::builder().use_server_cookie(false).build().expect("config")); - Dtls::new_12(config, cert, Instant::now()) - } - - #[test] - fn test_dtls_default() { - let mut dtls = new_instance(); - assert!(!dtls.is_active()); - dtls.set_active(true); - assert!(dtls.is_active()); - dtls.set_active(false); - } - - #[test] - fn is_send() { - fn is_send(_t: T) {} - fn is_sync(_t: T) {} - is_send(new_instance()); - is_sync(new_instance()); - } - - #[test] - fn is_unwind_safe() { - fn is_unwind_safe(_t: T) {} - is_unwind_safe(new_instance()); - } - - #[test] - fn test_protocol_version_12() { - let dtls = new_instance(); - assert_eq!(dtls.protocol_version(), Some(ProtocolVersion::DTLS1_2)); - } - - #[test] - #[should_panic(expected = "requires a PSK configuration")] - fn new_12_psk_panics_without_psk_config() { - let config = Arc::new(Config::default()); - let _ = Dtls::new_12_psk(config, Instant::now()); - } - - #[test] - #[should_panic(expected = "Server certificate cannot be empty")] - fn new_12_panics_on_empty_certificate() { - let cert = generate_self_signed_certificate().expect("Failed to generate cert"); - let config = Arc::new(Config::default()); - let empty = DtlsCertificate { - certificate: vec![], - private_key: cert.private_key, - }; - let _ = Dtls::new_12(config, empty, Instant::now()); - } - - fn make_record(content_type: u8, body: &[u8]) -> Vec { - let mut pkt = Vec::with_capacity(13 + body.len()); - pkt.push(content_type); - pkt.extend_from_slice(&[0xFE, 0xFD]); // version - pkt.extend_from_slice(&[0x00, 0x00]); // epoch - pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // seq - pkt.extend_from_slice(&(body.len() as u16).to_be_bytes()); - pkt.extend_from_slice(body); - pkt - } - - /// Build a handshake message: 12-byte header + body bytes. - fn make_handshake(msg_type: u8, length: u32, frag_off: u32, frag_len: u32, body: &[u8]) -> Vec { - let mut hs = Vec::with_capacity(12 + body.len()); - hs.push(msg_type); - hs.extend_from_slice(&length.to_be_bytes()[1..]); // 3-byte length - hs.extend_from_slice(&[0x00, 0x00]); // message_seq - hs.extend_from_slice(&frag_off.to_be_bytes()[1..]); // 3-byte fragment_offset - hs.extend_from_slice(&frag_len.to_be_bytes()[1..]); // 3-byte fragment_length - hs.extend_from_slice(body); - hs - } - - fn dtls12_ch_body_with_extensions(extensions: &[u8]) -> Vec { - let mut body = Vec::new(); - body.extend_from_slice(&[0xFE, 0xFD]); // client_version - body.extend_from_slice(&[0u8; 32]); // random - body.push(0); // session_id length - body.push(0); // cookie length - body.extend_from_slice(&[0x00, 0x02]); // cipher_suites length - body.extend_from_slice(&[0xC0, 0x2B]); // ECDHE_ECDSA_AES128_GCM_SHA256 - body.push(1); // compression_methods length - body.push(0); // null compression - body.extend_from_slice(&(extensions.len() as u16).to_be_bytes()); - body.extend_from_slice(extensions); - body - } - - #[test] - fn dtls12_server_discards_oversized_ec_point_formats_extension() { - let mut extensions = Vec::new(); - extensions.extend_from_slice(&[0x00, 0x0B]); // ec_point_formats - extensions.extend_from_slice(&[0x00, 0x05]); // extension body length - extensions.extend_from_slice(&[ - 0x04, // Four point formats. - 0x00, // Uncompressed. - 0x00, // Uncompressed. - 0x00, // Uncompressed. - 0x00, // Uncompressed. - ]); - extensions.extend_from_slice(&[0x00, 0x17]); // extended_master_secret - extensions.extend_from_slice(&[0x00, 0x00]); // empty extension body - - let body = dtls12_ch_body_with_extensions(&extensions); - let len = body.len() as u32; - let hs = make_handshake(0x01, len, 0, len, &body); - let pkt = make_record(0x16, &hs); - - let mut dtls = new_instance_12_no_cookie(); - dtls.handle_packet(&pkt) - .expect("malformed extension should be discarded"); - } - - #[test] - fn dtls12_server_discards_trailing_ec_point_formats_extension() { - let mut extensions = Vec::new(); - extensions.extend_from_slice(&[0x00, 0x0B]); // ec_point_formats - extensions.extend_from_slice(&[0x00, 0x03]); // extension body length - extensions.extend_from_slice(&[ - 0x01, // One point format. - 0x00, // Uncompressed. - 0xFF, // Trailing extension body byte beyond the inner vector. - ]); - extensions.extend_from_slice(&[0x00, 0x17]); // extended_master_secret - extensions.extend_from_slice(&[0x00, 0x00]); // empty extension body - - let body = dtls12_ch_body_with_extensions(&extensions); - let len = body.len() as u32; - let hs = make_handshake(0x01, len, 0, len, &body); - let pkt = make_record(0x16, &hs); - - let mut dtls = new_instance_12_no_cookie(); - dtls.handle_packet(&pkt) - .expect("malformed extension should be discarded"); - } - - #[test] - fn dtls12_server_accepts_unknown_ec_point_formats_extension() { - let mut extensions = Vec::new(); - extensions.extend_from_slice(&[0x00, 0x0B]); // ec_point_formats - extensions.extend_from_slice(&[0x00, 0x04]); // extension body length - extensions.extend_from_slice(&[ - 0x03, // Three point formats. - 0x02, // ANSI X9.62 compressed char2. - 0x00, // Uncompressed. - 0xFF, // Unknown/private point format. - ]); - extensions.extend_from_slice(&[0x00, 0x17]); // extended_master_secret - extensions.extend_from_slice(&[0x00, 0x00]); // empty extension body - - let body = dtls12_ch_body_with_extensions(&extensions); - let len = body.len() as u32; - let hs = make_handshake(0x01, len, 0, len, &body); - let pkt = make_record(0x16, &hs); - - let mut dtls = new_instance_12_no_cookie(); - dtls.handle_timeout(Instant::now()).unwrap(); - dtls.handle_packet(&pkt) - .expect("unknown ec_point_formats values should not fail server-side parsing"); - } -} - -#[cfg(test)] -mod tests; diff --git a/rs/moq-webrtc/src/vendor/dimpl/rng.rs b/rs/moq-webrtc/src/vendor/dimpl/rng.rs deleted file mode 100644 index e9b8443d2e5..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/rng.rs +++ /dev/null @@ -1,95 +0,0 @@ -//! Seedable random number generator for deterministic testing. -//! -//! When a seed is provided via [`Config::rng_seed`], all non-cryptographic -//! randomness will be deterministic. This is useful for testing and debugging. - -use rand::distr::{Distribution, StandardUniform}; -use rand::rngs::StdRng; -use rand::{RngExt, SeedableRng}; - -/// A random number generator that can be seeded for deterministic behavior. -/// -/// When created with a seed, it produces deterministic random values. -/// When created without a seed, it uses the thread-local random generator. -pub struct SeededRng { - inner: Option, -} - -impl SeededRng { - /// Create a new RNG with an optional seed. - /// - /// If `seed` is `Some`, the RNG will produce deterministic values. - /// If `seed` is `None`, it will use the thread-local random generator. - pub fn new(seed: Option) -> Self { - let inner = seed.map(StdRng::seed_from_u64); - Self { inner } - } - - /// Generate a random value of type T. - pub fn random(&mut self) -> T - where - StandardUniform: Distribution, - { - match self.inner.as_mut() { - Some(rng) => rng.random(), - None => rand::random(), - } - } -} - -impl std::fmt::Debug for SeededRng { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let is_seeded = self.inner.is_some(); - f.debug_struct("SeededRng").field("seeded", &is_seeded).finish() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn seeded_rng_is_deterministic() { - let mut rng1 = SeededRng::new(Some(12345)); - let mut rng2 = SeededRng::new(Some(12345)); - - let values1: [u8; 10] = [ - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - rng1.random(), - ]; - - let values2: [u8; 10] = [ - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - rng2.random(), - ]; - - assert_eq!(values1, values2, "Same seed should produce same values"); - } - - #[test] - fn different_seeds_produce_different_values() { - let mut rng1 = SeededRng::new(Some(12345)); - let mut rng2 = SeededRng::new(Some(54321)); - - let value1: u64 = rng1.random(); - let value2: u64 = rng2.random(); - - assert_ne!(value1, value2, "Different seeds should produce different values"); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/client_hello_recovery.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/client_hello_recovery.rs deleted file mode 100644 index fb15c32a3c9..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/client_hello_recovery.rs +++ /dev/null @@ -1,120 +0,0 @@ -use std::collections::VecDeque; -use std::sync::Arc; -use std::time::Instant; - -use crate::vendor::dimpl::certificate::generate_self_signed_certificate; -use crate::vendor::dimpl::{Config, Dtls}; - -use super::dtls12::common; -use common::drain_outputs; - -#[test] -fn corrected_client_hello_completes_after_malformed_extension() { - assert_client_hello_recovery(false); -} - -#[test] -fn corrected_client_hello_completes_after_malformed_extension_with_cookie() { - assert_client_hello_recovery(true); -} - -fn assert_client_hello_recovery(use_cookie: bool) { - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new(Config::builder().use_server_cookie(use_cookie).build().expect("config")); - { - for kind in [10u16, 13, 14] { - for fragmented in [false, true] { - let now = Instant::now(); - let mut client = Dtls::new_12(config.clone(), certificate.clone(), now); - let mut server = Dtls::new_12(config.clone(), certificate.clone(), now); - client.set_active(true); - client.handle_timeout(now).expect("client clock"); - let mut hello = drain_outputs(&mut client).packets; - assert_eq!(hello.len(), 1); - server.handle_timeout(now).expect("server clock"); - drain_outputs(&mut server); - if use_cookie { - let mut challenge = Vec::new(); - for packet in &hello { - server.handle_packet(packet).expect("initial hello"); - challenge.extend(drain_outputs(&mut server).packets); - } - assert!(!challenge.is_empty(), "server cookie challenge"); - hello.clear(); - for packet in challenge { - client.handle_packet(&packet).expect("cookie challenge"); - hello.extend(drain_outputs(&mut client).packets); - } - assert_eq!(hello.len(), 1, "second ClientHello"); - // The legacy cookie follows the session id. - let cookie_start = 60 + hello[0][59] as usize; - assert!( - hello[0][cookie_start] != 0, - "second ClientHello must include the cookie" - ); - } - let mut malformed = hello[0].clone(); - let start = extension_start(&malformed, kind).expect("required test extension"); - malformed[start] = 0xff; - let chunk = if fragmented { - (malformed.len() - 25).div_ceil(2) - } else { - malformed.len() - 25 - }; - for (index, body) in malformed[25..].chunks(chunk).enumerate() { - let mut fragment = malformed[..25].to_vec(); - fragment.extend_from_slice(body); - fragment[5..11].copy_from_slice(&(index as u64).to_be_bytes()[2..]); - fragment[11..13].copy_from_slice(&((12 + body.len()) as u16).to_be_bytes()); - fragment[19..22].copy_from_slice(&((index * chunk) as u32).to_be_bytes()[1..]); - fragment[22..25].copy_from_slice(&(body.len() as u32).to_be_bytes()[1..]); - server.handle_packet(&fragment).expect("discard malformed hello"); - assert!( - drain_outputs(&mut server).packets.is_empty(), - "extension {kind}, fragmented={fragmented}, cookie={use_cookie}" - ); - } - server.handle_packet(&hello[0]).expect("corrected hello"); - let mut connected = [false; 2]; - let mut pending = VecDeque::new(); - let output = drain_outputs(&mut server); - connected[1] |= output.connected; - pending.extend(output.packets.into_iter().map(|packet| (0, packet))); - for _ in 0..100 { - let Some((recipient, packet)) = pending.pop_front() else { - break; - }; - let target = if recipient == 0 { &mut client } else { &mut server }; - target.handle_packet(&packet).expect("handshake packet"); - let output = drain_outputs(target); - connected[recipient] |= output.connected; - pending.extend(output.packets.into_iter().map(|packet| (1 - recipient, packet))); - } - assert_eq!( - connected, - [true, true], - "extension {kind}, fragmented={fragmented}, cookie={use_cookie}" - ); - } - } - } -} - -fn extension_start(hello: &[u8], kind: u16) -> Option { - // Record (13), handshake (12), version (2), random (32). - let mut cursor = 59; - cursor += 1 + hello[cursor] as usize; // session id - cursor += 1 + hello[cursor] as usize; // cookie - cursor += 2 + u16::from_be_bytes([hello[cursor], hello[cursor + 1]]) as usize; - cursor += 1 + hello[cursor] as usize; // compression - cursor += 2; // extensions length - while cursor < hello.len() { - let extension = u16::from_be_bytes([hello[cursor], hello[cursor + 1]]); - let len = u16::from_be_bytes([hello[cursor + 2], hello[cursor + 3]]) as usize; - if extension == kind { - return Some(cursor + 4); - } - cursor += 4 + len; - } - None -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/common.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/common.rs deleted file mode 100644 index 9a5cbbd0dd6..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/common.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Shared helpers for DTLS 1.2 integration tests. - -#![allow(unused)] - -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::{Config, Dtls, Output, SrtpProfile}; - -/// Parsed DTLS 1.2 record header. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct RecHdr { - pub ctype: u8, - pub epoch: u16, - pub seq: u64, -} - -/// Handshake message types (RFC 5246 / 6347). -pub const CLIENT_HELLO: u8 = 1; -pub const SERVER_HELLO: u8 = 2; -pub const HELLO_VERIFY_REQUEST: u8 = 3; -pub const CERTIFICATE: u8 = 11; -pub const SERVER_HELLO_DONE: u8 = 14; - -/// Parse DTLS 1.2 record headers from a datagram. -pub fn parse_records(datagram: &[u8]) -> Vec { - let mut out = Vec::new(); - let mut i = 0usize; - while i + 13 <= datagram.len() { - let ctype = datagram[i]; - let epoch = u16::from_be_bytes([datagram[i + 3], datagram[i + 4]]); - let seq_bytes = [ - 0u8, - 0u8, - datagram[i + 5], - datagram[i + 6], - datagram[i + 7], - datagram[i + 8], - datagram[i + 9], - datagram[i + 10], - ]; - let seq = u64::from_be_bytes(seq_bytes); - let len = u16::from_be_bytes([datagram[i + 11], datagram[i + 12]]) as usize; - out.push(RecHdr { ctype, epoch, seq }); - i += 13 + len; - } - out -} - -/// Collect record headers from a slice of datagrams. -pub fn collect_headers(datagrams: &[Vec]) -> Vec { - datagrams.iter().flat_map(|d| parse_records(d)).collect() -} - -/// Parse handshake message types from a datagram (content_type=22). -pub fn parse_handshake_types(datagram: &[u8]) -> Vec { - let mut out = Vec::new(); - let mut i = 0usize; - while i + 13 <= datagram.len() { - let ctype = datagram[i]; - let len = u16::from_be_bytes([datagram[i + 11], datagram[i + 12]]) as usize; - - // Only parse handshake records (content_type=22) - if ctype == 22 && i + 14 <= datagram.len() { - // Handshake message type is first byte of payload - let hs_type = datagram[i + 13]; - out.push(hs_type); - } - i += 13 + len; - } - out -} - -/// Assert that retransmitted records have the same epochs but increased sequence numbers. -pub fn assert_epochs_and_seq_increased(init: &[RecHdr], resend: &[RecHdr]) { - assert_eq!( - init.len(), - resend.len(), - "record count must match between initial and resend" - ); - for (a, b) in init.iter().zip(resend.iter()) { - assert_eq!(a.epoch, b.epoch, "epoch must match for the same record on resend"); - assert!(b.seq > a.seq, "sequence must increase on resend: {:?} -> {:?}", a, b); - } -} - -/// Poll until `Timeout`, collecting only packets. -pub fn collect_packets(endpoint: &mut Dtls) -> Vec> { - let mut out = Vec::new(); - let mut buf = vec![0u8; 2048]; - loop { - match endpoint.poll_output(&mut buf) { - Output::Packet(p) => out.push(p.to_vec()), - Output::Timeout(_) => break, - _ => {} - } - } - out -} - -/// Collected outputs from polling an endpoint to `Timeout`. -#[derive(Default, Debug)] -pub struct DrainedOutputs { - pub packets: Vec>, - pub connected: bool, - pub peer_cert: Option>, - pub keying_material: Option<(Vec, SrtpProfile)>, - pub app_data: Vec>, - pub timeout: Option, - pub close_notify: bool, -} - -/// Poll until `Timeout`, collecting everything. -pub fn drain_outputs(endpoint: &mut Dtls) -> DrainedOutputs { - let mut result = DrainedOutputs::default(); - let mut buf = vec![0u8; 2048]; - loop { - match endpoint.poll_output(&mut buf) { - Output::Packet(p) => result.packets.push(p.to_vec()), - Output::Connected => result.connected = true, - Output::PeerCert(cert) => result.peer_cert = Some(cert.to_vec()), - Output::KeyingMaterial(km, profile) => { - result.keying_material = Some((km.to_vec(), profile)); - } - Output::ApplicationData(data) => result.app_data.push(data.to_vec()), - Output::CloseNotify => result.close_notify = true, - Output::Timeout(t) => { - result.timeout = Some(t); - break; - } - _ => {} - } - } - result -} - -/// Deliver a slice of packets to a destination endpoint. -pub fn deliver_packets(packets: &[Vec], dest: &mut Dtls) { - for p in packets { - // Ignore errors - they may be expected for duplicates/replays - let _ = dest.handle_packet(p); - } -} - -/// Trigger a timeout by advancing time 2 seconds. -pub fn trigger_timeout(ep: &mut Dtls, now: &mut Instant) { - *now += Duration::from_secs(2); - ep.handle_timeout(*now).expect("handle_timeout"); -} - -/// Create a DTLS 1.2 config with default settings. -pub fn dtls12_config() -> Arc { - Arc::new(Config::default()) -} - -/// Create a DTLS 1.2 config with custom MTU. -pub fn dtls12_config_with_mtu(mtu: usize) -> Arc { - Arc::new(Config::builder().mtu(mtu).build().expect("Failed to build config")) -} - -/// Complete a full DTLS 1.2 handshake between client and server. -/// -/// Returns the final `Instant` (time advanced during the handshake). -/// Panics if the handshake does not complete within the iteration limit. -pub fn complete_dtls12_handshake(client: &mut Dtls, server: &mut Dtls, mut now: Instant) -> Instant { - let mut client_connected = false; - let mut server_connected = false; - - for i in 0..60 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(client); - let server_out = drain_outputs(server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, server); - deliver_packets(&server_out.packets, client); - - if client_connected && server_connected { - return now; - } - - // Trigger retransmissions periodically - if i % 5 == 4 { - now += Duration::from_secs(2); - } else { - now += Duration::from_millis(50); - } - } - - panic!("DTLS 1.2 handshake did not complete within iteration limit"); -} - -/// Create a connected DTLS 1.2 client/server pair with self-signed certificates. -/// -/// Returns `(client, server, now)` with the handshake already completed. -pub fn setup_connected_12_pair(now: Instant) -> (Dtls, Dtls, Instant) { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = dtls12_config(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let now = complete_dtls12_handshake(&mut client, &mut server, now); - (client, server, now) -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/data.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/data.rs deleted file mode 100644 index 137be99a7d8..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/data.rs +++ /dev/null @@ -1,405 +0,0 @@ -//! DTLS 1.2 application data tests. - -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::Dtls; - -use crate::vendor::dimpl::tests::dtls12::common::*; - -#[test] -fn dtls12_application_data_exchange() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let client_data = b"hello"; - let server_data = b"world"; - - let mut client_connected = false; - let mut server_connected = false; - let mut client_received: Vec = Vec::new(); - let mut server_received: Vec = Vec::new(); - let mut client_sent = false; - let mut server_sent = false; - - for _ in 0..50 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - // Collect received app data - for data in &client_out.app_data { - client_received.extend_from_slice(data); - } - for data in &server_out.app_data { - server_received.extend_from_slice(data); - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - // Send data once connected - if client_connected && !client_sent { - client.send_application_data(client_data).expect("client send"); - client_sent = true; - } - if server_connected && !server_sent { - server.send_application_data(server_data).expect("server send"); - server_sent = true; - } - - if !client_received.is_empty() && !server_received.is_empty() { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - assert_eq!(server_received, client_data, "Server should receive client's data"); - assert_eq!(client_received, server_data, "Client should receive server's data"); -} - -#[test] -fn dtls12_multiple_application_data_messages() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // First complete handshake - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..50 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - - // Now send 5 distinct messages - let messages = vec![ - b"Message 1".to_vec(), - b"Message 2".to_vec(), - b"Message 3 is a bit longer".to_vec(), - b"Message 4".to_vec(), - b"Message 5 - the final one".to_vec(), - ]; - - for msg in &messages { - client.send_application_data(msg).expect("client send"); - } - - let mut server_received: Vec> = Vec::new(); - - for _ in 0..20 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - deliver_packets(&client_out.packets, &mut server); - - let server_out = drain_outputs(&mut server); - for data in server_out.app_data { - server_received.push(data); - } - - if server_received.len() >= messages.len() { - break; - } - - now += Duration::from_millis(10); - } - - // Flatten and compare to verify all messages received in order - let expected: Vec = messages.iter().flatten().copied().collect(); - let received: Vec = server_received.iter().flatten().copied().collect(); - - assert_eq!(received, expected, "All 5 messages should be received in order"); -} - -#[test] -fn dtls12_bidirectional_data_exchange() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Complete handshake - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..50 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - - // Exchange data in both directions simultaneously for 10 rounds - let rounds = 10; - let mut client_received_count = 0; - let mut server_received_count = 0; - - for i in 0..rounds { - let client_msg = format!("Client message {}", i); - let server_msg = format!("Server message {}", i); - - client - .send_application_data(client_msg.as_bytes()) - .expect("client send"); - server - .send_application_data(server_msg.as_bytes()) - .expect("server send"); - - for _ in 0..10 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_received_count += client_out.app_data.len(); - server_received_count += server_out.app_data.len(); - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - now += Duration::from_millis(5); - } - } - - assert_eq!( - client_received_count, rounds, - "Client should receive all {} server messages", - rounds - ); - assert_eq!( - server_received_count, rounds, - "Server should receive all {} client messages", - rounds - ); -} - -#[test] -fn dtls12_many_small_messages() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Complete handshake - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..50 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - - // Send 100 small messages from client to server. - // Drain and deliver after each send to respect the Sans-IO poll-to-timeout - // contract and the transmit queue capacity. - let message_count = 100usize; - let mut received_count = 0usize; - - for i in 0..message_count { - let msg = format!("M{}", i); - client.send_application_data(msg.as_bytes()).expect("send"); - - let client_pkts = collect_packets(&mut client); - deliver_packets(&client_pkts, &mut server); - - let server_out = drain_outputs(&mut server); - for data in &server_out.app_data { - assert_eq!(data, msg.as_bytes(), "message {} should match", i); - received_count += 1; - } - } - - assert_eq!( - received_count, message_count, - "All 100 small messages should be received" - ); -} - -#[test] -fn dtls12_large_application_data() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Complete handshake - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..50 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - - // Send data larger than default MTU (1150 bytes) - let large_data: Vec = (0..2000).map(|i| (i % 256) as u8).collect(); - - client - .send_application_data(&large_data) - .expect("client send large data"); - - let mut server_received: Vec = Vec::new(); - - for _ in 0..50 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - deliver_packets(&client_out.packets, &mut server); - - let server_out = drain_outputs(&mut server); - for data in server_out.app_data { - server_received.extend_from_slice(&data); - } - - if server_received.len() >= large_data.len() { - break; - } - - now += Duration::from_millis(10); - } - - assert_eq!( - server_received, large_data, - "Server should receive the full 2000-byte payload intact" - ); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/edge.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/edge.rs deleted file mode 100644 index 05cef985241..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/edge.rs +++ /dev/null @@ -1,1088 +0,0 @@ -//! DTLS 1.2 edge case and error recovery tests. - -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::certificate::generate_self_signed_certificate; -use crate::vendor::dimpl::crypto::Dtls12CipherSuite; -use crate::vendor::dimpl::{Config, Dtls, Output}; - -use crate::vendor::dimpl::tests::dtls12::common::*; - -fn dtls12_alert_record(seq: u64, level: u8, description: u8) -> Vec { - let mut out = Vec::new(); - out.push(21); // Alert - out.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 - out.extend_from_slice(&0u16.to_be_bytes()); // epoch 0 - out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number - out.extend_from_slice(&2u16.to_be_bytes()); // alert payload length - out.extend_from_slice(&[level, description]); - out -} - -fn dtls12_epoch1_record(seq: u64, len: usize) -> Vec { - let mut out = Vec::with_capacity(13 + len); - out.push(23); // ApplicationData - out.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 - out.extend_from_slice(&1u16.to_be_bytes()); // epoch 1 - out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number - out.extend_from_slice(&(len as u16).to_be_bytes()); - out.resize(13 + len, 0); - out -} - -#[test] -fn oversized_application_data_reports_buffer_too_small() { - let now = Instant::now(); - let (mut client, mut server, _now) = setup_connected_12_pair(now); - let payload = vec![0x5a; 4000]; - - client.send_application_data(&payload).expect("send application data"); - - let mut large_buf = vec![0u8; 8192]; - let mut packets = Vec::new(); - loop { - match client.poll_output(&mut large_buf) { - Output::Packet(packet) => packets.push(packet.to_vec()), - Output::Timeout(_) => break, - _ => {} - } - } - - deliver_packets(&packets, &mut server); - - let mut small_buf = vec![0u8; 2048]; - match server.poll_output(&mut small_buf) { - Output::BufferTooSmall { needed } => assert_eq!(needed, payload.len()), - output => panic!("expected BufferTooSmall, got {output:?}"), - } - - match server.poll_output(&mut large_buf) { - Output::ApplicationData(data) => assert_eq!(data, payload.as_slice()), - output => panic!("expected retained application data, got {output:?}"), - } -} - -fn dtls12_config_for_suite(suite: Dtls12CipherSuite) -> Arc { - let mut provider = Config::default().crypto_provider().clone(); - let selected = provider - .cipher_suites - .iter() - .copied() - .find(|cs| cs.suite() == suite) - .unwrap_or_else(|| panic!("suite {:?} not found in provider", suite)); - - let suites = Box::leak(Box::new([selected])); - provider.cipher_suites = suites; - - Arc::new( - Config::builder() - .with_crypto_provider(provider) - .build() - .expect("build config for single suite"), - ) -} - -fn dtls12_min_protected_fragment_len(suite: Dtls12CipherSuite) -> usize { - match suite { - Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 => 24, - Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => 16, - Dtls12CipherSuite::PSK_AES128_CCM_8 => 16, - _ => panic!("unknown cipher suite"), - } -} - -#[test] -fn dtls12_malformed_datagram_is_discarded_without_processing_alerts() { - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = dtls12_config(); - let now = Instant::now(); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut packet = dtls12_alert_record(1, 2, 40); - packet.push(0xFF); // trailing truncated record header - - server - .handle_packet(&packet) - .expect("malformed datagram should be discarded"); - - let mut buf = [0; 1500]; - assert!(!matches!(server.poll_output(&mut buf), Output::CloseNotify)); -} - -#[test] -fn dtls12_too_many_control_records_are_discarded() { - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = dtls12_config(); - let now = Instant::now(); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut packet = Vec::new(); - for seq in 1..=9 { - packet.extend_from_slice(&dtls12_alert_record(seq, 1, 0)); - } - - server - .handle_packet(&packet) - .expect("too many records should be discarded"); -} - -#[test] -fn dtls12_recovers_from_corrupted_packet() { - //! During handshake, corrupt 2 bytes in one packet before delivery so the - //! DTLS record header is invalid. The receiver drops the corrupted packet. - //! After a timeout the sender retransmits, and the handshake completes - //! normally via the retransmission path. - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // FLIGHT 1: Client sends ClientHello - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let f1 = collect_packets(&mut client); - assert!(!f1.is_empty(), "client should emit ClientHello"); - - // Corrupt the record header itself (version field at bytes 1-2) so - // the record is rejected at parse time and nothing enters queue_rx. - for mut p in f1 { - if p.len() > 5 { - p[1] ^= 0xFF; - p[2] ^= 0xFF; - } - // Server should reject the record due to invalid version - let _ = server.handle_packet(&p); - } - - // Server has no valid packet yet - arm its timers so it's ready - server.handle_timeout(now).expect("server arm"); - let s_pkts = collect_packets(&mut server); - assert!(s_pkts.is_empty(), "server should have nothing to send yet"); - - // Trigger client retransmission timeout (initial RTO is ~1s) - trigger_timeout(&mut client, &mut now); - let f1_resend = collect_packets(&mut client); - assert!( - !f1_resend.is_empty(), - "client should retransmit ClientHello after timeout" - ); - - // Deliver the clean retransmission to server - for p in &f1_resend { - server.handle_packet(p).expect("server recv clean CH"); - } - - // FLIGHT 2: Server sends HelloVerifyRequest - server.handle_timeout(now).expect("server arm flight 2"); - let f2 = collect_packets(&mut server); - assert!(!f2.is_empty(), "server should emit HelloVerifyRequest"); - for p in &f2 { - client.handle_packet(p).expect("client recv HVR"); - } - - // FLIGHT 3: Client sends ClientHello with cookie - client.handle_timeout(now).expect("client arm flight 3"); - let f3 = collect_packets(&mut client); - assert!(!f3.is_empty(), "client should emit ClientHello with cookie"); - for p in &f3 { - server.handle_packet(p).expect("server recv CH+cookie"); - } - - // FLIGHT 4: Server sends ServerHello, Certificate, etc. - server.handle_timeout(now).expect("server arm flight 4"); - let f4 = collect_packets(&mut server); - assert!(!f4.is_empty(), "server should emit ServerHello flight"); - for p in &f4 { - client.handle_packet(p).expect("client recv flight 4"); - } - - // FLIGHT 5: Client sends CKX, CCS, Finished - client.handle_timeout(now).expect("client arm flight 5"); - let f5 = collect_packets(&mut client); - assert!(!f5.is_empty(), "client should emit flight 5"); - for p in &f5 { - server.handle_packet(p).expect("server recv flight 5"); - } - - // FLIGHT 6: Server sends CCS, Finished (Connected may be emitted here) - server.handle_timeout(now).expect("server arm flight 6"); - let server_out = drain_outputs(&mut server); - assert!(!server_out.packets.is_empty(), "server should emit flight 6"); - for p in &server_out.packets { - client.handle_packet(p).expect("client recv flight 6"); - } - - // Drain client outputs to check for Connected event - client.handle_timeout(now).expect("client final timeout"); - let client_out = drain_outputs(&mut client); - - assert!( - client_out.connected, - "Client should be connected after recovering from corrupted packet" - ); - assert!( - server_out.connected, - "Server should be connected after recovering from corrupted packet" - ); -} - -#[test] -fn dtls12_discards_wrong_epoch_record() { - //! After a completed handshake (epoch 1), inject a crafted packet with - //! epoch 0 and content_type handshake (22). Verify it is silently dropped - //! and application data exchange still works. - - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - // Craft a DTLS 1.2 record with epoch 0 (pre-handshake) and content_type 22 (handshake). - // DTLS 1.2 record header: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) - let bogus = vec![ - 22, // content_type: handshake - 0xFE, 0xFD, // version: DTLS 1.2 - 0x00, 0x00, // epoch: 0 (wrong - should be 1 post-handshake) - 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, // sequence number - 0x00, 0x05, // length: 5 - 0x01, // handshake type: ClientHello - 0x00, 0x00, 0x00, 0x00, // dummy payload - ]; - - // Should be silently discarded (no error) - client - .handle_packet(&bogus) - .expect("wrong epoch record should be silently discarded"); - - // Verify application data exchange still works after the bogus packet. - client.send_application_data(b"ping").expect("client send app data"); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - deliver_packets(&client_out.packets, &mut server); - - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - assert!( - server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), - "Server should receive application data after wrong-epoch bogus packet" - ); -} - -#[test] -fn dtls12_short_encrypted_records_do_not_panic() { - for suite in [ - Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, - Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, - ] { - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = dtls12_config_for_suite(suite); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - now = complete_dtls12_handshake(&mut client, &mut server, now); - - for len in 0..dtls12_min_protected_fragment_len(suite) { - let short = dtls12_epoch1_record(0x100 + len as u64, len); - client - .handle_packet(&short) - .expect("short encrypted record should be silently discarded"); - } - - server - .send_application_data(b"still alive") - .expect("server send app data"); - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - deliver_packets(&server_out.packets, &mut client); - - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!( - client_out.app_data.iter().any(|d| d.as_slice() == b"still alive"), - "client should receive application data after short encrypted {suite:?} records" - ); - } -} - -#[test] -fn dtls12_discards_truncated_record() { - //! Deliver a 3-byte packet (too short to be a valid DTLS 1.2 record header, - //! which requires 13 bytes). Verify it is silently dropped and the - //! handshake/connection continues. - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Inject a truncated packet before the handshake begins - let truncated = vec![0x16, 0xFE, 0xFD]; // 3 bytes - too short for any DTLS record - let result = client.handle_packet(&truncated); - // Should either return Ok (silently discarded) or a non-fatal error - match result { - Ok(()) => {} // silently discarded - expected - Err(e) => { - // Some parse errors are acceptable as long as the endpoint survives - eprintln!("Truncated packet returned error (non-fatal): {}", e); - } - } - - // Now complete the handshake to prove the endpoint is still functional - now = complete_dtls12_handshake(&mut client, &mut server, now); - - // Also inject a truncated packet after the handshake and verify app data works - let truncated_post = vec![0x17, 0xFE, 0xFD]; // 3 bytes, content_type = app data - let result = client.handle_packet(&truncated_post); - match result { - Ok(()) => {} - Err(e) => { - eprintln!("Post-handshake truncated packet returned error (non-fatal): {}", e); - } - } - - // Verify application data exchange still works - client.send_application_data(b"hello").expect("client send app data"); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - deliver_packets(&client_out.packets, &mut server); - - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - assert!( - server_out.app_data.iter().any(|d| d.as_slice() == b"hello"), - "Server should receive application data after truncated bogus packets" - ); -} - -#[test] -fn dtls12_discards_unauthenticated_close_notify() { - //! After a completed handshake (epoch 1), inject a plaintext close_notify - //! alert at epoch 0. Since the connection is authenticated, the - //! unauthenticated alert must be silently discarded and the connection - //! must remain operational. - - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - // Craft a close_notify alert record at epoch 0 (plaintext alert). - // Since DTLS 1.2 post-handshake records should be at epoch 1 and encrypted, - // an epoch 0 plaintext alert should be silently discarded. - let close_notify_epoch0 = vec![ - 21, // content_type: alert - 0xFE, 0xFD, // version: DTLS 1.2 - 0x00, 0x00, // epoch: 0 (plaintext - will be discarded post-handshake) - 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, // sequence number - 0x00, 0x02, // length: 2 - 0x01, // level: warning - 0x00, // description: close_notify - ]; - - // Epoch 0 alert post-handshake must be silently discarded (not an error). - server - .handle_packet(&close_notify_epoch0) - .expect("epoch 0 alert must be silently discarded post-handshake"); - - // Verify the server can still process data after the alert - client - .send_application_data(b"after-alert") - .expect("client send after alert"); - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - deliver_packets(&client_out.packets, &mut server); - - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - assert!( - server_out.app_data.iter().any(|d| d.as_slice() == b"after-alert"), - "Server should still receive app data after close_notify alert at epoch 0" - ); -} - -#[test] -fn dtls12_rejects_renegotiation() { - //! After a completed handshake, inject a ClientHello record to simulate - //! a renegotiation attempt. Verify it is rejected (either silently dropped - //! or returns `Error::RenegotiationAttempt`). - - let now = Instant::now(); - let (_client, mut server, _now) = setup_connected_12_pair(now); - - // Craft a ClientHello record at epoch 0 to simulate a renegotiation attempt. - // This is a plaintext handshake record with a minimal ClientHello. - let renegotiation_hello = vec![ - 22, // content_type: handshake - 0xFE, 0xFD, // version: DTLS 1.2 - 0x00, 0x00, // epoch: 0 - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // sequence number - 0x00, 0x2F, // length: 47 bytes of handshake payload - // Handshake header - 0x01, // msg_type: ClientHello - 0x00, 0x00, 0x23, // length: 35 - 0x00, 0x01, // message_seq: 1 - 0x00, 0x00, 0x00, // fragment_offset: 0 - 0x00, 0x00, 0x23, // fragment_length: 35 - // ClientHello body - 0xFE, 0xFD, // client_version: DTLS 1.2 - // random (32 bytes) - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, - 0x00, // session_id length: 0 - 0x00, // cookie length: 0 - 0x00, // cipher_suites length will make this invalid, but that's fine - ]; - - // The server should reject the renegotiation attempt. - // It may return an error or silently discard it. - let result = server.handle_packet(&renegotiation_hello); - match result { - Ok(()) => { - // Silently discarded - acceptable (epoch 0 record post-handshake) - } - Err(e) => { - // RenegotiationAttempt or other error - also acceptable - eprintln!("Renegotiation attempt correctly rejected with error: {}", e); - } - } - - // Verify the connection still works after the renegotiation attempt - we need - // a client to send data, so re-create using the existing pair's server. - // Since _client was moved, just verify server can still queue data. - let result = server.send_application_data(b"post-reneg"); - assert!( - result.is_ok(), - "Server should still accept sends after renegotiation attempt was rejected" - ); -} - -#[test] -fn dtls12_mixed_datagram_plaintext_first_then_valid() { - //! Test that a UDP datagram with bogus plaintext ApplicationData FIRST - //! followed by a valid encrypted record is handled correctly: the bogus - //! record is silently discarded and the valid one is still processed. - - let now = Instant::now(); - let (mut client, mut server, now) = setup_connected_12_pair(now); - - // Send valid application data from client and capture the encrypted packet. - client.send_application_data(b"valid-data").expect("send valid data"); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "Should have valid packet"); - let valid_packet = &client_out.packets[0]; - - // Craft a plaintext ApplicationData record (epoch 0). - let bogus_record = vec![ - 0x17, // content_type: ApplicationData - 0xFE, 0xFD, // version: DTLS 1.2 - 0x00, 0x00, // epoch: 0 (plaintext) - 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, // sequence_number - 0x00, 0x06, // length: 6 - 0x62, 0x6F, 0x67, 0x75, 0x73, 0x21, // "bogus!" - ]; - - // Construct a mixed datagram: bogus plaintext record FIRST, then valid record. - let mut mixed_datagram = bogus_record; - mixed_datagram.extend_from_slice(valid_packet); - - // Deliver the mixed datagram to server. - server - .handle_packet(&mixed_datagram) - .expect("mixed datagram should not error"); - - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - - // The valid record should still be processed despite the bogus first record. - assert!( - server_out.app_data.iter().any(|d| d.as_slice() == b"valid-data"), - "Server should receive the valid encrypted ApplicationData even when bogus record comes first" - ); - - // The bogus plaintext record should NOT produce any output. - assert_eq!( - server_out.app_data.len(), - 1, - "Should receive exactly 1 app data (the valid one), not the bogus plaintext" - ); - assert!( - !server_out.app_data.iter().any(|d| d.as_slice() == b"bogus!"), - "Bogus plaintext ApplicationData must not be delivered" - ); -} - -#[test] -fn dtls12_mixed_datagram_valid_first_then_bogus() { - //! Test that a UDP datagram with a valid encrypted record FIRST followed - //! by bogus plaintext ApplicationData is handled correctly: the valid - //! record is processed and the trailing bogus record is discarded. - - let now = Instant::now(); - let (mut client, mut server, now) = setup_connected_12_pair(now); - - // Send valid application data from client and capture the encrypted packet. - client.send_application_data(b"valid-data").expect("send valid data"); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "Should have valid packet"); - let valid_packet = &client_out.packets[0]; - - // Craft a plaintext ApplicationData record (epoch 0). - let bogus_record = vec![ - 0x17, // content_type: ApplicationData - 0xFE, 0xFD, // version: DTLS 1.2 - 0x00, 0x00, // epoch: 0 (plaintext) - 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, // sequence_number - 0x00, 0x06, // length: 6 - 0x62, 0x6F, 0x67, 0x75, 0x73, 0x21, // "bogus!" - ]; - - // Construct a mixed datagram: valid record FIRST, then bogus plaintext. - let mut mixed_datagram = valid_packet.clone(); - mixed_datagram.extend_from_slice(&bogus_record); - - // Deliver the mixed datagram to server. - server - .handle_packet(&mixed_datagram) - .expect("mixed datagram should not error"); - - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - - // The valid record should be processed. - assert!( - server_out.app_data.iter().any(|d| d.as_slice() == b"valid-data"), - "Server should receive the valid encrypted ApplicationData even when bogus record follows" - ); - - // The bogus trailing record should NOT produce any output. - assert_eq!( - server_out.app_data.len(), - 1, - "Should receive exactly 1 app data (the valid one), not the bogus plaintext" - ); -} - -#[test] -fn dtls12_bad_encrypted_prefix_does_not_drop_valid_tail() { - let now = Instant::now(); - let (mut client, mut server, now) = setup_connected_12_pair(now); - - client - .send_application_data(b"bad-prefix-clean-resend") - .expect("send first application data"); - client.handle_timeout(now).expect("client timeout"); - let first_out = drain_outputs(&mut client); - let first_packet = first_out - .packets - .first() - .expect("first application data packet") - .clone(); - - client - .send_application_data(b"valid-tail") - .expect("send second application data"); - client.handle_timeout(now).expect("client timeout"); - let second_out = drain_outputs(&mut client); - let second_packet = second_out - .packets - .first() - .expect("second application data packet") - .clone(); - - let mut corrupted_first = first_packet.clone(); - *corrupted_first.last_mut().expect("encrypted packet has ciphertext") ^= 0x55; - - let mut mixed_datagram = corrupted_first; - mixed_datagram.extend_from_slice(&second_packet); - - server - .handle_packet(&mixed_datagram) - .expect("bad encrypted prefix should be discarded without dropping valid tail"); - let server_out = drain_outputs(&mut server); - assert_eq!( - server_out.app_data, - vec![b"valid-tail".to_vec()], - "valid tail record should be delivered despite bad encrypted prefix" - ); - - server - .handle_packet(&first_packet) - .expect("clean first packet should remain replay-acceptable"); - let server_out = drain_outputs(&mut server); - assert_eq!(server_out.app_data, vec![b"bad-prefix-clean-resend".to_vec()]); -} - -#[test] -fn dtls12_relabelled_encrypted_handshake_failure_is_not_silently_discarded() { - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = dtls12_config(); - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let f1 = collect_packets(&mut client); - for p in &f1 { - server.handle_packet(p).expect("server recv ClientHello"); - } - - server.handle_timeout(now).expect("server arm flight 2"); - let f2 = collect_packets(&mut server); - for p in &f2 { - client.handle_packet(p).expect("client recv HelloVerifyRequest"); - } - - client.handle_timeout(now).expect("client arm flight 3"); - let f3 = collect_packets(&mut client); - for p in &f3 { - server.handle_packet(p).expect("server recv ClientHello with cookie"); - } - - server.handle_timeout(now).expect("server arm flight 4"); - let f4 = collect_packets(&mut server); - for p in &f4 { - client.handle_packet(p).expect("client recv server flight"); - } - - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client arm flight 5"); - let mut f5 = collect_packets(&mut client); - assert!(!f5.is_empty(), "client should emit flight 5"); - - let mut relabelled = false; - let mut observed_error = None; - for p in &mut f5 { - let mut offset = 0; - while offset + 13 <= p.len() { - let epoch = u16::from_be_bytes([p[offset + 3], p[offset + 4]]); - let len = u16::from_be_bytes([p[offset + 11], p[offset + 12]]) as usize; - if p[offset] == 22 && epoch >= 1 { - p[offset] = 23; - relabelled = true; - break; - } - offset += 13 + len; - } - - match server.handle_packet(p) { - Ok(()) => {} - Err(e) => { - observed_error = Some(e); - break; - } - } - } - - assert!(relabelled, "flight 5 should contain an encrypted Handshake record"); - assert!( - matches!( - observed_error, - Some(crate::vendor::dimpl::Error::CryptoError(_) | crate::vendor::dimpl::Error::SecurityError(_)) - ), - "relabeled encrypted handshake must remain fatal, got {observed_error:?}" - ); -} - -#[test] -fn dtls12_app_data_after_close_notify_is_ignored() { - //! Simulate UDP reordering: the client sends app data, then close_notify, - //! but the close_notify datagram arrives at the server first. The app data - //! datagram arriving afterwards must be silently discarded. - - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - // Step 1: Client sends app data - capture the packet but don't deliver yet. - client.send_application_data(b"before-close").expect("send app data"); - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let app_data_out = drain_outputs(&mut client); - let app_data_packets = app_data_out.packets.clone(); - assert!(!app_data_packets.is_empty(), "Should have app data packet"); - - // Step 2: Client sends close_notify. - client.close().unwrap(); - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let close_out = drain_outputs(&mut client); - assert!(!close_out.packets.is_empty(), "Should have close_notify packet"); - - // Step 3: Deliver close_notify FIRST (simulating UDP reordering). - deliver_packets(&close_out.packets, &mut server); - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - - assert!(server_out.close_notify, "Server should emit CloseNotify"); - - // Step 4: Now deliver the app data datagram that was sent BEFORE the alert - // but arrived AFTER - it must be discarded. - deliver_packets(&app_data_packets, &mut server); - now += Duration::from_millis(10); - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - - assert!( - server_out.app_data.is_empty(), - "ApplicationData arriving after close_notify must be discarded" - ); -} - -#[test] -fn dtls12_close_during_handshake_emits_no_packets() { - //! Call close() on the client while the handshake is in progress. - //! Per `Dtls::close` API contract, close() during handshake silently - //! discards state without sending any packets. - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Start handshake - client sends ClientHello - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "Client should emit ClientHello"); - - // Deliver to server, server responds - deliver_packets(&client_out.packets, &mut server); - server.handle_timeout(now).expect("server timeout"); - let _server_out = drain_outputs(&mut server); - - // Now abort the client mid-handshake - client.close().unwrap(); - - // After close(), polling must not emit any more packets (library policy, not RFC mandate). - let client_out = drain_outputs(&mut client); - assert!( - client_out.packets.is_empty(), - "Client should not emit packets after close() during handshake" - ); - - // Even after a timeout, no packets should appear. - let later = now + Duration::from_secs(5); - // handle_timeout may error since state is Closed, which is fine - let _ = client.handle_timeout(later); - let client_out = drain_outputs(&mut client); - assert!( - client_out.packets.is_empty(), - "Client should not emit packets after timeout post-close()" - ); -} - -#[test] -fn dtls12_reciprocal_close_notify_and_no_further_sends() { - //! When the server receives a close_notify from the client, it must send - //! a reciprocal close_notify back (RFC 5246 §7.2.1) and transition to - //! Closed. DTLS 1.2 does not support half-close: subsequent - //! send_application_data calls on both sides must fail. - - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - assert!(!client.is_closing()); - assert!(!client.is_closed()); - assert!(!server.is_closing()); - assert!(!server.is_closed()); - - // Client sends close_notify - client.close().unwrap(); - assert!(client.is_closing()); - assert!(!client.is_closed()); - - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "Client should emit close_notify alert"); - assert!(!client.is_closing()); - assert!(client.is_closed()); - - // Deliver to server - deliver_packets(&client_out.packets, &mut server); - server.handle_timeout(now).expect("server timeout"); - assert!(server.is_closing()); - assert!(!server.is_closed()); - - let server_out = drain_outputs(&mut server); - - // Server should emit CloseNotify event - assert!(server_out.close_notify, "Server should emit Output::CloseNotify"); - - // Server should emit a reciprocal close_notify packet. - assert!( - !server_out.packets.is_empty(), - "Server should emit a reciprocal close_notify packet" - ); - assert!(!server.is_closing()); - assert!(server.is_closed()); - - // Deliver reciprocal back to client and verify it sees CloseNotify. - deliver_packets(&server_out.packets, &mut client); - client.handle_timeout(now).expect("client timeout after reciprocal"); - assert!(client.is_closing()); - assert!(!client.is_closed()); - - let client_out2 = drain_outputs(&mut client); - assert!( - client_out2.close_notify, - "Client should emit Output::CloseNotify after receiving reciprocal close_notify" - ); - assert!(!client.is_closing()); - assert!(client.is_closed()); - - // No half-close in DTLS 1.2: both sides must reject further sends. - assert!( - server.send_application_data(b"after-close").is_err(), - "send_application_data must fail after close_notify in DTLS 1.2" - ); - assert!( - client.send_application_data(b"after-close").is_err(), - "send_application_data must fail after close() in DTLS 1.2" - ); -} - -#[test] -fn dtls12_close_state_matrix() { - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - assert!(!client.is_closing()); - assert!(!client.is_closed()); - assert!(!server.is_closing()); - assert!(!server.is_closed()); - - client.close().unwrap(); - assert!(client.is_closing(), "local close pending"); - assert!(!client.is_closed(), "local close not drained"); - - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "local close_notify packet"); - assert!(!client.is_closing(), "local close drained"); - assert!(client.is_closed(), "local close terminal"); - - deliver_packets(&client_out.packets, &mut server); - server.handle_timeout(now).expect("server timeout"); - assert!(server.is_closing(), "remote close pending"); - assert!(!server.is_closed(), "remote close not drained"); - - let server_out = drain_outputs(&mut server); - assert!(server_out.close_notify, "remote CloseNotify event"); - assert!(!server_out.packets.is_empty(), "remote reciprocal close_notify packet"); - assert!(!server.is_closing(), "remote close drained"); - assert!(server.is_closed(), "remote close terminal"); -} - -#[test] -fn dtls12_discard_pending_writes_on_close_notify() { - //! Send application data from the server, then deliver a close_notify from - //! the client before the server polls. The pending data must be discarded - //! per RFC 5246 §7.2.1 - only the reciprocal close_notify is emitted. - - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - // Server queues some application data (not yet polled) - server - .send_application_data(b"pending-data") - .expect("server send pending data"); - - // Client sends close_notify - client.close().unwrap(); - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - - // Deliver the close_notify to the server (before it polls its pending data) - deliver_packets(&client_out.packets, &mut server); - - // Now poll the server - pending data should have been discarded - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - - assert!(server_out.close_notify, "Server should see CloseNotify"); - assert!( - !server_out.packets.is_empty(), - "Server should emit reciprocal close_notify" - ); - - // Deliver reciprocal to client - verify no app data leaked - deliver_packets(&server_out.packets, &mut client); - client.handle_timeout(now).expect("client timeout after reciprocal"); - let client_out2 = drain_outputs(&mut client); - - assert!( - client_out2.close_notify, - "Client should emit Output::CloseNotify after receiving reciprocal close_notify" - ); - assert!( - client_out2.app_data.is_empty(), - "Pending data must be discarded when close_notify is received" - ); -} - -#[test] -fn dtls12_fatal_alert_during_handshake() { - //! During the handshake (peer_encryption_enabled == false), an epoch 0 - //! fatal alert (level=2) should be accepted and return a SecurityError. - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut _server = Dtls::new_12(config, server_cert, now); - - // Start the handshake so the client is expecting a response - client.handle_timeout(now).expect("client timeout"); - let _client_out = drain_outputs(&mut client); - - // Craft a fatal alert at epoch 0 (during handshake, this is legitimate) - let fatal_alert = vec![ - 21, // content_type: alert - 0xFE, 0xFD, // version: DTLS 1.2 - 0x00, 0x00, // epoch: 0 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // sequence number - 0x00, 0x02, // length: 2 - 0x02, // level: fatal - 0x28, // description: handshake_failure (40) - ]; - - let result = client.handle_packet(&fatal_alert); - assert!(result.is_err(), "Fatal alert during handshake should return an error"); - let err = result.unwrap_err(); - assert!(matches!( - err, - crate::vendor::dimpl::Error::SecurityError(crate::vendor::dimpl::SecurityError::FatalAlert { description: 40 }) - )); -} - -#[test] -fn dtls12_app_data_delivered_before_close_notify() { - //! When app data and close_notify arrive together, the app data must be - //! delivered before CloseNotify. - - let mut now = Instant::now(); - let (mut client, mut server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - // Send app data then immediately close - client.send_application_data(b"before-close").expect("send app data"); - client.close().unwrap(); - - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - - deliver_packets(&client_out.packets, &mut server); - - // Poll server outputs and verify ordering: ApplicationData before CloseNotify - server.handle_timeout(now).expect("server timeout"); - let mut saw_app_data = false; - let mut saw_close_notify = false; - let mut close_after_data = false; - let mut buf = vec![0u8; 2048]; - loop { - match server.poll_output(&mut buf) { - Output::ApplicationData(data) => { - assert!(!saw_close_notify, "ApplicationData must not appear after CloseNotify"); - if data == b"before-close" { - saw_app_data = true; - } - } - Output::CloseNotify => { - saw_close_notify = true; - if saw_app_data { - close_after_data = true; - } - } - Output::Timeout(_) => break, - _ => {} - } - } - assert!(saw_app_data, "Server should receive the app data"); - assert!(saw_close_notify, "Server should see CloseNotify"); - assert!(close_after_data, "CloseNotify must come after ApplicationData"); -} - -#[test] -fn dtls12_close_notify_not_retransmitted() { - //! After sending close_notify, the alert must not be retransmitted. - //! RFC 6347 §4.2.7: "Alert messages are not retransmitted at all, - //! even when they occur in the context of a handshake." - - let mut now = Instant::now(); - let (mut client, _server, now_hs) = setup_connected_12_pair(now); - now = now_hs; - - // Client sends close_notify - client.close().unwrap(); - now += Duration::from_millis(10); - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "Client should emit close_notify alert"); - - // Advance time 5 times (5 seconds each) - no retransmissions should occur - for _ in 0..5 { - now += Duration::from_secs(5); - let _ = client.handle_timeout(now); - let out = drain_outputs(&mut client); - assert!( - out.packets.is_empty(), - "close_notify must not be retransmitted (RFC 6347 §4.2.7)" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/fragmentation.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/fragmentation.rs deleted file mode 100644 index d88672a06f7..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/fragmentation.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! DTLS 1.2 fragmentation test (MTU-based). - -use std::collections::VecDeque; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::{Config, Dtls, Output}; - -use crate::vendor::dimpl::tests::dtls12::common::*; - -#[test] -fn dtls12_fragmentation_dimpl_to_dimpl() { - //! Verify that a dimpl-to-dimpl handshake completes successfully with a - //! small MTU that forces handshake message fragmentation. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config_with_mtu(200); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - let mut max_packet_size = 0usize; - - for _ in 0..40 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - // Track max packet size to verify MTU compliance - for p in &client_out.packets { - if p.len() > max_packet_size { - max_packet_size = p.len(); - } - } - for p in &server_out.packets { - if p.len() > max_packet_size { - max_packet_size = p.len(); - } - } - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!( - client_connected, - "Client should connect with small MTU (dimpl-to-dimpl)" - ); - assert!( - server_connected, - "Server should connect with small MTU (dimpl-to-dimpl)" - ); - assert!( - max_packet_size <= 200, - "All packets should respect 200-byte MTU: max was {}", - max_packet_size - ); -} - -#[test] -fn dtls12_fragmented_handshake_with_packet_loss() { - //! Use a small MTU so flights are fragmented into multiple packets. - //! Drop the first packet of the first flight, then trigger a retransmit. - //! Verify the handshake still completes. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config_with_mtu(200); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // FLIGHT 1: Client sends ClientHello (possibly fragmented). - // Trigger the initial timeout to start the handshake. - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let flight1 = collect_packets(&mut client); - assert!( - !flight1.is_empty(), - "Client should emit at least one packet for flight 1" - ); - - // Drop the first packet of flight 1 and deliver the rest (if any). - deliver_packets(&flight1[1..], &mut server); - - // Trigger retransmit on the client so it resends the full flight. - trigger_timeout(&mut client, &mut now); - let retransmit1 = collect_packets(&mut client); - assert!(!retransmit1.is_empty(), "Client should retransmit flight 1"); - - // Deliver the full retransmitted flight to the server. - deliver_packets(&retransmit1, &mut server); - - // Now continue the handshake normally until completion. - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..40 { - server.handle_timeout(now).expect("server timeout"); - let server_out = drain_outputs(&mut server); - if server_out.connected { - server_connected = true; - } - deliver_packets(&server_out.packets, &mut client); - - client.handle_timeout(now).expect("client timeout"); - let client_out = drain_outputs(&mut client); - if client_out.connected { - client_connected = true; - } - deliver_packets(&client_out.packets, &mut server); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!( - client_connected, - "Client should connect after retransmit of dropped fragment" - ); - assert!( - server_connected, - "Server should connect after retransmit of dropped fragment" - ); -} - -#[test] -fn dtls12_out_of_order_fragments() { - //! Use a small MTU to force fragmentation. Before delivering each flight, - //! reverse the packet order. Verify the handshake still completes, proving - //! fragment reassembly handles out-of-order delivery. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config_with_mtu(200); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..40 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - // Reverse packet order before delivery to simulate out-of-order fragments - let mut client_packets = client_out.packets; - let mut server_packets = server_out.packets; - client_packets.reverse(); - server_packets.reverse(); - - deliver_packets(&client_packets, &mut server); - deliver_packets(&server_packets, &mut client); - - if client_connected && server_connected { - break; - } - - // Reordered protected records may be discarded until CCS is processed. - // Give the retransmission timer enough time to recover those records. - now += Duration::from_secs(1); - } - - assert!(client_connected, "Client should connect with out-of-order fragments"); - assert!(server_connected, "Server should connect with out-of-order fragments"); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs deleted file mode 100644 index 08ba513a03c..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/handshake.rs +++ /dev/null @@ -1,890 +0,0 @@ -//! DTLS 1.2 handshake tests (cookie retry, parallel handshakes, basic handshake). - -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::{Config, Dtls, SrtpProfile}; - -use crate::vendor::dimpl::tests::dtls12::common::*; - -#[test] -fn dtls12_client_certificate_not_required() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = Arc::new( - Config::builder() - .require_client_certificate(false) - .build() - .expect("build config"), - ); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - complete_dtls12_handshake(&mut client, &mut server, now); -} - -#[test] -fn dtls12_empty_client_certificate_is_rejected_when_required() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - use crate::vendor::dimpl::{CertificateError, Error}; - - let mut now = Instant::now(); - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config = Arc::new(Config::builder().build().expect("build config")); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - - for step in 0..60 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - for packet in &client_out.packets { - if packet.len() >= 25 && packet[0] == 22 && packet[13] == CERTIFICATE { - // Replace the client's plaintext Certificate record with an - // empty certificate list, preserving record and handshake sequence numbers. - let mut empty = packet[..25].to_vec(); - empty[11..13].copy_from_slice(&15u16.to_be_bytes()); - empty[14..17].copy_from_slice(&[0, 0, 3]); - empty[22..25].copy_from_slice(&[0, 0, 3]); - empty.extend_from_slice(&[0, 0, 0]); - assert!(matches!( - server.handle_packet(&empty), - Err(Error::CertificateError(CertificateError::NoClientCertificateReceived)) - )); - let output = drain_outputs(&mut server); - assert_eq!(output.packets.len(), 1, "one fatal alert packet"); - let alert = &output.packets[0]; - assert_eq!(alert[0], 21, "DTLS Alert record"); - assert_eq!(&alert[3..5], &[0, 0], "pre-key-exchange epoch"); - assert_eq!(&alert[13..], &[2, 40], "fatal handshake_failure"); - assert!(server.is_closed()); - return; - } - server.handle_packet(packet).expect("server packet"); - } - deliver_packets(&server_out.packets, &mut client); - if step % 5 == 4 { - now += Duration::from_secs(2); - } else { - now += Duration::from_millis(50); - } - } - panic!("client did not send Certificate"); -} - -#[test] -fn dtls12_cookie_retry_proceeds_to_server_hello() { - //! Verify that after HelloVerifyRequest, the ClientHello with cookie - //! is properly processed and the server sends ServerHello (not another HVR). - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = Arc::new(Config::builder().build().expect("Failed to build config")); - - let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); - client.set_active(true); - - let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); - server.set_active(false); - - // FLIGHT 1: Client sends ClientHello (no cookie) - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let f1 = collect_packets(&mut client); - assert!(!f1.is_empty(), "client should emit ClientHello"); - - // Verify it's a ClientHello - let f1_hs_types: Vec = f1.iter().flat_map(|p| parse_handshake_types(p)).collect(); - assert!( - f1_hs_types.contains(&CLIENT_HELLO), - "flight 1 should contain ClientHello, got {:?}", - f1_hs_types - ); - - // Deliver to server - for p in &f1 { - server.handle_packet(p).expect("server recv f1"); - } - - // FLIGHT 2: Server sends HelloVerifyRequest - server.handle_timeout(now).expect("server arm flight 2"); - let f2 = collect_packets(&mut server); - assert!(!f2.is_empty(), "server should emit HelloVerifyRequest"); - - // Verify it's a HelloVerifyRequest - let f2_hs_types: Vec = f2.iter().flat_map(|p| parse_handshake_types(p)).collect(); - assert!( - f2_hs_types.contains(&HELLO_VERIFY_REQUEST), - "flight 2 should contain HelloVerifyRequest, got {:?}", - f2_hs_types - ); - - // Deliver to client - for p in &f2 { - client.handle_packet(p).expect("client recv f2"); - } - - // FLIGHT 3: Client sends ClientHello WITH cookie (message_seq=1 per RFC 6347) - client.handle_timeout(now).expect("client arm flight 3"); - let f3 = collect_packets(&mut client); - assert!(!f3.is_empty(), "client should emit ClientHello with cookie"); - - let f3_hs_types: Vec = f3.iter().flat_map(|p| parse_handshake_types(p)).collect(); - assert!( - f3_hs_types.contains(&CLIENT_HELLO), - "flight 3 should contain ClientHello (with cookie), got {:?}", - f3_hs_types - ); - - // Deliver to server - THIS IS WHERE THE BUG MANIFESTS - for p in &f3 { - server.handle_packet(p).expect("server recv f3"); - } - - // FLIGHT 4: Server should send ServerHello, Certificate, etc. - NOT HelloVerifyRequest - server.handle_timeout(now).expect("server arm flight 4"); - let f4 = collect_packets(&mut server); - assert!( - !f4.is_empty(), - "server should emit flight 4 after ClientHello with cookie" - ); - - let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); - - // THE KEY ASSERTION: Server should NOT send another HelloVerifyRequest - assert!( - !f4_hs_types.contains(&HELLO_VERIFY_REQUEST), - "server should NOT send HelloVerifyRequest after valid cookie - BUG! got {:?}", - f4_hs_types - ); - - // Server should send ServerHello - assert!( - f4_hs_types.contains(&SERVER_HELLO), - "server should send ServerHello after valid cookie, got {:?}", - f4_hs_types - ); - - // Should also contain Certificate and ServerHelloDone - assert!( - f4_hs_types.contains(&CERTIFICATE), - "server should send Certificate, got {:?}", - f4_hs_types - ); - assert!( - f4_hs_types.contains(&SERVER_HELLO_DONE), - "server should send ServerHelloDone, got {:?}", - f4_hs_types - ); - - println!("SUCCESS: Server correctly processed ClientHello with cookie and sent ServerHello flight"); -} - -#[test] -fn dtls12_parallel_handshakes_with_cookies() { - //! Test multiple parallel DTLS handshakes to ensure cookie handling - //! works correctly under concurrent load (the original bug scenario). - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = Arc::new(Config::builder().build().expect("Failed to build config")); - - // Create 5 parallel client-server pairs - let mut pairs: Vec<(Dtls, Dtls)> = (0..5) - .map(|_| { - let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); - client.set_active(true); - let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); - server.set_active(false); - (client, server) - }) - .collect(); - - // Run all handshakes through the cookie exchange phase - for (i, (client, server)) in pairs.iter_mut().enumerate() { - // Flight 1: ClientHello - client.handle_timeout(now).expect("client timeout"); - client.handle_timeout(now).expect("client arm f1"); - let f1 = collect_packets(client); - for p in &f1 { - server.handle_packet(p).expect("server recv f1"); - } - - // Flight 2: HelloVerifyRequest - server.handle_timeout(now).expect("server arm f2"); - let f2 = collect_packets(server); - for p in &f2 { - client.handle_packet(p).expect("client recv f2"); - } - - // Flight 3: ClientHello with cookie - client.handle_timeout(now).expect("client arm f3"); - let f3 = collect_packets(client); - for p in &f3 { - server.handle_packet(p).expect("server recv f3"); - } - - // Flight 4: Should be ServerHello, not HelloVerifyRequest - server.handle_timeout(now).expect("server arm f4"); - let f4 = collect_packets(server); - let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); - - assert!( - !f4_hs_types.contains(&HELLO_VERIFY_REQUEST), - "pair {}: server sent HelloVerifyRequest instead of ServerHello - BUG!", - i - ); - assert!( - f4_hs_types.contains(&SERVER_HELLO), - "pair {}: server should send ServerHello, got {:?}", - i, - f4_hs_types - ); - } - - println!( - "SUCCESS: All {} parallel handshakes processed cookies correctly", - pairs.len() - ); -} - -#[test] -fn dtls12_retransmit_no_cookie_after_cookie_sent() { - //! Simulates the real Firefox bug scenario: - //! 1. Client sends ClientHello (no cookie) - //! 2. Server sends HelloVerifyRequest - //! 3. Client sends ClientHello (with cookie) - //! 4. Client's timer fires and it ALSO retransmits the original no-cookie ClientHello - //! 5. Server should NOT get confused by this out-of-order retransmit - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = Arc::new(Config::builder().build().expect("Failed to build config")); - - let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); - client.set_active(true); - - let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); - server.set_active(false); - - // Flight 1: ClientHello (no cookie) - client.handle_timeout(now).expect("client timeout"); - client.handle_timeout(now).expect("client arm f1"); - let f1 = collect_packets(&mut client); - assert!(!f1.is_empty()); - - // Save a copy of the original no-cookie ClientHello for later retransmit - let f1_copy = f1.clone(); - - // Deliver to server - for p in &f1 { - server.handle_packet(p).expect("server recv f1"); - } - - // Flight 2: HelloVerifyRequest - server.handle_timeout(now).expect("server arm f2"); - let f2 = collect_packets(&mut server); - assert!(!f2.is_empty()); - - // Deliver to client - for p in &f2 { - client.handle_packet(p).expect("client recv f2"); - } - - // Flight 3: ClientHello WITH cookie - client.handle_timeout(now).expect("client arm f3"); - let f3 = collect_packets(&mut client); - assert!(!f3.is_empty()); - - // Deliver the cookie version to server - for p in &f3 { - server.handle_packet(p).expect("server recv f3 with cookie"); - } - - // NOW simulate Firefox's retransmit timer firing - send the ORIGINAL - // no-cookie ClientHello again (this is what Firefox does in the real bug) - for p in &f1_copy { - // This should not cause the handshake to fail - server.handle_packet(p).expect("server recv retransmit of no-cookie CH"); - } - - // Server should still send ServerHello flight, not another HelloVerifyRequest - server.handle_timeout(now).expect("server arm f4"); - let f4 = collect_packets(&mut server); - assert!(!f4.is_empty(), "server should emit flight 4"); - - let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); - - // The key test: even after receiving the retransmitted no-cookie ClientHello, - // the server should proceed with ServerHello (having already processed the cookie version) - assert!( - f4_hs_types.contains(&SERVER_HELLO), - "server should send ServerHello even after retransmit of no-cookie CH, got {:?}", - f4_hs_types - ); - - println!("SUCCESS: Server correctly handled out-of-order retransmit scenario"); -} - -#[test] -fn dtls12_retransmit_no_cookie_before_cookie_received() { - //! Tests the specific bug scenario from webrtc deployments: - //! - //! 1. Client sends ClientHello (seq=0, no cookie) - //! 2. Server sends HelloVerifyRequest, clears queue_rx - //! 3. Client retransmits old ClientHello (seq=0, no cookie) - HVR was lost/delayed - //! 4. Server resends HelloVerifyRequest (correct), but OLD ClientHello must NOT - //! be inserted into queue_rx, otherwise it blocks the new ClientHello - //! 5. Client sends ClientHello (seq=1, with cookie) - //! 6. Server should process it and send ServerHello - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = Arc::new(Config::builder().build().expect("Failed to build config")); - - let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); - client.set_active(true); - - let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); - server.set_active(false); - - // Flight 1: ClientHello (no cookie) - client.handle_timeout(now).expect("client timeout"); - client.handle_timeout(now).expect("client arm f1"); - let f1 = collect_packets(&mut client); - assert!(!f1.is_empty()); - - // Save a copy of the original no-cookie ClientHello for retransmit simulation - let f1_copy = f1.clone(); - - // Deliver to server - for p in &f1 { - server.handle_packet(p).expect("server recv f1"); - } - - // Flight 2: HelloVerifyRequest - server.handle_timeout(now).expect("server arm f2"); - let f2 = collect_packets(&mut server); - assert!(!f2.is_empty()); - - // Simulate: HVR is "lost" - don't deliver to client yet - // Instead, client's retransmit timer fires and sends the old ClientHello again - - // THIS IS THE BUG TRIGGER: old ClientHello (seq=0) arrives at server - // BEFORE the cookie-bearing ClientHello (seq=1) - for p in &f1_copy { - server.handle_packet(p).expect("server recv retransmit of no-cookie CH"); - } - - // Server should resend HelloVerifyRequest (this is correct behavior) - // The bug was that the old ClientHello got inserted into queue_rx - let f2_resend = collect_packets(&mut server); - let f2_resend_types: Vec = f2_resend.iter().flat_map(|p| parse_handshake_types(p)).collect(); - assert!( - f2_resend_types.contains(&HELLO_VERIFY_REQUEST), - "server should resend HelloVerifyRequest after duplicate, got {:?}", - f2_resend_types - ); - - // Now deliver the original HVR to client - for p in &f2 { - client.handle_packet(p).expect("client recv f2"); - } - - // Flight 3: ClientHello WITH cookie (seq=1) - client.handle_timeout(now).expect("client arm f3"); - let f3 = collect_packets(&mut client); - assert!(!f3.is_empty()); - - // Deliver to server - THIS IS WHERE THE BUG MANIFESTED - // Before fix: queue_rx had old ClientHello (seq=0), blocking this one - for p in &f3 { - server.handle_packet(p).expect("server recv f3 with cookie"); - } - - // Server should now send ServerHello flight - server.handle_timeout(now).expect("server arm f4"); - let f4 = collect_packets(&mut server); - assert!(!f4.is_empty(), "server should emit flight 4"); - - let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); - - // THE KEY ASSERTION: Server must NOT be stuck sending HelloVerifyRequest - assert!( - !f4_hs_types.contains(&HELLO_VERIFY_REQUEST), - "server should NOT resend HelloVerifyRequest after valid cookie, got {:?}", - f4_hs_types - ); - - // Server should send ServerHello - assert!( - f4_hs_types.contains(&SERVER_HELLO), - "server should send ServerHello after cookie CH, got {:?}", - f4_hs_types - ); - - println!("SUCCESS: Old duplicate ClientHello did not block new ClientHello with cookie"); -} - -#[test] -fn dtls12_basic_handshake() { - //! Complete a full dimpl-to-dimpl DTLS 1.2 handshake and verify both - //! client and server reach the connected state. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..30 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); -} - -#[test] -fn dtls12_handshake_with_keying_material() { - //! Complete a DTLS 1.2 handshake with SRTP profile configured and verify - //! both sides derive identical SRTP keying material. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_km: Option<(Vec, SrtpProfile)> = None; - let mut server_km: Option<(Vec, SrtpProfile)> = None; - - for _ in 0..30 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if let Some(km) = client_out.keying_material { - client_km = Some(km); - } - if let Some(km) = server_out.keying_material { - server_km = Some(km); - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_km.is_some() && server_km.is_some() { - break; - } - - now += Duration::from_millis(10); - } - - let client_km = client_km.expect("Client should have keying material"); - let server_km = server_km.expect("Server should have keying material"); - - assert_eq!( - client_km.0, server_km.0, - "Client and server keying material should match" - ); - assert_eq!(client_km.1, server_km.1, "Client and server SRTP profile should match"); - assert!(!client_km.0.is_empty(), "Keying material should not be empty"); -} - -#[test] -fn dtls12_peer_certificate_exchange() { - //! Complete a DTLS 1.2 handshake and verify the client can access the - //! server's certificate and the server can access the client's certificate. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let expected_client_cert = client_cert.certificate.clone(); - let expected_server_cert = server_cert.certificate.clone(); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_peer_cert: Option> = None; - let mut server_peer_cert: Option> = None; - - for _ in 0..30 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if let Some(cert) = client_out.peer_cert { - client_peer_cert = Some(cert); - } - if let Some(cert) = server_out.peer_cert { - server_peer_cert = Some(cert); - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_peer_cert.is_some() && server_peer_cert.is_some() { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_peer_cert.is_some(), "Client should receive server's certificate"); - assert!(server_peer_cert.is_some(), "Server should receive client's certificate"); - - assert_eq!( - client_peer_cert.unwrap(), - expected_server_cert, - "Client should receive server's certificate" - ); - assert_eq!( - server_peer_cert.unwrap(), - expected_client_cert, - "Server should receive client's certificate" - ); -} - -#[test] -fn dtls12_handshake_client_certificate_auth() { - //! Configure the server to require a client certificate, complete the - //! handshake, and verify the server received and validated the client - //! certificate. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let expected_client_cert = client_cert.certificate.clone(); - - let config = Arc::new( - Config::builder() - .require_client_certificate(true) - .build() - .expect("Failed to build config"), - ); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut server_connected = false; - let mut server_peer_cert: Option> = None; - - for _ in 0..30 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if server_out.connected { - server_connected = true; - } - if let Some(cert) = server_out.peer_cert { - server_peer_cert = Some(cert); - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if server_connected && server_peer_cert.is_some() { - break; - } - - now += Duration::from_millis(10); - } - - assert!( - server_connected, - "Server should be connected after client certificate auth" - ); - assert!(server_peer_cert.is_some(), "Server should receive client's certificate"); - assert_eq!( - server_peer_cert.unwrap(), - expected_client_cert, - "Server should receive the correct client certificate" - ); -} - -#[test] -fn dtls12_handshake_secp384r1_key_exchange() { - //! Configure to use only P-384 for key exchange, complete the handshake, - //! and verify both sides reach connected. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - use crate::vendor::dimpl::crypto::rind; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - // Build a crypto provider with only the P-384 key exchange group. - let mut provider = rind::default_provider().unwrap(); - let p384_vec: Vec<&'static dyn crate::vendor::dimpl::crypto::SupportedKxGroup> = provider - .kx_groups - .iter() - .copied() - .filter(|g| g.name() == crate::vendor::dimpl::NamedGroup::Secp384r1) - .collect(); - // leak: intentional leak to produce a &'static slice for the provider field - let p384_only: &'static [&'static dyn crate::vendor::dimpl::crypto::SupportedKxGroup] = - Box::leak(p384_vec.into_boxed_slice()); - provider.kx_groups = p384_only; - - let config = Arc::new( - Config::builder() - .with_crypto_provider(provider) - .build() - .expect("Failed to build config with P-384 only"), - ); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..30 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected with P-384"); - assert!(server_connected, "Server should be connected with P-384"); -} - -#[test] -fn dtls12_handshake_timeout_expires() { - //! Create client and server but never deliver packets. Trigger timeouts - //! repeatedly and verify the handshake eventually times out/fails. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - // Use a short handshake timeout to speed up the test. - let config = Arc::new( - Config::builder() - .handshake_timeout(Duration::from_secs(5)) - .flight_retries(2) - .build() - .expect("Failed to build config"), - ); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_timed_out = false; - let mut server_timed_out = false; - - // Run for many iterations, advancing time each round, but never deliver - // packets between client and server. - for _ in 0..100 { - if !client_timed_out { - match client.handle_timeout(now) { - Ok(()) => { - // Drain outputs but discard packets (never deliver them) - let _ = drain_outputs(&mut client); - } - Err(_) => { - client_timed_out = true; - } - } - } - - if !server_timed_out { - match server.handle_timeout(now) { - Ok(()) => { - let _ = drain_outputs(&mut server); - } - Err(_) => { - server_timed_out = true; - } - } - } - - if client_timed_out && server_timed_out { - break; - } - - now += Duration::from_secs(2); - } - - assert!( - client_timed_out, - "Client handshake should eventually time out when no packets are delivered" - ); -} - -#[test] -fn dtls12_handshake_p384_certificate() { - //! DTLS 1.2 handshake where both sides use P-384 ECDSA certificates. - //! Regression test: the server's ServerKeyExchange must sign with the - //! same hash algorithm it advertises on the wire (SHA-384 for P-384). - - let p384 = || { - let key = rind_rcgen::KeyPair::generate(&rcgen::PKCS_ECDSA_P384_SHA384).expect("P-384 key"); - let mut params = rcgen::CertificateParams::new(vec!["WebRTC".to_string()]).expect("certificate params"); - // rcgen draws no serial number without its own crypto backend. - params.serial_number = Some(1u64.into()); - let cert = params.self_signed(&key).expect("self-signed certificate"); - crate::vendor::dimpl::DtlsCertificate { - certificate: cert.der().to_vec(), - private_key: key.to_pkcs8().secret_pkcs8_der().to_vec(), - } - }; - - let config = dtls12_config(); - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), p384(), now); - client.set_active(true); - - let mut server = Dtls::new_12(config, p384(), now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..30 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should connect with P-384 cert"); - assert!(server_connected, "Server should connect with P-384 cert"); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/main.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/main.rs deleted file mode 100644 index c47da7d2df9..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/main.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub mod common; -mod data; -mod edge; -mod fragmentation; -mod handshake; -mod psk; -mod reorder; -mod retransmit; diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/psk.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/psk.rs deleted file mode 100644 index e4d2ee10475..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/psk.rs +++ /dev/null @@ -1,399 +0,0 @@ -//! DTLS 1.2 PSK handshake tests. - -use std::sync::Arc; -use std::time::Instant; - -use crate::vendor::dimpl::crypto::Dtls12CipherSuite; -use crate::vendor::dimpl::{Config, Dtls, Error, PskResolver}; - -use crate::vendor::dimpl::tests::dtls12::common::{deliver_packets, drain_outputs}; - -/// Simple PSK resolver that returns a fixed key for a known identity. -struct FixedPsk { - identity: Vec, - key: Vec, -} - -impl PskResolver for FixedPsk { - fn resolve(&self, identity: &[u8]) -> Option> { - if identity == self.identity { - Some(self.key.clone()) - } else { - None - } - } -} - -fn psk_provider(suite: Dtls12CipherSuite) -> crate::vendor::dimpl::crypto::CryptoProvider { - let mut provider = Config::default().crypto_provider().clone(); - let psk_suite = provider - .cipher_suites - .iter() - .copied() - .find(|cs| cs.suite() == suite) - .unwrap_or_else(|| panic!("{:?} not in provider", suite)); - - let suites = Box::leak(Box::new([psk_suite])); - provider.cipher_suites = suites; - provider -} - -/// Returns (client_config, server_config) for PSK tests. -fn psk_configs_for_suite(suite: Dtls12CipherSuite) -> (Arc, Arc) { - let identity = b"test-device".to_vec(); - let key = b"0123456789abcdef".to_vec(); // 16 bytes - - let resolver = Arc::new(FixedPsk { - identity: identity.clone(), - key, - }); - - let provider = psk_provider(suite); - - let client = Arc::new( - Config::builder() - .with_crypto_provider(provider.clone()) - .with_psk_client(identity, resolver.clone()) - .build() - .expect("build PSK client config"), - ); - - let server = Arc::new( - Config::builder() - .with_crypto_provider(provider) - .with_psk_server(Some(b"hint".to_vec()), resolver) - .build() - .expect("build PSK server config"), - ); - - (client, server) -} - -fn psk_configs() -> (Arc, Arc) { - psk_configs_for_suite(Dtls12CipherSuite::PSK_AES128_CCM_8) -} - -#[test] -fn dtls12_psk_self_handshake() { - let (client_config, server_config) = psk_configs(); - let now = Instant::now(); - - let mut client = Dtls::new_12_psk(client_config, now); - client.set_active(true); - - let mut server = Dtls::new_12_psk(server_config, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..60 { - client.handle_timeout(Instant::now()).unwrap(); - server.handle_timeout(Instant::now()).unwrap(); - - // Drain client → server - let client_out = drain_outputs(&mut client); - if client_out.connected { - client_connected = true; - } - deliver_packets(&client_out.packets, &mut server); - - // Drain server → client - let server_out = drain_outputs(&mut server); - if server_out.connected { - server_connected = true; - } - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - } - - assert!(client_connected, "PSK client should connect"); - assert!(server_connected, "PSK server should connect"); -} - -#[test] -fn dtls12_psk_application_data_roundtrip() { - let (client_config, server_config) = psk_configs(); - let now = Instant::now(); - - let mut client = Dtls::new_12_psk(client_config, now); - client.set_active(true); - - let mut server = Dtls::new_12_psk(server_config, now); - server.set_active(false); - - // Complete handshake - for _ in 0..60 { - client.handle_timeout(Instant::now()).unwrap(); - server.handle_timeout(Instant::now()).unwrap(); - - let co = drain_outputs(&mut client); - deliver_packets(&co.packets, &mut server); - - let so = drain_outputs(&mut server); - deliver_packets(&so.packets, &mut client); - - if co.connected || so.connected { - // One more round to let both sides finish - client.handle_timeout(Instant::now()).unwrap(); - server.handle_timeout(Instant::now()).unwrap(); - - let co2 = drain_outputs(&mut client); - deliver_packets(&co2.packets, &mut server); - - let so2 = drain_outputs(&mut server); - deliver_packets(&so2.packets, &mut client); - break; - } - } - - // Send data client → server - let payload = b"Hello from PSK client!"; - client.send_application_data(payload).expect("send app data"); - - let co = drain_outputs(&mut client); - deliver_packets(&co.packets, &mut server); - - let so = drain_outputs(&mut server); - assert!( - so.app_data.iter().any(|d| d == payload), - "Server should receive client's application data" - ); - - // Send data server → client - let reply = b"Hello from PSK server!"; - server.send_application_data(reply).expect("send app data"); - - let so = drain_outputs(&mut server); - deliver_packets(&so.packets, &mut client); - - let co = drain_outputs(&mut client); - assert!( - co.app_data.iter().any(|d| d == reply), - "Client should receive server's application data" - ); -} - -#[test] -fn psk_invalid_identity_fails_at_finished() { - struct FailingResolver; - impl PskResolver for FailingResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - None - } - } - - struct PassingResolver; - impl PskResolver for PassingResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(vec![0u8; 32]) - } - } - - let server_config = crate::vendor::dimpl::Config::builder() - .with_psk_server(None, Arc::new(FailingResolver)) - .build() - .expect("server config should build"); - let mut server = Dtls::new_12_psk(Arc::new(server_config), Instant::now()); - - let client_config = crate::vendor::dimpl::Config::builder() - .with_psk_client(b"test_identity".to_vec(), Arc::new(PassingResolver)) - .build() - .expect("client config should build"); - let mut client = Dtls::new_12_psk(Arc::new(client_config), Instant::now()); - client.set_active(true); - - // Drive the handshake; expect a SecurityError from mismatched PSK keys. - let mut error_found = false; - for _ in 0..60 { - if let Err(e) = client.handle_timeout(Instant::now()) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - let co = drain_outputs(&mut client); - for p in &co.packets { - if let Err(e) = server.handle_packet(p) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - } - if error_found { - break; - } - assert!(!co.connected, "client should not connect with mismatched PSK"); - - if let Err(e) = server.handle_timeout(Instant::now()) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - let so = drain_outputs(&mut server); - for p in &so.packets { - if let Err(e) = client.handle_packet(p) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - } - if error_found { - break; - } - assert!(!so.connected, "server should not connect with mismatched PSK"); - } - - assert!(error_found, "Expected SecurityError from PSK verification failure"); -} - -#[test] -fn psk_mismatched_keys_fail_at_finished_via_mac() { - // Both resolvers return Some, so server.psk_valid stays Some(true) and - // the defense-in-depth flag check is bypassed - any failure here must - // come from the Finished MAC mismatch itself. Exercises the primary - // cryptographic guarantee independently of the flag. - - struct ZeroKey; - impl PskResolver for ZeroKey { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(vec![0u8; 32]) - } - } - struct OneKey; - impl PskResolver for OneKey { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(vec![0xAA; 32]) - } - } - - let server_config = crate::vendor::dimpl::Config::builder() - .with_psk_server(None, Arc::new(ZeroKey)) - .build() - .expect("server config should build"); - let mut server = Dtls::new_12_psk(Arc::new(server_config), Instant::now()); - - let client_config = crate::vendor::dimpl::Config::builder() - .with_psk_client(b"test_identity".to_vec(), Arc::new(OneKey)) - .build() - .expect("client config should build"); - let mut client = Dtls::new_12_psk(Arc::new(client_config), Instant::now()); - client.set_active(true); - - let mut error_found = false; - for _ in 0..60 { - if let Err(e) = client.handle_timeout(Instant::now()) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - let co = drain_outputs(&mut client); - for p in &co.packets { - if let Err(e) = server.handle_packet(p) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - } - if error_found { - break; - } - assert!(!co.connected, "client should not connect with mismatched PSK keys"); - - if let Err(e) = server.handle_timeout(Instant::now()) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - let so = drain_outputs(&mut server); - for p in &so.packets { - if let Err(e) = client.handle_packet(p) { - assert!( - matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), - "unexpected error: {e:?}" - ); - error_found = true; - break; - } - } - if error_found { - break; - } - assert!(!so.connected, "server should not connect with mismatched PSK keys"); - } - - assert!(error_found, "Expected SecurityError from Finished MAC mismatch"); -} - -#[test] -fn psk_valid_identity_succeeds() { - struct AlwaysPassResolver; - impl PskResolver for AlwaysPassResolver { - fn resolve(&self, _identity: &[u8]) -> Option> { - Some(vec![0u8; 32]) - } - } - - let server_config = crate::vendor::dimpl::Config::builder() - .with_psk_server(None, Arc::new(AlwaysPassResolver)) - .build() - .expect("server config should build"); - let mut server = Dtls::new_12_psk(Arc::new(server_config), Instant::now()); - - let client_config = crate::vendor::dimpl::Config::builder() - .with_psk_client(b"test_identity".to_vec(), Arc::new(AlwaysPassResolver)) - .build() - .expect("client config should build"); - let mut client = Dtls::new_12_psk(Arc::new(client_config), Instant::now()); - client.set_active(true); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..60 { - client.handle_timeout(Instant::now()).unwrap(); - server.handle_timeout(Instant::now()).unwrap(); - - let co = drain_outputs(&mut client); - if co.connected { - client_connected = true; - } - deliver_packets(&co.packets, &mut server); - - let so = drain_outputs(&mut server); - if so.connected { - server_connected = true; - } - deliver_packets(&so.packets, &mut client); - - if client_connected && server_connected { - break; - } - } - - assert!(client_connected, "PSK client should connect"); - assert!(server_connected, "PSK server should connect"); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/reorder.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/reorder.rs deleted file mode 100644 index 7b044cfc763..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/reorder.rs +++ /dev/null @@ -1,430 +0,0 @@ -//! DTLS 1.2 packet reordering, replay, and duplicate tests. - -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::Dtls; - -use crate::vendor::dimpl::tests::dtls12::common::*; - -#[test] -fn dtls12_discards_scrambled_datagram_and_accepts_clean_retransmission() { - use crate::vendor::dimpl::Config; - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let certificate = || generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .use_server_cookie(false) - .build() - .expect("valid config"), - ); - let now = Instant::now(); - let mut client = Dtls::new_12(Arc::clone(&config), certificate(), now); - client.set_active(true); - let mut server = Dtls::new_12(config, certificate(), now); - server.set_active(false); - server.handle_timeout(now).expect("initialize server"); - assert!(drain_outputs(&mut server).packets.is_empty()); - - client.handle_timeout(now).expect("start ClientHello"); - let client_hello = drain_outputs(&mut client); - client.handle_timeout(now).expect("arm client flight timer"); - assert!(drain_outputs(&mut client).packets.is_empty()); - let mut server_flight = Vec::new(); - for packet in &client_hello.packets { - server.handle_packet(packet).expect("receive ClientHello"); - server_flight.extend(drain_outputs(&mut server).packets); - } - server.handle_timeout(now).expect("arm server flight timer"); - assert!(drain_outputs(&mut server).packets.is_empty()); - let mut client_flight = Vec::new(); - for packet in &server_flight { - client.handle_packet(packet).expect("receive server flight"); - client_flight.extend(drain_outputs(&mut client).packets); - } - assert_eq!(client_flight.len(), 1, "reproduce reordering within one datagram"); - client.handle_timeout(now).expect("arm client final-flight timer"); - let deadline = drain_outputs(&mut client).timeout.expect("client retry deadline"); - - let mut remaining = &client_flight[0][..]; - let mut records = Vec::new(); - while !remaining.is_empty() { - let length = 13 + usize::from(u16::from_be_bytes([remaining[11], remaining[12]])); - records.push(&remaining[..length]); - remaining = &remaining[length..]; - } - assert!( - records.len() >= 5, - "client flight includes certificate, key exchange, verify, CCS and Finished" - ); - let scrambled: Vec = records.iter().rev().flat_map(|record| record.iter().copied()).collect(); - server - .handle_packet(&scrambled) - .expect("silently discard scrambled datagram"); - let discarded = drain_outputs(&mut server); - assert!(discarded.packets.is_empty()); - assert!(!discarded.connected); - - client.handle_timeout(deadline).expect("retransmit clean final flight"); - let retry = drain_outputs(&mut client); - assert!(!retry.packets.is_empty()); - let mut final_flight = Vec::new(); - let mut server_connected = false; - for packet in &retry.packets { - server.handle_packet(packet).expect("accept clean retransmission"); - let output = drain_outputs(&mut server); - server_connected |= output.connected; - final_flight.extend(output.packets); - } - assert!(server_connected, "scrambled copy must not poison the receive queue"); - let mut client_connected = false; - for packet in &final_flight { - client.handle_packet(packet).expect("receive server final flight"); - client_connected |= drain_outputs(&mut client).connected; - } - assert!(client_connected); -} - -#[test] -fn dtls12_handles_duplicate_packets() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..80 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - // Deliver originals first - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - // Drain any events triggered by the original delivery before - // injecting duplicates, so the state machine has advanced past - // the flight boundary. - let server_mid = drain_outputs(&mut server); - let client_mid = drain_outputs(&mut client); - server_connected |= server_mid.connected; - client_connected |= client_mid.connected; - - // Now deliver duplicates -- these should be tolerated - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(20); - } - - assert!(client_connected, "Client should connect despite duplicate packets"); - assert!(server_connected, "Server should connect despite duplicate packets"); -} - -#[test] -fn dtls12_handles_out_of_order_packets() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..40 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - // Deliver packets in reverse order - let mut client_packets = client_out.packets.clone(); - let mut server_packets = server_out.packets.clone(); - client_packets.reverse(); - server_packets.reverse(); - - deliver_packets(&client_packets, &mut server); - deliver_packets(&server_packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should connect with out-of-order packets"); - assert!(server_connected, "Server should connect with out-of-order packets"); -} - -#[test] -fn dtls12_replay_window_rejects_old_app_data() { - //! After handshake, send 100 app data messages from client to server. - //! Then replay the very first encrypted packet. The replayed packet - //! should be silently dropped (not delivered as application data again). - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Complete handshake - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..40 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - - // Send the first message and capture its encrypted packet - client.send_application_data(b"message 1").expect("send message 1"); - let first_out = drain_outputs(&mut client); - assert!(!first_out.packets.is_empty(), "Should have packets for message 1"); - let early_packet = first_out.packets[0].clone(); - - // Deliver and verify it arrives - deliver_packets(&first_out.packets, &mut server); - let server_out = drain_outputs(&mut server); - assert_eq!(server_out.app_data.len(), 1, "Server should receive message 1"); - - // Send 99 more messages to advance the replay window well past the first - for i in 2..=100 { - let msg = format!("message {}", i); - client.send_application_data(msg.as_bytes()).expect("send message"); - - let client_out = drain_outputs(&mut client); - deliver_packets(&client_out.packets, &mut server); - let server_out = drain_outputs(&mut server); - assert!(!server_out.app_data.is_empty(), "Server should receive message {}", i); - } - - // Now replay the very first encrypted packet - let _ = server.handle_packet(&early_packet); - let replay_out = drain_outputs(&mut server); - - assert!( - replay_out.app_data.is_empty(), - "Replayed old packet should NOT produce application data (replay protection)" - ); -} - -#[test] -fn dtls12_replay_window_rejects_duplicate_app_data() { - //! After handshake, send one app data message. Deliver it, then deliver - //! the exact same encrypted packet again. Only one copy should be received. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - // Complete handshake - let mut client_connected = false; - let mut server_connected = false; - - for _ in 0..40 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - deliver_packets(&client_out.packets, &mut server); - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - now += Duration::from_millis(10); - } - - assert!(client_connected, "Client should be connected"); - assert!(server_connected, "Server should be connected"); - - // Send a single app data message - client.send_application_data(b"only once").expect("send app data"); - let client_out = drain_outputs(&mut client); - assert!(!client_out.packets.is_empty(), "Should have packets for app data"); - - // Save the encrypted packet for replay - let encrypted_packet = client_out.packets[0].clone(); - - // First delivery -- should produce app data - let _ = server.handle_packet(&encrypted_packet); - let first_out = drain_outputs(&mut server); - assert_eq!( - first_out.app_data.len(), - 1, - "First delivery should produce exactly one app data" - ); - assert_eq!(first_out.app_data[0], b"only once"); - - // Second delivery of exact same packet -- should be silently dropped - let _ = server.handle_packet(&encrypted_packet); - let dup_out = drain_outputs(&mut server); - assert!( - dup_out.app_data.is_empty(), - "Duplicate packet should NOT produce application data (replay protection)" - ); -} - -#[test] -fn dtls12_handles_delayed_burst_delivery() { - //! During handshake, hold all packets for 3 rounds of timeouts, then - //! deliver them all at once in a burst. Verify handshake still completes. - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_connected = false; - let mut server_connected = false; - - // Hold packets for delayed delivery - let mut held_server_packets: Vec> = Vec::new(); - let mut held_client_packets: Vec> = Vec::new(); - let mut hold_rounds = 0; - const HOLD_DURATION: usize = 3; // Hold packets for 3 rounds before delivering - - for _round in 0..200 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - // Collect packets - held_server_packets.extend(server_out.packets.iter().cloned()); - held_client_packets.extend(client_out.packets.iter().cloned()); - - hold_rounds += 1; - - // Deliver burst every HOLD_DURATION rounds - if hold_rounds >= HOLD_DURATION { - // Deliver all held packets at once - for p in &held_client_packets { - let _ = server.handle_packet(p); - } - for p in &held_server_packets { - let _ = client.handle_packet(p); - } - - held_server_packets.clear(); - held_client_packets.clear(); - hold_rounds = 0; - } - - client_connected |= client_out.connected; - server_connected |= server_out.connected; - - if client_connected && server_connected { - // Deliver any remaining packets - for p in &held_client_packets { - let _ = server.handle_packet(p); - } - for p in &held_server_packets { - let _ = client.handle_packet(p); - } - break; - } - - now += Duration::from_millis(20); - } - - assert!(client_connected, "Client should connect despite delayed delivery"); - assert!(server_connected, "Server should connect despite delayed delivery"); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/retransmit.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/retransmit.rs deleted file mode 100644 index 4714f0a0e89..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/dtls12/retransmit.rs +++ /dev/null @@ -1,1243 +0,0 @@ -//! DTLS 1.2 retransmission and duplicate handling tests. - -#![allow(unused)] - -use std::collections::VecDeque; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::{Config, Dtls, Output}; - -use crate::vendor::dimpl::tests::dtls12::common::*; - -struct FinalFlightResend { - client: Dtls, - server: Dtls, - f6_init: Vec>, - f6_resend: Vec>, - stale_epoch0_handshake: Vec, -} - -fn prepare_server_final_flight_resend(max_queue_rx: usize) -> FinalFlightResend { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let mut now = Instant::now(); - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config_client = Arc::new( - Config::builder() - .mtu(115) - .max_queue_rx(max_queue_rx) - .build() - .expect("Failed to build config"), - ); - let config_server = Arc::new( - Config::builder() - .mtu(115) - .max_queue_rx(max_queue_rx) - .build() - .expect("Failed to build config"), - ); - - let mut client = Dtls::new_12(config_client, client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config_server, server_cert, now); - server.set_active(false); - - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let f1 = collect_packets(&mut client); - for packet in f1 { - server.handle_packet(&packet).expect("server recv f1"); - } - - server.handle_timeout(now).expect("server arm flight 2"); - let f2 = collect_packets(&mut server); - assert!(!f2.is_empty(), "server should emit flight 2 after CH"); - for packet in f2 { - client.handle_packet(&packet).expect("client recv f2"); - } - - client.handle_timeout(now).expect("client arm flight 3"); - let f3 = collect_packets(&mut client); - assert!(!f3.is_empty(), "client should emit flight 3 after HVR"); - let stale_epoch0_handshake = - first_record_matching(&f3, 22, 0).expect("flight 3 should contain a plaintext ClientHello record"); - for packet in f3 { - server.handle_packet(&packet).expect("server recv f3"); - } - - server.handle_timeout(now).expect("server arm flight 4"); - let f4 = collect_packets(&mut server); - assert!(!f4.is_empty(), "server should emit flight 4 after CH+cookie"); - for packet in f4 { - client.handle_packet(&packet).expect("client recv f4"); - } - - client.handle_timeout(now).expect("client arm flight 5"); - let f5_init = collect_packets(&mut client); - assert!(!f5_init.is_empty(), "client should emit flight 5 after server flight"); - for packet in &f5_init { - server.handle_packet(packet).expect("server recv f5"); - } - - server.handle_timeout(now).expect("server arm flight 6"); - let f6_init = collect_packets(&mut server); - assert!(!f6_init.is_empty(), "server should emit initial flight 6"); - let f6_init_hdrs = collect_headers(&f6_init); - assert!( - f6_init_hdrs.iter().any(|h| h.ctype == 20 && h.epoch == 0), - "server flight 6 should include epoch 0 CCS" - ); - assert!( - f6_init_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), - "server flight 6 should include epoch 1 Finished" - ); - - trigger_timeout(&mut client, &mut now); - let f5_resend = collect_packets(&mut client); - assert!(!f5_resend.is_empty(), "client should resend flight 5"); - for packet in &f5_resend { - server.handle_packet(packet).expect("server recv f5 resend"); - } - - let f6_resend = collect_packets(&mut server); - assert!( - !f6_resend.is_empty(), - "server should resend flight 6 upon receiving duplicate Finished" - ); - let f6_resend_hdrs = collect_headers(&f6_resend); - assert!( - f6_resend_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), - "resend flight 6 should include epoch 1 Finished" - ); - assert_epochs_and_seq_increased(&f6_init_hdrs, &f6_resend_hdrs); - server.handle_timeout(now).expect("arm server resend cooldown"); - assert!(collect_packets(&mut server).is_empty()); - - FinalFlightResend { - client, - server, - f6_init, - f6_resend, - stale_epoch0_handshake, - } -} - -fn first_record_matching(datagrams: &[Vec], content_type: u8, epoch: u16) -> Option> { - for datagram in datagrams { - let mut offset = 0usize; - while offset + 13 <= datagram.len() { - let len = u16::from_be_bytes([datagram[offset + 11], datagram[offset + 12]]) as usize; - let end = offset + 13 + len; - if end > datagram.len() { - break; - } - - let record_epoch = u16::from_be_bytes([datagram[offset + 3], datagram[offset + 4]]); - if datagram[offset] == content_type && record_epoch == epoch { - return Some(datagram[offset..end].to_vec()); - } - - offset = end; - } - } - - None -} - -#[test] -fn dtls12_client_hello_retransmits_using_advertised_deadlines() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - let certificate = generate_self_signed_certificate().expect("generate client certificate"); - let mut client = Dtls::new_12(Arc::new(Config::default()), certificate, now); - client.set_active(true); - - client.handle_timeout(now).expect("start client handshake"); - let initial_output = drain_outputs(&mut client); - assert!(!initial_output.packets.is_empty(), "client should emit ClientHello"); - - let retransmit_at = initial_output - .timeout - .expect("client should advertise a retransmission deadline"); - assert!(retransmit_at >= now + Duration::from_millis(750)); - assert!(retransmit_at <= now + Duration::from_millis(1250)); - client - .handle_timeout(retransmit_at - Duration::from_nanos(1)) - .expect("before ClientHello retransmission"); - let before_retransmission = drain_outputs(&mut client); - assert!(before_retransmission.packets.is_empty(), "must not retransmit early"); - assert_eq!(before_retransmission.timeout, Some(retransmit_at)); - client.handle_timeout(retransmit_at).expect("retransmit ClientHello"); - let retransmission_output = drain_outputs(&mut client); - - assert!( - !retransmission_output.packets.is_empty(), - "the dropped ClientHello flight was not retransmitted" - ); -} - -#[test] -fn dtls12_resends_each_flight_epoch_and_sequence_increase() { - let now0 = Instant::now(); - let mut now = now0; - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - // Certificates for client and server - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config_client = Arc::new(Config::default()); - let config_server = Arc::new(Config::default()); - - // Client - let mut client = Dtls::new_12(config_client, client_cert.clone(), now); - client.set_active(true); - - // Server - let mut server = Dtls::new_12(config_server, server_cert.clone(), now); - server.set_active(false); - - // FLIGHT 1 (ClientHello): block initial, deliver resend - client.handle_timeout(now).expect("client timeout start"); - // flight_begin reset the flight timer; arm it again so poll_output yields packets - client.handle_timeout(now).expect("client arm flight 1"); - let init1_pkts = collect_packets(&mut client); - let init1_hdrs = collect_headers(&init1_pkts); - trigger_timeout(&mut client, &mut now); - let resend1_pkts = collect_packets(&mut client); - let resend1_hdrs = collect_headers(&resend1_pkts); - assert_epochs_and_seq_increased(&init1_hdrs, &resend1_hdrs); - for p in resend1_pkts { - server.handle_packet(&p).expect("server recv f1"); - } - - // FLIGHT 2 (HelloVerifyRequest): capture initial from server, block, deliver resend - server.handle_timeout(now).expect("server arm flight 2"); - let init2_pkts = collect_packets(&mut server); - assert!(!init2_pkts.is_empty(), "server should emit flight 2 after CH"); - let init2_hdrs = collect_headers(&init2_pkts); - trigger_timeout(&mut server, &mut now); - let resend2_pkts = collect_packets(&mut server); - let resend2_hdrs = collect_headers(&resend2_pkts); - assert_epochs_and_seq_increased(&init2_hdrs, &resend2_hdrs); - for p in resend2_pkts { - client.handle_packet(&p).expect("client recv f2"); - } - - // FLIGHT 3 (ClientHello with cookie): block initial, deliver resend - client.handle_timeout(now).expect("client arm flight 3"); - let init3_pkts = collect_packets(&mut client); - assert!(!init3_pkts.is_empty(), "client should emit flight 3 after HVR"); - let init3_hdrs = collect_headers(&init3_pkts); - trigger_timeout(&mut client, &mut now); - let resend3_pkts = collect_packets(&mut client); - let resend3_hdrs = collect_headers(&resend3_pkts); - assert_epochs_and_seq_increased(&init3_hdrs, &resend3_hdrs); - for p in resend3_pkts { - server.handle_packet(&p).expect("server recv f3"); - } - - // FLIGHT 4 (ServerHello, Certificate, SKE, CR, SHD): block initial, deliver resend - server.handle_timeout(now).expect("server arm flight 4"); - let init4_pkts = collect_packets(&mut server); - assert!(!init4_pkts.is_empty(), "server should emit flight 4 after CH+cookie"); - let init4_hdrs = collect_headers(&init4_pkts); - trigger_timeout(&mut server, &mut now); - let resend4_pkts = collect_packets(&mut server); - let resend4_hdrs = collect_headers(&resend4_pkts); - assert_epochs_and_seq_increased(&init4_hdrs, &resend4_hdrs); - for p in resend4_pkts { - client.handle_packet(&p).expect("client recv f4"); - } - - // FLIGHT 5 (Client cert?, CKX, CV?, CCS, Finished): block initial, deliver resend - client.handle_timeout(now).expect("client arm flight 5"); - let init5_pkts = collect_packets(&mut client); - assert!( - !init5_pkts.is_empty(), - "client should emit flight 5 after server flight" - ); - let init5_hdrs = collect_headers(&init5_pkts); - trigger_timeout(&mut client, &mut now); - let resend5_pkts = collect_packets(&mut client); - let resend5_hdrs = collect_headers(&resend5_pkts); - assert_epochs_and_seq_increased(&init5_hdrs, &resend5_hdrs); - // Additionally, ensure Finished is epoch 1 is present in the set - assert!( - resend5_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), - "client flight 5 should include epoch 1 Finished" - ); - for p in resend5_pkts { - server.handle_packet(&p).expect("server recv f5"); - } - - // FLIGHT 6 (Server CCS, Finished): no resend timer after final flight - server.handle_timeout(now).expect("server arm flight 6"); - let init6_pkts = collect_packets(&mut server); - assert!( - !init6_pkts.is_empty(), - "server should emit flight 6 after client flight 5" - ); - let init6_hdrs = collect_headers(&init6_pkts); - // Final flight should include epoch 1 Finished in the initial transmission - assert!( - init6_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), - "server flight 6 should include epoch 1 Finished" - ); - // Ensure no timer-driven resend occurs after final flight - trigger_timeout(&mut server, &mut now); - let resend6_pkts = collect_packets(&mut server); - assert!(resend6_pkts.is_empty(), "no resend after final flight"); -} - -#[test] -fn dtls12_duplicate_triggers_server_resend_of_final_flight() { - let result = prepare_server_final_flight_resend(Config::default().max_queue_rx()); - assert!(!result.f6_init.is_empty(), "server should emit initial flight 6"); - assert!( - !result.f6_resend.is_empty(), - "server should resend flight 6 upon receiving duplicate Finished" - ); -} - -#[test] -fn dtls12_resend_replaces_pending_handshake_flight_tail() { - let now0 = Instant::now(); - let mut now = now0; - - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config_client = Arc::new(Config::builder().mtu(115).build().expect("Failed to build config")); - let config_server = Arc::new(Config::builder().mtu(115).build().expect("Failed to build config")); - - let expected_initial_headers = { - let mut client = Dtls::new_12(Arc::clone(&config_client), client_cert.clone(), now0); - client.set_active(true); - - let mut server = Dtls::new_12(Arc::clone(&config_server), server_cert.clone(), now0); - server.set_active(false); - - client.handle_timeout(now0).expect("client timeout start"); - client.handle_timeout(now0).expect("client arm flight 1"); - for p in collect_packets(&mut client) { - server.handle_packet(&p).expect("control server recv f1"); - } - - server.handle_timeout(now0).expect("control server arm flight 2"); - for p in collect_packets(&mut server) { - client.handle_packet(&p).expect("control client recv f2"); - } - - client.handle_timeout(now0).expect("control client arm flight 3"); - for p in collect_packets(&mut client) { - server.handle_packet(&p).expect("control server recv f3"); - } - - server.handle_timeout(now0).expect("control server arm flight 4"); - collect_headers(&collect_packets(&mut server)) - }; - assert!( - !expected_initial_headers.is_empty(), - "control flight 4 should contain records" - ); - - let mut client = Dtls::new_12(config_client, client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config_server, server_cert, now); - server.set_active(false); - - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let f1 = collect_packets(&mut client); - for p in f1 { - server.handle_packet(&p).expect("server recv f1"); - } - - server.handle_timeout(now).expect("server arm flight 2"); - let f2 = collect_packets(&mut server); - for p in f2 { - client.handle_packet(&p).expect("client recv f2"); - } - - client.handle_timeout(now).expect("client arm flight 3"); - let f3 = collect_packets(&mut client); - for p in f3 { - server.handle_packet(&p).expect("server recv f3"); - } - - server.handle_timeout(now).expect("server arm flight 4"); - let first_initial = poll_one_packet(&mut server); - let first_initial_headers = parse_records(&first_initial); - assert!( - !first_initial_headers.is_empty(), - "first initial flight 4 packet should contain records" - ); - - trigger_timeout(&mut server, &mut now); - let pending = collect_packets(&mut server); - assert!(!pending.is_empty(), "server should emit flight 4 resend after timeout"); - let pending_headers = collect_headers(&pending); - assert_eq!( - pending_headers.len(), - expected_initial_headers.len(), - "resend should replace the undrained original flight tail instead of appending to it; \ - expected initial {expected_initial_headers:?}, pending {pending_headers:?}" - ); - assert!( - pending_headers - .iter() - .zip(expected_initial_headers.iter()) - .all(|(resend, initial)| resend.ctype == initial.ctype - && resend.epoch == initial.epoch - && resend.seq > initial.seq), - "resend should contain only a fresh copy of the flight, got expected initial \ - {expected_initial_headers:?}, first polled {first_initial_headers:?}, pending \ - {pending_headers:?}" - ); -} - -#[test] -fn dtls12_final_flight_resend_can_share_post_release_appdata_tail() { - let FinalFlightResend { - mut server, - stale_epoch0_handshake, - .. - } = prepare_server_final_flight_resend(Config::default().max_queue_rx()); - - let cooldown = drain_outputs(&mut server).timeout.expect("resend cooldown"); - server - .handle_timeout(cooldown) - .expect("expire previous resend cooldown"); - assert!(collect_packets(&mut server).is_empty()); - - let filler = vec![0x55; 50]; - for i in 0..9 { - server - .send_application_data(&filler) - .unwrap_or_else(|err| panic!("queue filler app data {i}: {err:?}")); - } - server.send_application_data(b"x").expect("queue final small app data"); - - server - .handle_packet(&stale_epoch0_handshake) - .expect("post-release duplicate should trigger final-flight resend"); - - let pending_headers = collect_headers(&collect_packets(&mut server)); - let app_data_records = pending_headers - .iter() - .filter(|header| header.ctype == 23 && header.epoch == 1) - .count(); - assert_eq!( - app_data_records, 10, - "post-release final-flight resend must preserve queued app-data records, got \ - {pending_headers:?}" - ); - assert!( - pending_headers - .iter() - .any(|header| header.ctype == 22 && header.epoch == 1), - "server should retain and resend encrypted final-flight Finished, got \ - {pending_headers:?}" - ); -} - -#[test] -fn dtls12_late_retransmitted_ccs_does_not_pin_receive_queue() { - //! After the handshake, a peer can still retransmit its final flight. The - //! epoch-0 ChangeCipherSpec in that flight must be ignored; otherwise it - //! remains unhandled and prevents handled app-data records behind it from - //! being purged. - - const RX_QUEUE_LIMIT: usize = 8; - - let FinalFlightResend { - mut client, - mut server, - f6_init, - f6_resend, - stale_epoch0_handshake: _, - } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); - - deliver_packets(&f6_init, &mut client); - let client_connected = drain_outputs(&mut client).connected; - assert!(client_connected, "client should connect after initial flight 6"); - - for packet in &f6_resend { - client - .handle_packet(packet) - .expect("late final-flight resend should be tolerated"); - } - - for i in 0..=RX_QUEUE_LIMIT { - let msg = format!("post-ccs app data {i}"); - server.send_application_data(msg.as_bytes()).expect("send app data"); - - let server_out = drain_outputs(&mut server); - assert!(!server_out.packets.is_empty(), "server should emit app-data packets"); - - for packet in &server_out.packets { - client - .handle_packet(packet) - .expect("late CCS must not make receive queue fill"); - } - - let client_out = drain_outputs(&mut client); - assert!( - client_out.app_data.iter().any(|received| received == msg.as_bytes()), - "client should receive app data after late CCS" - ); - } -} - -#[test] -fn dtls12_late_epoch0_handshake_does_not_pin_receive_queue() { - //! After peer encryption is enabled, plaintext epoch-0 handshake records are - //! unauthenticated and no longer actionable. They must be ignored for the - //! same queue-pinning reason as late CCS records. - - const RX_QUEUE_LIMIT: usize = 8; - - let FinalFlightResend { - mut client, - mut server, - f6_init, - f6_resend: _, - stale_epoch0_handshake: _, - } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); - - deliver_packets(&f6_init, &mut client); - let client_connected = drain_outputs(&mut client).connected; - assert!(client_connected, "client should connect after initial flight 6"); - - client - .handle_packet(&malformed_epoch0_handshake_packet(0x7fff)) - .expect("late epoch-0 handshake should be tolerated"); - - for i in 0..=RX_QUEUE_LIMIT { - let msg = format!("post-handshake app data {i}"); - server.send_application_data(msg.as_bytes()).expect("send app data"); - - let server_out = drain_outputs(&mut server); - assert!(!server_out.packets.is_empty(), "server should emit app-data packets"); - - for packet in &server_out.packets { - client - .handle_packet(packet) - .expect("late epoch-0 handshake must not make receive queue fill"); - } - - let client_out = drain_outputs(&mut client); - assert!( - client_out.app_data.iter().any(|received| received == msg.as_bytes()), - "client should receive app data after late epoch-0 handshake" - ); - } -} - -fn malformed_epoch0_handshake_packet(sequence_number: u64) -> Vec { - let sequence_bytes = sequence_number.to_be_bytes(); - let mut packet = Vec::with_capacity(14); - packet.push(22); - packet.extend_from_slice(&[0xfe, 0xfd]); - packet.extend_from_slice(&0u16.to_be_bytes()); - packet.extend_from_slice(&sequence_bytes[2..]); - packet.extend_from_slice(&1u16.to_be_bytes()); - packet.push(0xff); - packet -} - -fn append_record(mut packet: Vec, record: &[u8]) -> Vec { - packet.extend_from_slice(record); - packet -} - -fn poll_one_packet(endpoint: &mut Dtls) -> Vec { - let mut buf = vec![0u8; 2048]; - loop { - match endpoint.poll_output(&mut buf) { - Output::Packet(packet) => return packet.to_vec(), - Output::Timeout(_) => panic!("expected queued packet"), - _ => {} - } - } -} - -#[test] -fn dtls12_late_epoch0_handshake_trailing_app_data_does_not_pin_receive_queue() { - //! A stale epoch-0 handshake can arrive behind a valid encrypted record in - //! the same datagram. The encrypted app data should still be delivered, and - //! the stale plaintext handshake must not keep that datagram in the queue. - - const RX_QUEUE_LIMIT: usize = 8; - - let FinalFlightResend { - mut client, - mut server, - f6_init, - f6_resend: _, - stale_epoch0_handshake, - } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); - - deliver_packets(&f6_init, &mut client); - let client_connected = drain_outputs(&mut client).connected; - assert!(client_connected, "client should connect after initial flight 6"); - - for i in 0..=RX_QUEUE_LIMIT { - let msg = format!("post-handshake app data {i}"); - server.send_application_data(msg.as_bytes()).expect("send app data"); - - let server_out = drain_outputs(&mut server); - assert!(!server_out.packets.is_empty(), "server should emit app-data packets"); - - for packet in server_out.packets { - let packet = if i == 0 { - append_record(packet, &stale_epoch0_handshake) - } else { - packet - }; - client - .handle_packet(&packet) - .expect("trailing late epoch-0 handshake must not make receive queue fill"); - } - - let client_out = drain_outputs(&mut client); - assert!( - client_out.app_data.iter().any(|received| received == msg.as_bytes()), - "client should receive app data after trailing late epoch-0 handshake" - ); - } -} - -#[test] -fn dtls12_handshake_completes_after_packet_loss() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = dtls12_config(); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - let mut drop_next_client_packet = true; // Drop first ClientHello - - for i in 0..60 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - // Simulate packet loss: drop first client packet batch - if !client_out.packets.is_empty() && drop_next_client_packet { - drop_next_client_packet = false; - // Don't deliver client packets this round - } else { - deliver_packets(&client_out.packets, &mut server); - } - - deliver_packets(&server_out.packets, &mut client); - - if client_connected && server_connected { - break; - } - - // Advance time to trigger retransmissions periodically - if i % 5 == 4 { - now += Duration::from_secs(2); - } else { - now += Duration::from_millis(10); - } - } - - assert!(client_connected, "Client should connect despite initial packet loss"); - assert!(server_connected, "Server should connect despite initial packet loss"); -} - -#[test] -fn dtls12_handshake_completes_with_early_packet_loss() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - // Use a config with more retries to handle packet loss - let config = Arc::new( - Config::builder() - .flight_retries(8) - .build() - .expect("Failed to build config"), - ); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - - // Drop first 2 client packets and first 2 server packets to test retransmission - let mut client_packets_to_drop = 2; - let mut server_packets_to_drop = 2; - - for i in 0..60 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - // Deliver client packets, dropping first N - for packet in &client_out.packets { - if client_packets_to_drop > 0 { - client_packets_to_drop -= 1; - } else { - let _ = server.handle_packet(packet); - } - } - - // Deliver server packets, dropping first N - for packet in &server_out.packets { - if server_packets_to_drop > 0 { - server_packets_to_drop -= 1; - } else { - let _ = client.handle_packet(packet); - } - } - - if client_connected && server_connected { - break; - } - - // Trigger retransmissions periodically - if i % 5 == 4 { - now += Duration::from_secs(2); - } else { - now += Duration::from_millis(10); - } - } - - assert!(client_connected, "Client should connect despite early packet loss"); - assert!(server_connected, "Server should connect despite early packet loss"); -} - -#[test] -fn dtls12_survives_random_packet_loss_pattern() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - - let config = Arc::new( - Config::builder() - .flight_retries(8) - .build() - .expect("Failed to build config"), - ); - - let mut now = Instant::now(); - - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - - let mut client_connected = false; - let mut server_connected = false; - let mut total_dropped = 0; - let mut total_delivered = 0; - - // Deterministic pattern: drop every 3rd packet across both directions - let mut global_packet_index = 0usize; - - for i in 0..100 { - client.handle_timeout(now).expect("client timeout"); - server.handle_timeout(now).expect("server timeout"); - - let client_out = drain_outputs(&mut client); - let server_out = drain_outputs(&mut server); - - if client_out.connected { - client_connected = true; - } - if server_out.connected { - server_connected = true; - } - - for packet in &client_out.packets { - if global_packet_index % 3 == 2 { - total_dropped += 1; - } else { - let _ = server.handle_packet(packet); - total_delivered += 1; - } - global_packet_index += 1; - } - - for packet in &server_out.packets { - if global_packet_index % 3 == 2 { - total_dropped += 1; - } else { - let _ = client.handle_packet(packet); - total_delivered += 1; - } - global_packet_index += 1; - } - - if client_connected && server_connected { - break; - } - - // Trigger retransmissions periodically - if i % 5 == 4 { - now += Duration::from_secs(2); - } else { - now += Duration::from_millis(10); - } - } - - assert!(client_connected, "Client should connect despite every-3rd-packet loss"); - assert!(server_connected, "Server should connect despite every-3rd-packet loss"); - assert!(total_dropped > 0, "Test should have dropped at least one packet"); -} - -#[test] -fn dtls12_retransmit_exponential_backoff() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - - // Use a known start RTO and enough retries to observe backoff - let config = Arc::new( - Config::builder() - .flight_start_rto(Duration::from_secs(1)) - .flight_retries(4) - .handshake_timeout(Duration::from_secs(120)) - .build() - .expect("Failed to build config"), - ); - - let mut now = Instant::now(); - let mut client = Dtls::new_12(config, client_cert, now); - client.set_active(true); - - // No server -- we never deliver packets. - // Start the handshake. - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let _ = collect_packets(&mut client); - - // Record successive timeout values returned by poll_output. - // Each handle_timeout that fires the flight timer should produce a new, - // larger timeout. - let mut timeouts: Vec = Vec::new(); - - // Collect the first timeout - let mut buf = vec![0u8; 2048]; - loop { - if let Output::Timeout(t) = client.poll_output(&mut buf) { - timeouts.push(t); - break; - } - } - - // Fire successive timeouts, never delivering packets - for _ in 0..3 { - // Advance past the reported timeout - now = *timeouts.last().expect("should have a timeout") + Duration::from_millis(1); - client.handle_timeout(now).expect("client handle_timeout"); - let _ = collect_packets(&mut client); - - // Collect the next timeout - loop { - if let Output::Timeout(t) = client.poll_output(&mut buf) { - timeouts.push(t); - break; - } - } - } - - // Verify we collected multiple timeout values - assert!( - timeouts.len() >= 4, - "Should have at least 4 timeout values, got {}", - timeouts.len() - ); - - // Verify each successive interval is strictly larger (exponential backoff). - // Interval[i] = timeout[i+1] - timeout[i] should be increasing. - let mut intervals: Vec = Vec::new(); - for pair in timeouts.windows(2) { - let interval = pair[1].duration_since(pair[0]); - intervals.push(interval); - } - - for pair in intervals.windows(2) { - assert!( - pair[1] > pair[0], - "Backoff intervals should increase: {:?} should be > {:?}", - pair[1], - pair[0] - ); - } -} - -#[test] -fn dtls12_handshake_timeout_aborts() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - - // Configure a very short handshake timeout so we hit it quickly - let config = Arc::new( - Config::builder() - .handshake_timeout(Duration::from_secs(5)) - .flight_start_rto(Duration::from_secs(1)) - .flight_retries(10) // Many retries, but the handshake timeout will fire first - .build() - .expect("Failed to build config"), - ); - - let mut now = Instant::now(); - let mut client = Dtls::new_12(config, client_cert, now); - client.set_active(true); - - // Start the handshake - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let _ = collect_packets(&mut client); - - // Keep triggering timeouts without ever delivering packets. - // The handshake_timeout (5s) should eventually cause handle_timeout to return an error. - let mut got_timeout_error = false; - for _ in 0..100 { - now += Duration::from_secs(1); - match client.handle_timeout(now) { - Ok(()) => { - // Drain any packets to keep the state machine consistent - let _ = collect_packets(&mut client); - } - Err(e) => { - let msg = format!("{}", e); - assert!(msg.contains("timeout"), "Expected timeout error, got: {}", msg); - got_timeout_error = true; - break; - } - } - } - - assert!( - got_timeout_error, - "Client should report a timeout error when handshake_timeout is exceeded" - ); -} - -/// Before the peer is confirmed (the legitimate retransmission window), a stale -/// plaintext ClientHello still triggers a flight-6 resend, so a lost flight 6 -/// recovers. This is the contrast case to the post-confirmation suppression -/// below: the gate must not break legitimate retransmission. -#[test] -fn dtls12_stale_client_hello_before_peer_confirmed_triggers_resend() { - const RX_QUEUE_LIMIT: usize = 8; - let FinalFlightResend { - mut server, - stale_epoch0_handshake, - .. - } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); - - let cooldown = drain_outputs(&mut server).timeout.expect("resend cooldown"); - server - .handle_timeout(cooldown) - .expect("expire previous resend cooldown"); - assert!(collect_packets(&mut server).is_empty()); - - // The server has sent flight 6 but has no confirmation the client received - // it (no authenticated application data has arrived). A stale ClientHello - // here means "peer still needs my flight" and must drive a resend. - server - .handle_packet(&stale_epoch0_handshake) - .expect("stale ClientHello must be tolerated"); - let resend = collect_packets(&mut server); - - assert!( - !resend.is_empty(), - "server must resend flight 6 on a stale ClientHello while the peer is unconfirmed" - ); -} - -/// Once the peer is confirmed to have completed the handshake (the server has -/// received authenticated application data from the client), a replayed -/// plaintext ClientHello is unauthenticated noise and must not trigger a flight -/// retransmission. This closes the resend-amplification window that an attacker -/// could otherwise drive with spoofed epoch-0 handshakes. -#[test] -fn dtls12_stale_client_hello_after_peer_confirmed_triggers_no_resend() { - const RX_QUEUE_LIMIT: usize = 8; - let FinalFlightResend { - mut client, - mut server, - f6_resend, - stale_epoch0_handshake, - .. - } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); - - // Finish the handshake: deliver the server's resent flight 6 to the client. - deliver_packets(&f6_resend, &mut client); - assert!( - drain_outputs(&mut client).connected, - "client should connect once it receives flight 6" - ); - - // Client application data is the server's signal that the client completed - // (it could only send it after receiving flight 6). - client - .send_application_data(b"client-app-data") - .expect("client sends application data"); - let client_app = collect_packets(&mut client); - assert!(!client_app.is_empty(), "client should emit app-data packet"); - deliver_packets(&client_app, &mut server); - let server_out = drain_outputs(&mut server); - assert_eq!( - server_out.app_data, - vec![b"client-app-data".to_vec()], - "server should receive the client's application data" - ); - - // Replay the stale plaintext ClientHello at the now-confirmed server. - server - .handle_packet(&stale_epoch0_handshake) - .expect("stale ClientHello must be tolerated"); - let resend = collect_packets(&mut server); - - assert!( - resend.is_empty(), - "server must not resend its flight after the client is confirmed connected" - ); -} - -fn forged_epoch1_app_data() -> Vec { - // A DTLS 1.2 record header advertising epoch-1 ApplicationData with a - // garbage (undecryptable) body. The content type lives in the cleartext - // header, so this looks like app data before anything is decrypted. - let mut rec = Vec::new(); - rec.push(23); // ContentType::ApplicationData - rec.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 - rec.extend_from_slice(&1u16.to_be_bytes()); // epoch 1 - rec.extend_from_slice(&[0, 0, 0, 0, 0, 1]); // 48-bit sequence number - rec.extend_from_slice(&2u16.to_be_bytes()); // fragment length - rec.extend_from_slice(&[0xAA, 0xBB]); // garbage fragment - rec -} - -/// A forged epoch-1 application-data record arriving before peer encryption is -/// enabled must not confirm the peer handshake. The record advertises -/// ApplicationData in its cleartext header and is queued undecrypted, so without -/// the authentication guard it would falsely mark the peer confirmed and suppress -/// the flight-6 resend that a genuinely lost flight needs. -#[test] -fn dtls12_forged_epoch1_appdata_before_encryption_does_not_confirm_peer() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let mut now = Instant::now(); - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - let config_client = Arc::new(Config::builder().mtu(115).build().expect("config")); - let config_server = Arc::new(Config::builder().mtu(115).build().expect("config")); - - let mut client = Dtls::new_12(config_client, client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config_server, server_cert, now); - server.set_active(false); - - // Flight 1: ClientHello. - client.handle_timeout(now).expect("client timeout start"); - client.handle_timeout(now).expect("client arm flight 1"); - let f1 = collect_packets(&mut client); - for packet in &f1 { - server.handle_packet(packet).expect("server recv f1"); - } - - // Flight 2: HelloVerifyRequest. - server.handle_timeout(now).expect("server arm flight 2"); - let f2 = collect_packets(&mut server); - assert!(!f2.is_empty(), "server should emit flight 2"); - for packet in &f2 { - client.handle_packet(packet).expect("client recv f2"); - } - - // Flight 3: ClientHello with cookie. - client.handle_timeout(now).expect("client arm flight 3"); - let f3 = collect_packets(&mut client); - assert!(!f3.is_empty(), "client should emit flight 3"); - for packet in &f3 { - server.handle_packet(packet).expect("server recv f3"); - } - - // Flight 4: server hello flight. - server.handle_timeout(now).expect("server arm flight 4"); - let f4 = collect_packets(&mut server); - assert!(!f4.is_empty(), "server should emit flight 4"); - for packet in &f4 { - client.handle_packet(packet).expect("client recv f4"); - } - - // Inject the forged epoch-1 app-data record while the server still has peer - // encryption disabled (it has not seen the client CCS yet). - let _ = server.handle_packet(&forged_epoch1_app_data()); - let _ = drain_outputs(&mut server); - - // Flight 5: CKE, CCS, Finished. Server completes and emits flight 6. - client.handle_timeout(now).expect("client arm flight 5"); - let f5 = collect_packets(&mut client); - assert!(!f5.is_empty(), "client should emit flight 5"); - for packet in &f5 { - server.handle_packet(packet).expect("server recv f5"); - } - server.handle_timeout(now).expect("server arm flight 6"); - let f6_init = collect_packets(&mut server); - assert!(!f6_init.is_empty(), "server should emit flight 6"); - - // Drop flight 6. The client retransmits flight 5 on timeout. - trigger_timeout(&mut client, &mut now); - let f5_resend = collect_packets(&mut client); - assert!(!f5_resend.is_empty(), "client should resend flight 5"); - for packet in &f5_resend { - server.handle_packet(packet).expect("server recv f5 resend"); - } - - // The forged record must not have confirmed the peer, so the duplicate - // flight 5 still drives a flight-6 resend. - let f6_resend = collect_packets(&mut server); - assert!( - !f6_resend.is_empty(), - "forged pre-encryption app data must not confirm the peer; flight 6 must still resend" - ); -} - -/// A byte-identical duplicate of an epoch-1 datagram that arrives before the -/// server has processed the client CCS must be dropped, not panic. Before peer -/// encryption is enabled, epoch-1 records are queued undecrypted and bypass the -/// replay window, so the duplicate reaches the receive queue. Here the first -/// flight-5 datagram is lost, which holds the server short of the CCS while the -/// Finished datagram is parked; a network-duplicated copy of it then arrives. -#[test] -fn dtls12_duplicate_epoch1_before_ccs_is_dropped() { - use crate::vendor::dimpl::certificate::generate_self_signed_certificate; - - let now = Instant::now(); - let client_cert = generate_self_signed_certificate().expect("gen client cert"); - let server_cert = generate_self_signed_certificate().expect("gen server cert"); - // Small MTU so the epoch-1 Finished leads its own datagram. - let config_client = Arc::new(Config::builder().mtu(115).build().expect("config")); - let config_server = Arc::new(Config::builder().mtu(115).build().expect("config")); - - let mut client = Dtls::new_12(config_client, client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config_server, server_cert, now); - server.set_active(false); - - // Poll after every packet and retain any response emitted during polling. - let deliver_flight = |endpoint: &mut Dtls, flight: &[Vec]| { - let mut response = Vec::new(); - for packet in flight { - endpoint.handle_packet(packet).expect("receive flight"); - response.extend(collect_packets(endpoint)); - } - response - }; - - server.handle_timeout(now).expect("initialize server random"); - assert!(collect_packets(&mut server).is_empty()); - - // Flights 1-5: ClientHello, HelloVerifyRequest, ClientHello with cookie, - // server hello flight, then Certificate/CKE/CertificateVerify/CCS/Finished. - client.handle_timeout(now).expect("client timeout start"); - let f1 = collect_packets(&mut client); - assert!(!f1.is_empty(), "client should emit flight 1"); - let f2 = deliver_flight(&mut server, &f1); - assert!(!f2.is_empty(), "server should emit flight 2"); - let f3 = deliver_flight(&mut client, &f2); - assert!(!f3.is_empty(), "client should emit flight 3"); - let f4 = deliver_flight(&mut server, &f3); - assert!(!f4.is_empty(), "server should emit flight 4"); - let f5 = deliver_flight(&mut client, &f4); - let finished = f5 - .iter() - .find(|d| parse_records(d).first().map(|h| h.epoch) == Some(1)) - .expect("flight 5 should have a datagram led by the epoch-1 Finished") - .clone(); - - // Lose the first flight-5 datagram. The server cannot reach the CCS, so the - // Finished stays queued undecrypted. - for packet in &f5[1..] { - server.handle_packet(packet).expect("server recv f5"); - drain_outputs(&mut server); - } - - // A byte-identical duplicate of the Finished datagram arrives. - server.handle_packet(&finished).expect("server recv duplicate Finished"); - drain_outputs(&mut server); - - // The client retransmits flight 5 and the handshake completes. Drain each - // mutation immediately, retaining responses and connection notifications. - let mut pending = VecDeque::new(); - let mut connected = [false; 2]; - for attempt in 1..=60 { - let now = now + Duration::from_secs(attempt); - for (index, endpoint) in [&mut client, &mut server].into_iter().enumerate() { - endpoint.handle_timeout(now).expect("recovery timeout"); - let output = drain_outputs(endpoint); - connected[index] |= output.connected; - pending.extend(output.packets.into_iter().map(|packet| (1 - index, packet))); - } - while let Some((index, packet)) = pending.pop_front() { - let endpoint = if index == 0 { &mut client } else { &mut server }; - endpoint.handle_packet(&packet).expect("recovery packet"); - let output = drain_outputs(endpoint); - connected[index] |= output.connected; - pending.extend(output.packets.into_iter().map(|packet| (1 - index, packet))); - } - if connected.iter().all(|connected| *connected) { - return; - } - } - panic!("handshake should complete after retransmission"); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/mod.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/mod.rs deleted file mode 100644 index e19e1ae763d..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! dimpl's integration tests, run against the vendored module. - -mod client_hello_recovery; -#[path = "dtls12/main.rs"] -mod dtls12; -mod pre_encryption; -mod premature_records; -mod timing; diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/pre_encryption.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/pre_encryption.rs deleted file mode 100644 index b8d8cad4700..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/pre_encryption.rs +++ /dev/null @@ -1,205 +0,0 @@ -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::certificate::generate_self_signed_certificate; -use crate::vendor::dimpl::{Config, Dtls, Error, Output, UnexpectedMessageError}; - -const UNAUTHENTICATED_INPUT: &[u8] = b"unauthenticated input"; - -#[derive(Default)] -struct Observed { - packets: Vec>, - connected: bool, - app_data: Vec>, -} - -fn drain(endpoint: &mut Dtls, observed: &mut Observed) { - let mut buffer = [0; 2048]; - loop { - match endpoint.poll_output(&mut buffer) { - Output::Packet(packet) => observed.packets.push(packet.to_vec()), - Output::Connected => observed.connected = true, - Output::ApplicationData(data) => observed.app_data.push(data.to_vec()), - Output::Timeout(_) => return, - _ => {} - } - } -} - -fn deliver_packets(source: &mut Observed, destination: &mut Dtls, observed: &mut Observed) { - for packet in std::mem::take(&mut source.packets) { - // A peer may send CCS and Finished in separate UDP datagrams. Keep - // that legal ordering so CCS enables encryption before Finished is - // queued, rather than both arriving in one coalesced datagram. - let mut remaining = packet.as_slice(); - while !remaining.is_empty() { - let length = 13 + u16::from_be_bytes([remaining[11], remaining[12]]) as usize; - destination.handle_packet(&remaining[..length]).expect("receive record"); - drain(destination, observed); - remaining = &remaining[length..]; - } - } -} - -fn pre_encryption_record(epoch: u16, sequence: u16) -> Vec { - let mut packet = Vec::new(); - packet.push(23); // ApplicationData - packet.extend_from_slice(&[0xfe, 0xfd]); - packet.extend_from_slice(&epoch.to_be_bytes()); - packet.extend_from_slice(&(sequence as u64).to_be_bytes()[2..]); - packet.extend_from_slice(&(UNAUTHENTICATED_INPUT.len() as u16).to_be_bytes()); - packet.extend_from_slice(UNAUTHENTICATED_INPUT); - packet -} - -fn assert_pre_encryption_record_is_not_delivered(epoch: u16) { - let mut now = Instant::now(); - let config = Arc::new(Config::builder().build().expect("config")); - let client_cert = generate_self_signed_certificate().expect("client certificate"); - let server_cert = generate_self_signed_certificate().expect("server certificate"); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_out = Observed::default(); - let mut server_out = Observed::default(); - - let packet = pre_encryption_record(epoch, 0x1234); - let mut record_injected = false; - - for _ in 0..40 { - client.handle_timeout(now).expect("client timeout"); - drain(&mut client, &mut client_out); - server.handle_timeout(now).expect("server timeout"); - drain(&mut server, &mut server_out); - deliver_packets(&mut client_out, &mut server, &mut server_out); - if !record_injected - && server_out - .packets - .iter() - .any(|packet| packet.first() == Some(&22) && packet.get(13) == Some(&2)) - { - // Inject after ServerHello: DTLS 1.2's HelloVerifyRequest resets - // the receive queue, so input before the cookie retry is discarded. - server.handle_packet(&packet).expect("receive before CCS"); - drain(&mut server, &mut server_out); - assert!(server_out.app_data.is_empty()); - record_injected = true; - } - deliver_packets(&mut server_out, &mut client, &mut client_out); - if client_out.connected && server_out.connected { - break; - } - now += Duration::from_millis(10); - } - assert!(record_injected, "input must reach the pre-encryption queue"); - assert!(client_out.connected && server_out.connected, "handshake completes"); - assert_eq!( - server_out.app_data, - Vec::>::new(), - "pre-encryption epoch {epoch} bytes must be authenticated before delivery" - ); - - client.send_application_data(b"authenticated").expect("send"); - drain(&mut client, &mut client_out); - deliver_packets(&mut client_out, &mut server, &mut server_out); - assert_eq!(server_out.app_data, [b"authenticated".to_vec()]); -} - -#[test] -fn dtls12_pre_encryption_unknown_epoch_is_not_application_data() { - assert_pre_encryption_record_is_not_delivered(2); -} - -fn split_records(packets: Vec>) -> Vec> { - let mut records = Vec::new(); - for packet in packets { - let mut remaining = packet.as_slice(); - while !remaining.is_empty() { - let length = 13 + u16::from_be_bytes([remaining[11], remaining[12]]) as usize; - records.push(remaining[..length].to_vec()); - remaining = &remaining[length..]; - } - } - records -} - -fn assert_handshake_completion_rejects_old_epoch(to_server: bool) { - let now = Instant::now(); - let config = Arc::new(Config::builder().use_server_cookie(false).build().expect("config")); - let client_cert = generate_self_signed_certificate().expect("client certificate"); - let server_cert = generate_self_signed_certificate().expect("server certificate"); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - let mut server = Dtls::new_12(config, server_cert, now); - client.set_active(true); - server.set_active(false); - let mut client_out = Observed::default(); - let mut server_out = Observed::default(); - server.handle_timeout(now).expect("start server"); - drain(&mut server, &mut server_out); - client.handle_timeout(now).expect("start client"); - drain(&mut client, &mut client_out); - if !to_server { - deliver_packets(&mut client_out, &mut server, &mut server_out); - } - let (source, destination, observed) = if to_server { - (&mut client_out, &mut server, &mut server_out) - } else { - (&mut server_out, &mut client, &mut client_out) - }; - let message_type = if to_server { 1 } else { 2 }; - let packet = source - .packets - .iter() - .find(|packet| packet[0] == 22 && packet[13] == message_type) - .expect("plaintext hello flight"); - let length = 13 + u16::from_be_bytes([packet[11], packet[12]]) as usize; - let mut invalid = packet[..length].to_vec(); - // Buffer a future message. A high record sequence lets DTLS 1.2's CCS - // sort ahead of it, so the genuine handshake can reach completion. - invalid[5..11].copy_from_slice(&0xff00u64.to_be_bytes()[2..]); - invalid[17..19].copy_from_slice(&0xff00u16.to_be_bytes()); - let result = destination.handle_packet(&invalid); - drain(destination, observed); - result.expect("buffer future plaintext while the handshake is in progress"); - - // Deliver records separately so enabling encryption does not reparse and - // discard the buffered plaintext alongside a coalesced protected flight. - for _ in 0..10 { - for to_server_now in [true, false] { - let (source, destination, observed) = if to_server_now { - (&mut client_out, &mut server, &mut server_out) - } else { - (&mut server_out, &mut client, &mut client_out) - }; - for packet in split_records(std::mem::take(&mut source.packets)) { - let result = destination.handle_packet(&packet); - drain(destination, observed); - if result.is_err() { - assert_eq!(to_server_now, to_server); - assert_eq!( - result, - Err(Error::UnexpectedMessage(UnexpectedMessageError::UnexpectedEpoch)) - ); - assert!(!observed.connected, "must reject before emitting Connected"); - assert!( - packet[3..5] == [0, 1], - "error must occur at completion, after receiving protected Finished" - ); - return; - } - } - } - } - panic!("old-epoch record survived the transition to application data"); -} - -#[test] -fn dtls12_client_errors_on_old_epoch_at_handshake_completion() { - assert_handshake_completion_rejects_old_epoch(false); -} - -#[test] -fn dtls12_server_errors_on_old_epoch_at_handshake_completion() { - assert_handshake_completion_rejects_old_epoch(true); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/premature_records.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/premature_records.rs deleted file mode 100644 index eebca7ed740..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/premature_records.rs +++ /dev/null @@ -1,370 +0,0 @@ -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::certificate::generate_self_signed_certificate; -use crate::vendor::dimpl::{Config, Dtls, Output}; - -const UNAUTHENTICATED_INPUT: &[u8] = b"unauthenticated input"; - -#[derive(Default)] -struct Observed { - packets: Vec>, - connected: bool, - app_data: Vec>, -} - -fn drain(endpoint: &mut Dtls, observed: &mut Observed) { - let mut buffer = [0; 2048]; - loop { - match endpoint.poll_output(&mut buffer) { - Output::Packet(packet) => observed.packets.push(packet.to_vec()), - Output::Connected => observed.connected = true, - Output::ApplicationData(data) => observed.app_data.push(data.to_vec()), - Output::Timeout(_) => return, - _ => {} - } - } -} - -fn deliver_packets(source: &mut Observed, destination: &mut Dtls, observed: &mut Observed) { - for packet in std::mem::take(&mut source.packets) { - destination.handle_packet(&packet).expect("receive packet"); - drain(destination, observed); - } -} - -fn retry_handshake( - mut now: Instant, - client: &mut Dtls, - server: &mut Dtls, - client_out: &mut Observed, - server_out: &mut Observed, -) { - for _ in 0..10 { - now += Duration::from_secs(1); - client.handle_timeout(now).expect("client retry"); - drain(client, client_out); - server.handle_timeout(now).expect("server retry"); - drain(server, server_out); - deliver_packets(client_out, server, server_out); - deliver_packets(server_out, client, client_out); - if client_out.connected && server_out.connected { - return; - } - } - panic!("handshake must recover through retransmission"); -} - -fn split_records(packets: &[Vec]) -> Vec> { - let mut records = Vec::new(); - for packet in packets { - let mut remaining = packet.as_slice(); - while !remaining.is_empty() { - let length = 13 + u16::from_be_bytes([remaining[11], remaining[12]]) as usize; - records.push(remaining[..length].to_vec()); - remaining = &remaining[length..]; - } - } - records -} - -fn pre_encryption_record(epoch: u16, sequence: u16) -> Vec { - let mut packet = Vec::new(); - packet.push(23); // ApplicationData - packet.extend_from_slice(&[0xfe, 0xfd]); - packet.extend_from_slice(&epoch.to_be_bytes()); - packet.extend_from_slice(&(sequence as u64).to_be_bytes()[2..]); - packet.extend_from_slice(&(UNAUTHENTICATED_INPUT.len() as u16).to_be_bytes()); - packet.extend_from_slice(UNAUTHENTICATED_INPUT); - packet -} - -fn assert_pre_encryption_records_need_no_queue_slot(capacity: usize) { - let now = Instant::now(); - let config = Arc::new(Config::builder().max_queue_rx(capacity).build().expect("config")); - let certificate = generate_self_signed_certificate().expect("certificate"); - let mut server = Dtls::new_12(config, certificate, now); - server.set_active(false); - let mut observed = Observed::default(); - let epoch = 1; - let packet = pre_encryption_record(epoch, 0x1234); - server.handle_packet(&packet).expect("discard premature record"); - drain(&mut server, &mut observed); - - // Both duplicate and distinct premature records are dropped. Neither can - // consume a queue slot or cause the duplicate-epoch-1 panic. - for sequence in [0x1234, 0x1235, 0x1234] { - server - .handle_packet(&pre_encryption_record(epoch, sequence)) - .expect("discard premature record without filling the queue"); - drain(&mut server, &mut observed); - } - assert!(observed.packets.is_empty()); - assert!(observed.app_data.is_empty()); -} - -#[test] -fn dtls12_pre_encryption_duplicate_at_queue_capacity_is_dropped() { - assert_pre_encryption_records_need_no_queue_slot(1); -} - -#[test] -fn dtls12_premature_duplicate_does_not_panic() { - assert_pre_encryption_records_need_no_queue_slot(8); -} - -#[test] -fn dtls12_premature_short_copy_does_not_block_retransmission() { - let now = Instant::now(); - let config = Arc::new( - Config::builder() - .mtu(200) - .use_server_cookie(false) - .build() - .expect("config"), - ); - let client_cert = generate_self_signed_certificate().expect("client certificate"); - let server_cert = generate_self_signed_certificate().expect("server certificate"); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_out = Observed::default(); - let mut server_out = Observed::default(); - server.handle_timeout(now).expect("server timeout"); - drain(&mut server, &mut server_out); - client.handle_timeout(now).expect("client timeout"); - drain(&mut client, &mut client_out); - deliver_packets(&mut client_out, &mut server, &mut server_out); - deliver_packets(&mut server_out, &mut client, &mut client_out); - - let flight = split_records(&std::mem::take(&mut client_out.packets)); - let finished = flight - .iter() - .find(|record| record[0] == 22 && record[3..5] == [0, 1]) - .expect("client emits epoch-1 Finished"); - // A too-short protected record is discarded without a fatal authentication - // error. It cannot establish the identity of the genuine Finished before CCS. - let mut short_copy = finished[..13].to_vec(); - short_copy[0] = 23; - short_copy[11..13].copy_from_slice(&2u16.to_be_bytes()); - short_copy.extend_from_slice(&[0xaa, 0xbb]); - server.handle_packet(&short_copy).expect("discard premature short copy"); - drain(&mut server, &mut server_out); - server - .handle_packet(finished) - .expect("discard premature clean Finished"); - drain(&mut server, &mut server_out); - // CCS enables decryption, but the prematurely received Finished was dropped. - for record in flight.iter().filter(|record| record[3..5] == [0, 0]) { - server.handle_packet(record).expect("receive clean flight"); - drain(&mut server, &mut server_out); - } - assert!(!server_out.connected, "early Finished was discarded"); - retry_handshake(now, &mut client, &mut server, &mut client_out, &mut server_out); -} - -#[test] -fn dtls12_pre_encryption_handshake_ciphertext_cannot_advance_the_handshake() { - let now = Instant::now(); - let config = Arc::new( - Config::builder() - .mtu(200) - .use_server_cookie(false) - .build() - .expect("config"), - ); - let client_cert = generate_self_signed_certificate().expect("client certificate"); - let server_cert = generate_self_signed_certificate().expect("server certificate"); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_out = Observed::default(); - let mut server_out = Observed::default(); - server.handle_timeout(now).expect("server timeout"); - drain(&mut server, &mut server_out); - client.handle_timeout(now).expect("client timeout"); - drain(&mut client, &mut client_out); - deliver_packets(&mut client_out, &mut server, &mut server_out); - - let flight = split_records(&std::mem::take(&mut server_out.packets)); - let hello_done = flight - .iter() - .find(|record| record[0] == 22 && record[13] == 14) - .expect("server emits ServerHelloDone"); - let prefix = flight - .iter() - .rev() - .find(|record| *record != hello_done) - .expect("server emits a preceding plaintext record"); - for record in flight - .iter() - .filter(|record| *record != hello_done && *record != prefix) - { - client.handle_packet(record).expect("receive server flight"); - drain(&mut client, &mut client_out); - } - assert!(client_out.packets.is_empty(), "await ServerHelloDone"); - - // An epoch-1 record is ciphertext even when its opaque payload happens to - // have the shape of a plaintext handshake. This record is too short to - // authenticate and must never substitute for the missing epoch-0 message. - let mut opaque = hello_done.clone(); - opaque[3..5].copy_from_slice(&1u16.to_be_bytes()); - client.handle_packet(&opaque).expect("discard premature future epoch"); - drain(&mut client, &mut client_out); - assert!( - client_out.packets.is_empty(), - "unauthenticated epoch-1 bytes must not trigger the client's next flight" - ); - - // The same forged payload must remain opaque beside a valid plaintext - // record, where the coalesced-flight path temporarily stages ciphertext. - client - .handle_packet(&[prefix.as_slice(), opaque.as_slice()].concat()) - .expect("receive plaintext followed by forged protected handshake"); - drain(&mut client, &mut client_out); - assert!(client_out.packets.is_empty(), "await authenticated handshake"); - - client - .handle_packet(hello_done) - .expect("receive genuine ServerHelloDone"); - drain(&mut client, &mut client_out); - assert!(!client_out.packets.is_empty(), "genuine handshake progresses"); - deliver_packets(&mut client_out, &mut server, &mut server_out); - deliver_packets(&mut server_out, &mut client, &mut client_out); - assert!(client_out.connected && server_out.connected); -} - -#[test] -fn dtls12_pre_encryption_ciphertext_cannot_substitute_for_plaintext_ccs() { - let now = Instant::now(); - let config = Arc::new(Config::builder().use_server_cookie(false).build().expect("config")); - let client_cert = generate_self_signed_certificate().expect("client certificate"); - let server_cert = generate_self_signed_certificate().expect("server certificate"); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_out = Observed::default(); - let mut server_out = Observed::default(); - server.handle_timeout(now).expect("server timeout"); - drain(&mut server, &mut server_out); - client.handle_timeout(now).expect("client timeout"); - drain(&mut client, &mut client_out); - deliver_packets(&mut client_out, &mut server, &mut server_out); - deliver_packets(&mut server_out, &mut client, &mut client_out); - deliver_packets(&mut client_out, &mut server, &mut server_out); - let flight = split_records(&std::mem::take(&mut server_out.packets)); - let ccs = flight.iter().find(|record| record[0] == 20).expect("server emits CCS"); - let finished = flight - .iter() - .find(|record| record[0] == 22 && record[3..5] == [0, 1]) - .expect("server emits protected Finished"); - - // This is an undecryptable future-epoch control record, not a legitimate - // epoch-0 CCS. It must not make buffered Finished eligible for processing. - let mut opaque = ccs.clone(); - opaque[3..5].copy_from_slice(&1u16.to_be_bytes()); - client.handle_packet(&opaque).expect("discard premature future CCS"); - drain(&mut client, &mut client_out); - client.handle_packet(finished).expect("discard premature Finished"); - drain(&mut client, &mut client_out); - assert!( - !client_out.connected, - "unauthenticated epoch-1 CCS must not enable peer encryption" - ); - - client.handle_packet(ccs).expect("receive genuine CCS"); - drain(&mut client, &mut client_out); - assert!(!client_out.connected, "CCS cannot release a discarded Finished"); - client.handle_packet(finished).expect("receive retransmitted Finished"); - drain(&mut client, &mut client_out); - assert!(client_out.connected, "authenticated Finished completes the handshake"); -} - -fn assert_old_plaintext_hello_preserves_authenticated_data(plaintext_first: bool) { - let now = Instant::now(); - let config = Arc::new( - Config::builder() - .max_queue_rx(8) - .use_server_cookie(false) - .build() - .expect("config"), - ); - let client_cert = generate_self_signed_certificate().expect("client certificate"); - let server_cert = generate_self_signed_certificate().expect("server certificate"); - let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); - client.set_active(true); - let mut server = Dtls::new_12(config, server_cert, now); - server.set_active(false); - let mut client_out = Observed::default(); - let mut server_out = Observed::default(); - server.handle_timeout(now).expect("server timeout"); - drain(&mut server, &mut server_out); - client.handle_timeout(now).expect("client timeout"); - drain(&mut client, &mut client_out); - let client_hello = split_records(&client_out.packets) - .into_iter() - .find(|record| record[0] == 22 && record[13] == 1) - .expect("client emits plaintext ClientHello"); - for _ in 0..4 { - deliver_packets(&mut client_out, &mut server, &mut server_out); - deliver_packets(&mut server_out, &mut client, &mut client_out); - } - assert!(client_out.connected && server_out.connected); - - client - .send_application_data(b"authenticated beside an old hello") - .expect("send application data"); - drain(&mut client, &mut client_out); - assert_eq!(client_out.packets.len(), 1, "one protected data record"); - let protected = client_out.packets.pop().expect("protected data packet"); - let mixed = if plaintext_first { - [client_hello, protected.clone()].concat() - } else { - [protected.clone(), client_hello].concat() - }; - server.handle_packet(&mixed).expect("receive mixed datagram"); - drain(&mut server, &mut server_out); - - // If the old hello discards its entire datagram after the protected record - // updates the replay window, even a clean copy cannot recover the data. - server.handle_packet(&protected).expect("receive clean protected copy"); - drain(&mut server, &mut server_out); - assert_eq!( - server_out.app_data, - [b"authenticated beside an old hello".to_vec()], - "discarding a stale plaintext hello must preserve authenticated records beside it" - ); - - // A trailing stale hello must not retain its already consumed datagram and - // pin every subsequent handled record until the bounded queue is full. - for sequence in 0..16u8 { - client - .send_application_data(&[sequence]) - .expect("send subsequent authenticated data"); - drain(&mut client, &mut client_out); - for packet in std::mem::take(&mut client_out.packets) { - let result = server.handle_packet(&packet); - drain(&mut server, &mut server_out); - assert_eq!( - result, - Ok(()), - "a stale hello must not fill the queue at data record {sequence}" - ); - } - } - assert_eq!(server_out.app_data.len(), 17); -} - -#[test] -fn dtls12_old_plaintext_hello_does_not_discard_authenticated_data() { - assert_old_plaintext_hello_preserves_authenticated_data(true); -} - -#[test] -fn dtls12_trailing_old_plaintext_hello_does_not_pin_receive_queue() { - assert_old_plaintext_hello_preserves_authenticated_data(false); -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/tests/timing.rs b/rs/moq-webrtc/src/vendor/dimpl/tests/timing.rs deleted file mode 100644 index 2abe4fd1e48..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/tests/timing.rs +++ /dev/null @@ -1,1054 +0,0 @@ -use std::mem; -use std::ops::Range; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::certificate::generate_self_signed_certificate; -use crate::vendor::dimpl::{Config, Dtls, DtlsCertificate, Error, Output, ProtocolVersion, TimeoutError}; - -use super::dtls12::common; - -use common::{DrainedOutputs, drain_outputs}; - -const VERSIONS: &[Version] = &[Version::Dtls12]; -const BUDGET: Duration = Duration::from_millis(100); -const LONG_RTO: Duration = Duration::from_secs(1); -const PAIRS: &[(Version, Version)] = &[(Version::Dtls12, Version::Dtls12)]; - -// Offsets in a datagram holding one plaintext record (RFC 6347 §4.1, §4.2.2). -const CONTENT_TYPE: usize = 0; -const RECORD_EPOCH: Range = 3..5; -const RECORD_SEQUENCE: Range = 5..11; -const RECORD_LENGTH: Range = 11..13; -const RECORD_HEADER_LEN: usize = 13; -const MESSAGE_LENGTH: Range = 14..17; -const MESSAGE_SEQ: Range = 17..19; -const FRAGMENT_OFFSET: Range = 19..22; -const FRAGMENT_LENGTH: Range = 22..25; -const HANDSHAKE_HEADER_LEN: usize = 12; -const HANDSHAKE_BODY: usize = RECORD_HEADER_LEN + HANDSHAKE_HEADER_LEN; -// ClientHello legacy_version (2) and random (32) precede the session id. -const SESSION_ID_LENGTH: usize = HANDSHAKE_BODY + 34; - -#[derive(Clone, Copy, Debug)] -enum Version { - Dtls12, -} - -impl Version { - fn endpoint(self, config: Arc, certificate: DtlsCertificate, now: Instant) -> Dtls { - match self { - Self::Dtls12 => Dtls::new_12(config, certificate, now), - } - } -} - -fn config() -> Arc { - Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .flight_retries(0) - .build() - .expect("valid timing config"), - ) -} - -fn drain(endpoint: &mut Dtls) -> (Vec>, Instant) { - let mut packets = Vec::new(); - let mut buffer = vec![0; 65536]; - for _ in 0..100 { - match endpoint.poll_output(&mut buffer) { - Output::Packet(packet) => packets.push(packet.to_vec()), - Output::Timeout(deadline) => return (packets, deadline), - Output::BufferTooSmall { .. } => panic!("unexpected BufferTooSmall output"), - _ => {} - } - } - panic!("poll cycle did not reach Timeout"); -} - -fn start_endpoint( - version: Version, - active: bool, - config: Arc, - certificate: &DtlsCertificate, - now: Instant, -) -> (Dtls, Vec>, Instant) { - let mut endpoint = version.endpoint(config.clone(), certificate.clone(), now); - endpoint.set_active(active); - endpoint.handle_timeout(now).expect("initialize clock"); - let (mut packets, mut deadline) = drain(&mut endpoint); - if !active { - let mut peer = version.endpoint(config, certificate.clone(), now); - peer.set_active(true); - peer.handle_timeout(now).expect("queue peer ClientHello"); - for packet in drain(&mut peer).0 { - endpoint.handle_packet(&packet).expect("accept ClientHello"); - let output = drain(&mut endpoint); - packets.extend(output.0); - deadline = output.1; - } - } - assert!(!packets.is_empty(), "{version:?}, active={active}"); - (endpoint, packets, deadline) -} - -fn merge_output(received: &mut DrainedOutputs, output: DrainedOutputs) { - received.connected |= output.connected; - received.app_data.extend(output.app_data); - received.packets.extend(output.packets); - received.timeout = output.timeout; -} - -fn deliver_queued(source: &mut DrainedOutputs, target: &mut Dtls, received: &mut DrainedOutputs) { - for packet in mem::take(&mut source.packets) { - target.handle_packet(&packet).expect("deliver packet"); - merge_output(received, drain_outputs(target)); - } -} - -fn exchange(client: &mut Dtls, server: &mut Dtls, now: Instant) -> (DrainedOutputs, DrainedOutputs) { - let mut client_output = drain_outputs(client); - let mut server_output = drain_outputs(server); - for _ in 0..100 { - deliver_queued(&mut client_output, server, &mut server_output); - deliver_queued(&mut server_output, client, &mut client_output); - client.handle_timeout(now).expect("client pending progress"); - merge_output(&mut client_output, drain_outputs(client)); - server.handle_timeout(now).expect("server pending progress"); - merge_output(&mut server_output, drain_outputs(server)); - if client_output.packets.is_empty() && server_output.packets.is_empty() { - return (client_output, server_output); - } - } - panic!("packet exchange did not settle"); -} - -fn connected_pair( - versions: (Version, Version), - config: Arc, - certificate: &DtlsCertificate, - now: Instant, -) -> (Dtls, Dtls) { - let mut client = versions.0.endpoint(config.clone(), certificate.clone(), now); - let mut server = versions.1.endpoint(config, certificate.clone(), now); - client.set_active(true); - client.handle_timeout(now).expect("start client"); - server.handle_timeout(now).expect("server clock"); - let output = exchange(&mut client, &mut server, now); - assert!(output.0.connected, "client {versions:?}"); - assert!(output.1.connected, "server {versions:?}"); - assert_eq!(client.protocol_version(), server.protocol_version()); - (client, server) -} - -fn assert_expires_at(endpoint: &mut Dtls, expected: Instant) { - for _ in 0..20 { - let deadline = drain(endpoint).1; - if deadline == expected { - assert_eq!( - endpoint.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Connect)) - ); - return; - } - assert!(deadline < expected, "overall deadline moved later"); - endpoint.handle_timeout(deadline).expect("retry budget remains"); - } - panic!("overall deadline was not advertised"); -} - -fn corrupt_client_hello_extension(hello: &mut [u8], extension_type: u16) { - let mut cursor = SESSION_ID_LENGTH; - cursor += 1 + hello[cursor] as usize; // session id - cursor += 1 + hello[cursor] as usize; // cookie - cursor += 2 + u16::from_be_bytes([hello[cursor], hello[cursor + 1]]) as usize; // cipher suites - cursor += 1 + hello[cursor] as usize; // compression methods - cursor += 2; // extensions length - while cursor + 4 <= hello.len() { - let kind = u16::from_be_bytes([hello[cursor], hello[cursor + 1]]); - let length = u16::from_be_bytes([hello[cursor + 2], hello[cursor + 3]]) as usize; - if kind == extension_type { - assert!(length >= 2); - hello[cursor + 4..cursor + 6].copy_from_slice(&u16::MAX.to_be_bytes()); - return; - } - cursor += 4 + length; - } - panic!("missing ClientHello extension {extension_type}"); -} - -#[test] -fn rejected_extensions_and_corrected_hello_share_original_deadline() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .use_server_cookie(false) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .build() - .expect("config"), - ); - for &(client_version, server_version) in PAIRS { - for extension_type in [10, 14] { - let mut client = client_version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("client clock"); - let (hello, _) = drain(&mut client); - assert_eq!(hello.len(), 1); - let mut malformed = hello[0].clone(); - corrupt_client_hello_extension(&mut malformed, extension_type); - - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - server.handle_packet(&malformed).expect("discard malformed extension"); - let rejected = drain(&mut server); - assert!(rejected.0.is_empty()); - assert!(rejected.1 == base + BUDGET, "{client_version:?} -> {server_version:?}"); - - let reception = base + Duration::from_millis(50); - server.handle_timeout(reception).expect("original budget remains"); - drain(&mut server); - server.handle_packet(&malformed).expect("repeated rejection"); - assert_eq!(drain(&mut server).1, base + BUDGET); - server - .handle_packet(&hello[0]) - .expect("valid ClientHello after rejected input"); - let accepted = drain(&mut server); - assert!( - !accepted.0.is_empty(), - "{client_version:?} -> {server_version:?}, extension {extension_type}: {server:?}" - ); - assert_eq!(accepted.1, base + BUDGET); - assert_expires_at(&mut server, base + BUDGET); - } - } -} - -#[test] -fn initial_poll_schedules_client_progress_without_spinning_idle_servers() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for &version in VERSIONS { - let mut endpoint = version.endpoint(config(), certificate.clone(), base); - let idle = drain(&mut endpoint); - assert!(idle.0.is_empty()); - assert!(idle.1 > base); - endpoint.set_active(true); - let initial = drain(&mut endpoint); - assert!(initial.0.is_empty()); - assert_eq!(initial.1, base); - endpoint.handle_timeout(initial.1).expect("initial client progress"); - let initial = drain(&mut endpoint); - assert!(!initial.0.is_empty()); - assert_eq!(initial.1, base + BUDGET); - endpoint.handle_timeout(base).expect("same logical instant"); - let after = drain(&mut endpoint); - assert!(after.0.is_empty()); - assert_eq!(after.1, initial.1); - } -} - -#[test] -fn handshake_completes_after_rejected_client_hello() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .use_server_cookie(false) - .handshake_timeout(BUDGET) - .build() - .expect("config"), - ); - for &(client_version, server_version) in PAIRS { - for extension_type in [10, 14] { - let mut client = client_version.endpoint(config.clone(), certificate.clone(), base); - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("client clock"); - let (hello, _) = drain(&mut client); - assert_eq!(hello.len(), 1); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - let mut malformed = hello[0].clone(); - corrupt_client_hello_extension(&mut malformed, extension_type); - server.handle_packet(&malformed).expect("rejected ClientHello"); - assert!(drain(&mut server).0.is_empty()); - server.handle_packet(&hello[0]).expect("valid ClientHello retry"); - let output = exchange(&mut client, &mut server, base); - assert!(output.0.connected, "{client_version:?} -> {server_version:?}"); - assert!(output.1.connected, "{client_version:?} -> {server_version:?}"); - let later = base + Duration::from_secs(1); - client.handle_timeout(later).expect("completed client"); - server.handle_timeout(later).expect("completed server"); - exchange(&mut client, &mut server, later); - } - } -} - -#[test] -fn rejected_later_fragments_keep_first_reception_deadline() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .use_server_cookie(false) - .max_queue_rx(50) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .build() - .expect("config"), - ); - for &(client_version, server_version) in PAIRS { - let mut client = client_version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("client clock"); - let (hello, _) = drain(&mut client); - assert_eq!(hello.len(), 1); - let mut malformed = hello[0].clone(); - corrupt_client_hello_extension(&mut malformed, 14); - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - let chunk = 32; - assert!(malformed.len() > HANDSHAKE_BODY + chunk); - for (index, body) in malformed[HANDSHAKE_BODY..].chunks(chunk).enumerate() { - if index == 1 { - server - .handle_timeout(base + Duration::from_millis(70)) - .expect("partial budget"); - drain(&mut server); - } - let mut fragment = malformed[..HANDSHAKE_BODY].to_vec(); - fragment.extend_from_slice(body); - fragment[RECORD_SEQUENCE].copy_from_slice(&(index as u64).to_be_bytes()[2..]); - fragment[RECORD_LENGTH].copy_from_slice(&((HANDSHAKE_HEADER_LEN + body.len()) as u16).to_be_bytes()); - fragment[FRAGMENT_OFFSET].copy_from_slice(&((index * chunk) as u32).to_be_bytes()[1..]); - fragment[FRAGMENT_LENGTH].copy_from_slice(&(body.len() as u32).to_be_bytes()[1..]); - server - .handle_packet(&fragment) - .expect("accept fragment or reject completed extension"); - let output = drain(&mut server); - assert!(output.0.is_empty()); - assert_eq!( - output.1, - base + BUDGET, - "{client_version:?} -> {server_version:?}, fragment {index}" - ); - } - assert_expires_at(&mut server, base + BUDGET); - } -} - -#[test] -fn later_message_rejection_does_not_undo_accepted_client_hello() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .use_server_cookie(false) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .build() - .expect("config"), - ); - for &(client_version, server_version) in PAIRS { - let mut client = client_version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("client clock"); - let (hello, _) = drain(&mut client); - assert_eq!(hello.len(), 1); - let mut packet = hello[0].clone(); - // A second record carrying a one-byte Certificate (type 11) message. - let certificate_message = [11, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0]; - let mut malformed_certificate = packet[..RECORD_HEADER_LEN].to_vec(); - malformed_certificate[RECORD_SEQUENCE].copy_from_slice(&1u64.to_be_bytes()[2..]); - malformed_certificate[RECORD_LENGTH].copy_from_slice(&(certificate_message.len() as u16).to_be_bytes()); - malformed_certificate.extend_from_slice(&certificate_message); - packet.extend_from_slice(&malformed_certificate); - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - server - .handle_packet(&packet) - .expect("accept ClientHello and discard malformed certificate"); - let output = drain(&mut server); - assert!(!output.0.is_empty()); - assert_eq!(output.1, base + BUDGET, "{client_version:?} -> {server_version:?}"); - assert_expires_at(&mut server, base + BUDGET); - } -} - -#[test] -fn clients_start_at_emission_not_construction_or_timeout() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for &version in VERSIONS { - let mut client = version.endpoint(config(), certificate.clone(), base); - let late = base + Duration::from_secs(60); - client.handle_timeout(late).expect("idle server has no deadline"); - assert!(drain(&mut client).1 > late); - client.set_active(true); - client.handle_timeout(late).expect("queue initial ClientHello"); - // Test-only polling exception (#161): keep ClientHello queued across a - // clock update to prove its timers start at emission, not construction. - let emission = late + Duration::from_secs(60); - client.handle_timeout(emission).expect("unsent flight has no timer"); - let (packets, deadline) = drain(&mut client); - assert!(!packets.is_empty(), "{version:?}"); - assert_eq!(deadline, emission + BUDGET, "{version:?}"); - client - .handle_timeout(deadline - Duration::from_nanos(1)) - .expect("full budget remains"); - assert_eq!(drain(&mut client).1, deadline); - assert_eq!( - client.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Connect)) - ); - } -} - -#[test] -fn too_small_output_does_not_start_or_exhaust_client_timers() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for &version in VERSIONS { - let mut client = version.endpoint(config(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("queue ClientHello"); - // Test-only polling exception (#161): retain the packet after each - // BufferTooSmall to verify neither timer runs before successful output. - for seconds in [1, 10, 100] { - client - .handle_timeout(base + Duration::from_secs(seconds)) - .expect("not emitted"); - assert!(matches!(client.poll_output(&mut []), Output::BufferTooSmall { .. })); - } - let emission = base + Duration::from_secs(100); - let (packets, deadline) = drain(&mut client); - assert_eq!(packets.len(), 1, "{version:?}"); - assert_eq!(deadline, emission + BUDGET, "{version:?}"); - assert_eq!( - client.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Connect)) - ); - } -} - -#[test] -fn too_small_retry_output_does_not_start_or_exhaust_flight_timers() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let initial_rto = Duration::from_millis(20); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .handshake_timeout(Duration::from_secs(10)) - .flight_start_rto(initial_rto) - .flight_retries(1) - .build() - .expect("retry configuration"), - ); - for &version in VERSIONS { - for active in [false, true] { - let (mut endpoint, original, retry_at) = - start_endpoint(version, active, config.clone(), &certificate, base); - endpoint.handle_timeout(retry_at).expect("queue retry"); - assert!(matches!(endpoint.poll_output(&mut []), Output::BufferTooSmall { .. })); - - let emission = retry_at + Duration::from_secs(1); - endpoint - .handle_timeout(emission) - .expect("unemitted retry has no running timer"); - assert!(matches!(endpoint.poll_output(&mut []), Output::BufferTooSmall { .. })); - - let (retried, deadline) = drain(&mut endpoint); - assert_eq!(retried.len(), original.len(), "{version:?}, active={active}"); - let nominal = initial_rto * 2; - assert!(deadline >= emission + nominal.mul_f64(0.75)); - assert!(deadline <= emission + nominal.mul_f64(1.25)); - } - } -} - -#[test] -fn servers_start_at_late_client_hello_reception() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for &version in VERSIONS { - let mut server = version.endpoint(config(), certificate.clone(), base); - for seconds in [1, 10, 100] { - let now = base + Duration::from_secs(seconds); - server.handle_timeout(now).expect("passive server"); - assert!(drain(&mut server).1 > now); - server.handle_packet(&[0, 1, 2]).expect("malformed input is discarded"); - assert!(drain(&mut server).1 > now); - } - let reception = base + Duration::from_secs(100); - let mut client = version.endpoint(config(), certificate.clone(), reception); - client.set_active(true); - client.handle_timeout(reception).expect("queue ClientHello"); - for packet in drain(&mut client).0 { - server.handle_packet(&packet).expect("accept ClientHello"); - drain(&mut server); - } - let deadline = drain(&mut server).1; - assert_eq!(deadline, reception + BUDGET, "{version:?}"); - assert_eq!( - server.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Connect)) - ); - } -} - -#[test] -fn configured_rto_jitter_and_exact_retry_counts_apply_to_every_role() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for initial_rto in [ - Duration::from_nanos(1), - Duration::from_micros(80), - Duration::from_millis(20), - ] { - for retries in [0, 1, 3] { - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .handshake_timeout(Duration::from_secs(3600)) - .flight_start_rto(initial_rto) - .flight_retries(retries) - .build() - .expect("valid retry configuration"), - ); - for &version in VERSIONS { - for active in [false, true] { - let (mut endpoint, original, mut deadline) = - start_endpoint(version, active, config.clone(), &certificate, base); - let mut now = base; - for attempt in 0..=retries { - let nominal = initial_rto * (1 << attempt); - let interval = deadline.duration_since(now); - assert!(interval >= nominal.mul_f64(0.75).max(Duration::from_nanos(1))); - assert!(interval <= nominal.mul_f64(1.25).max(Duration::from_nanos(1))); - endpoint - .handle_timeout(deadline - Duration::from_nanos(1)) - .expect("not yet due"); - let before = drain(&mut endpoint); - assert!(before.0.is_empty()); - assert_eq!(before.1, deadline); - if attempt == retries { - assert_eq!( - endpoint.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Handshake)) - ); - } else { - endpoint.handle_timeout(deadline).expect("retry available"); - now = deadline; - let output = drain(&mut endpoint); - assert_eq!(output.0.len(), original.len(), "{version:?}, active={active}"); - deadline = output.1; - } - } - } - } - } - } -} - -#[test] -fn overall_deadline_precedes_long_rto_with_generous_retries() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .flight_retries(100) - .build() - .expect("valid timing config"), - ); - for &version in VERSIONS { - for active in [false, true] { - let (mut endpoint, _, deadline) = start_endpoint(version, active, config.clone(), &certificate, base); - assert_eq!(deadline, base + BUDGET, "{version:?}, active={active}"); - assert_eq!( - endpoint.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Connect)) - ); - } - } -} - -#[test] -fn duplicate_client_hellos_share_the_flight_retry_budget() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let initial_rto = Duration::from_millis(20); - for use_cookie in [false, true] { - for (retries, timed_retries) in [(0, 0), (1, 0), (2, 0), (2, 1)] { - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .use_server_cookie(use_cookie) - .flight_start_rto(initial_rto) - .flight_retries(retries) - .handshake_timeout(Duration::from_secs(1)) - .build() - .expect("retry config"), - ); - for &(client_version, server_version) in PAIRS { - let mut client = client_version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("client clock"); - let (hello, _) = drain(&mut client); - assert_eq!(hello.len(), 1); - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - server.handle_packet(&hello[0]).expect("initial ClientHello"); - let (original, mut retry_at) = drain(&mut server); - assert!(!original.is_empty()); - let suppress_duplicate_bursts = server.protocol_version() == Some(ProtocolVersion::DTLS1_2); - let mut now = base; - for _ in 0..timed_retries { - server.handle_timeout(retry_at).expect("timer retry"); - now = retry_at; - let output = drain(&mut server); - assert_eq!(output.0.len(), original.len()); - retry_at = output.1; - } - let remaining = retries - timed_retries; - let mut resends = timed_retries; - for duplicate in 0..remaining + 2 { - now += Duration::from_millis(1); - server.handle_timeout(now).expect("before retry timer"); - assert!(drain(&mut server).0.is_empty()); - server.handle_packet(&hello[0]).expect("duplicate ClientHello"); - let output = drain(&mut server); - let expected_packets = if resends < retries && (!suppress_duplicate_bursts || resends == 0) { - original.len() - } else { - 0 - }; - assert_eq!( - output.0.len(), - expected_packets, - "{client_version:?} -> {server_version:?}, retries={retries}, duplicate={duplicate}" - ); - if expected_packets > 0 { - resends += 1; - let nominal = initial_rto * (1 << resends); - assert!(output.1 >= now + nominal.mul_f64(0.75)); - assert!(output.1 <= now + nominal.mul_f64(1.25)); - retry_at = output.1; - } else { - assert_eq!(output.1, retry_at); - } - } - for attempt in resends..retries { - now = retry_at; - server.handle_timeout(now).expect("remaining timer retry"); - let output = drain(&mut server); - assert_eq!(output.0.len(), original.len()); - let nominal = initial_rto * (1 << (attempt + 1)); - assert!(output.1 >= now + nominal.mul_f64(0.75)); - assert!(output.1 <= now + nominal.mul_f64(1.25)); - retry_at = output.1; - } - assert_eq!( - server.handle_timeout(retry_at), - Err(Error::Timeout(TimeoutError::Handshake)) - ); - } - } - } -} - -#[test] -fn zero_retry_servers_answer_every_retransmitted_final_flight() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = |retries| { - Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .handshake_timeout(Duration::from_secs(60)) - .flight_start_rto(Duration::from_millis(20)) - .flight_retries(retries) - .build() - .expect("retry configuration"), - ) - }; - for &(client_version, server_version) in PAIRS { - let mut client = client_version.endpoint(config(3), certificate.clone(), base); - let mut server = server_version.endpoint(config(0), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("client clock"); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - let mut client_connected = false; - let mut to_server = drain(&mut client).0; - let mut lost_final_flight = Vec::new(); - 'handshake: for _ in 0..20 { - let mut to_client = Vec::new(); - for packet in mem::take(&mut to_server) { - server.handle_packet(&packet).expect("server receives"); - let output = drain_outputs(&mut server); - if output.connected { - lost_final_flight = output.packets; - break 'handshake; - } - to_client.extend(output.packets); - } - for packet in to_client { - client.handle_packet(&packet).expect("client receives"); - let output = drain_outputs(&mut client); - client_connected |= output.connected; - to_server.extend(output.packets); - } - } - assert!(!lost_final_flight.is_empty(), "server sends a final flight"); - - let mut answer = Vec::new(); - for round in 0..2 { - let retry_at = drain(&mut client).1; - client - .handle_timeout(retry_at) - .expect("client retransmits its final flight"); - server.handle_timeout(retry_at).expect("completed server"); - assert!(drain(&mut server).0.is_empty(), "no timer-driven resend"); - answer.clear(); - for packet in drain(&mut client).0 { - server.handle_packet(&packet).expect("retransmitted final flight"); - answer.extend(drain(&mut server).0); - } - assert!( - !answer.is_empty(), - "{client_version:?} -> {server_version:?}, round {round}" - ); - } - for packet in &answer { - client.handle_packet(packet).expect("final flight answer"); - client_connected |= drain_outputs(&mut client).connected; - } - assert!(client_connected, "{client_version:?} -> {server_version:?}"); - let later = base + Duration::from_secs(30); - client.handle_timeout(later).expect("client handshake settled"); - assert!( - drain(&mut client).0.is_empty(), - "{client_version:?} -> {server_version:?}: client still retransmits" - ); - } -} - -#[test] -fn first_client_fragment_starts_deadline_and_later_emissions_do_not_refresh_it() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .mtu(64) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .flight_retries(0) - .build() - .expect("fragmented configuration"), - ); - for &version in VERSIONS { - let mut client = version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("queue fragments"); - // Test-only polling exception (#161): leave the first fragment pending - // after BufferTooSmall while advancing the logical clock. - assert!(matches!(client.poll_output(&mut []), Output::BufferTooSmall { .. })); - let emission = base + Duration::from_secs(60); - client.handle_timeout(emission).expect("no emitted fragments yet"); - let mut buffer = [0; 64]; - assert!(matches!(client.poll_output(&mut buffer), Output::Packet(_))); - // Test-only polling exception (#161): pause after the first fragment - // to verify later fragments cannot refresh the original deadline. - client - .handle_timeout(emission + Duration::from_millis(70)) - .expect("first fragment has full budget"); - let (remaining, deadline) = drain(&mut client); - assert!(!remaining.is_empty()); - assert_eq!(deadline, emission + BUDGET); - assert_eq!( - client.handle_timeout(deadline), - Err(Error::Timeout(TimeoutError::Connect)) - ); - } -} - -#[test] -fn server_fragments_and_duplicates_preserve_first_reception() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .mtu(64) - .handshake_timeout(BUDGET) - .flight_start_rto(LONG_RTO) - .flight_retries(0) - .build() - .expect("fragmented configuration"), - ); - for &(client_version, server_version) in PAIRS { - for reverse in [false, true] { - for complete in [false, true] { - let reception = base + Duration::from_secs(60); - let mut client = client_version.endpoint(config.clone(), certificate.clone(), reception); - client.set_active(true); - client.handle_timeout(reception).expect("queue fragmented ClientHello"); - let mut fragments = drain(&mut client).0; - assert!(fragments.len() > 1); - if reverse { - fragments.reverse(); - } - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - server.handle_timeout(reception).expect("late passive server"); - assert!(drain(&mut server).1 > reception + BUDGET); - server - .handle_packet(&fragments[0]) - .expect("accept first arriving fragment"); - let first_output = drain(&mut server); - assert!(first_output.0.is_empty()); - assert_eq!(first_output.1, reception + BUDGET); - server - .handle_timeout(reception + Duration::from_millis(20)) - .expect("incomplete assembly"); - drain(&mut server); - server.handle_packet(&fragments[0]).expect("duplicate fragment"); - assert_eq!(drain(&mut server).1, first_output.1); - if complete { - server - .handle_timeout(reception + Duration::from_millis(70)) - .expect("remaining assembly budget"); - drain(&mut server); - let mut responses = Vec::new(); - for fragment in &fragments[1..] { - server.handle_packet(fragment).expect("complete ClientHello"); - let output = drain(&mut server); - responses.extend(output.0); - assert_eq!(output.1, first_output.1); - } - assert!(!responses.is_empty()); - assert_eq!(server.protocol_version(), Some(ProtocolVersion::DTLS1_2)); - } - assert_eq!( - server.handle_timeout(first_output.1), - Err(Error::Timeout(TimeoutError::Connect)) - ); - } - } - } -} - -#[test] -fn server_clock_start_depends_on_fragment_structure_not_body_validity() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for &version in VERSIONS { - let (_, hello, _) = start_endpoint(version, true, config(), &certificate, base); - assert_eq!(hello.len(), 1); - let hello = &hello[0]; - let mut inputs = vec![("unrelated bytes", vec![0, 1, 2])]; - - let mut empty = hello[..HANDSHAKE_BODY].to_vec(); - empty[RECORD_LENGTH].copy_from_slice(&(HANDSHAKE_HEADER_LEN as u16).to_be_bytes()); - empty[MESSAGE_LENGTH].fill(0); - empty[FRAGMENT_LENGTH].fill(0); - inputs.push(("empty ClientHello", empty)); - - let mut zero_fragment = hello[..HANDSHAKE_BODY].to_vec(); - zero_fragment[RECORD_LENGTH].copy_from_slice(&(HANDSHAKE_HEADER_LEN as u16).to_be_bytes()); - zero_fragment[FRAGMENT_LENGTH].fill(0); - inputs.push(("zero-length fragment", zero_fragment)); - - let mut outside_message = hello.clone(); - outside_message[FRAGMENT_OFFSET].fill(0xff); - inputs.push(("fragment outside message", outside_message)); - - let mut malformed_body = hello.clone(); - // An empty session id and cookie leave the cipher suites length next. - let cipher_suites_length = SESSION_ID_LENGTH + 2; - assert_eq!(&malformed_body[SESSION_ID_LENGTH..cipher_suites_length], &[0, 0]); - malformed_body[cipher_suites_length..cipher_suites_length + 2].fill(0xff); - inputs.push(("malformed complete body", malformed_body)); - - // A well-framed but too-short body still starts the peer's attempt. - // Its rejection belongs to the body parser, not the timer. - let mut short_body = hello[..HANDSHAKE_BODY + 1].to_vec(); - short_body[RECORD_LENGTH].copy_from_slice(&((HANDSHAKE_HEADER_LEN + 1) as u16).to_be_bytes()); - short_body[MESSAGE_LENGTH].copy_from_slice(&1u32.to_be_bytes()[1..]); - short_body[FRAGMENT_LENGTH].copy_from_slice(&1u32.to_be_bytes()[1..]); - inputs.push(("short complete body", short_body)); - - let mut future_message = hello.clone(); - future_message[MESSAGE_SEQ].copy_from_slice(&1u16.to_be_bytes()); - inputs.push(("unexpected handshake sequence", future_message)); - - let mut encrypted = hello.clone(); - encrypted[CONTENT_TYPE] = 23; - encrypted[RECORD_EPOCH].copy_from_slice(&1u16.to_be_bytes()); - inputs.push(("unrelated encrypted application data", encrypted)); - - let mut ccs = hello[..RECORD_HEADER_LEN].to_vec(); - ccs[CONTENT_TYPE] = 20; - ccs[RECORD_LENGTH].copy_from_slice(&1u16.to_be_bytes()); - ccs.push(1); - inputs.push(("unrelated ChangeCipherSpec", ccs)); - - for (label, input) in inputs { - let mut server = version.endpoint(config(), certificate.clone(), base); - server.handle_timeout(base).expect("passive server"); - drain(&mut server); - server.handle_packet(&input).expect("discard or defer unrelated input"); - let output = drain(&mut server); - assert!(output.0.is_empty(), "{version:?}: {label}"); - if matches!(label, "malformed complete body" | "short complete body") { - assert_eq!(output.1, base + BUDGET, "{version:?}: {label}"); - assert_expires_at(&mut server, base + BUDGET); - continue; - } - assert!(output.1 > base + BUDGET, "{version:?}: {label} started the clock"); - let reception = base + Duration::from_secs(60); - server - .handle_timeout(reception) - .expect("rejected input did not arm timers"); - drain(&mut server); - } - } -} - -#[test] -fn cookie_exchanges_and_fresh_flights_reset_only_retry_state() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - let rto = Duration::from_millis(20); - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .handshake_timeout(BUDGET) - .flight_start_rto(rto) - .flight_retries(8) - .build() - .expect("valid cookie configuration"), - ); - for &(client_version, server_version) in PAIRS { - let mut client = client_version.endpoint(config.clone(), certificate.clone(), base); - let mut server = server_version.endpoint(config.clone(), certificate.clone(), base); - client.set_active(true); - client.handle_timeout(base).expect("start client"); - server.handle_timeout(base).expect("server clock"); - drain(&mut server); - let (hello, client_retry) = drain(&mut client); - let mut cookie_packets = Vec::new(); - let mut server_retry = base; - for packet in hello { - server.handle_packet(&packet).expect("initial ClientHello"); - let output = drain(&mut server); - cookie_packets.extend(output.0); - server_retry = output.1; - } - assert!(!cookie_packets.is_empty()); - client.handle_timeout(client_retry).expect("retry ClientHello"); - assert!(!drain(&mut client).0.is_empty()); - server.handle_timeout(server_retry).expect("retry cookie challenge"); - assert!(!drain(&mut server).0.is_empty()); - let now = client_retry.max(server_retry) + Duration::from_millis(1); - client.handle_timeout(now).expect("client clock before challenge"); - server - .handle_timeout(now) - .expect("server clock before challenge response"); - drain(&mut client); - drain(&mut server); - - let mut cookie_hello = Vec::new(); - let mut next_client = now; - for packet in &cookie_packets { - client.handle_packet(packet).expect("cookie challenge"); - let output = drain(&mut client); - cookie_hello.extend(output.0); - next_client = output.1; - } - assert!(!cookie_hello.is_empty()); - assert!(next_client >= now + rto.mul_f64(0.75)); - assert!(next_client <= now + rto.mul_f64(1.25)); - for packet in cookie_packets { - client.handle_packet(&packet).expect("duplicate cookie challenge"); - let output = drain(&mut client); - if client.protocol_version() == Some(ProtocolVersion::DTLS1_2) { - assert!(!output.0.is_empty()); - assert!(output.1 >= now + (rto * 2).mul_f64(0.75)); - assert!(output.1 <= now + (rto * 2).mul_f64(1.25)); - } else { - assert!(output.0.is_empty()); - assert_eq!(output.1, next_client); - } - } - - let mut server_flight = Vec::new(); - let mut next_server = now; - for packet in cookie_hello { - server.handle_packet(&packet).expect("ClientHello with cookie"); - let output = drain(&mut server); - server_flight.extend(output.0); - next_server = output.1; - } - assert!(!server_flight.is_empty()); - assert!(next_server >= now + rto.mul_f64(0.75)); - assert!(next_server <= now + rto.mul_f64(1.25)); - assert_expires_at(&mut client, base + BUDGET); - assert_expires_at(&mut server, base + BUDGET); - } -} - -#[test] -fn completed_handshakes_stay_connected_after_deadline() { - let base = Instant::now(); - let certificate = generate_self_signed_certificate().expect("certificate"); - for use_cookie in [false, true] { - let config = Arc::new( - Config::builder() - .dangerously_set_rng_seed(42) - .use_server_cookie(use_cookie) - .handshake_timeout(BUDGET) - .flight_start_rto(Duration::from_millis(20)) - .flight_retries(3) - .build() - .expect("small handshake budget"), - ); - for &versions in PAIRS { - let (mut client, mut server) = connected_pair(versions, config.clone(), &certificate, base); - for round in 0..6 { - let now = base + Duration::from_secs(60 + round); - client.handle_timeout(now).expect("completed client deadline disabled"); - server.handle_timeout(now).expect("completed server deadline disabled"); - let idle = exchange(&mut client, &mut server, now); - assert!(idle.0.timeout.expect("client timeout") > now); - assert!(idle.1.timeout.expect("server timeout") > now); - - client.send_application_data(b"client traffic").expect("client send"); - let received = exchange(&mut client, &mut server, now); - assert_eq!(received.1.app_data, [b"client traffic".to_vec()]); - server.send_application_data(b"server traffic").expect("server send"); - let received = exchange(&mut client, &mut server, now); - assert_eq!(received.0.app_data, [b"server traffic".to_vec()]); - assert!(received.0.timeout.expect("client timeout") > now); - assert!(received.1.timeout.expect("server timeout") > now); - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/time_tricks.rs b/rs/moq-webrtc/src/vendor/dimpl/time_tricks.rs deleted file mode 100644 index fd3bc1ab07b..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/time_tricks.rs +++ /dev/null @@ -1,66 +0,0 @@ -use std::time::SystemTime; -use std::time::{Duration, Instant}; -use tracing::warn; - -use once_cell::sync::Lazy; - -// The goal here is to make a constant "beginning of time" in both Instant and SystemTime -// that we can use as relative values for the rest of dimpl. -// This is indeed a bit dodgy, but we want dimpl's internal idea of time to be completely -// driven from the external API using `Instant`. What works against us is that Instant can't -// represent things like UNIX EPOCH (but SystemTime can). -static BEGINNING_OF_TIME: Lazy<(Instant, SystemTime)> = Lazy::new(|| { - // These two should be "frozen" the same instant. Hopefully they are not differing too much. - let now = Instant::now(); - let now_sys = SystemTime::now(); - - // Find an Instant in the past which is up to an hour back. - let beginning_of_time = { - let mut secs = 3600; - loop { - let dur = Duration::from_secs(secs); - if let Some(v) = now.checked_sub(dur) { - break v; - } - secs -= 1; - if secs == 0 { - panic!("Failed to find a beginning of time instant"); - } - } - }; - - // This might be less than 1 hour if the machine uptime is less. - let since_beginning_of_time = Instant::now() - beginning_of_time; - - let beginning_of_time_sys = now_sys - since_beginning_of_time; - - // This pair represents our "beginning of time" for the same moment. - (beginning_of_time, beginning_of_time_sys) -}); - -pub trait InstantExt { - /// Convert an Instant to a Duration for unix time. - /// - /// First ever time must be "now". - /// - /// panics if `time` goes backwards, i.e. we use this for one Instant and then an earlier Instant. - fn to_unix_duration(&self) -> Duration; -} - -impl InstantExt for Instant { - fn to_unix_duration(&self) -> Duration { - // This is a bit fishy. We "freeze" a moment in time for Instant and SystemTime, - // so we can make relative comparisons of Instant - Instant and translate that to - // SystemTime - unix epoch. Hopefully the error is quite small. - if *self < BEGINNING_OF_TIME.0 { - warn!("Time went backwards from beginning_of_time Instant"); - } - - let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0); - let system_time = BEGINNING_OF_TIME.1 + duration_since_time_0; - - system_time - .duration_since(SystemTime::UNIX_EPOCH) - .expect("clock to go forwards from unix epoch") - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/timer.rs b/rs/moq-webrtc/src/vendor/dimpl/timer.rs deleted file mode 100644 index 268483d2fcb..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/timer.rs +++ /dev/null @@ -1,478 +0,0 @@ -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::{Config, SeededRng, TimeoutError}; - -const JITTER_RANGE: f32 = 0.5; -const IDLE_INTERVAL: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60); - -pub struct HandshakeTimers { - handshake_timeout: Duration, - handshake: Timeout, - flight: Timeout, - backoff: ExponentialBackoff, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Timeout { - Disabled, - Unarmed, - Armed(Instant), -} - -pub struct ExponentialBackoff { - start_rto: Duration, - retries: usize, - rto: Duration, - jitter: f32, - left: usize, -} - -impl HandshakeTimers { - pub fn new(config: &Config, rng: &mut SeededRng) -> Self { - Self { - handshake_timeout: config.handshake_timeout(), - handshake: Timeout::Unarmed, - flight: Timeout::Disabled, - backoff: ExponentialBackoff::new(config.flight_start_rto(), config.flight_retries(), rng), - } - } - - pub fn start_handshake(&mut self, now: Instant) { - if self.handshake == Timeout::Unarmed { - self.handshake = Timeout::Armed(deadline(now, self.handshake_timeout)); - } - } - - #[cfg(test)] - pub fn handshake_deadline(&self) -> Timeout { - self.handshake - } - - pub fn begin_flight(&mut self, rng: &mut SeededRng) { - self.backoff.reset(rng); - self.flight = Timeout::Unarmed; - } - - pub fn flight_sent(&mut self, now: Instant) { - if self.flight == Timeout::Unarmed { - self.flight = Timeout::Armed(deadline(now, self.backoff.rto())); - } - } - - pub fn stop_flight(&mut self) { - self.flight = Timeout::Disabled; - } - - pub fn finish_handshake(&mut self) { - self.handshake = Timeout::Disabled; - } - - pub fn stop(&mut self) { - self.finish_handshake(); - self.stop_flight(); - } - - pub fn rto(&self) -> Duration { - self.backoff.rto() - } - - /// Reserve a retry for a saved flight. Emission arms its next timeout. - /// - /// After the handshake finishes, resending the final flight in answer to - /// peer retransmissions ignores the remaining budget (RFC 6347 §4.2.4). - pub fn request_resend(&mut self, rng: &mut SeededRng) -> bool { - let final_flight = self.handshake == Timeout::Disabled && self.flight == Timeout::Disabled; - if self.flight == Timeout::Unarmed || !(final_flight || self.backoff.can_retry()) { - return false; - } - self.backoff.attempt(rng); - if matches!(self.flight, Timeout::Armed(_)) { - self.flight = Timeout::Unarmed; - } - true - } - - pub fn handle_timeout(&mut self, now: Instant, rng: &mut SeededRng) -> Result { - if let Timeout::Armed(timeout) = self.handshake - && now >= timeout - { - return Err(TimeoutError::Connect); - } - if let Timeout::Armed(timeout) = self.flight - && now >= timeout - { - if !self.request_resend(rng) { - return Err(TimeoutError::Handshake); - } - return Ok(true); - } - Ok(false) - } - - pub fn poll_timeout(&self, now: Instant) -> Instant { - match (self.handshake, self.flight) { - (Timeout::Armed(connect), Timeout::Armed(flight)) => connect.min(flight), - (Timeout::Armed(timeout), _) | (_, Timeout::Armed(timeout)) => timeout, - _ => deadline(now, IDLE_INTERVAL), - } - } -} - -impl ExponentialBackoff { - pub fn new(start_rto: Duration, retries: usize, rng: &mut SeededRng) -> Self { - Self { - start_rto, - retries, - rto: start_rto, - jitter: Self::jitter(rng), - left: retries, - } - } - - pub fn reset(&mut self, rng: &mut SeededRng) { - self.rto = self.start_rto; - self.jitter = Self::jitter(rng); - self.left = self.retries; - } - - pub fn rto(&self) -> Duration { - let jitter = self.rto.mul_f64(f64::from(self.jitter.abs())); - if self.jitter < 0.0 { - self.rto.saturating_sub(jitter) - } else { - self.rto.saturating_add(jitter) - } - .max(Duration::from_nanos(1)) - } - - fn jitter(rng: &mut SeededRng) -> f32 { - rng.random::() * JITTER_RANGE - (JITTER_RANGE / 2.0) - } - - pub fn attempt(&mut self, rng: &mut SeededRng) { - let (n, overflow) = self.left.overflowing_sub(1); - - if overflow { - return; - } - - self.left = n; - self.jitter = Self::jitter(rng); - self.rto = self.rto.saturating_mul(2); - } - - pub fn can_retry(&self) -> bool { - self.left > 0 - } -} - -/// Add a logical delay, reducing unrepresentable intervals until they fit. -pub fn deadline(now: Instant, mut delay: Duration) -> Instant { - loop { - if let Some(deadline) = now.checked_add(delay) { - return deadline; - } - delay /= 2; - } -} - -#[cfg(test)] -mod test { - use super::*; - - fn timers(retries: usize) -> (HandshakeTimers, SeededRng) { - let config = Config::builder() - .handshake_timeout(Duration::from_secs(2)) - .flight_start_rto(Duration::from_millis(20)) - .flight_retries(retries) - .build() - .expect("valid timing config"); - let mut rng = SeededRng::new(Some(42)); - (HandshakeTimers::new(&config, &mut rng), rng) - } - - #[test] - fn idle_and_unsent_flights_do_not_run_clocks() { - let (mut timers, mut rng) = timers(0); - let now = Instant::now(); - assert!(timers.poll_timeout(now) > now); - assert_eq!(timers.handle_timeout(now, &mut rng), Ok(false)); - timers.flight_sent(now); - assert_eq!(timers.flight, Timeout::Disabled); - timers.begin_flight(&mut rng); - let late = now + Duration::from_secs(100); - assert_eq!(timers.handle_timeout(late, &mut rng), Ok(false)); - assert!(timers.poll_timeout(late) > late); - assert_eq!(timers.handshake_deadline(), Timeout::Unarmed); - timers.start_handshake(late); - assert_eq!(timers.poll_timeout(late), late + Duration::from_secs(2)); - timers.flight_sent(late); - let retry_at = late + timers.rto(); - assert_eq!(timers.poll_timeout(late), retry_at); - assert_eq!(timers.handle_timeout(late, &mut rng), Ok(false)); - assert_eq!(timers.handle_timeout(retry_at, &mut rng), Err(TimeoutError::Handshake)); - } - - #[test] - fn flights_and_fragments_preserve_deadline() { - let (mut timers, mut rng) = timers(1); - let now = Instant::now(); - timers.start_handshake(now); - let original = timers.handshake_deadline(); - timers.begin_flight(&mut rng); - timers.flight_sent(now); - let first_retry = timers.poll_timeout(now); - timers.flight_sent(now + Duration::from_millis(1)); - assert_eq!(timers.poll_timeout(now), first_retry); - assert_eq!(timers.handle_timeout(first_retry, &mut rng), Ok(true)); - timers.flight_sent(first_retry); - let last_retry = timers.poll_timeout(first_retry); - assert_eq!( - timers.handle_timeout(last_retry, &mut rng), - Err(TimeoutError::Handshake) - ); - timers.begin_flight(&mut rng); - assert_eq!(timers.poll_timeout(last_retry), now + Duration::from_secs(2)); - timers.flight_sent(last_retry); - assert!(timers.poll_timeout(last_retry) < now + Duration::from_secs(2)); - timers.start_handshake(last_retry); - assert_eq!(timers.handshake_deadline(), original); - timers.stop_flight(); - assert_eq!(timers.poll_timeout(last_retry), now + Duration::from_secs(2)); - } - - #[test] - fn overall_deadline_wins_over_flight_deadline() { - let (mut timers, mut rng) = timers(usize::MAX); - let now = Instant::now(); - timers.start_handshake(now); - timers.begin_flight(&mut rng); - timers.backoff.rto = Duration::from_secs(10); - timers.flight_sent(now); - assert_eq!(timers.poll_timeout(now), now + Duration::from_secs(2)); - assert_eq!( - timers.handle_timeout(now + Duration::from_secs(2), &mut rng), - Err(TimeoutError::Connect) - ); - } - - #[test] - fn completion_disables_handshake_but_allows_key_update_flights() { - let (mut timers, mut rng) = timers(1); - let now = Instant::now(); - timers.start_handshake(now); - timers.begin_flight(&mut rng); - timers.flight_sent(now); - timers.finish_handshake(); - assert_eq!(timers.poll_timeout(now), now + timers.rto()); - timers.stop(); - let later = now + Duration::from_secs(100); - timers.start_handshake(later); - timers.flight_sent(later); - assert_eq!(timers.handshake_deadline(), Timeout::Disabled); - assert!(timers.poll_timeout(later) > later); - assert_eq!(timers.handle_timeout(later, &mut rng), Ok(false)); - timers.begin_flight(&mut rng); - timers.flight_sent(later); - assert_eq!(timers.poll_timeout(later), later + timers.rto()); - assert_eq!(timers.handle_timeout(later + timers.rto(), &mut rng), Ok(true)); - timers.stop_flight(); - assert!(timers.poll_timeout(later) > later); - } - - #[test] - fn deadline_overflow_does_not_panic() { - let now = Instant::now(); - assert_eq!(deadline(now, Duration::ZERO), now); - assert_eq!(deadline(now, Duration::from_nanos(1)), now + Duration::from_nanos(1)); - assert!(now.checked_add(Duration::MAX).is_none()); - assert!(deadline(now, Duration::MAX) > now); - } - - #[test] - fn duplicate_and_timed_resends_share_attempts() { - let (mut timers, mut rng) = timers(2); - let now = Instant::now(); - timers.start_handshake(now); - timers.begin_flight(&mut rng); - assert!(!timers.request_resend(&mut rng)); - assert_eq!(timers.backoff.left, 2); - timers.flight_sent(now); - let first_retry = timers.poll_timeout(now); - assert_eq!(timers.handle_timeout(first_retry, &mut rng), Ok(true)); - assert_eq!(timers.backoff.left, 1); - assert_eq!(timers.flight, Timeout::Unarmed); - timers.flight_sent(first_retry); - assert!(timers.request_resend(&mut rng)); - assert_eq!(timers.backoff.left, 0); - assert!(!timers.request_resend(&mut rng)); - assert_eq!(timers.poll_timeout(first_retry), now + Duration::from_secs(2)); - timers.flight_sent(first_retry); - let exhausted = timers.poll_timeout(first_retry); - assert_eq!(timers.handle_timeout(exhausted, &mut rng), Err(TimeoutError::Handshake)); - } - - #[test] - fn final_flight_resends_ignore_budget_without_restarting_timers() { - let (mut timers, mut rng) = timers(0); - let now = Instant::now(); - timers.start_handshake(now); - timers.begin_flight(&mut rng); - timers.flight_sent(now); - timers.stop(); - for _ in 0..3 { - assert!(timers.request_resend(&mut rng)); - timers.flight_sent(now); - } - assert_eq!(timers.handshake_deadline(), Timeout::Disabled); - assert_eq!(timers.flight, Timeout::Disabled); - assert_eq!( - timers.handle_timeout(now + Duration::from_secs(100), &mut rng), - Ok(false) - ); - } - - #[test] - fn stopped_flight_keeps_budget_until_handshake_finishes() { - let (mut timers, mut rng) = timers(1); - let now = Instant::now(); - timers.start_handshake(now); - timers.begin_flight(&mut rng); - timers.flight_sent(now); - timers.stop_flight(); - assert!(timers.request_resend(&mut rng)); - assert!(!timers.request_resend(&mut rng)); - timers.finish_handshake(); - assert!(timers.request_resend(&mut rng)); - } - - #[test] - fn proportional_jitter() { - let mut rng = SeededRng::new(Some(42)); - for rto in [ - Duration::from_nanos(4), - Duration::from_micros(100), - Duration::from_millis(20), - Duration::from_secs(1), - Duration::from_secs(100), - ] { - let mut exp = ExponentialBackoff::new(rto, 1, &mut rng); - exp.jitter = -0.25; - assert_eq!(exp.rto(), rto - rto / 4); - exp.jitter = 0.0; - assert_eq!(exp.rto(), rto); - exp.jitter = 0.25; - assert_eq!(exp.rto(), rto + rto / 4); - } - } - - #[test] - fn smallest_rto_stays_positive() { - let mut rng = SeededRng::new(Some(42)); - let mut exp = ExponentialBackoff::new(Duration::from_nanos(1), 1, &mut rng); - for jitter in [-0.25, 0.0, 0.25] { - exp.jitter = jitter; - assert_eq!(exp.rto(), Duration::from_nanos(1)); - } - } - - #[test] - fn overflow_saturates() { - let mut rng = SeededRng::new(Some(42)); - let mut exp = ExponentialBackoff::new(Duration::MAX, usize::MAX, &mut rng); - exp.jitter = 0.25; - assert_eq!(exp.rto(), Duration::MAX); - exp.attempt(&mut rng); - assert_eq!(exp.rto, Duration::MAX); - assert_eq!(exp.left, usize::MAX - 1); - exp.jitter = -0.25; - assert!(exp.rto() < Duration::MAX); - assert!(exp.rto() > Duration::MAX / 2); - } - - #[test] - fn zero_retries_and_reset() { - let mut rng = SeededRng::new(Some(42)); - let start = Duration::from_millis(20); - let mut exp = ExponentialBackoff::new(start, 0, &mut rng); - let initial = exp.rto(); - assert!(!exp.can_retry()); - exp.attempt(&mut rng); - assert_eq!(exp.rto(), initial); - exp.reset(&mut rng); - assert!(!exp.can_retry()); - assert_eq!(exp.rto, start); - - let mut exp = ExponentialBackoff::new(start, 2, &mut rng); - exp.attempt(&mut rng); - exp.attempt(&mut rng); - assert!(!exp.can_retry()); - exp.reset(&mut rng); - assert!(exp.can_retry()); - assert_eq!(exp.left, 2); - assert_eq!(exp.rto, start); - } - - #[test] - fn seeded_jitter_is_repeatable_and_bounded() { - let mut first_rng = SeededRng::new(Some(42)); - let mut second_rng = SeededRng::new(Some(42)); - let mut first = ExponentialBackoff::new(Duration::from_millis(20), 10, &mut first_rng); - let mut second = ExponentialBackoff::new(Duration::from_millis(20), 10, &mut second_rng); - for _ in 0..10 { - assert_eq!(first.rto(), second.rto()); - assert!((-0.25..0.25).contains(&first.jitter)); - assert!(first.rto() >= first.rto - first.rto / 4); - assert!(first.rto() <= first.rto + first.rto / 4); - first.attempt(&mut first_rng); - second.attempt(&mut second_rng); - } - } - - #[test] - fn attempts() { - let mut rng = SeededRng::new(Some(42)); - let mut exp = ExponentialBackoff::new(Duration::from_secs(1), 5, &mut rng); - - let n1 = dbg!(exp.rto().as_millis()); - assert_eq!(exp.rto().as_millis(), n1); - - exp.attempt(&mut rng); - - let n2 = dbg!(exp.rto().as_millis()); - assert_eq!(exp.rto().as_millis(), n2); - assert!(n2 > n1); - - exp.attempt(&mut rng); - - let n3 = dbg!(exp.rto().as_millis()); - assert_eq!(exp.rto().as_millis(), n3); - assert!(n3 > n2); - - exp.attempt(&mut rng); - - let n4 = dbg!(exp.rto().as_millis()); - assert_eq!(exp.rto().as_millis(), n4); - assert!(n4 > n3); - assert!(exp.can_retry()); - - exp.attempt(&mut rng); - - let n5 = dbg!(exp.rto().as_millis()); - assert_eq!(exp.rto().as_millis(), n5); - assert!(n5 > n4); - assert!(exp.can_retry()); - - exp.attempt(&mut rng); - - let n6 = dbg!(exp.rto().as_millis()); - assert_eq!(exp.rto().as_millis(), n6); - assert!(n6 > n5); - assert!(!exp.can_retry()); - - exp.attempt(&mut rng); - - assert_eq!(exp.rto().as_millis(), n6); - assert!(!exp.can_retry()); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/types.rs b/rs/moq-webrtc/src/vendor/dimpl/types.rs deleted file mode 100644 index b2393bb6c33..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/types.rs +++ /dev/null @@ -1,897 +0,0 @@ -//! Shared DTLS types. -//! -//! These types represent cryptographic primitives and protocol elements. - -use std::cmp::Ordering; -use std::fmt; -use std::time::Instant; - -use arrayvec::ArrayVec; -use nom::IResult; -use nom::bytes::complete::take; -use nom::number::complete::{be_u8, be_u16}; - -use crate::vendor::dimpl::SeededRng; -use crate::vendor::dimpl::buffer::Buf; -use crate::vendor::dimpl::time_tricks::InstantExt; - -pub type NamedGroupVec = ArrayVec; - -// ============================================================================ -// Random -// ============================================================================ - -/// ClientHello / ServerHello random value (32 bytes on the wire). -/// -/// The first 4 bytes are `gmt_unix_time` ([`Random::new_with_time`]). -/// -/// After construction nothing accesses sub-fields - all consumers use -/// [`bytes`](Self::bytes) or [`serialize`](Self::serialize). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Random { - /// The 32 raw bytes of the random value. - pub bytes: [u8; 32], -} - -impl Random { - /// Timestamp in first 4 bytes (DTLS 1.2 style). - pub fn new_with_time(now: Instant, rng: &mut SeededRng) -> Self { - let gmt_duration = now.to_unix_duration(); - // This is valid until year 2106, at which point I will be beyond caring. - let gmt_unix_time = gmt_duration.as_secs() as u32; - - let random_bytes: [u8; 28] = rng.random(); - - let mut bytes = [0u8; 32]; - bytes[..4].copy_from_slice(&gmt_unix_time.to_be_bytes()); - bytes[4..].copy_from_slice(&random_bytes); - - Self { bytes } - } - - /// Parse a 32-byte `Random` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], Random> { - let (input, data) = take(32_usize)(input)?; - let mut bytes = [0u8; 32]; - bytes.copy_from_slice(data); - Ok((input, Random { bytes })) - } - - /// Serialize this `Random` to wire format. - pub fn serialize(&self, output: &mut Buf) { - output.extend_from_slice(&self.bytes); - } -} - -// ============================================================================ -// Named Groups (Key Exchange) -// ============================================================================ - -/// Elliptic curves and key exchange groups (RFC 8422, RFC 8446). -/// -/// Used for Elliptic Curve Diffie-Hellman Ephemeral (ECDHE) key exchange. -/// The same named groups are used in both DTLS 1.2 and DTLS 1.3. -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct NamedGroup(u16); - -#[allow(non_upper_case_globals)] -impl NamedGroup { - /// sect163k1 (deprecated). - pub const Sect163k1: Self = Self(1); - /// sect163r1 (deprecated). - pub const Sect163r1: Self = Self(2); - /// sect163r2 (deprecated). - pub const Sect163r2: Self = Self(3); - /// sect193r1 (deprecated). - pub const Sect193r1: Self = Self(4); - /// sect193r2 (deprecated). - pub const Sect193r2: Self = Self(5); - /// sect233k1 (deprecated). - pub const Sect233k1: Self = Self(6); - /// sect233r1 (deprecated). - pub const Sect233r1: Self = Self(7); - /// sect239k1 (deprecated). - pub const Sect239k1: Self = Self(8); - /// sect283k1 (deprecated). - pub const Sect283k1: Self = Self(9); - /// sect283r1 (deprecated). - pub const Sect283r1: Self = Self(10); - /// sect409k1 (deprecated). - pub const Sect409k1: Self = Self(11); - /// sect409r1 (deprecated). - pub const Sect409r1: Self = Self(12); - /// sect571k1 (deprecated). - pub const Sect571k1: Self = Self(13); - /// sect571r1 (deprecated). - pub const Sect571r1: Self = Self(14); - /// secp160k1 (deprecated). - pub const Secp160k1: Self = Self(15); - /// secp160r1 (deprecated). - pub const Secp160r1: Self = Self(16); - /// secp160r2 (deprecated). - pub const Secp160r2: Self = Self(17); - /// secp192k1 (deprecated). - pub const Secp192k1: Self = Self(18); - /// secp192r1 (deprecated). - pub const Secp192r1: Self = Self(19); - /// secp224k1. - pub const Secp224k1: Self = Self(20); - /// secp224r1. - pub const Secp224r1: Self = Self(21); - /// secp256k1. - pub const Secp256k1: Self = Self(22); - /// secp256r1 / P-256 (supported by dimpl). - pub const Secp256r1: Self = Self(23); - /// secp384r1 / P-384 (supported by dimpl). - pub const Secp384r1: Self = Self(24); - /// secp521r1 / P-521. - pub const Secp521r1: Self = Self(25); - /// X25519 (Curve25519 for ECDHE). - pub const X25519: Self = Self(29); - /// X448 (Curve448 for ECDHE). - pub const X448: Self = Self(30); - - /// Convert a wire format u16 value to a `NamedGroup`. - pub const fn from_u16(value: u16) -> Self { - Self(value) - } - - /// Convert this `NamedGroup` to its wire format u16 value. - pub const fn as_u16(&self) -> u16 { - self.0 - } - - /// Returns true if this is not a known TLS named group wire value. - pub const fn is_unknown(&self) -> bool { - !matches!(*self, Self(1..=25 | 29..=30)) - } - - /// Parse a `NamedGroup` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], NamedGroup> { - let (input, value) = be_u16(input)?; - Ok((input, NamedGroup::from_u16(value))) - } - - /// Returns true if this named group is supported by this implementation. - pub fn is_supported(&self) -> bool { - Self::supported().contains(self) - } - - /// All recognized named groups (every non-`Unknown` variant). - pub const fn all() -> &'static [NamedGroup; 27] { - &[ - NamedGroup::Sect163k1, - NamedGroup::Sect163r1, - NamedGroup::Sect163r2, - NamedGroup::Sect193r1, - NamedGroup::Sect193r2, - NamedGroup::Sect233k1, - NamedGroup::Sect233r1, - NamedGroup::Sect239k1, - NamedGroup::Sect283k1, - NamedGroup::Sect283r1, - NamedGroup::Sect409k1, - NamedGroup::Sect409r1, - NamedGroup::Sect571k1, - NamedGroup::Sect571r1, - NamedGroup::Secp160k1, - NamedGroup::Secp160r1, - NamedGroup::Secp160r2, - NamedGroup::Secp192k1, - NamedGroup::Secp192r1, - NamedGroup::Secp224k1, - NamedGroup::Secp224r1, - NamedGroup::Secp256k1, - NamedGroup::Secp256r1, - NamedGroup::Secp384r1, - NamedGroup::Secp521r1, - NamedGroup::X25519, - NamedGroup::X448, - ] - } - - /// Supported named groups in preference order. - pub const fn supported() -> &'static [NamedGroup; 4] { - &[ - NamedGroup::X25519, - NamedGroup::Secp256r1, - NamedGroup::Secp384r1, - NamedGroup::Secp521r1, - ] - } -} - -impl fmt::Debug for NamedGroup { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - NamedGroup::Sect163k1 => f.write_str("Sect163k1"), - NamedGroup::Sect163r1 => f.write_str("Sect163r1"), - NamedGroup::Sect163r2 => f.write_str("Sect163r2"), - NamedGroup::Sect193r1 => f.write_str("Sect193r1"), - NamedGroup::Sect193r2 => f.write_str("Sect193r2"), - NamedGroup::Sect233k1 => f.write_str("Sect233k1"), - NamedGroup::Sect233r1 => f.write_str("Sect233r1"), - NamedGroup::Sect239k1 => f.write_str("Sect239k1"), - NamedGroup::Sect283k1 => f.write_str("Sect283k1"), - NamedGroup::Sect283r1 => f.write_str("Sect283r1"), - NamedGroup::Sect409k1 => f.write_str("Sect409k1"), - NamedGroup::Sect409r1 => f.write_str("Sect409r1"), - NamedGroup::Sect571k1 => f.write_str("Sect571k1"), - NamedGroup::Sect571r1 => f.write_str("Sect571r1"), - NamedGroup::Secp160k1 => f.write_str("Secp160k1"), - NamedGroup::Secp160r1 => f.write_str("Secp160r1"), - NamedGroup::Secp160r2 => f.write_str("Secp160r2"), - NamedGroup::Secp192k1 => f.write_str("Secp192k1"), - NamedGroup::Secp192r1 => f.write_str("Secp192r1"), - NamedGroup::Secp224k1 => f.write_str("Secp224k1"), - NamedGroup::Secp224r1 => f.write_str("Secp224r1"), - NamedGroup::Secp256k1 => f.write_str("Secp256k1"), - NamedGroup::Secp256r1 => f.write_str("Secp256r1"), - NamedGroup::Secp384r1 => f.write_str("Secp384r1"), - NamedGroup::Secp521r1 => f.write_str("Secp521r1"), - NamedGroup::X25519 => f.write_str("X25519"), - NamedGroup::X448 => f.write_str("X448"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -// ============================================================================ -// Hash Algorithms -// ============================================================================ - -/// Hash algorithms used in DTLS (RFC 5246, RFC 8446). -/// -/// Specifies the hash algorithm to be used in digital signatures, -/// PRF/HKDF operations, and transcript hashing. -#[repr(transparent)] -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct HashAlgorithm(u8); - -impl Default for HashAlgorithm { - fn default() -> Self { - Self::None - } -} - -#[allow(non_upper_case_globals)] -impl HashAlgorithm { - /// No hash (not typically used). - pub const None: Self = Self(0); - /// MD5 hash (deprecated, not supported). - pub const MD5: Self = Self(1); - /// SHA-1 hash (deprecated, not supported). - pub const SHA1: Self = Self(2); - /// SHA-224 hash. - pub const SHA224: Self = Self(3); - /// SHA-256 hash (supported by dimpl). - pub const SHA256: Self = Self(4); - /// SHA-384 hash (supported by dimpl). - pub const SHA384: Self = Self(5); - /// SHA-512 hash. - pub const SHA512: Self = Self(6); - - pub(crate) const UNKNOWN_DERIVED: Self = Self(u8::MAX); - - /// Convert a wire format u8 value to a `HashAlgorithm`. - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - /// Convert this `HashAlgorithm` to its wire format u8 value. - pub const fn as_u8(&self) -> u8 { - self.0 - } - - /// Returns true if this is not a known DTLS hash algorithm wire value. - pub const fn is_unknown(&self) -> bool { - self.0 > Self::SHA512.0 - } - - /// Parse a `HashAlgorithm` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], HashAlgorithm> { - let (input, value) = be_u8(input)?; - Ok((input, HashAlgorithm::from_u8(value))) - } - - /// Returns the output length in bytes for this hash algorithm. - pub const fn output_len(&self) -> usize { - match *self { - HashAlgorithm::None => 0, - HashAlgorithm::MD5 => 16, - HashAlgorithm::SHA1 => 20, - HashAlgorithm::SHA224 => 28, - HashAlgorithm::SHA256 => 32, - HashAlgorithm::SHA384 => 48, - HashAlgorithm::SHA512 => 64, - _ => 0, - } - } -} - -impl fmt::Debug for HashAlgorithm { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - HashAlgorithm::None => f.write_str("None"), - HashAlgorithm::MD5 => f.write_str("MD5"), - HashAlgorithm::SHA1 => f.write_str("SHA1"), - HashAlgorithm::SHA224 => f.write_str("SHA224"), - HashAlgorithm::SHA256 => f.write_str("SHA256"), - HashAlgorithm::SHA384 => f.write_str("SHA384"), - HashAlgorithm::SHA512 => f.write_str("SHA512"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -// ============================================================================ -// Signature Algorithms -// ============================================================================ - -/// Signature algorithms used in DTLS handshakes. -/// -/// Represents the underlying signature primitive (RSA, ECDSA, etc.). -/// Used internally for signing operations across both DTLS versions. -#[repr(transparent)] -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct SignatureAlgorithm(u8); - -impl Default for SignatureAlgorithm { - fn default() -> Self { - Self::Anonymous - } -} - -#[allow(non_upper_case_globals)] -impl SignatureAlgorithm { - /// Anonymous (no certificate). - pub const Anonymous: Self = Self(0); - /// RSA signatures. - pub const RSA: Self = Self(1); - /// DSA signatures. - pub const DSA: Self = Self(2); - /// ECDSA signatures. - pub const ECDSA: Self = Self(3); - - pub(crate) const UNKNOWN_DERIVED: Self = Self(u8::MAX); - - /// Convert an 8-bit value into a `SignatureAlgorithm`. - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - /// Convert this `SignatureAlgorithm` into its 8-bit representation. - pub const fn as_u8(&self) -> u8 { - self.0 - } - - /// Returns true if this is not a known DTLS signature algorithm wire value. - pub const fn is_unknown(&self) -> bool { - self.0 > Self::ECDSA.0 - } - - /// Parse a `SignatureAlgorithm` from network bytes. - pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAlgorithm> { - let (input, value) = be_u8(input)?; - Ok((input, SignatureAlgorithm::from_u8(value))) - } -} - -impl fmt::Debug for SignatureAlgorithm { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - SignatureAlgorithm::Anonymous => f.write_str("Anonymous"), - SignatureAlgorithm::RSA => f.write_str("RSA"), - SignatureAlgorithm::DSA => f.write_str("DSA"), - SignatureAlgorithm::ECDSA => f.write_str("ECDSA"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -// ============================================================================ -// Content Type -// ============================================================================ - -/// DTLS record content types. -/// -/// Identifies the type of data in a DTLS record. These values are the same -/// for both DTLS 1.2 and DTLS 1.3. -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct ContentType(u8); - -#[allow(non_upper_case_globals)] -impl ContentType { - /// Change Cipher Spec (used in DTLS 1.2, compatibility-only in 1.3). - pub const ChangeCipherSpec: Self = Self(20); - /// Alert message. - pub const Alert: Self = Self(21); - /// Handshake message. - pub const Handshake: Self = Self(22); - /// Application data. - pub const ApplicationData: Self = Self(23); - /// ACK (DTLS 1.3 only, RFC 9147 Section 7). - pub const Ack: Self = Self(26); - - /// Convert a u8 value to a `ContentType`. - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - /// Convert this `ContentType` to its u8 value. - pub const fn as_u8(&self) -> u8 { - self.0 - } - - /// Returns true if this is not a known DTLS record content type. - pub const fn is_unknown(&self) -> bool { - !matches!(*self, Self(20..=23 | 26)) - } - - /// Parse a `ContentType` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], ContentType> { - let (input, byte) = be_u8(input)?; - Ok((input, Self::from_u8(byte))) - } -} - -impl fmt::Debug for ContentType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - ContentType::ChangeCipherSpec => f.write_str("ChangeCipherSpec"), - ContentType::Alert => f.write_str("Alert"), - ContentType::Handshake => f.write_str("Handshake"), - ContentType::ApplicationData => f.write_str("ApplicationData"), - ContentType::Ack => f.write_str("Ack"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -// ============================================================================ -// Sequence Number -// ============================================================================ - -/// DTLS record sequence number (epoch + sequence). -/// -/// Both DTLS 1.2 and DTLS 1.3 use an epoch and sequence number for -/// replay protection and AEAD nonce construction. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct Sequence { - /// The epoch (incremented on key change). - pub epoch: u16, - /// The sequence number within the epoch (technically u48). - pub sequence_number: u64, -} - -impl Sequence { - /// Create a new sequence with the given epoch and sequence number 0. - pub fn new(epoch: u16) -> Self { - Self { - epoch, - sequence_number: 0, - } - } -} - -impl fmt::Display for Sequence { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "[epoch: {}, sequence_number: {}]", self.epoch, self.sequence_number,) - } -} - -impl Ord for Sequence { - fn cmp(&self, other: &Self) -> Ordering { - if self.epoch < other.epoch { - Ordering::Less - } else if self.epoch > other.epoch { - Ordering::Greater - } else { - self.sequence_number.cmp(&other.sequence_number) - } - } -} - -impl PartialOrd for Sequence { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -// ============================================================================ -// Protocol Version -// ============================================================================ - -/// DTLS protocol version identifiers. -/// -/// Used in record headers and handshake messages for both DTLS 1.2 and 1.3. -#[repr(transparent)] -#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] -pub struct ProtocolVersion(u16); - -impl ProtocolVersion { - /// DTLS 1.0. - pub const DTLS1_0: Self = Self(0xFEFF); - /// DTLS 1.2. - pub const DTLS1_2: Self = Self(0xFEFD); - /// DTLS 1.3. - pub const DTLS1_3: Self = Self(0xFEFC); - - /// Convert a wire format u16 value to a `ProtocolVersion`. - pub const fn from_u16(value: u16) -> Self { - Self(value) - } - - /// Convert this `ProtocolVersion` to its wire format u16 value. - pub const fn as_u16(&self) -> u16 { - self.0 - } - - /// Returns true if this is not a known DTLS protocol version wire value. - pub const fn is_unknown(&self) -> bool { - !matches!(*self, Self(0xFEFF | 0xFEFD | 0xFEFC)) - } - - /// Parse a `ProtocolVersion` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], ProtocolVersion> { - let (input, version) = be_u16(input)?; - Ok((input, ProtocolVersion::from_u16(version))) - } - - /// Serialize this `ProtocolVersion` to wire format. - pub fn serialize(&self, output: &mut Buf) { - output.extend_from_slice(&self.as_u16().to_be_bytes()); - } -} - -impl fmt::Debug for ProtocolVersion { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - ProtocolVersion::DTLS1_0 => f.write_str("DTLS1_0"), - ProtocolVersion::DTLS1_2 => f.write_str("DTLS1_2"), - ProtocolVersion::DTLS1_3 => f.write_str("DTLS1_3"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -// ============================================================================ -// Compression Method -// ============================================================================ - -/// TLS compression methods. -/// -/// Used in ClientHello/ServerHello for both DTLS 1.2 and 1.3. -/// TLS 1.3 only uses Null compression but includes it for compatibility. -#[repr(transparent)] -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct CompressionMethod(u8); - -impl Default for CompressionMethod { - fn default() -> Self { - Self::Null - } -} - -#[allow(non_upper_case_globals)] -impl CompressionMethod { - /// No compression. - pub const Null: Self = Self(0x00); - /// DEFLATE compression. - pub const Deflate: Self = Self(0x01); - - /// Convert a u8 value to a `CompressionMethod`. - pub const fn from_u8(value: u8) -> Self { - Self(value) - } - - /// Returns true if this compression method is supported by this implementation. - pub fn is_supported(&self) -> bool { - Self::supported().contains(self) - } - - /// All recognized compression methods (every non-`Unknown` variant). - pub const fn all() -> &'static [CompressionMethod; 2] { - &[CompressionMethod::Null, CompressionMethod::Deflate] - } - - /// Supported compression methods. - /// - /// Only null compression is supported. TLS 1.3 / DTLS 1.3 (RFC 8446 - /// §4.1.2) mandates exactly one compression method (null). DEFLATE - /// is recognized by parsing but not accepted. - pub const fn supported() -> &'static [CompressionMethod; 1] { - &[CompressionMethod::Null] - } - - /// Convert this `CompressionMethod` to its u8 value. - pub const fn as_u8(&self) -> u8 { - self.0 - } - - /// Returns true if this is not a known TLS compression method wire value. - pub const fn is_unknown(&self) -> bool { - self.0 > Self::Deflate.0 - } - - /// Parse a `CompressionMethod` from wire format. - pub fn parse(input: &[u8]) -> IResult<&[u8], CompressionMethod> { - let (input, value) = be_u8(input)?; - Ok((input, CompressionMethod::from_u8(value))) - } -} - -impl fmt::Debug for CompressionMethod { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - CompressionMethod::Null => f.write_str("Null"), - CompressionMethod::Deflate => f.write_str("Deflate"), - _ => f.debug_tuple("Unknown").field(&self.0).finish(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn named_group_newtype_shape() { - assert_eq!(std::mem::size_of::(), 2); - assert_eq!(NamedGroup::default().as_u16(), 0); - assert!(NamedGroup::default().is_unknown()); - } - - #[test] - fn named_group_wire_roundtrip() { - for group in NamedGroup::all() { - assert_eq!(NamedGroup::from_u16(group.as_u16()), *group); - assert!(!group.is_unknown()); - } - - let unknown = NamedGroup::from_u16(0xFFFF); - assert_eq!(unknown.as_u16(), 0xFFFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn named_group_debug_stays_enum_like() { - assert_eq!(format!("{:?}", NamedGroup::Secp256r1), "Secp256r1"); - assert_eq!(format!("{:?}", NamedGroup::X25519), "X25519"); - assert_eq!(format!("{:?}", NamedGroup::from_u16(0xFFFF)), "Unknown(65535)"); - } - - #[test] - fn hash_algorithm_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - assert_eq!(HashAlgorithm::default().as_u8(), 0); - assert_eq!(HashAlgorithm::default(), HashAlgorithm::None); - } - - #[test] - fn hash_algorithm_wire_roundtrip() { - let known = [ - (0, HashAlgorithm::None), - (1, HashAlgorithm::MD5), - (2, HashAlgorithm::SHA1), - (3, HashAlgorithm::SHA224), - (4, HashAlgorithm::SHA256), - (5, HashAlgorithm::SHA384), - (6, HashAlgorithm::SHA512), - ]; - - for (wire, algorithm) in known { - assert_eq!(HashAlgorithm::from_u8(wire), algorithm); - assert_eq!(algorithm.as_u8(), wire); - assert!(!algorithm.is_unknown()); - } - - let unknown = HashAlgorithm::from_u8(7); - assert_eq!(unknown.as_u8(), 7); - assert!(unknown.is_unknown()); - } - - #[test] - fn hash_algorithm_output_len() { - assert_eq!(HashAlgorithm::None.output_len(), 0); - assert_eq!(HashAlgorithm::MD5.output_len(), 16); - assert_eq!(HashAlgorithm::SHA1.output_len(), 20); - assert_eq!(HashAlgorithm::SHA224.output_len(), 28); - assert_eq!(HashAlgorithm::SHA256.output_len(), 32); - assert_eq!(HashAlgorithm::SHA384.output_len(), 48); - assert_eq!(HashAlgorithm::SHA512.output_len(), 64); - assert_eq!(HashAlgorithm::from_u8(7).output_len(), 0); - } - - #[test] - fn hash_algorithm_debug_stays_enum_like() { - assert_eq!(format!("{:?}", HashAlgorithm::None), "None"); - assert_eq!(format!("{:?}", HashAlgorithm::SHA256), "SHA256"); - assert_eq!(format!("{:?}", HashAlgorithm::from_u8(7)), "Unknown(7)"); - } - - #[test] - fn signature_algorithm_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - assert_eq!(SignatureAlgorithm::default().as_u8(), 0); - assert_eq!(SignatureAlgorithm::default(), SignatureAlgorithm::Anonymous); - } - - #[test] - fn signature_algorithm_wire_roundtrip() { - let known = [ - (0, SignatureAlgorithm::Anonymous), - (1, SignatureAlgorithm::RSA), - (2, SignatureAlgorithm::DSA), - (3, SignatureAlgorithm::ECDSA), - ]; - - for (wire, algorithm) in known { - assert_eq!(SignatureAlgorithm::from_u8(wire), algorithm); - assert_eq!(algorithm.as_u8(), wire); - assert!(!algorithm.is_unknown()); - } - - let unknown = SignatureAlgorithm::from_u8(4); - assert_eq!(unknown.as_u8(), 4); - assert!(unknown.is_unknown()); - } - - #[test] - fn signature_algorithm_debug_stays_enum_like() { - assert_eq!(format!("{:?}", SignatureAlgorithm::Anonymous), "Anonymous"); - assert_eq!(format!("{:?}", SignatureAlgorithm::ECDSA), "ECDSA"); - assert_eq!(format!("{:?}", SignatureAlgorithm::from_u8(4)), "Unknown(4)"); - } - - #[test] - fn compression_method_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - assert_eq!(CompressionMethod::default().as_u8(), 0); - assert_eq!(CompressionMethod::default(), CompressionMethod::Null); - } - - #[test] - fn compression_method_wire_roundtrip() { - let known = [(0x00, CompressionMethod::Null), (0x01, CompressionMethod::Deflate)]; - - for (wire, method) in known { - assert_eq!(CompressionMethod::from_u8(wire), method); - assert_eq!(method.as_u8(), wire); - assert!(!method.is_unknown()); - } - - let unknown = CompressionMethod::from_u8(0x02); - assert_eq!(unknown.as_u8(), 0x02); - assert!(unknown.is_unknown()); - } - - #[test] - fn compression_method_debug_stays_enum_like() { - assert_eq!(format!("{:?}", CompressionMethod::Null), "Null"); - assert_eq!(format!("{:?}", CompressionMethod::Deflate), "Deflate"); - assert_eq!(format!("{:?}", CompressionMethod::from_u8(0x02)), "Unknown(2)"); - } - - #[test] - fn content_type_newtype_shape() { - assert_eq!(std::mem::size_of::(), 1); - assert_eq!(ContentType::default().as_u8(), 0); - assert!(ContentType::default().is_unknown()); - } - - #[test] - fn content_type_wire_roundtrip() { - let known = [ - (20, ContentType::ChangeCipherSpec), - (21, ContentType::Alert), - (22, ContentType::Handshake), - (23, ContentType::ApplicationData), - (26, ContentType::Ack), - ]; - - for (wire, content_type) in known { - assert_eq!(ContentType::from_u8(wire), content_type); - assert_eq!(content_type.as_u8(), wire); - assert!(!content_type.is_unknown()); - } - - let unknown = ContentType::from_u8(24); - assert_eq!(unknown.as_u8(), 24); - assert!(unknown.is_unknown()); - } - - #[test] - fn content_type_debug_stays_enum_like() { - assert_eq!(format!("{:?}", ContentType::ChangeCipherSpec), "ChangeCipherSpec"); - assert_eq!(format!("{:?}", ContentType::Handshake), "Handshake"); - assert_eq!(format!("{:?}", ContentType::from_u8(24)), "Unknown(24)"); - } - - #[test] - fn protocol_version_newtype_shape() { - assert_eq!(std::mem::size_of::(), 2); - assert_eq!(ProtocolVersion::default().as_u16(), 0); - assert!(ProtocolVersion::default().is_unknown()); - } - - #[test] - fn protocol_version_wire_roundtrip() { - let known = [ - (0xFEFF, ProtocolVersion::DTLS1_0), - (0xFEFD, ProtocolVersion::DTLS1_2), - (0xFEFC, ProtocolVersion::DTLS1_3), - ]; - - for (wire, version) in known { - assert_eq!(ProtocolVersion::from_u16(wire), version); - assert_eq!(version.as_u16(), wire); - assert!(!version.is_unknown()); - } - - let unknown = ProtocolVersion::from_u16(0xFFFF); - assert_eq!(unknown.as_u16(), 0xFFFF); - assert!(unknown.is_unknown()); - } - - #[test] - fn protocol_version_debug_stays_enum_like() { - assert_eq!(format!("{:?}", ProtocolVersion::DTLS1_2), "DTLS1_2"); - assert_eq!(format!("{:?}", ProtocolVersion::from_u16(0xFFFF)), "Unknown(65535)"); - } - - #[test] - fn random_parse() { - let data = [ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, - ]; - - let expected = Random { bytes: data }; - - let (_, parsed) = Random::parse(&data).unwrap(); - assert_eq!(parsed, expected); - } - - #[test] - fn random_serialize() { - let random = Random { - bytes: [ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, - 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, - ], - }; - - let mut serialized = Buf::new(); - random.serialize(&mut serialized); - - assert_eq!(&*serialized, &random.bytes); - } - - #[test] - fn compression_supported_has_only_null() { - let supported = CompressionMethod::supported(); - assert_eq!( - supported, - &[CompressionMethod::Null], - "Only Null compression should be supported" - ); - } - - #[test] - fn random_parse_roundtrip() { - let data = [ - 0x5F, 0x37, 0xA9, 0x4B, // could be gmt_unix_time in 1.2 - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, - 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, - ]; - - let (_, parsed) = Random::parse(&data).unwrap(); - let mut serialized = Buf::new(); - parsed.serialize(&mut serialized); - - assert_eq!(&*serialized, &data[..]); - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/util.rs b/rs/moq-webrtc/src/vendor/dimpl/util.rs deleted file mode 100644 index c5402c1a482..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/util.rs +++ /dev/null @@ -1,116 +0,0 @@ -use arrayvec::ArrayVec; -use nom::error::{ErrorKind, ParseError, make_error}; -use nom::{Err, IResult, Input, Parser}; - -/// A combinator that parses items using the provided parser but only collects -/// items that pass a filter predicate. Allows zero matches. -#[inline(always)] -pub fn many0( - mut parser: F, - predicate: P, -) -> impl FnMut(I) -> IResult, E> -where - I: Clone + Input, - F: Parser, - P: Fn(&O) -> bool, - E: ParseError, -{ - move |mut i: I| { - let mut acc = ArrayVec::new(); - - loop { - let len = i.input_len(); - if len == 0 { - break; - } - - match parser.parse(i.clone()) { - Err(Err::Error(_)) => break, - Err(e) => return Err(e), - Ok((i1, o)) => { - // infinite loop check: the parser must always consume - if i1.input_len() == len { - return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many0))); - } - - i = i1; - // Only collect items that pass the filter - if predicate(&o) && acc.try_push(o).is_err() { - return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many0))); - } - } - } - } - - Ok((i, acc)) - } -} - -/// A combinator that parses items using the provided parser but only collects -/// items that pass a filter predicate. Requires at least one item to pass the filter. -#[inline(always)] -pub fn many1( - mut parser: F, - predicate: P, -) -> impl FnMut(I) -> IResult, E> -where - I: Clone + Input, - F: Parser, - P: Fn(&O) -> bool, - E: ParseError, -{ - move |mut i: I| { - let mut acc = ArrayVec::new(); - let original_input = i.clone(); - - loop { - let len = i.input_len(); - if len == 0 { - break; - } - - match parser.parse(i.clone()) { - Err(Err::Error(_)) => break, - Err(e) => return Err(e), - Ok((i1, o)) => { - // infinite loop check: the parser must always consume - if i1.input_len() == len { - return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1))); - } - - i = i1; - // Only collect items that pass the filter - if predicate(&o) && acc.try_push(o).is_err() { - return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1))); - } - } - } - } - - // Require at least one item to pass the filter - if acc.is_empty() { - Err(Err::Error(E::from_error_kind(original_input, ErrorKind::Many1))) - } else { - Ok((i, acc)) - } - } -} - -pub fn be_u48>(input: I) -> IResult -where - I: Input, -{ - let bound: usize = 6; - - if input.input_len() < bound { - Err(Err::Error(make_error(input, ErrorKind::Eof))) - } else { - let mut res = 0u64; - - for byte in input.iter_elements().take(bound) { - res = (res << 8) + byte as u64; - } - - Ok((input.take_from(bound), res)) - } -} diff --git a/rs/moq-webrtc/src/vendor/dimpl/window.rs b/rs/moq-webrtc/src/vendor/dimpl/window.rs deleted file mode 100644 index dd7686018de..00000000000 --- a/rs/moq-webrtc/src/vendor/dimpl/window.rs +++ /dev/null @@ -1,143 +0,0 @@ -/// Sliding replay window for DTLS record sequence numbers. -/// -/// Maintains the latest accepted sequence number and a 64-bit bitmap of the -/// last 64 seen sequence numbers to reject duplicates and old records. -/// -/// Each epoch should have its own `ReplayWindow` instance. The caller is -/// responsible for routing records to the correct per-epoch window. -#[derive(Debug, Default)] -pub struct ReplayWindow { - max_seq: u64, - window: u64, -} - -impl ReplayWindow { - pub fn new() -> Self { - Self::default() - } - - /// Check if the given sequence number is acceptable (not a replay, not too old). - /// Read-only: does not modify the window state. - pub fn check(&self, seqno: u64) -> bool { - if seqno > self.max_seq { - true - } else { - let offset = self.max_seq - seqno; - if offset >= 64 { - return false; // too old - } - let mask = 1u64 << offset; - (self.window & mask) == 0 // false if duplicate - } - } - - /// Update the window state to record that `seqno` has been received. - /// Must only be called after the record has been authenticated (decrypted successfully). - pub fn update(&mut self, seqno: u64) { - if seqno > self.max_seq { - let delta = seqno - self.max_seq; - if delta > 63 { - // Jump exceeds window size: clear entirely, only newest is seen - self.window = 1; - } else { - self.window <<= delta; - self.window |= 1; // mark newest as seen - } - self.max_seq = seqno; - } else { - let offset = self.max_seq - seqno; - if offset < 64 { - self.window |= 1u64 << offset; - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Helper: check and update in one step (simulates authenticated record). - fn check_and_update(w: &mut ReplayWindow, seqno: u64) -> bool { - if w.check(seqno) { - w.update(seqno); - true - } else { - false - } - } - - #[test] - fn accepts_fresh_and_rejects_duplicate() { - let mut w = ReplayWindow::new(); - assert!(check_and_update(&mut w, 1)); - assert!(!check_and_update(&mut w, 1)); // duplicate - assert!(check_and_update(&mut w, 2)); // next fresh - } - - #[test] - fn accepts_out_of_order_within_window() { - let mut w = ReplayWindow::new(); - assert!(check_and_update(&mut w, 10)); // establish max=10 - assert!(check_and_update(&mut w, 8)); // unseen within 64 - assert!(!check_and_update(&mut w, 8)); // duplicate now - assert!(check_and_update(&mut w, 9)); // unseen within 64 - } - - #[test] - fn rejects_too_old() { - let mut w = ReplayWindow::new(); - assert!(check_and_update(&mut w, 100)); - // offset = 64 -> too old - assert!(!check_and_update(&mut w, 36)); - // offset = 63 -> allowed once - assert!(check_and_update(&mut w, 37)); - } - - #[test] - fn handles_large_jump_and_window_shift() { - let mut w = ReplayWindow::new(); - assert!(check_and_update(&mut w, 1)); - // Large forward jump clears the window entirely - assert!(check_and_update(&mut w, 80)); - // Within window of new max and unseen - assert!(check_and_update(&mut w, 79)); - // Too old relative to new max - assert!(!check_and_update(&mut w, 15)); - } - - #[test] - fn large_jump_does_not_leave_stale_bits() { - let mut w = ReplayWindow::new(); - assert!(check_and_update(&mut w, 0)); - // Jump of 200 exceeds window size (64). The window must be fully - // cleared so no stale bits from seq 0 remain. - assert!(check_and_update(&mut w, 200)); - // seq 137 is within the window (offset = 200 - 137 = 63) and was - // never seen, so it must be accepted. - assert!(check_and_update(&mut w, 137)); - } - - #[test] - fn check_does_not_modify_window() { - let mut w = ReplayWindow::new(); - w.update(10); - // check alone should not change state - assert!(w.check(11)); - assert!(w.check(11)); // still acceptable because update was never called - w.update(11); - assert!(!w.check(11)); // now it's a duplicate - } - - #[test] - fn failed_auth_does_not_advance_window() { - let mut w = ReplayWindow::new(); - w.update(5); - // Simulate receiving seq 200 that passes check but fails authentication - assert!(w.check(200)); - // Do NOT call update (authentication failed) - // Legitimate packet at seq 6 should still be accepted - assert!(w.check(6)); - w.update(6); - } -} diff --git a/rs/moq-webrtc/src/vendor/is/agent.rs b/rs/moq-webrtc/src/vendor/is/agent.rs deleted file mode 100644 index 52d80e5f044..00000000000 --- a/rs/moq-webrtc/src/vendor/is/agent.rs +++ /dev/null @@ -1,3003 +0,0 @@ -use std::collections::{HashSet, VecDeque}; -use std::fmt; -use std::net::SocketAddr; -use std::ops::RangeInclusive; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tracing::{debug, trace, warn}; - -use serde::{Deserialize, Serialize}; - -use crate::vendor::is::Sha1HmacProvider; -use crate::vendor::is::preference::default_local_preference; -use crate::vendor::is::stun::{Class as StunClass, Method as StunMethod, StunTiming}; -use crate::vendor::is::stun::{StunMessage, StunPacket, TransId}; -use crate::vendor::str0m_proto::{DATAGRAM_MTU_TARGET, DATAGRAM_MTU_WARN, Id, Transmit}; -use crate::vendor::str0m_proto::{NonCryptographicRng, Pii, Protocol}; - -use crate::vendor::is::candidate::{Candidate, CandidateKind}; -use crate::vendor::is::pair::{CandidatePair, CheckState, PairId}; - -/// Handles the ICE protocol for a given peer. -/// -/// Each connection between two peers corresponds to one [`IceAgent`] on either end. -/// To form connections to multiple peers, a peer needs to create a dedicated [`IceAgent`] for -/// each one. -#[derive(Debug)] -pub struct IceAgent { - /// Last time handle_timeout run (paced by timing_advance). - /// - /// This drives the state forward. - last_now: Option, - - /// Timing advance (Ta) value. - /// - /// ICE agents SHOULD use a default Ta value, 50 ms, but MAY use another - /// value based on the characteristics of the associated data. - timing_advance: Duration, - - /// Whether this agent is operating as ice-lite. - /// ice-lite is a minimal version of the ICE specification, intended for servers - /// running on a public IP address. ice-lite requires the media server to only answer - /// incoming STUN binding requests and acting as a controlled entity in the ICE - /// process itself. - ice_lite: bool, - - // The default limit of candidate pairs for the checklist set is 100, - // but the value MUST be configurable. - max_candidate_pairs: Option, - - /// Whether we have previously exceeded the `max_candidate_pairs` limit. - has_exceeded_max_candidate_pairs: bool, - - /// Credentials for this side. Set on init and ice-restart. - local_credentials: IceCreds, - - /// Credentials for the remote side. Set when we learn about it. - remote_credentials: Option, - - /// If this side is controlling or controlled. - controlling: bool, - - /// Number used in STUN attribute ICE-CONTROLLING and ICE-CONTROLLED. - /// An ICE agent MUST use the same number for all Binding requests, - /// for all streams, within an ICE session - control_tie_breaker: u64, - - /// Current state of the agent. - state: IceConnectionState, - - /// All local candidates, in the order they are "discovered" (either by - /// adding explicitly using add_candidate, or via binding/allocation - /// requests. - local_candidates: Vec, - - /// All remote candidates, in the order we get to know them. - remote_candidates: Vec, - - /// The candidate pairs. - candidate_pairs: Vec, - - /// Transmit packet ready to be polled by poll_transmit. - transmit: VecDeque, - - /// Events ready to be polled by poll_event. - events: VecDeque, - - /// Queue of incoming STUN requests we might have to queue up before we receive - /// the remote_credentials. - stun_server_queue: VecDeque, - - /// Remote addresses we have seen traffic appear from. This is used - /// to dedupe [`IceAgentEvent::DiscoveredRecv`]. - discovered_recv: HashSet<(Protocol, SocketAddr)>, - - /// Currently nominated pair for sending. This is used to evaluate - /// if we get a better candidate for [`IceAgentEvent::NominatedSend`]. - nominated_send: Option, - - /// Statistics counter for the agent. - stats: IceAgentStats, - - /// SHA1-HMAC provider for STUN message integrity. - sha1_hmac_provider: &'static dyn Sha1HmacProvider, - - /// The timing configuration for STUN bindings. - timing_config: StunTiming, - - /// Pluggable calculation of local preference. - local_preference: LocalPreferenceHolder, - - /// Target MTU (start) and warn threshold (end). Buffer sizing uses the - /// target; oversized outgoing datagrams above the warn threshold log a warning. - mtu: RangeInclusive, -} - -/// IceAgent contains only static references to thread-safe traits, -/// so it's safe to use across panic boundaries. -impl UnwindSafe for IceAgent {} -impl RefUnwindSafe for IceAgent {} - -// Stupid holder to implement fmt::Debug -struct LocalPreferenceHolder(Arc); - -/// Trait for pluggable LocalPreference calculation -pub trait LocalPreference: RefUnwindSafe + Send + Sync + 'static { - /// Calculate the local preference for a candidate. - /// - /// The `same_kind` parameter is the number of candidates of the same IP version that - /// have already been added to the agent. - /// - /// The `c` parameter is the candidate to calculate the preference for. - fn calculate(&self, c: &Candidate, same_kind: usize) -> u32; -} - -/// Blanket impl for functions that look like preference calculations. -impl LocalPreference for F -where - F: Fn(&Candidate, usize) -> u32 + RefUnwindSafe + Send + Sync + 'static, -{ - fn calculate(&self, c: &Candidate, same_kind: usize) -> u32 { - (self)(c, same_kind) - } -} - -#[derive(Debug)] -struct StunRequest { - now: Instant, - proto: Protocol, - source: SocketAddr, - destination: SocketAddr, - trans_id: TransId, - prio: u32, - use_candidate: bool, - remote_ufrag: String, - ice_controlling: Option, - ice_controlled: Option, -} - -impl StunRequest { - fn role_conflict_tiebreaker(&self, controlling: bool) -> Option { - if controlling { - self.ice_controlling - } else { - self.ice_controlled - } - } -} - -fn role_name(controlling: bool) -> &'static str { - if controlling { "controlling" } else { "controlled" } -} - -const REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION: &str = "tmp_prflx"; - -/// States the ICE connection can be in. -/// -/// More details on connection states can be found in the [ICE RFC][1]. -/// -/// [1]: https://www.rfc-editor.org/rfc/rfc8445 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum IceConnectionState { - /// The ICE agent is gathering addresses. - New, - - /// The ICE agent is checking pairs of local and remote candidates against one - /// another to try to find a compatible match, but has not yet found a pair - /// which will allow the peer connection to be made. It is possible that - /// gathering of candidates is also still underway. - Checking, - - /// A usable pairing of local and remote candidates has been found, and the - /// connection has been established. The agent is not in `Completed` because - /// it is still gathering candidates or is still checking candidates against - /// one another looking for a better connection to use. - Connected, - - /// The ICE agent has finished gathering candidates, has checked all pairs - /// against one another, and has found a working connection. - Completed, - - /// Connection failed. This is a less stringent test than `failed` and may trigger - /// intermittently and resolve just as spontaneously on less reliable networks, - /// or during temporary disconnections. When the problem resolves, the connection - /// may return to the connected state. - Disconnected, - // - // NB: The failed and closed state doesn't really have a mapping in this implementation. - // We never end trickle ice and it's always possible to "come back" if more remote - // candidates are added. - // - // The ICE candidate has checked all candidates pairs against one another and has - // failed to find compatible matches. - // Failed, - // The ICE agent has shut down and is no longer handling requests. - // Closed, -} - -impl IceConnectionState { - /// Tells if this state is a connected state. - pub fn is_connected(&self) -> bool { - use IceConnectionState::*; - matches!(self, Connected | Completed) - } - - /// Tells if this state is a disconnected state. - pub fn is_disconnected(&self) -> bool { - *self == IceConnectionState::Disconnected - } -} - -/// Credentials for STUN packages. -/// -/// By matching IceCreds in STUN to SDP, we know which STUN belongs to which Peer. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct IceCreds { - /// From a=ice-ufrag - pub ufrag: String, - /// From a=ice-pwd - pub pass: String, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct IceAgentStats { - pub bind_request_sent: u64, - pub bind_success_recv: u64, - pub bind_request_recv: u64, - pub discovered_recv_count: u64, - pub nomination_send_count: u64, -} - -/// Events from an [`IceAgent`]. -#[derive(Debug, PartialEq, Eq)] -pub enum IceAgentEvent { - /// The agent restarted (or started). - IceRestart(IceCreds), - - /// Connection state changed. - /// - /// This is mostly for show since the actual addresses to use will be - /// communicated in `PossibleRemote` and `NominatedLocal`. - IceConnectionStateChange(IceConnectionState), - - /// A possible remote socket for the peer. - /// - /// The application should associate this with the peer. There will - /// be more than one of these, and traffic might eventually come in - /// on any of them. - /// - /// For each ICE restart, the app will only receive unique addresses once. - DiscoveredRecv { - /// The protocol to use for the socket. - proto: Protocol, - /// The remote socket to look out for. - source: SocketAddr, - }, - - /// A nominated local and remote socket for sending data. - /// - /// As opposed to the ICE spec, we can send this multiple times without - /// requiring an ICE restart. The application should always use the values - /// of the last emitted event to send data. - NominatedSend { - /// The protocol to use for the socket. - proto: Protocol, - /// The local socket address to send datagrams from. - /// - /// This will correspond to some local address added to - /// [`IceAgent::add_local_candidate`]. - source: SocketAddr, - /// The remote address to send datagrams to. - destination: SocketAddr, - }, -} - -impl IceCreds { - /// Creates a new instance of `IceCreds` with random values for the username fragment and password. - pub fn new() -> Self { - // Username Fragment and Password: Values used to perform connectivity - // checks. The values MUST be unguessable, with at least 128 bits of - // random number generator output used to generate the password, and - // at least 24 bits of output to generate the username fragment. - let ufrag = Id::<16>::random().to_string(); - let pass = Id::<22>::random().to_string(); - IceCreds { ufrag, pass } - } -} - -impl IceAgent { - /// Create a new [`IceAgent`] using the test SHA1-HMAC provider. - #[cfg(test)] - pub fn new(local_credentials: IceCreds) -> Self { - Self::with_hmac(local_credentials, &crate::vendor::is::DefaultSha1HmacProvider) - } - - /// Create a new [`IceAgent`] with a specific SHA1-HMAC provider. - pub fn with_hmac(local_credentials: IceCreds, sha1_hmac_provider: &'static dyn Sha1HmacProvider) -> Self { - IceAgent { - last_now: None, - ice_lite: false, - max_candidate_pairs: None, - has_exceeded_max_candidate_pairs: false, - local_credentials, - remote_credentials: None, - controlling: false, - control_tie_breaker: NonCryptographicRng::u64(), - state: IceConnectionState::New, - local_candidates: vec![], - remote_candidates: vec![], - candidate_pairs: vec![], - transmit: VecDeque::new(), - events: VecDeque::new(), - stun_server_queue: VecDeque::new(), - discovered_recv: HashSet::new(), - nominated_send: None, - stats: IceAgentStats::default(), - timing_advance: Duration::from_millis(50), - timing_config: StunTiming::default(), - local_preference: LocalPreferenceHolder(Arc::new(default_local_preference)), - sha1_hmac_provider, - mtu: DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN, - } - } - - /// Set the UDP datagram MTU range used for sizing internal buffers (target..=warn). - pub fn set_mtu(&mut self, mtu: RangeInclusive) { - self.mtu = mtu; - } - - /// Target MTU used for sizing outgoing STUN buffers. - pub fn mtu(&self) -> usize { - *self.mtu.start() - } - - /// Threshold above which an outgoing datagram triggers an MTU warning. - pub fn mtu_warn(&self) -> usize { - *self.mtu.end() - } - - /// Sets the control tie breaker of this agent. - /// - /// By default, this is randomly generated and per the ICE spec, - /// this MUST be the same for the duration of an ICE session. - pub fn set_control_tie_breaker(&mut self, tie_breaker: u64) { - self.control_tie_breaker = tie_breaker; - } - - /// The maximum number of candidate pairs to test. - /// - /// Any pairs above this limit will be dropped (worst priority first). - pub fn set_max_candidate_pairs(&mut self, max: usize) { - self.max_candidate_pairs = Some(max); - self.has_exceeded_max_candidate_pairs = false; // Reset the flag. - } - - /// Whether ice_lite is enabled. - /// - /// Default is disabled. - pub fn ice_lite(&self) -> bool { - self.ice_lite - } - - /// Enable or disable ice_lite. - /// - /// Default is disabled. - pub fn set_ice_lite(&mut self, enabled: bool) { - self.ice_lite = enabled; - } - - /// Set a new timing advance (Ta) value. - /// - /// Ta specifies the minimum increment of time that has to pass between calls to - /// [`IceAgent::handle_timeout`]s (guided via [`IceAgent::poll_timeout`]). - /// - /// Defaults to 50ms. - pub fn set_timing_advance(&mut self, duration: Duration) { - self.timing_advance = duration - } - - /// Local ice credentials. - pub fn local_credentials(&self) -> &IceCreds { - &self.local_credentials - } - - /// Sets the local ice credentials. - pub fn set_local_credentials(&mut self, r: IceCreds) { - if self.local_credentials != r { - debug!("Set local credentials: {:?}", Pii(&r)); - self.local_credentials = r; - } - } - - /// Sets the initial STUN **R**etransmission **T**ime**O**ut. - /// - /// It defines the initial period of time between transmission of a request - /// and the first retransmit of that request. The actual RTO doubles with - /// each retransmit up until the configured maximum RTO. - /// - /// Defaults to 250ms. - pub fn set_initial_stun_rto(&mut self, timeout: Duration) { - if self.timing_config.initial_rto == timeout { - return; - } - - self.timing_config.initial_rto = timeout; - - debug!("initial_rto = {timeout:?}"); - - self.bust_candidate_pair_timeout_caches(); - } - - /// Sets the maximum STUN **R**etransmission **T**ime**O**ut. - /// - /// It defines the maximum period of time between transmission of a request - /// and the first retransmit of that request. Once a candidate pair is - /// successful, this is how often we check that a STUN binding is alive. - /// As the STUN bindings of a successful candidate pair start to time out, - /// we probe the binding more often by halfing this value, up until the - /// maximum number of retransmits before we declare them failed. - /// - /// Defaults to 3000ms. - pub fn set_max_stun_rto(&mut self, timeout: Duration) { - if self.timing_config.max_rto == timeout { - return; - } - - self.timing_config.max_rto = timeout; - - debug!("max_rto = {timeout:?}"); - - self.bust_candidate_pair_timeout_caches(); - } - - /// Sets the maximum number of retransmits for STUN messages. - /// - /// Defaults to 9. - pub fn set_max_stun_retransmits(&mut self, num: usize) { - if self.timing_config.max_retransmits == num { - return; - } - - self.timing_config.max_retransmits = num; - - debug!("max_retransmits = {num}"); - } - - /// Sets the local preference calculation. - /// - /// This must be used before adding any local candidates. - pub fn set_local_preference(&mut self, p: impl LocalPreference) { - self.local_preference = LocalPreferenceHolder(Arc::new(p)); - } - - fn bust_candidate_pair_timeout_caches(&mut self) { - for pair in self.candidate_pairs.iter_mut() { - pair.reset_cached_next_attempt_time(); - } - } - - /// How long we at most tolerate missing replies for a successful candidate pair - /// before considering it failed. - pub fn ice_timeout(&self) -> Duration { - self.timing_config.timeout() - } - - /// Local ice candidates. - /// - /// The candidates have their ufrag filled out to the local credentials. - pub fn local_candidates(&self) -> impl Iterator + Clone + '_ { - self.local_candidates.iter().filter(|c| !c.discarded()).cloned() - } - - /// Remote ice candidates. - pub fn remote_candidates(&self) -> impl Iterator + Clone + '_ { - self.remote_candidates.iter().filter(|c| !c.discarded()).cloned() - } - - /// Determines whether any remote candidates match the specified address and - /// have been verified with a STUN request/response. - pub fn has_viable_remote_candidate(&self, addr: SocketAddr) -> bool { - self.candidate_pairs - .iter() - .filter(|cand| cand.state() == CheckState::Succeeded) - .any(|pair| self.remote_candidates[pair.remote_idx()].addr() == addr) - } - - /// Remote ice credentials. - pub fn remote_credentials(&self) -> Option<&IceCreds> { - self.remote_credentials.as_ref() - } - - /// Sets the remote ice credentials. - pub fn set_remote_credentials(&mut self, r: IceCreds) { - if self.remote_credentials.as_ref() != Some(&r) { - debug!("Set remote credentials: {:?}", Pii(&r)); - self.remote_credentials = Some(r); - } - } - - /// Determine whether an equivalent remote candidate is part of a viable candidate pair. - pub fn find_pair_for_equivalent_remote_candidate(&self, c: &Candidate) -> Option<&CandidatePair> { - self.candidate_pairs.iter().find(|pair| { - let o = &self.remote_candidates[pair.remote_idx()]; - c.addr() == o.addr() - && c.base() == o.base() - && c.proto() == o.proto() - && c.kind() == o.kind() - && c.raddr() == o.raddr() - }) - } - - /// Credentials for STUN. - /// - /// The username for the credential is formed by concatenating the - /// username fragment provided by the peer with the username fragment of - /// the ICE agent sending the request, separated by a colon (":"). - /// - /// The password is equal to the password provided by the peer. - /// - /// The responses utilize the same usernames and passwords as the requests - /// (note that the USERNAME attribute is not present in the response). - /// - /// ### Panics - /// - /// Panics if there are no remote credentials set. - fn stun_credentials(&self, reply: bool) -> (String, String) { - let local = &self.local_credentials; - - let (left, right, peer_pass) = if reply { - ("not_used", "not_used", "not_used") - } else { - let peer = self.remote_credentials.as_ref().expect("Remote ICE credentials"); - (&peer.ufrag[..], &local.ufrag[..], &peer.pass[..]) - }; - - let username = format!("{left}:{right}"); - let password = if reply { local.pass.clone() } else { peer_pass.into() }; - - (username, password) - } - - /// Whether this side is controlling or controlled. - #[allow(unused)] - pub fn controlling(&self) -> bool { - self.controlling - } - - /// Set whether we are the controlling side. - /// - /// You should not call this function after ICE candidate pair formation - /// has started, as the controlling state influences candidate prio! - pub fn set_controlling(&mut self, v: bool) { - self.controlling = v; - } - - /// Current ice agent state. - pub fn state(&self) -> IceConnectionState { - self.state - } - - /// Stats for the agent. - /// - /// Resets on ICE restart. - #[allow(unused)] - pub fn stats(&self) -> IceAgentStats { - self.stats - } - - /// Adds a local candidate. - /// - /// Returns `Some` if the candidate was added and `None` in all other cases. - /// If the candidate was added, it should be signalled to the remote party. - /// - /// Adding loopback addresses or multicast/broadcast addresses causes - /// an error. - pub fn add_local_candidate(&mut self, mut c: Candidate) -> Option<&Candidate> { - let ip = c.addr().ip(); - - if self.ice_lite { - // Reject all non-host candidates. - if c.kind() != CandidateKind::Host { - debug!("Reject non-host candidate due to ice-lite mode: {:?}", c); - return None; - } - } - - // Count the number of existing candidates of the same kind. - let same_kind = self - .local_candidates - .iter() - .filter(|v| v.kind() == c.kind()) - .filter(|v| v.addr().is_ipv6() == ip.is_ipv6()) - .count(); - - // Delegate local preference calculation to pluggable algo. - let pref = self.local_preference.0.calculate(&c, same_kind); - trace!("Calculated local preference: {}", pref); - c.set_local_preference(pref); - - // "Adopt" any incoming candidate by setting our current ufrag. - c.set_ufrag(&self.local_credentials.ufrag); - - // A candidate is redundant if and only if its transport address and base equal those - // of another candidate. The agent SHOULD eliminate the redundant - // candidate with the lower priority. - // - // NB this must be done _after_ set_local_preference(), since the prio() used in the - // elimination is calculated from that preference. - let maybe_redundant = self - .local_candidates - .iter_mut() - .enumerate() - .find(|(_, v)| v.addr() == c.addr() && v.base() == c.base() && v.proto() == c.proto()); - - let local_idx = if let Some((idx, other)) = maybe_redundant { - if other.discarded() && c.kind() == other.kind() && c.raddr() == other.raddr() { - debug!("Re-enable previously discarded local: {:?}", other); - other.set_discarded(false); - idx - } else { - if c.prio() < other.prio() { - // The new candidate is not better than what we already got. - debug!( - "Reject redundant candidate, current: {:?} rejected: {:?}", - Pii(&other), - Pii(&c) - ); - return None; - } - - // Stop using the current candidate in favor of the new one. - debug!( - "Replace redundant candidate, current: {:?} replaced with: {:?}", - Pii(&other), - Pii(&c) - ); - other.set_discarded(true); - self.discard_candidate_pairs_by_local(idx); - - let new_idx = self.local_candidates.len(); - - debug!("Add local candidate ({new_idx}): {:?}", Pii(&c)); - self.local_candidates.push(c); - - new_idx - } - } else { - let new_idx = self.local_candidates.len(); - - debug!("Add local candidate ({new_idx}): {:?}", Pii(&c)); - self.local_candidates.push(c); - - new_idx - }; - - // These are the indexes of the remote candidates this candidate should be paired with. - let remote_idxs: Vec<_> = self - .remote_candidates - .iter() - .enumerate() - .filter(|(_, v)| !v.discarded() && v.addr().is_ipv4() == ip.is_ipv4()) - .map(|(i, _)| i) - .collect(); - - // We always run in trickle ice mode. - // - // https://www.rfc-editor.org/rfc/rfc8838.html#section-10 - // A Trickle ICE agent MUST NOT pair a local candidate until it has been trickled - // to the remote party. - // - // TODO: The trickle ice spec is strange. What does it mean "has been trickled to the - // remote party"? Since we don't get a confirmation that the candidate has been received - // by the remote party, whether we form local pairs directly or later seems irrelevant. - self.form_pairs(&[local_idx], &remote_idxs); - - // We specifically use indexing here instead of `.get`. - // If the index is wrong, this is a bug! - Some(&self.local_candidates[local_idx]) - } - - /// Adds a remote candidate. - /// - /// Returns `false` if the candidate was not added because it is redundant. - /// Adding loopback addresses or multicast/broadcast addresses causes - /// an error. - pub fn add_remote_candidate(&mut self, mut c: Candidate) { - // This is a a:rtcp-mux-only implementation. The only component - // we accept is 1 for RTP. - if c.component_id() != 1 { - debug!("Reject candidate for component other than 1: {:?}", Pii(&c)); - return; - } - - if let Some(creds) = &self.remote_credentials { - if let Some(ufrag) = c.ufrag() { - if ufrag != creds.ufrag { - debug!( - "Reject candidate with ufrag mismatch: {} != {}", - Pii(&ufrag), - Pii(&creds.ufrag) - ); - return; - } - } - } - - // After we accepted the ufrag, don't keep this around since it will look - // confusing inspecting the state. - c.clear_ufrag(); - - let existing_pair = self.find_pair_for_equivalent_remote_candidate(&c); - let existing_candidate = existing_pair.map(|p| (p.remote_idx(), &self.remote_candidates[p.remote_idx()])); - - let existing_idx = match existing_candidate { - Some((_, o)) if !o.discarded() => { - // Existing non-discarded candidate in viable pair, ignore - // Discarded candidates and candidates not in a viable pair are handled below - trace!("Ignoring candidate({c:?}) that exactly matches existing non-discarded candidate"); - return; - } - Some((i, o)) if o.discarded() => Some(i), - _ => None, - }; - - let existing_prflx = self.remote_candidates.iter_mut().enumerate().find(|(_, v)| { - v.foundation() == REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION - && v.kind() == CandidateKind::PeerReflexive - && v.addr() == c.addr() - }); - - let ipv4 = c.addr().is_ipv4(); - - let remote_idx = if let Some((idx, existing)) = existing_prflx { - // If any subsequent candidate exchanges contain this peer-reflexive - // candidate, it will signal the actual foundation for the candidate. - debug!( - "Replace peer reflexive candidate, current: {:?} replaced with: {:?}", - Pii(&existing), - Pii(&c) - ); - *existing = c; - idx - } else { - let existing_discarded = existing_idx.and_then(|idx| { - let o = &mut self.remote_candidates[idx]; - - o.discarded().then_some((idx, o)) - }); - - if let Some((idx, other)) = existing_discarded { - debug!("Re-enable previously discarded remote: {:?}", Pii(&other)); - other.set_discarded(false); - idx - } else { - let new_idx = self.remote_candidates.len(); - - debug!("Add remote candidate ({new_idx}): {:?}", Pii(&c)); - self.remote_candidates.push(c); - - new_idx - } - }; - - // These are the indexes of the local candidates this candidate should be paired with. - let local_idxs: Vec<_> = self - .local_candidates - .iter() - .enumerate() - .filter(|(_, v)| !v.discarded() && v.addr().is_ipv4() == ipv4) - .map(|(i, _)| i) - .collect(); - - let remote_idxs = [remote_idx]; - self.form_pairs(&local_idxs, &remote_idxs); - } - - /// Form pairs given two slices of indexes into the local_candidates and remote_candidates. - fn form_pairs(&mut self, local_idxs: &[usize], remote_idxs: &[usize]) { - // Ensure to first update the kinds so any log statements are up-to-date. - for pair in &mut self.candidate_pairs { - pair.update_kinds(&self.local_candidates, &self.remote_candidates); - } - - for local_idx in local_idxs { - 'outer: for remote_idx in remote_idxs { - let local = &self.local_candidates[*local_idx]; - let remote = &self.remote_candidates[*remote_idx]; - - // Candidates in a pair must share the same protocol - if local.proto() != remote.proto() { - continue 'outer; - } - - let prio = CandidatePair::calculate_prio(self.controlling, remote.prio(), local.prio()); - let mut pair = CandidatePair::new(*local_idx, local.kind(), *remote_idx, remote.kind(), prio); - - trace!("Form pair local: {:?} remote: {:?}", local, remote); - - // The agent prunes each checklist. This is done by removing a - // candidate pair if it is redundant with a higher-priority candidate - // pair in the same checklist. Two candidate pairs are redundant if - // their local candidates have the same base and their remote candidates - // are identical. - - for (check_idx, check) in self.candidate_pairs.iter().enumerate() { - let check_local = check.local_candidate(&self.local_candidates); - let check_remote = check.remote_candidate(&self.remote_candidates); - - let redundant = local.base() == check_local.base() - && remote.addr() == check_remote.addr() - && local.proto() == check_local.proto() - && remote.proto() == check_remote.proto(); - - if redundant { - if check.prio() >= pair.prio() { - // skip this new pair since there is a redundant pair already in the - // list with higher/equal priority. - debug!( - "Reject redundant pair, current: {:?} rejected: {:?}", - Pii(&check), - Pii(&pair) - ); - } else { - // replace the existing candidate pair, since the new one got a higher prio. - pair.copy_nominated_and_success_state(&self.candidate_pairs[check_idx]); - - debug!( - "Replace redundant pair, current: {:?} replaced with: {:?}", - Pii(&check), - Pii(&pair) - ); - - if self.ice_lite { - debug!("Retain incoming binding requests for pair"); - pair.copy_remote_binding_requests(&self.candidate_pairs[check_idx]); - } - - self.candidate_pairs[check_idx] = pair; - } - - // There can only be one candidate pair per local base / remote addr. - // Since we found that redundant entry, there's no point in checking further - // candidate pairs. - continue 'outer; - } - } - - debug!("Add new pair {:?}", Pii(&pair)); - - // This is not a redundant pair, add it. - self.candidate_pairs.push(pair); - } - } - - // NB it would be nicer to have BTreeSet, but that makes it impossible to - // get mut references to the elements in the list. - self.candidate_pairs.sort(); - - // an ICE agent MUST limit the total number of connectivity checks - // the agent performs across all checklists in the checklist set. - // This is done by limiting the total number of candidate pairs in the - // checklist set. The default limit of candidate pairs for the checklist - // set is 100, but the value MUST be configurable. - // - // TODO: How does this work with trickle ice? - let max = self.max_candidate_pairs.unwrap_or(100); - - let num_pairs = self.candidate_pairs.len(); - if num_pairs > max && !self.has_exceeded_max_candidate_pairs { - warn!(%max, %num_pairs, "Exceeded max number of candidate pairs"); - self.has_exceeded_max_candidate_pairs = true; - } - - while self.candidate_pairs.len() > max { - let pair = self.candidate_pairs.pop(); - debug!("Remove overflow pair {:?}", Pii(&pair)); - } - } - - /// Invalidate a candidate and remove it from the connection. - /// - /// This is done for host candidates disappearing due to changes in the network - /// interfaces like a WiFi disconnecting or changing IPs. - /// - /// It can also be used to invalidate _remote_ candidates, i.e. if the remote - /// has signalled us that they have invalidated one of their candidates. - /// - /// Returns `true` if the candidate was found and invalidated. - pub fn invalidate_candidate(&mut self, c: &Candidate) -> bool { - if let Some((idx, other)) = self.local_candidates.iter_mut().enumerate().find(|(_, v)| { - v.addr() == c.addr() - && v.base() == c.base() - && v.raddr() == c.raddr() - && v.kind() == c.kind() - && v.proto() == c.proto() - }) { - if !other.discarded() { - debug!("Local candidate to discard {:?}", Pii(&other)); - other.set_discarded(true); - self.discard_candidate_pairs_by_local(idx); - return true; - } - } - - if let Some((idx, other)) = self.remote_candidates.iter_mut().enumerate().find(|(_, v)| { - v.addr() == c.addr() - && v.base() == c.base() - && v.raddr() == c.raddr() - && v.kind() == c.kind() - && v.proto() == c.proto() - }) { - if !other.discarded() { - debug!("Remote candidate to discard {:?}", Pii(&other)); - other.set_discarded(true); - self.discard_candidate_pairs_by_remote(idx); - return true; - } - } - - debug!("No local or remote candidate found: {:?}", Pii(&c)); - false - } - - /// Restart ICE. - /// - /// This is useful when detecting a change in network interfaces, such as - /// current session running off a 4G, and we connect to a WiFi. The session - /// should continue sending data over the 4G until we redone the ICE gathering - /// process. - #[allow(unused)] - pub fn ice_restart(&mut self, local_credentials: IceCreds, keep_local_candidates: bool) { - // An ICE agent MAY restart ICE for existing data streams. An ICE - // restart causes all previous states of the data streams, excluding the - // roles of the agents, to be flushed. The only difference between an - // ICE restart and a brand new data session is that during the restart, - // data can continue to be sent using existing data sessions, and a new - // data session always requires the roles to be determined. - - self.remote_credentials = None; - self.remote_candidates.clear(); - self.candidate_pairs.clear(); - self.has_exceeded_max_candidate_pairs = false; - self.transmit.clear(); - self.events.clear(); - self.discovered_recv.clear(); - - if keep_local_candidates { - // If we're keeping the candidates, we must update the ufrag to the new credentials. - // This is so anyone inspecting `.local_candidates()` will get the correct ufrag. - for c in &mut self.local_candidates { - c.set_ufrag(&local_credentials.ufrag) - } - } else { - self.local_candidates.clear(); - } - - self.local_credentials = local_credentials; - - self.emit_event(IceAgentEvent::IceRestart(self.local_credentials.clone())); - self.set_connection_state(IceConnectionState::Checking, "ice restart"); - } - - /// Re-create all candidate pairs from the current candidates. - /// - /// This is similar to an ICE restart but also retains all remote candidates. - pub fn recreate_candidate_pairs(&mut self) { - self.candidate_pairs.clear(); - - let local_idxs: Vec<_> = self - .local_candidates - .iter() - .enumerate() - .filter(|(_, v)| !v.discarded()) - .map(|(i, _)| i) - .collect(); - let remote_idxs: Vec<_> = self - .remote_candidates - .iter() - .enumerate() - .filter(|(_, v)| !v.discarded()) - .map(|(i, _)| i) - .collect(); - - self.form_pairs(&local_idxs, &remote_idxs); - self.set_connection_state(IceConnectionState::Checking, "recreate candidate pairs"); - } - - /// Discard candidate pairs that contain the candidate identified by a local index. - fn discard_candidate_pairs_by_local(&mut self, local_idx: usize) { - trace!("Discard pairs for local candidate index: {:?}", local_idx); - self.candidate_pairs.retain(|c| c.local_idx() != local_idx); - } - - /// Discard candidate pairs that contain the candidate identified by a remote index. - fn discard_candidate_pairs_by_remote(&mut self, remote: usize) { - trace!("Discard pairs for remote candidate index: {:?}", remote); - self.candidate_pairs.retain(|c| c.remote_idx() != remote); - } - - /// Tells whether the message is for this agent instance. - /// - /// This is used to multiplex multiple ice agents on a server sharing the same UDP socket. - /// - /// For binding requests, if no remote credentials have been set using - /// `set_remote_credentials`, the remote ufrag is not checked. - pub fn accepts_message(&self, message: &StunMessage<'_>) -> bool { - trace!("Check if accepts message: {:?}", message); - - let sha1_hmac = |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads); - - let do_integrity_check = |is_request: bool| -> bool { - let (_, password) = self.stun_credentials(is_request); - let integrity_passed = message.verify(password.as_bytes(), sha1_hmac); - - // The integrity is always the last thing we check - if integrity_passed { - trace!("Message accepted"); - } else { - trace!("Message rejected, integrity check failed"); - } - integrity_passed - }; - - let method = message.method(); - let class = message.class(); - match (method, class) { - (StunMethod::Binding, StunClass::Indication) => { - // https://datatracker.ietf.org/doc/html/rfc8489#section-6.3.2 - // An Indication can be safely ignored, its purpose is to refresh NATs in the - // network path. Some clients MAY omit USERNAME attribute. - false - } - (StunMethod::Binding, StunClass::Request) => { - // The username for the credential is formed by concatenating the - // username fragment provided by the peer with the username fragment of - // the ICE agent sending the request, separated by a colon (":"). - // The existence of this username is checked in the STUN parser. - let (local, remote) = message.split_username().unwrap(); - - let local_creds = self.local_credentials(); - if local != local_creds.ufrag { - trace!( - "Message rejected, local user mismatch: {} != {}", - local, local_creds.ufrag - ); - return false; - } - - if let Some(remote_creds) = &self.remote_credentials { - if remote != remote_creds.ufrag { - trace!( - "Message rejected, remote user mismatch: {} != {}", - remote, remote_creds.ufrag - ); - return false; - } - } - - do_integrity_check(true) - } - (StunMethod::Binding, StunClass::Success | StunClass::Failure) => { - let belongs_to_a_candidate_pair = self - .candidate_pairs - .iter() - .any(|pair| pair.binding_attempt(message.trans_id()).is_some()); - - if !belongs_to_a_candidate_pair { - trace!("Message rejected, transaction ID does not belong to any of our candidate pairs"); - return false; - } - - do_integrity_check(false) - } - (StunMethod::Binding, StunClass::Unknown) => { - // Without a known class, it's impossible to know how to validate the message - trace!("Message rejected, unknown STUN class"); - false - } - (StunMethod::Unknown, _) => { - // Without a known method, it's impossible to know how to validate the message - trace!("Message rejected, unknown STUN method"); - false - } - ( - StunMethod::Allocate - | StunMethod::Refresh - | StunMethod::Send - | StunMethod::Data - | StunMethod::CreatePermission - | StunMethod::ChannelBind, - _, - ) => { - // Unexpected TURN related message - trace!("Message rejected, TURN method({method:?}) unexpected in this context"); - false - } - } - } - - /// Handles an incoming STUN message. - /// - /// Will not be used if [`IceAgent::accepts_message`] returns false. - pub fn handle_packet(&mut self, now: Instant, packet: StunPacket) -> bool { - trace!("Handle receive: {:?}", &packet.message); - - // Regardless of whether we have remote_creds at this point, we can - // at least check the message integrity. - if !self.accepts_message(&packet.message) { - debug!("Message not accepted"); - return false; - } - - if packet.message.is_binding_request() { - self.stun_server_handle_message(now, &packet); - } else if packet.message.is_successful_binding_response() { - self.stun_client_handle_response(now, packet.message); - } else if packet.message.is_failed_binding_response() { - self.stun_client_handle_error(packet.message); - } - - self.emit_event(IceAgentEvent::DiscoveredRecv { - proto: packet.proto, - source: packet.source, - }); - - // TODO handle unsuccessful responses. - - true - } - - /// Provide the current time to the [`IceAgent`]. - /// - /// Typically, you will want to call [`IceAgent::poll_timeout`] and "wake-up" - /// the agent once that time is reached. - pub fn handle_timeout(&mut self, now: Instant) { - // This happens exactly once because evaluate_state() below will - // switch away from New -> Checking. - if self.state == IceConnectionState::New { - self.emit_event(IceAgentEvent::IceRestart(self.local_credentials.clone())); - } - - self.evaluate_state(now); - - // First we try to empty the queue of saved STUN requests. - if self.remote_credentials.is_some() { - let queue = &mut self.stun_server_queue; - - // No need hanging on to very old requests. - while let Some(peek) = queue.front() { - if now - peek.now >= self.timing_config.timeout() { - let r = queue.pop_front(); - trace!("Drop too old enqueued STUN request: {:?}", r.unwrap()); - } else { - break; - } - } - - if let Some(req) = self.stun_server_queue.pop_front() { - debug!("Handle enqueued STUN request: {:?}", Pii(&req)); - self.stun_server_handle_request(req); - return; - } - } - - self.last_now = Some(now); - - self.evaluate_nomination(); - - // prune failed candidates. - let mut any_pruned = false; - self.candidate_pairs.retain(|p| { - let keep = if self.ice_lite { - p.is_ice_lite_alive(now) - } else { - p.is_still_possible(now, &self.timing_config) - }; - if !keep { - debug!("Remove failed pair: {:?}", Pii(&p)); - any_pruned = true; - } - keep - }); - if any_pruned { - self.evaluate_nomination(); - self.evaluate_state(now); - } - - if self.remote_credentials.is_none() { - trace!("Stop timeout due to missing remote credentials"); - return; - } - - if self.ice_lite { - // Remote binding request time is the timestamp in the CandidatePair that - // is used to decide whether something is timed out or not. We need all - // pairs to have this time set, so that pairs that don't receive any - // STUN binding requests eventually times out. - for p in &mut self.candidate_pairs { - if p.remote_binding_request_time().is_none() { - p.increase_remote_binding_requests(now); - } - } - - trace!("Stop timeout since ice-lite do no checks"); - return; - } - - // when do we need to handle the next candidate pair? - let next = self - .candidate_pairs - .iter_mut() - .enumerate() - .map(|(i, c)| (i, c.next_binding_attempt(now, &self.timing_config))) - .min_by_key(|(_, t)| *t); - - if let Some((idx, deadline)) = next { - if now >= deadline { - let pair = &self.candidate_pairs[idx]; - trace!("Handle next triggered pair: {:?}", pair); - self.stun_client_binding_request(now, idx); - } else { - // trace!("Next triggered pair is in the future: {:?}", deadline - now); - } - } - } - - /// Poll for the next datagram to send. - pub fn poll_transmit(&mut self) -> Option { - let x = self.transmit.pop_front(); - if let Some(x) = &x { - if x.contents.len() > self.mtu_warn() { - warn!("ICE above MTU {}: {}", self.mtu_warn(), x.contents.len()); - } - trace!("Poll transmit: {:?}", x); - } - x - } - - /// Poll for the next time to call [`IceAgent::handle_timeout`]. - /// - /// For optimal performance, you should call this every time the [`IceAgent`]s state changes. - /// For example, after you call [`IceAgent::add_local_candidate`] or [`IceAgent::add_remote_candidate`]. - /// - /// Returns `None` until the first ever `handle_timeout` is called. - pub fn poll_timeout(&mut self) -> Option { - // if we never called handle_timeout, there will be no current time. - let last_now = self.last_now?; - - let has_request = !self.stun_server_queue.is_empty(); - let has_transmit = !self.transmit.is_empty(); - - // We must empty the queued replies or stuff to send as soon as possible. - if has_request || has_transmit { - return Some(last_now + self.timing_advance); - } - - // when do we need to handle the next candidate pair? - let maybe_next = if self.ice_lite { - // ice-lite doesn't do checks. - None - } else { - self.candidate_pairs - .iter_mut() - .map(|c| c.next_binding_attempt(last_now, &self.timing_config)) - .min() - }; - - // Time must advance with at least Ta. - let next = if let Some(next) = maybe_next { - if next < last_now + self.timing_advance { - last_now + self.timing_advance - } else { - next - } - } else { - // IDLE for a while. - last_now + Duration::from_secs(3) - }; - - Some(next) - } - - fn emit_event(&mut self, event: IceAgentEvent) { - if let IceAgentEvent::DiscoveredRecv { proto, source } = event { - if !self.discovered_recv.insert((proto, source)) { - // we already dispatched this discovered - return; - } - self.stats.discovered_recv_count += 1; - } else if matches!(event, IceAgentEvent::NominatedSend { .. }) { - self.stats.nomination_send_count += 1; - } - - trace!("Enqueueing event: {:?}", event); - self.events.push_back(event); - } - - /// Return a pending [`IceAgentEvent`] from this agent. - pub fn poll_event(&mut self) -> Option { - let x = self.events.pop_front(); - if x.is_some() { - trace!("Poll event: {:?}", x); - } - x - } - - fn stun_server_handle_message(&mut self, now: Instant, packet: &StunPacket) { - let message = &packet.message; - let prio = message - .prio() - // this should be guarded in the parsing - .expect("STUN request prio"); - let use_candidate = message.use_candidate(); - - if use_candidate { - trace!("Binding request sent USE-CANDIDATE"); - } - - let trans_id = message.trans_id(); - - // The existence of USERNAME is checked by the STUN parser. - let (_, remote_ufrag) = message.split_username().unwrap(); - - // Because we might have to delay stun requests until we receive the remote - // credentials, we extract all relevant bits of information so it can be owned. - let req = StunRequest { - now, - proto: packet.proto, - source: packet.source, - destination: packet.destination, - trans_id, - prio, - use_candidate, - remote_ufrag: remote_ufrag.into(), - ice_controlling: message.ice_controlling(), - ice_controlled: message.ice_controlled(), - }; - - if self.remote_credentials.is_some() { - self.stun_server_handle_request(req); - } else { - debug!( - "Enqueue STUN request due to missing remote credentials: {:?}", - Pii(&req) - ); - - let queue = &mut self.stun_server_queue; - - // It is possible (and in fact very likely) that the - // initiating agent will receive a Binding request prior to receiving - // the candidates from its peer. - queue.push_back(req); - - // This is some denial-of-service attack protection. - while queue.len() > 100 { - let r = queue.pop_front(); - debug!("Remove overflow STUN request {:?}", Pii(&r)); - } - - // If this happens, the agent MUST - // immediately generate a response. The agent has sufficient - // information at this point to generate the response; the password from - // the peer is not required. - - // TODO: The spec seems to indicate we can generate a reply, but that seems - // to fly in the face of logic. A reply requires a fingerprint message integrity - // and we can't construct that until we get the remote password. - } - } - - fn stun_server_handle_request(&mut self, req: StunRequest) { - let remote_creds = self.remote_credentials.as_ref().expect("Remote ICE creds"); - if req.remote_ufrag != remote_creds.ufrag { - // this check can be delayed due to receiving STUN bind requests before we - // get the exchange on the signal level. - debug!( - "STUN request rejected, remote user mismatch (enqueued): {} != {}", - Pii(&req.remote_ufrag), - Pii(&remote_creds.ufrag) - ); - return; - } - - // Drop requests that did not arrive on one of our local candidates - // before doing anything else. We must not mutate state, send replies - // (including 487 Role Conflict) or create peer-reflexive candidates - // for traffic that isn't actually directed at one of our interfaces. - let local_idx = match self.local_candidates.iter().position(|v| { - matches!(v.kind(), CandidateKind::Host | CandidateKind::Relayed) - && v.addr() == req.destination - && v.proto() == req.proto - }) { - Some(i) => i, - None => { - // Receiving traffic for an IP address that neither is a HOST nor RELAY - // is most likely a configuration fault where the user forgot to add a - // candidate for the local interface. We are network-connected application - // so we need to handle this gracefully: Log a message and discard the packet. - debug!("Discarding STUN request on unknown interface: {}", Pii(req.destination)); - return; - } - }; - - // Role conflict detection: if the peer claims the same role as us, - // the agent with the higher tiebreaker keeps its role and the loser yields. - if let Some(peer_tb) = req.role_conflict_tiebreaker(self.controlling) { - debug!( - "Role conflict on {} role: ours={}, peer={}", - role_name(self.controlling), - self.control_tie_breaker, - peer_tb, - ); - - if self.control_tie_breaker >= peer_tb { - self.send_role_conflict_reply(&req); - return; - } - - self.switch_role(!self.controlling); - } - - if req.use_candidate && self.controlling { - // the other side is not controlling, and it sent USE-CANDIDATE. that's wrong. - debug!("STUN request rejected, USE-CANDIDATE when local is controlling"); - return; - } - - self.stats.bind_request_recv += 1; - - // If the source transport address of the request does not match any - // existing remote candidates, it represents a new peer-reflexive remote - // candidate. - let found_in_remote = self - .remote_candidates - .iter() - .enumerate() - .filter(|(_, c)| !c.discarded() && c.proto() == req.proto && c.addr() == req.source) - // We may have multiple candidates with the same address - // (i.e. host and server-reflexive could be the same). - .max_by_key(|(_, c)| c.prio()); - - let remote_idx = if let Some((idx, _)) = found_in_remote { - trace!("Remote candidate for STUN request found"); - idx - } else { - let maybe_discarded = self - .remote_candidates - .iter() - .any(|c| c.discarded() && c.proto() == req.proto && c.addr() == req.source); - - if maybe_discarded { - // The remote has been discarded, we do not want to create a - // peer reflexive in this case. - trace!("STUN request ignored because remote candidate is discarded"); - return; - } - - // o The priority is the value of the PRIORITY attribute in the Binding - // request. - // - // o The foundation is an arbitrary value, different from the - // foundations of all other remote candidates. If any subsequent - // candidate exchanges contain this peer-reflexive candidate, it will - // signal the actual foundation for the candidate. - let c = Candidate::peer_reflexive( - req.proto, - req.source, - req.source, - req.prio, - // TODO: REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION should probably have - // a counter to really make it "different from the foundations of - // all other remote candidates". - // In practice it might no matter since we don't do the frozen-waiting - // dance for candidate pairs. - Some(REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION.into()), - self.local_credentials.ufrag.clone(), - ); - - debug!( - "Created peer reflexive remote candidate from STUN request: {:?}", - Pii(&c) - ); - - // This candidate is added to the list of remote candidates. However, - // the ICE agent does not pair this candidate with any local candidates. - self.remote_candidates.push(c); - - self.remote_candidates.len() - 1 - }; - - let maybe_pair = self - .candidate_pairs - .iter_mut() - .find(|p| p.local_idx() == local_idx && p.remote_idx() == remote_idx); - - if let Some(pair) = maybe_pair { - // When the pair is already on the checklist: - trace!("Found existing pair for STUN request: {:?}", pair); - - // TODO: The spec has all these ideas about resetting to Waiting state - // for the candidate pair. I think that's to do speeding up the triggered - // checks if a nomination comes through. It doesn't seem to make much - // sense in this implementation, where a nomination jumps the queue. - // https://datatracker.ietf.org/doc/html/rfc8445#section-7.3.1.4 - } else { - // If the pair is not already on the checklist: - let local = &self.local_candidates[local_idx]; - let remote = &self.remote_candidates[remote_idx]; - - if local.discarded() { - return; // Ignore STUN requests to discarded candidates - } - - let prio = CandidatePair::calculate_prio(self.controlling, remote.prio(), local.prio()); - - // * Its state is set to Waiting. (this is the default) - // * The pair is inserted into the checklist based on its priority. - // * The pair is enqueued into the triggered-check queue. - let pair = CandidatePair::new(local_idx, local.kind(), remote_idx, remote.kind(), prio); - - debug!("Created new pair for STUN request: {:?}", Pii(&pair)); - - self.candidate_pairs.push(pair); - self.candidate_pairs.sort(); - } - - let pair = self - .candidate_pairs - .iter_mut() - .find(|p| p.local_idx() == local_idx && p.remote_idx() == remote_idx) - // unwrap is fine since we have inserted a pair if it was missing. - .unwrap(); - - let local = pair.local_candidate(&self.local_candidates); - let proto = local.proto(); - let local_addr = local.base(); - let remote = pair.remote_candidate(&self.remote_candidates); - let remote_addr = remote.addr(); - - pair.increase_remote_binding_requests(req.now); - - if self.ice_lite && !self.controlling { - // ice-lite sends no checks of its own, so this pair can never be - // promoted by a binding response and stays `Waiting` for its - // whole life. `has_viable_remote_candidate` therefore never - // reports the remote, and `Rtc::accepts` refuses the peer's - // non-STUN traffic until nomination has given us a send address. - // - // An answered binding request is not return-routability proof - // the way a binding *response* is, and this does not claim to - // be. It is the only validation an ice-lite agent can ever - // have, and for a controlled agent it grants strictly less - // than an attacker already has: a forged USE-CANDIDATE request - // already reaches `pair.nominate()` below and redirects - // egress, while this only lets ingress reach DTLS/SRTP. - // - // A *controlling* ice-lite agent is left alone: there, - // `CheckState::Succeeded` feeds `evaluate_nomination()` just - // below, so promoting a pair here would let one forged request - // with a high PRIORITY choose the send address. - pair.record_remote_binding_request_success(); - } - - if !self.controlling && !pair.is_nominated() && req.use_candidate { - // We need to answer a nomination request with a binding request - // in the other direction. - // - // If this is ice-lite, we make it successful straight away. - pair.nominate(self.ice_lite); - } - - if self.controlling && pair.state() == CheckState::Succeeded { - // See if we can nominate something now. - self.evaluate_nomination(); - } - - let (_, password) = self.stun_credentials(true); - - let reply = StunMessage::binding_reply(req.trans_id, req.source); - - trace!("Send STUN reply: {} -> {} {:?}", local_addr, remote_addr, reply); - - let mut buf = vec![0_u8; self.mtu()]; - - let sha1_hmac = |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads); - let n = reply - .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac) - .expect("IO error writing STUN reply"); - buf.truncate(n); - - let trans = Transmit { - proto, - source: local_addr, - destination: remote_addr, - contents: buf.into(), - }; - - self.transmit.push_back(trans); - } - - fn send_role_conflict_reply(&mut self, req: &StunRequest) { - let (_, password) = self.stun_credentials(true); - - let reply = StunMessage::binding_role_conflict_reply(req.trans_id); - - debug!( - "Reply 487 Role Conflict (keep {} role): {} -> {}", - role_name(self.controlling), - req.destination, - req.source, - ); - - let mut buf = vec![0_u8; self.mtu()]; - - let sha1_hmac = |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads); - let n = reply - .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac) - .expect("IO error writing STUN error reply"); - buf.truncate(n); - - let trans = Transmit { - proto: req.proto, - source: req.destination, - destination: req.source, - contents: buf.into(), - }; - - self.transmit.push_back(trans); - } - - /// Switches the controlling/controlled role and recomputes pair priorities - /// per RFC 8445 §7.3.1.1. - fn switch_role(&mut self, controlling: bool) { - if self.controlling == controlling { - return; - } - - debug!( - "Switch role: {} -> {}", - role_name(self.controlling), - role_name(controlling), - ); - - self.controlling = controlling; - - for i in 0..self.candidate_pairs.len() { - let local_idx = self.candidate_pairs[i].local_idx(); - let remote_idx = self.candidate_pairs[i].remote_idx(); - let local_prio = self.local_candidates[local_idx].prio(); - let remote_prio = self.remote_candidates[remote_idx].prio(); - let new_prio = CandidatePair::calculate_prio(controlling, remote_prio, local_prio); - self.candidate_pairs[i].set_prio(new_prio); - } - self.candidate_pairs.sort(); - } - - fn stun_client_binding_request(&mut self, now: Instant, pair_idx: usize) { - let (username, password) = self.stun_credentials(false); - - let pair = &mut self.candidate_pairs[pair_idx]; - let local = pair.local_candidate(&self.local_candidates); - let remote = pair.remote_candidate(&self.remote_candidates); - let prio = local.prio_prflx(); - // Only the controlling side sends USE-CANDIDATE. - let use_candidate = self.controlling && pair.is_nominated(); - - let trans_id = pair.new_attempt(now, &self.timing_config, self.controlling); - - self.stats.bind_request_sent += 1; - - let binding = StunMessage::binding_request( - &username, - trans_id, - self.controlling, - self.control_tie_breaker, - prio, - use_candidate, - ); - - trace!("Send STUN request: {} -> {} {:?}", local.base(), remote.addr(), binding); - - let mut buf = vec![0_u8; self.mtu()]; - - let sha1_hmac = |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads); - let n = binding - .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac) - .expect("IO error writing STUN reply"); - buf.truncate(n); - - let trans = Transmit { - proto: local.proto(), - source: local.base(), - destination: remote.addr(), - contents: buf.into(), - }; - - self.transmit.push_back(trans); - } - - /// Handle a STUN binding error response. - /// - /// We only act on 487 (Role Conflict) per RFC 8445 §7.3.1.1: switch to - /// the opposite role, but only if the request that triggered the 487 was - /// sent under our current role. Otherwise the response is stale - - /// in-flight from before an earlier swap - and acting on it would flap. - fn stun_client_handle_error(&mut self, message: StunMessage<'_>) { - let Some((code, _)) = message.error_code() else { - return; - }; - if code != 487 { - debug!("Ignoring binding error response with code {code}"); - return; - } - - let trans_id = message.trans_id(); - let attempt = self.candidate_pairs.iter().find_map(|p| p.binding_attempt(trans_id)); - - let Some(attempt) = attempt else { - debug!("Ignore 487 for unknown transaction id"); - return; - }; - - if attempt.controlling() != self.controlling { - debug!( - "Ignore stale 487 (request was sent as {}, we are now {})", - role_name(attempt.controlling()), - role_name(self.controlling), - ); - return; - } - - debug!("Got 487 Role Conflict, switching from {}", role_name(self.controlling),); - self.switch_role(!self.controlling); - } - - fn stun_client_handle_response(&mut self, now: Instant, message: StunMessage<'_>) { - // Find the candidate pair that this trans_id was sent for. - let trans_id = message.trans_id(); - let maybe_pair = self - .candidate_pairs - .iter_mut() - .find(|p| p.binding_attempt(trans_id).is_some()); - - self.stats.bind_success_recv += 1; - - let pair = match maybe_pair { - Some(v) => v, - // Not finding the candidate pair is fine. That might mean the - // binding response came in "too late", after we discarded the - // pair for some reason. - None => { - debug!("No pair found for STUN response: {:?}", message); - return; - } - }; - - // The ICE agent MUST check the mapped address from the STUN response. - // If the transport address does not match any of the local candidates - // that the agent knows about, the mapped address represents a new - // candidate: a peer-reflexive candidate. - let mapped_address = message - .mapped_address() - // This should be caught in the parsing. - .expect("Mapped address in STUN response"); - - let found_in_local = self - .local_candidates - .iter() - .enumerate() - .find(|(_, c)| c.addr() == mapped_address); - - let (pair, valid_idx) = if let Some((valid_idx, _)) = found_in_local { - // Note, the valid_idx might not be the same as the local_idx that we - // sent the request from. This might happen for hosts with asymmetric - // routing, traffic leaving on one interface and responses coming back - // on another. - trace!("Found local candidate for mapped address: {}", mapped_address); - (pair, valid_idx) - } else { - let local_sent_from = pair.local_candidate(&self.local_candidates); - - // Like other candidates, a peer-reflexive candidate has a type, base, priority, - // and foundation. They are computed as follows: - - // o The priority is the value of the PRIORITY attribute in the Binding - // request. - // - // The PRIORITY attribute MUST be included in a Binding request and be - // set to the value computed by the algorithm in Section 5.1.2 for the - // local candidate, but with the candidate type preference of peer- - // reflexive candidates. - let prio = local_sent_from.prio_prflx(); - - // o The base is the local candidate of the candidate pair from which - // the Binding request was sent. - let base = local_sent_from.base(); - - // o The type is peer reflexive. - let candidate = Candidate::peer_reflexive( - local_sent_from.proto(), - mapped_address, - base, - prio, - None, - self.local_credentials.ufrag.clone(), - ); - - debug!( - "Created local peer reflexive candidate for mapped address: {}", - Pii(&mapped_address) - ); - - // The ICE agent does not need to pair the peer-reflexive candidate with - // remote candidates. - // If an agent wishes to pair the peer-reflexive candidate with remote - // candidates other than the one in the valid pair that will be generated, - // the agent MAY provide updated candidate information to the peer that includes - // the peer-reflexive candidate. This will cause the peer-reflexive candidate - // to be paired with all other remote candidates. - - // For now we do not tell the other side about discovered peer-reflexive candidates. - // We just include it in our list of local candidates and use it for the "valid pair". - self.local_candidates.push(candidate); - - let idx = self.local_candidates.len() - 1; - - (pair, idx) - }; - - pair.record_binding_response(now, trans_id, valid_idx); - - // For a controlled agent, a successful check can make a nominated pair valid. - self.evaluate_nomination(); - - // State might change when we get a response. - self.evaluate_state(now); - } - - fn evaluate_nomination(&mut self) { - let nominated_pair_priority = self.nominated_pair_priority(); - - let best_prio = if self.controlling { - // For controlling agents, we pick the best candidate pair using - // this strategy. - self.candidate_pairs - .iter_mut() - .filter(|p| p.state() == CheckState::Succeeded) - .max_by_key(|p| p.prio()) - } else { - // For controlled agents, we pick the best pair from what the controlling - // agent has indicated with USE-CANDIDATE stun attribute. RFC 8445 §7.3.1.5 - // lets us act on a nomination only once the pair is valid, i.e. our own - // check on it succeeded, so a pair the peer nominated but we cannot reach - // never becomes the send path. - self.candidate_pairs - .iter_mut() - .filter(|p| p.is_nominated() && p.state() == CheckState::Succeeded) - .max_by_key(|p| p.prio()) - }; - - if let Some(best_prio) = best_prio { - if let Some(nominated) = nominated_pair_priority { - if nominated == best_prio.prio() { - // The best prio is also the current nominated prio. Make - // no changes since there can be multiple pairs having the - // same best_prio. - return; - } - } - trace!("Nominating best candidate"); - - if !best_prio.is_nominated() && (self.controlling || self.ice_lite) { - // ice lite progresses pair to success straight away. - best_prio.nominate(self.ice_lite); - } - - let local = best_prio.local_candidate(&self.local_candidates); - let remote = best_prio.remote_candidate(&self.remote_candidates); - - self.nominated_send = Some(best_prio.id()); - self.emit_event(IceAgentEvent::NominatedSend { - proto: local.proto(), - source: local.base(), - destination: remote.addr(), - }) - } - } - - fn nominated_pair_priority(&self) -> Option { - let id = self.nominated_send?; - - self.candidate_pairs - .iter() - .find_map(|p| (p.id() == id).then_some(p.prio())) - } - - fn nominated_pair(&self) -> Option<&CandidatePair> { - let id = self.nominated_send?; - self.candidate_pairs.iter().find(|p| p.id() == id) - } - - /// The round-trip time of the most recent successful STUN binding - /// transaction on the nominated candidate pair. - /// - /// Returns `None` if there is no nominated pair, or no successful - /// binding response has been recorded on it. - /// - /// This is the ICE-level equivalent of - /// [`RTCIceCandidatePairStats.currentRoundTripTime`][1] and is updated - /// on every STUN keepalive/consent exchange - useful for measuring RTT - /// on receive-only endpoints where RTP-based RTT estimates aren't - /// available. - /// - /// [1]: https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime - pub fn nominated_pair_rtt(&self) -> Option { - self.nominated_pair().and_then(|p| p.last_successful_rtt()) - } - - /// Sum of all RTTs measured from successful STUN binding transactions - /// on the nominated candidate pair over its lifetime. - /// - /// Spec equivalent of [`RTCIceCandidatePairStats.totalRoundTripTime`][1]. - /// Divide by [`nominated_pair_responses_received`] to get the average. - /// - /// Returns `None` if there is no nominated pair. - /// - /// [`nominated_pair_responses_received`]: Self::nominated_pair_responses_received - /// [1]: https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime - pub fn nominated_pair_total_rtt(&self) -> Option { - self.nominated_pair().map(|p| p.total_round_trip_time()) - } - - /// Total number of STUN binding responses received on the nominated - /// candidate pair over its lifetime. - /// - /// Spec equivalent of [`RTCIceCandidatePairStats.responsesReceived`][1]. - /// - /// Returns `None` if there is no nominated pair. - /// - /// [1]: https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-responsesreceived - pub fn nominated_pair_responses_received(&self) -> Option { - self.nominated_pair().map(|p| p.responses_received()) - } - - fn set_connection_state(&mut self, state: IceConnectionState, reason: &'static str) { - if self.state != state { - debug!("State change ({}): {:?} -> {:?}", reason, self.state, state); - self.state = state; - self.emit_event(IceAgentEvent::IceConnectionStateChange(state)); - } - } - - fn evaluate_state(&mut self, now: Instant) { - use IceConnectionState::*; - - let mut any_nomination = false; - let mut any_still_possible = false; - - for p in &self.candidate_pairs { - // A nominated pair counts once it is valid (RFC 8445 §8.1.1), which is - // also when `evaluate_nomination` can make it the send path. Until then - // it is just another pair being checked. - if p.is_nominated() && p.state() == CheckState::Succeeded { - any_nomination = true; - } else if p.is_still_possible(now, &self.timing_config) { - any_still_possible = true; - } - } - - // As a special case, before the ice agent has received any candidates or - // discovered a peer reflexive via a STUN message, the agent is still viable. This is - // also the case for ice_restart. - if self.remote_candidates.is_empty() || self.local_candidates.is_empty() { - any_still_possible = true; - } - - match self.state { - New => { - self.set_connection_state(Checking, "new connection"); - } - Checking | Disconnected => { - if any_nomination { - if self.ice_lite { - self.set_connection_state(Completed, "got nomination in ice lite"); - return; - } - if any_still_possible { - self.set_connection_state(Connected, "got nomination, still trying others"); - } else { - self.set_connection_state(Completed, "got nomination, no others to try"); - } - } else if !any_still_possible { - self.set_connection_state(Disconnected, "no possible pairs"); - } else { - self.set_connection_state(Checking, "got new possible"); - } - } - Connected => { - if any_nomination { - if !any_still_possible { - self.set_connection_state(Completed, "no more possible to try"); - } - } else if any_still_possible { - self.set_connection_state(Checking, "got new possible"); - } else { - self.set_connection_state(Disconnected, "none nominated"); - } - } - Completed => { - if any_nomination { - if any_still_possible && !self.ice_lite { - self.set_connection_state(Connected, "got new possible"); - } - } else if any_still_possible { - self.set_connection_state(Checking, "got new possible"); - } else { - self.set_connection_state(Disconnected, "none nominated"); - } - } - } - } -} - -impl fmt::Debug for LocalPreferenceHolder { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("LocalPreferenceHolder").finish() - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::is::DefaultSha1HmacProvider; - use std::{iter, net::SocketAddr}; - - fn host(s: impl Into, proto: impl TryInto) -> Candidate { - let s: String = s.into(); - Candidate::host(s.parse().unwrap(), proto).unwrap() - } - - impl IceAgent { - pub(crate) fn num_candidate_pairs(&self) -> usize { - self.candidate_pairs.len() - } - - fn pair_indexes(&self) -> Vec<(usize, usize)> { - self.candidate_pairs - .iter() - .map(|c| (c.local_idx(), c.remote_idx())) - .collect() - } - } - - fn new_test_agent() -> IceAgent { - IceAgent::new(IceCreds::new()) - } - - fn ipv4_1() -> SocketAddr { - "1.2.3.4:5000".parse().unwrap() - } - fn ipv4_2() -> SocketAddr { - "2.3.4.5:5000".parse().unwrap() - } - fn ipv4_3() -> SocketAddr { - "3.4.5.6:5000".parse().unwrap() - } - fn ipv4_4() -> SocketAddr { - "4.5.6.7:5000".parse().unwrap() - } - fn ipv6_1() -> SocketAddr { - "[1001::]:5000".parse().unwrap() - } - fn ipv6_2() -> SocketAddr { - "[1002::]:5000".parse().unwrap() - } - - #[test] - fn local_preference_host() { - let mut agent = new_test_agent(); - - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - agent - .add_local_candidate(Candidate::host(ipv6_1(), "udp").unwrap()) - .unwrap(); - agent - .add_local_candidate(Candidate::host(ipv6_2(), "udp").unwrap()) - .unwrap(); - agent - .add_local_candidate(Candidate::host(ipv4_2(), "udp").unwrap()) - .unwrap(); - - let v: Vec<_> = agent.local_candidates.iter().map(|c| c.local_preference()).collect(); - - assert_eq!(v, vec![65534, 65535, 65533, 65532]); - } - - #[test] - fn discard_adding_redundant() { - let mut agent = new_test_agent(); - - // Frequently, a server-reflexive candidate and a host candidate will be - // redundant when the agent is not behind a NAT. - - let x2 = agent.add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()); - assert!(x2.is_some()); - - // this is redundant given we have the direct host candidate above. - let x1 = agent.add_local_candidate(Candidate::test_peer_rflx(ipv4_1(), ipv4_1(), "udp")); - assert!(x1.is_none()); - } - - #[test] - fn does_not_invalidate_local_candidate_with_same_ip_but_different_kind() { - let mut agent = new_test_agent(); - let host = Candidate::host(ipv4_1(), "udp").unwrap(); - let srflx = Candidate::server_reflexive(ipv4_1(), ipv4_1(), "udp").unwrap(); - - agent.add_local_candidate(host.clone()).unwrap(); - let invalidated = agent.invalidate_candidate(&srflx); - assert!(!invalidated); - - let invalidated = agent.invalidate_candidate(&host); - assert!(invalidated); - } - - #[test] - fn does_not_invalidate_local_candidate_with_same_ip_but_different_protocol() { - let mut agent = new_test_agent(); - let udp = Candidate::host(ipv4_1(), "udp").unwrap(); - let tcp = Candidate::host(ipv4_1(), "tcp").unwrap(); - - agent.add_local_candidate(udp.clone()).unwrap(); - agent.add_local_candidate(tcp.clone()).unwrap(); - - let invalidated = agent.invalidate_candidate(&tcp); - assert!(invalidated); - - let udp_discarded = agent - .local_candidates - .iter() - .find(|v| { - v.addr() == udp.addr() - && v.base() == udp.base() - && v.raddr() == udp.raddr() - && v.kind() == udp.kind() - && v.proto() == udp.proto() - }) - .unwrap() - .discarded(); - assert!(!udp_discarded); - - let tcp_discarded = agent - .local_candidates - .iter() - .find(|v| { - v.addr() == tcp.addr() - && v.base() == tcp.base() - && v.raddr() == tcp.raddr() - && v.kind() == tcp.kind() - && v.proto() == tcp.proto() - }) - .unwrap() - .discarded(); - assert!(tcp_discarded); - - let invalidated = agent.invalidate_candidate(&udp); - assert!(invalidated); - let udp_discarded = agent - .local_candidates - .iter() - .find(|v| { - v.addr() == udp.addr() - && v.base() == udp.base() - && v.raddr() == udp.raddr() - && v.kind() == udp.kind() - && v.proto() == udp.proto() - }) - .unwrap() - .discarded(); - assert!(udp_discarded); - } - - #[test] - fn does_not_invalidate_remote_candidate_with_same_ip_but_different_kind() { - let mut agent = new_test_agent(); - let host = Candidate::host(ipv4_1(), "udp").unwrap(); - let srflx = Candidate::server_reflexive(ipv4_1(), ipv4_1(), "udp").unwrap(); - - agent.add_remote_candidate(host.clone()); - let invalidated = agent.invalidate_candidate(&srflx); - - assert!(!invalidated); - - let invalidated = agent.invalidate_candidate(&host); - assert!(invalidated); - } - - #[test] - fn does_not_invalidate_remote_candidate_with_same_ip_but_different_protocol() { - let mut agent = new_test_agent(); - let udp = Candidate::host(ipv4_1(), "udp").unwrap(); - let tcp = Candidate::host(ipv4_1(), "tcp").unwrap(); - - agent.add_remote_candidate(udp.clone()); - agent.add_remote_candidate(tcp.clone()); - - let invalidated = agent.invalidate_candidate(&tcp); - assert!(invalidated); - - let udp_discarded = agent - .remote_candidates - .iter() - .find(|v| { - v.addr() == udp.addr() - && v.base() == udp.base() - && v.raddr() == udp.raddr() - && v.kind() == udp.kind() - && v.proto() == udp.proto() - }) - .unwrap() - .discarded(); - assert!(!udp_discarded); - - let tcp_discarded = agent - .remote_candidates - .iter() - .find(|v| { - v.addr() == tcp.addr() - && v.base() == tcp.base() - && v.raddr() == tcp.raddr() - && v.kind() == tcp.kind() - && v.proto() == tcp.proto() - }) - .unwrap() - .discarded(); - assert!(tcp_discarded); - - let invalidated = agent.invalidate_candidate(&udp); - assert!(invalidated); - let udp_discarded = agent - .remote_candidates - .iter() - .find(|v| { - v.addr() == udp.addr() - && v.base() == udp.base() - && v.raddr() == udp.raddr() - && v.kind() == udp.kind() - && v.proto() == udp.proto() - }) - .unwrap() - .discarded(); - assert!(udp_discarded); - } - - #[test] - fn discard_adding_redundant_by_address_and_protocol() { - let mut agent = new_test_agent(); - - // Candidates with the same SocketAddr but different protocols are considered distinct. - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .is_some() - ); - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_1(), "tcp").unwrap()) - .is_some() - ); - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_1(), "ssltcp").unwrap()) - .is_some() - ); - - // Verify these are rejected, since these tuples of address and protocol have been added. - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .is_none() - ); - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_1(), "ssltcp").unwrap()) - .is_none() - ); - - // Verify these are allowed, since these have different addresses. - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_2(), "udp").unwrap()) - .is_some() - ); - assert!( - agent - .add_local_candidate(Candidate::host(ipv4_2(), "ssltcp").unwrap()) - .is_some() - ); - } - - #[test] - fn discard_already_added_redundant() { - let mut agent = new_test_agent(); - - // Frequently, a server-reflexive candidate and a host candidate will be - // redundant when the agent is not behind a NAT. - - // this is contrived, but it is redundant when we add the host candidate below. - let x1 = agent.add_local_candidate(Candidate::test_peer_rflx(ipv4_1(), ipv4_1(), "udp")); - assert!(x1.is_some()); - - let x2 = agent.add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()); - assert!(x2.is_some()); - - let v: Vec<_> = agent.local_candidates.iter().map(|v| v.discarded()).collect(); - - assert_eq!(v, vec![true, false]); - } - - #[test] - fn form_pairs() { - let mut agent = new_test_agent(); - - // local 0 - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - // local 1 "udp" - agent - .add_local_candidate(Candidate::test_peer_rflx(ipv4_4(), ipv4_2(), "udp")) - .unwrap(); - // local 2 "tcp" - agent - .add_local_candidate(Candidate::host(ipv4_1(), "tcp").unwrap()) - .unwrap(); - - // remote 0 - agent.add_remote_candidate(Candidate::test_peer_rflx(ipv4_4(), ipv4_3(), "udp")); - // remote 1 "udp" - agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap()); - // remote 2 "tcp" - agent.add_remote_candidate(Candidate::host(ipv4_3(), "tcp").unwrap()); - - // we expect: - // (host/udp host/udp) - (0, 1) - // (host/udp rflx/udp) - (0, 1) - // (rflx/udp host/udp) - (1, 1) - // (rflx/udp rflx/udp) - (1, 0) - // (host/tcp host/tcp) - (2, 2) - - assert_eq!(agent.pair_indexes(), [(0, 1), (0, 0), (1, 1), (1, 0), (2, 2)]); - } - - #[test] - fn form_pairs_skip_redundant() { - let mut agent = new_test_agent(); - - agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap()); - agent.add_remote_candidate(Candidate::host(ipv4_3(), "tcp").unwrap()); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - // the UDP candidates should be pair up. - assert_eq!(agent.pair_indexes(), [(0, 0)]); - - // this local UDP candidate is redundant an won't form a new pair. - agent - .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp")) - .unwrap(); - - assert_eq!(agent.pair_indexes(), [(0, 0)]); - - // this local TCP candidate will be paired up (This is the 3rd local candidate) - agent - .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "tcp")) - .unwrap(); - - assert_eq!(agent.pair_indexes(), [(0, 0), (2, 1)]); - } - - #[test] - fn form_pairs_replace_redundant() { - let mut agent = new_test_agent(); - - agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap()); - agent - .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp")) - .unwrap(); - - assert_eq!(agent.pair_indexes(), [(0, 0)]); - - // this local candidate is redundant, but has higher priority than then existing pair. - // it replaces the existing pair. - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - assert_eq!(agent.pair_indexes(), [(1, 0)]); - } - - #[test] - fn form_pairs_replace_remote_redundant() { - let mut agent = new_test_agent(); - agent.set_ice_lite(true); - - // This is just prepping the test, this would have been discovered in a STUN packet. - let c = Candidate::peer_reflexive( - "udp", - ipv4_3(), - ipv4_3(), - 123, - Some(REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION.into()), - "".to_string(), - ); - - agent.add_remote_candidate(c); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - assert_eq!(agent.pair_indexes(), [(0, 0)]); - - let now = Instant::now(); - agent.candidate_pairs[0].nominate(true); - agent.candidate_pairs[0].increase_remote_binding_requests(now); - - // this remote should replace the "discovered" peer reflexive added above. - agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap()); - - // The index should not have changed, since we replaced the peer reflexive remote candidate. - assert_eq!(agent.pair_indexes(), [(0, 0)]); - - let pair = &agent.candidate_pairs[0]; - assert!(pair.is_nominated()); - - let (req, time) = pair.remote_binding_requests(); - assert_eq!(req, 1); - assert_eq!(time, Some(now)); - } - - #[test] - fn form_pairs_skip_invalidated_local() { - let mut agent = new_test_agent(); - - let local = Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"); - - agent.add_local_candidate(local.clone()).unwrap(); - agent.invalidate_candidate(&local); - - agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap()); - - // There should be no pairs since we invalidated the local candidate. - assert_eq!(agent.pair_indexes(), []); - } - - #[test] - fn form_pairs_skip_invalidated_remote() { - let mut agent = new_test_agent(); - - let remote = Candidate::host(ipv4_3(), "udp").unwrap(); - - agent.add_remote_candidate(remote.clone()); - agent.invalidate_candidate(&remote); - - agent - .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp")) - .unwrap(); - - // There should be no pairs since we invalidated the local candidate. - assert_eq!(agent.pair_indexes(), []); - } - - #[test] - fn poll_time_must_timing_advance() { - let mut agent = new_test_agent(); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap()); - - let now1 = Instant::now(); - agent.handle_timeout(now1); - let now2 = agent.poll_timeout().unwrap(); - - assert!(now2 - now1 == Duration::from_millis(50)); - } - - #[test] - fn no_disconnect_before_remote_candidates() { - let mut agent = new_test_agent(); - - let now = Instant::now(); - agent.handle_timeout(now); - - while let Some(ev) = agent.poll_event() { - if let IceAgentEvent::IceConnectionStateChange(s) = ev { - assert!(s != IceConnectionState::Disconnected); - } - } - - agent.handle_timeout(now + Duration::from_millis(200)); - while let Some(ev) = agent.poll_event() { - if let IceAgentEvent::IceConnectionStateChange(s) = ev { - assert!(s != IceConnectionState::Disconnected); - } - } - } - - #[test] - fn does_not_accept_response_with_unknown_transaction_id() { - let mut agent = new_test_agent(); - let remote_creds = IceCreds::new(); - let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap(); - remote_candidate.set_ufrag(&remote_creds.ufrag); - - agent.set_remote_credentials(remote_creds.clone()); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - agent.add_remote_candidate(remote_candidate); - agent.handle_timeout(Instant::now()); - - let payload = Vec::from(agent.poll_transmit().unwrap().contents); - let stun_message = StunMessage::parse(&payload).unwrap(); - - let valid_reply = make_authenticated_stun_reply(stun_message.trans_id(), ipv4_4(), &remote_creds.pass); - let fake_reply = make_authenticated_stun_reply(TransId::new(), ipv4_4(), &remote_creds.pass); - - assert!(!agent.accepts_message(&StunMessage::parse(&fake_reply).unwrap())); - assert!(agent.accepts_message(&StunMessage::parse(&valid_reply).unwrap())); - } - - #[test] - fn ignore_binding_indication() { - // STUN Binding Indication from OBS WHIP Client using Wireshark - // - // Session Traversal Utilities for NAT - // Message Type: 0x0011 (Binding Indication) - // Message Length: 8 - // Message Cookie: 2112a442 - // Message Transaction ID: fb9859e67da4bc991c0cab8f - // [STUN Network Version: RFC-5389/8489 (3)] - // Attributes - // FINGERPRINT - // Attribute Type: FINGERPRINT - // Attribute Length: 4 - // CRC-32: 0xed80c297 [correct] - // [CRC-32 Status: Good] - const BINDING: &[u8] = &[ - 0x00, 0x11, 0x00, 0x08, 0x21, 0x12, 0xa4, 0x42, 0xfb, 0x98, 0x59, 0xe6, 0x7d, 0xa4, 0xbc, 0x99, 0x1c, 0x0c, - 0xab, 0x8f, 0x80, 0x28, 0x00, 0x04, 0xed, 0x80, 0xc2, 0x97, - ]; - let stun_msg = StunMessage::parse(BINDING).unwrap(); - - let agent = new_test_agent(); - assert!(!agent.accepts_message(&stun_msg)); - } - - #[test] - fn queues_stun_binding_before_remote_creds() { - let mut agent = new_test_agent(); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - let remote_creds = IceCreds::new(); - let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap(); - remote_candidate.set_ufrag(&remote_creds.ufrag); - let prio = remote_candidate.prio(); - agent.add_remote_candidate(remote_candidate); - - let serialized_req = - make_serialized_binding_request(&agent.local_credentials, &remote_creds, !agent.controlling(), prio); - let binding_req = StunMessage::parse(&serialized_req).unwrap(); - - // Should not be dropped - assert!(agent.accepts_message(&binding_req)); - agent.handle_packet( - Instant::now(), - StunPacket { - message: binding_req, - source: ipv4_3(), - destination: ipv4_1(), - proto: Protocol::Udp, - }, - ); - - // Should not yet get a response - agent.handle_timeout(Instant::now()); - assert!(agent.poll_transmit().is_none()); - - agent.set_remote_credentials(remote_creds.clone()); - agent.handle_timeout(Instant::now()); - - // Now should have a response - let payload = Vec::from(agent.poll_transmit().unwrap().contents); - let stun_message = StunMessage::parse(&payload).unwrap(); - assert!(stun_message.is_successful_binding_response()); - } - - /// On simultaneous controlling/controlling startup, the lower-tiebreaker - /// agent typically receives the peer's request first (server-side swap) - /// while its own in-flight requests - sent under the old role - are - /// still being 487'd by the peer. Each of those stale 487s must be - /// ignored, otherwise the role flaps with every retransmit until the - /// in-flight drain finishes. - #[test] - pub fn ignores_stale_487_after_role_swap() { - let mut agent = new_test_agent(); - agent.set_controlling(true); - let remote_creds = IceCreds::new(); - agent.set_remote_credentials(remote_creds.clone()); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap(); - remote_candidate.set_ufrag(&remote_creds.ufrag); - agent.add_remote_candidate(remote_candidate); - - // Drive one binding request out - recorded as `controlling=true`. - agent.handle_timeout(Instant::now()); - let req_payload = Vec::from(agent.poll_transmit().unwrap().contents); - let trans_id = StunMessage::parse(&req_payload).unwrap().trans_id(); - - // Simulate that an earlier 487 (or a server-side conflict from an - // incoming peer request) already moved us to controlled. - agent.set_controlling(false); - - // Now the original request's 487 lands. It is stale: the attempt was - // sent as controlling, but we are no longer controlling. - let reply = make_role_conflict_reply(trans_id, &remote_creds.pass); - agent.handle_packet( - Instant::now(), - StunPacket { - proto: Protocol::Udp, - source: ipv4_3(), - destination: ipv4_1(), - message: StunMessage::parse(&reply).unwrap(), - }, - ); - - assert!(!agent.controlling(), "stale 487 must not flip role back to controlling"); - } - - #[test] - pub fn discards_packet_from_unknown_candidate() { - let mut agent = new_test_agent(); - let remote_creds = IceCreds::new(); - agent.set_remote_credentials(remote_creds.clone()); - - let request = make_serialized_binding_request(&agent.local_credentials, &remote_creds, false, 0); - - agent.handle_packet( - Instant::now(), - StunPacket { - proto: Protocol::Udp, - source: ipv4_1(), - destination: ipv4_2(), - message: StunMessage::parse(&request).unwrap(), - }, - ); - - assert!(agent.poll_transmit().is_none()); - } - - #[test] - pub fn no_disconnect_missing_local_candidates() { - let mut agent = new_test_agent(); - agent.set_remote_credentials(IceCreds::new().clone()); - - agent.add_remote_candidate(host("1.1.1.1:1000", "udp")); - agent.handle_timeout(Instant::now()); - agent.handle_timeout(Instant::now() + Duration::from_millis(100)); - - let events = iter::from_fn(|| agent.poll_event()).collect::>(); - assert!(!events.contains(&IceAgentEvent::IceConnectionStateChange( - IceConnectionState::Disconnected - ))); - } - - #[test] - fn discarded_local_candidates_are_not_returned() { - let mut agent = new_test_agent(); - let host1 = Candidate::host(ipv4_1(), "udp").unwrap(); - let host2 = Candidate::host(ipv4_2(), "udp").unwrap(); - - let host1 = agent.add_local_candidate(host1.clone()).unwrap().clone(); - let host2 = agent.add_local_candidate(host2.clone()).unwrap().clone(); - agent.invalidate_candidate(&host1); - - assert_eq!(agent.local_candidates().collect::>(), vec![host2]); - } - - #[test] - fn discarded_remote_candidates_are_not_returned() { - let mut agent = new_test_agent(); - let host1 = Candidate::host(ipv4_1(), "udp").unwrap(); - let host2 = Candidate::host(ipv4_2(), "udp").unwrap(); - - agent.add_remote_candidate(host1.clone()); - agent.add_remote_candidate(host2.clone()); - agent.invalidate_candidate(&host1); - - assert_eq!(agent.remote_candidates().collect::>(), vec![host2]); - } - - #[test] - fn ice_lite_remote_candidate_viable_after_binding_request() { - let mut agent = new_test_agent(); - agent.set_ice_lite(true); - agent.set_controlling(false); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - let remote_creds = IceCreds::new(); - agent.set_remote_credentials(remote_creds.clone()); - - let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap(); - remote_candidate.set_ufrag(&remote_creds.ufrag); - let prio = remote_candidate.prio(); - agent.add_remote_candidate(remote_candidate); - - // Nothing has been heard from the remote yet. - assert!(!agent.has_viable_remote_candidate(ipv4_3())); - - let serialized_req = make_serialized_binding_request( - &agent.local_credentials, - &remote_creds, - true, // the remote is the controlling agent - prio, - ); - let binding_req = StunMessage::parse(&serialized_req).unwrap(); - - let now = Instant::now(); - assert!(agent.handle_packet( - now, - StunPacket { - message: binding_req, - source: ipv4_3(), - destination: ipv4_1(), - proto: Protocol::Udp, - }, - )); - - // We answered a binding request whose integrity checked out against our - // local password. An ice-lite agent sends no checks of its own, so this - // is the only validation the pair will ever get, and it must be enough - // for the remote address to count as viable. - assert!(agent.has_viable_remote_candidate(ipv4_3())); - } - - #[test] - fn ice_lite_validation_survives_trickle() { - let mut agent = new_test_agent(); - agent.set_ice_lite(true); - agent.set_controlling(false); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - let remote_creds = IceCreds::new(); - agent.set_remote_credentials(remote_creds.clone()); - // Receive a check before the remote host candidate is signaled. - let remote = Candidate::host(ipv4_3(), "udp").unwrap(); - let serialized = - make_serialized_binding_request(&agent.local_credentials, &remote_creds, true, remote.prio() - 1); - assert!(agent.handle_packet( - Instant::now(), - StunPacket { - message: StunMessage::parse(&serialized).unwrap(), - source: ipv4_3(), - destination: ipv4_1(), - proto: Protocol::Udp, - } - )); - assert!(agent.has_viable_remote_candidate(ipv4_3())); - // The higher-priority signaled candidate replaces the peer-reflexive pair. - agent.add_remote_candidate(remote); - assert!( - agent.has_viable_remote_candidate(ipv4_3()), - "trickling the real candidate must retain validated ingress" - ); - } - - #[test] - fn ice_lite_controlling_does_not_nominate_on_a_binding_request() { - // The controlled case above is the supported one. A *controlling* - // ice-lite agent must not be promoted the same way: there, - // `CheckState::Succeeded` feeds `evaluate_nomination`, so one - // request - whose PRIORITY the sender chooses - would pick the - // send address without any return-routability proof. - let mut agent = new_test_agent(); - agent.set_ice_lite(true); - agent.set_controlling(true); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - let remote_creds = IceCreds::new(); - agent.set_remote_credentials(remote_creds.clone()); - - let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap(); - remote_candidate.set_ufrag(&remote_creds.ufrag); - let prio = remote_candidate.prio(); - agent.add_remote_candidate(remote_candidate); - - let serialized_req = make_serialized_binding_request( - &agent.local_credentials, - &remote_creds, - false, // we are the controlling agent - prio, - ); - let binding_req = StunMessage::parse(&serialized_req).unwrap(); - - assert!(agent.handle_packet( - Instant::now(), - StunPacket { - message: binding_req, - source: ipv4_3(), - destination: ipv4_1(), - proto: Protocol::Udp, - }, - )); - - assert!(!agent.has_viable_remote_candidate(ipv4_3())); - assert!( - !agent - .events - .iter() - .any(|e| matches!(e, IceAgentEvent::NominatedSend { .. })), - "a single binding request must not choose the send address" - ); - } - - #[test] - fn controlled_sends_only_on_a_nominated_pair_whose_check_succeeded() { - // RFC 8445 §7.3.1.5: the controlled agent acts on USE-CANDIDATE only - // for a pair that is, or becomes, valid. Here the peer nominates the - // highest-priority pair first, but our checks on it are never - // answered (one-way connectivity). It then nominates a lower-priority - // pair whose check succeeds. Media must go to the second pair. - let mut agent = new_test_agent(); - agent.set_controlling(false); - agent - .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap()) - .unwrap(); - - let remote_creds = IceCreds::new(); - agent.set_remote_credentials(remote_creds.clone()); - - let mut dead = Candidate::from_sdp_string("candidate:1 1 udp 2130706431 3.4.5.6 5000 typ host").unwrap(); - dead.set_ufrag(&remote_creds.ufrag); - let mut alive = Candidate::from_sdp_string("candidate:2 1 udp 1694498815 4.5.6.7 5000 typ host").unwrap(); - alive.set_ufrag(&remote_creds.ufrag); - let (dead_prio, alive_prio) = (dead.prio(), alive.prio()); - assert!(dead_prio > alive_prio); - agent.add_remote_candidate(dead); - agent.add_remote_candidate(alive); - - let nominate = |agent: &mut IceAgent, now: Instant, source: SocketAddr, prio: u32| { - let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag); - let req = StunMessage::binding_request(&username, TransId::new(), true, 0, prio, true); - let req = serialize_stun_msg(req, &agent.local_credentials.pass); - assert!(agent.handle_packet( - now, - StunPacket { - message: StunMessage::parse(&req).unwrap(), - source, - destination: ipv4_1(), - proto: Protocol::Udp, - }, - )); - }; - - // Answer our checks toward `alive` only; drop everything else. - let answer_alive = |agent: &mut IceAgent, now: Instant| { - let mut replies = vec![]; - while let Some(t) = agent.poll_transmit() { - let msg = StunMessage::parse(&t.contents).unwrap(); - if t.destination == ipv4_4() && msg.is_binding_request() { - replies.push(make_authenticated_stun_reply( - msg.trans_id(), - ipv4_1(), - &remote_creds.pass, - )); - } - } - for reply in replies { - agent.handle_packet( - now, - StunPacket { - message: StunMessage::parse(&reply).unwrap(), - source: ipv4_4(), - destination: ipv4_1(), - proto: Protocol::Udp, - }, - ); - } - }; - - let nominated_sends = |agent: &mut IceAgent| { - let mut v = vec![]; - while let Some(e) = agent.poll_event() { - if let IceAgentEvent::NominatedSend { destination, .. } = e { - v.push(destination); - } - } - v - }; - - let mut now = Instant::now(); - agent.handle_timeout(now); - - nominate(&mut agent, now, ipv4_3(), dead_prio); - for _ in 0..20 { - answer_alive(&mut agent, now); - now += Duration::from_millis(50); - agent.handle_timeout(now); - } - assert_eq!( - nominated_sends(&mut agent), - vec![], - "a nominated pair whose check has not succeeded must not be used" - ); - - nominate(&mut agent, now, ipv4_4(), alive_prio); - for _ in 0..20 { - answer_alive(&mut agent, now); - now += Duration::from_millis(50); - agent.handle_timeout(now); - } - assert_eq!(nominated_sends(&mut agent), vec![ipv4_4()]); - } - - fn make_serialized_binding_request( - local_creds: &IceCreds, - remote_creds: &IceCreds, - controlling: bool, - prio: u32, - ) -> Vec { - let username = format!("{}:{}", local_creds.ufrag, remote_creds.ufrag); - let binding_req = StunMessage::binding_request(&username, TransId::new(), controlling, 0, prio, false); - serialize_stun_msg(binding_req, &local_creds.pass) - } - - fn make_authenticated_stun_reply(tx_id: TransId, addr: SocketAddr, password: &str) -> Vec { - let reply = StunMessage::binding_reply(tx_id, addr); - serialize_stun_msg(reply, password) - } - - fn make_role_conflict_reply(tx_id: TransId, password: &str) -> Vec { - let reply = StunMessage::binding_role_conflict_reply(tx_id); - serialize_stun_msg(reply, password) - } - - /// Serializing will calculate a message integrity for it. You can then re-parse to get a message - /// that contains that correct integrity value. - fn serialize_stun_msg(msg: StunMessage<'_>, password: &str) -> Vec { - let mut buf = vec![0_u8; DATAGRAM_MTU_TARGET]; - - let sha1_hmac = |key: &[u8], payloads: &[&[u8]]| DefaultSha1HmacProvider.sha1_hmac(key, payloads); - let n = msg - .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac) - .expect("IO error writing STUN message"); - buf.truncate(n); - - buf - } - - #[test] - fn set_mtu_updates_mtu() { - let mut agent = IceAgent::new(IceCreds::new()); - assert_eq!(agent.mtu(), DATAGRAM_MTU_TARGET); - assert_eq!(agent.mtu_warn(), DATAGRAM_MTU_WARN); - - agent.set_mtu(900..=1280); - assert_eq!(agent.mtu(), 900); - assert_eq!(agent.mtu_warn(), 1280); - } -} diff --git a/rs/moq-webrtc/src/vendor/is/candidate.rs b/rs/moq-webrtc/src/vendor/is/candidate.rs deleted file mode 100644 index ecc9ae62551..00000000000 --- a/rs/moq-webrtc/src/vendor/is/candidate.rs +++ /dev/null @@ -1,1146 +0,0 @@ -use crate::vendor::is::IceError; -use crate::vendor::str0m_proto::{Protocol, TcpType}; -use serde::ser::SerializeStruct; -use serde::{Deserialize, Serialize, Serializer}; -use std::collections::hash_map::DefaultHasher; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; -use std::net::{IpAddr, SocketAddr}; - -/// ICE candidates are network addresses used to connect to a peer. -/// -/// There are different kinds of ICE candidates. The simplest kind is a -/// host candidate which is a socket address on a local (host) network interface. -#[derive(Clone, PartialEq, Eq, Hash)] -pub struct Candidate { - /// An arbitrary string used in the freezing algorithm to - /// group similar candidates. - /// - /// It is the same for two candidates that - /// have the same type, base IP address, protocol (UDP, TCP, etc.), - /// and STUN or TURN server. If any of these are different, then the - /// foundation will be different. - /// - /// For remote, this is communicated, and locally it's calculated. - foundation: Option, // 1-32 "ice chars", ALPHA / DIGIT / "+" / "/" - - /// A component is a piece of a data stream. - /// - /// A data stream may require multiple components, each of which has to - /// work in order for the data stream as a whole to work. For RTP/RTCP - /// data streams, unless RTP and RTCP are multiplexed in the same port, - /// there are two components per data stream -- one for RTP, and one - /// for RTCP. - component_id: u16, // 1 for RTP, 2 for RTCP - - /// Protocol for the candidate. - proto: Protocol, - - /// Priority. - /// - /// For remote, this is communicated, and locally it's (mostly) calculated. - /// For local peer reflexive it is set. - prio: Option, // 1-10 digits - - /// The actual address to use. This might be a host address, server reflex, relay etc. - addr: SocketAddr, // ip/port - - /// The base address - /// - /// "Base" refers to the address an agent sends from for a - /// particular candidate. Thus, as a degenerate case, host candidates - /// also have a base, but it's the same as the host candidate. - /// - /// * host - same as `addr`, i.e the local interface address - /// * peer/server reflexive - the local interface address - /// * relay - same as `addr`, the allocation on the TURN server - base: Option, // the "base" used for local candidates. - - /// Type of candidate. - kind: CandidateKind, // host/srflx/prflx/relay - - /// TCP connection role specified by the optional `tcptype` ICE candidate - /// extension. - tcptype: Option, - - /// Related address. - /// - /// For server-reflexive candidates, this is the internal IP/port the candidate corresponds to - /// (the one behind the NAT, usually). For relay candidates, this is the mapped address selected - /// by the TURN server. - raddr: Option, // ip/port - - /// Ufrag. - /// - /// This is used to tie an ice candidate to a specific ICE session. It's important - /// when trickle ICE is used in conjunction with ice restart, since it must be - /// possible the ice agent to know whether a candidate appearing belongs to - /// the current or previous session. - /// - /// This value is only set for incoming candidates. Once we use the candidate inside - /// pairs, the field is blanked to not be confusing during ice-restarts. - ufrag: Option, - - /// The address of the local interface. - /// - /// * host - same as `addr` - /// * peer/server reflexive - same as `base` - /// * relay - set explicitly - /// - /// This is an extension to the ICE spec that we use to track - /// local interfaces also for relayed candidates. - local: SocketAddr, - - /// The ice agent might assign a local preference if we have multiple candidates - /// that are the same type. - local_preference: Option, - - /// If we discarded this candidate (for example due to being redundant - /// against another candidate). - discarded: bool, -} - -impl fmt::Debug for Candidate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Candidate({}={}/{}", self.kind, self.addr, self.proto)?; - if let Some(base) = self.base { - if base != self.addr { - write!(f, " base={base}")?; - } - } - if let Some(raddr) = self.raddr { - write!(f, " raddr={raddr}")?; - } - write!(f, " prio={}", self.prio())?; - if self.discarded { - write!(f, " discarded")?; - } - write!(f, ")") - } -} - -impl Candidate { - /// Starts the typesafe builder. - /// - /// # Example - /// - /// ```ignore - /// # use crate::vendor::is::Candidate; - /// # use crate::vendor::is::IceError; - /// # use crate::vendor::str0m_proto::TcpType; - /// # use std::net::SocketAddr; - /// - /// let addr: SocketAddr = "192.168.1.1:12345".parse().unwrap(); - /// - /// // A standard UDP host candidate - /// let udp_host = Candidate::builder() - /// .udp() - /// .host(addr) - /// .build()?; - /// - /// // A TCP host candidate with a passive role - /// let tcp_host = Candidate::builder() - /// .tcp() - /// .host(addr) - /// .tcptype(TcpType::Passive) - /// .build()?; - /// - /// # Ok::<(), IceError>(()) - /// ``` - pub fn builder() -> CandidateBuilder { - CandidateBuilder { - protocol_state: NoProtocol(()), - route_state: NoRoute(()), - foundation: None, - component_id: 1, // Default RTP - prio: None, - tcptype: None, - raddr: None, - ufrag: None, - local_preference: None, - } - } - - #[allow(clippy::too_many_arguments)] - fn new( - foundation: Option, - component_id: u16, - proto: Protocol, - prio: Option, - addr: SocketAddr, - base: Option, - kind: CandidateKind, - raddr: Option, - tcptype: Option, - ufrag: Option, - local: SocketAddr, - ) -> Self { - Candidate { - foundation, - component_id, - proto, - prio, - addr, - base, - kind, - raddr, - tcptype, - ufrag, - local, - local_preference: None, - discarded: false, - } - } - - #[allow(clippy::too_many_arguments)] - pub fn from_parts( - foundation: String, - component_id: u16, - proto: Protocol, - prio: u32, - addr: SocketAddr, - kind: CandidateKind, - raddr: Option, - tcptype: Option, - ufrag: Option, - ) -> Self { - Candidate::new( - Some(foundation), - component_id, - proto, - Some(prio), - addr, - None, - kind, - raddr, - tcptype, - ufrag, - match kind { - CandidateKind::Host => addr, - CandidateKind::PeerReflexive | CandidateKind::ServerReflexive | CandidateKind::Relayed => { - Self::arbitrary_raddr(addr) - } - }, - ) - } - - /// Creates a host ICE candidate. - /// - /// Host candidates are local sockets directly on the host. - pub fn host(addr: SocketAddr, proto: impl TryInto) -> Result { - if !is_valid_ip(addr.ip()) { - return Err(IceError::BadCandidate(format!("invalid ip {}", addr.ip()))); - } - - Ok(Candidate::new( - None, - 1, // only RTP - parse_proto(proto)?, - None, - addr, - Some(addr), - CandidateKind::Host, - None, - None, - None, - addr, - )) - } - - /// Creates a server reflexive ICE candidate. - /// - /// Server reflexive candidates are local sockets mapped to external ip discovered - /// via a STUN binding request. - /// The `base` is the local interface that this address corresponds to. - pub fn server_reflexive( - addr: SocketAddr, - base: SocketAddr, - proto: impl TryInto, - ) -> Result { - if !is_valid_ip(addr.ip()) { - return Err(IceError::BadCandidate(format!("invalid ip {}", addr.ip()))); - } - - if addr.is_ipv4() != base.is_ipv4() { - return Err(IceError::BadCandidate( - "addr and base are different IP versions".to_owned(), - )); - } - - Ok(Candidate::new( - None, - 1, // only RTP - parse_proto(proto)?, - None, - addr, - Some(base), - CandidateKind::ServerReflexive, - Some(Self::arbitrary_raddr(addr)), - None, - None, - base, - )) - } - - /// Creates a relayed ICE candidate. - /// - /// Relayed candidates are server sockets relaying traffic to a local socket. - /// Allocate a TURN addr to use as a local candidate. - /// - /// * `addr` - The TURN server's allocated address for relaying traffic. - /// This is the address used for communication with the peer. - /// * `local` - The local interface address for this candidate. - /// This is the address from which the TURN allocation request was sent. - /// * `proto` - The transport protocol to use (UDP, TCP, etc.). - pub fn relayed(addr: SocketAddr, local: SocketAddr, proto: impl TryInto) -> Result { - if !is_valid_ip(addr.ip()) { - return Err(IceError::BadCandidate(format!("invalid ip {}", addr.ip()))); - } - - Ok(Candidate::new( - None, - 1, // only RTP - parse_proto(proto)?, - None, - addr, - Some(addr), - CandidateKind::Relayed, - Some(Self::arbitrary_raddr(addr)), - None, - None, - local, - )) - } - - /// Creates a new ICE candidate from a candidate attribute string. - /// - /// Expects the format from RFC 5245 section 15.1, e.g. - /// `candidate:1 1 udp 2113929471 203.0.113.100 10100 typ host`. - pub fn from_sdp_string(s: &str) -> Result { - crate::vendor::is::parse::parse_candidate(s) - } - - /// Creates a peer reflexive ICE candidate. - /// - /// Peer reflexive candidates are NAT:ed addresses discovered via STUN - /// binding responses. `addr` is the discovered address. `base` is the local - /// (host) address inside the NAT we used to get this response. - pub(crate) fn peer_reflexive( - proto: impl TryInto, - addr: SocketAddr, - base: SocketAddr, - prio: u32, - found: Option, - ufrag: String, - ) -> Self { - Candidate::new( - found, - 1, // only RTP - parse_proto(proto).expect("internal call to have correct protocol"), - Some(prio), - addr, - Some(base), - CandidateKind::PeerReflexive, - None, - None, - Some(ufrag), - base, - ) - } - - /// Create an arbitrary socket address, matching the format of the input address, - /// for placement in the `raddr` field. - /// - /// For non-host candidates, Firefox (and perhaps others) require the SDP string to - /// contain `raddr` and `rport` to correctly parse. While we could put honest values - /// here, those honest values are likely private IP addresses that we would rather not - /// expose to the world. Instead, browsers often spoof values to go here instead, and - /// we do the same. - /// - /// Note that `raddr` and `rport` are only for diagnostic purposes, and have no - /// bearing on ICE connectivity checks. - fn arbitrary_raddr(s: SocketAddr) -> SocketAddr { - use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6}; - match s { - SocketAddr::V4(_) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)), - SocketAddr::V6(_) => SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)), - } - } - - #[cfg(test)] - pub(crate) fn test_peer_rflx(addr: SocketAddr, base: SocketAddr, proto: impl TryInto) -> Self { - Candidate::new( - None, - 1, // only RTP - parse_proto(proto).expect("internal test to have correct protocol"), - None, - addr, - Some(base), - CandidateKind::PeerReflexive, - None, - None, - None, - base, - ) - } - - /// Candidate foundation. - /// - /// For local candidates this is calculated. - pub(crate) fn foundation(&self) -> String { - if let Some(v) = &self.foundation { - return v.clone(); - } - - // Two candidates have the same foundation when all of the - // following are true: - let mut hasher = DefaultHasher::new(); - - // o They have the same type (host, relayed, server reflexive, or peer - // reflexive). - self.kind.hash(&mut hasher); - - // o Their bases have the same IP address (the ports can be different). - self.base().ip().hash(&mut hasher); - - // o For reflexive and relayed candidates, the STUN or TURN servers - // used to obtain them have the same IP address (the IP address used - // by the agent to contact the STUN or TURN server). - if let Some(raddr) = self.raddr { - raddr.ip().hash(&mut hasher); - } - - // o They were obtained using the same transport protocol (TCP, UDP). - self.proto.hash(&mut hasher); - - let hash = hasher.finish(); - - format!("{:08x}{hash:x}", self.prio().to_be()) - } - - /// Returns the priority value for the specified ICE candidate. - /// - /// The priority is a positive integer between 1 and 2^31 - 1 (inclusive), calculated - /// according to the ICE specification defined in RFC 8445, Section 5.1.2. - pub fn prio(&self) -> u32 { - self.do_prio(false) - } - - pub(crate) fn prio_prflx(&self) -> u32 { - self.do_prio(true) - } - - fn do_prio(&self, as_prflx: bool) -> u32 { - // Remote candidates have their prio calculated on their side. - if let Some(prio) = &self.prio { - return *prio; - } - - let kind = if as_prflx { - CandidateKind::PeerReflexive - } else { - self.kind - }; - - // Per RFC5245 Sec. 4.1.2.1, the RECOMMENDED values for type preferences are - // 126 for host candidates, 110 for peer-reflexive candidates, 100 for - // server-reflexive candidates, and 0 for relayed candidates. The variations - // for non-UDP protocols are taken from libwebrtc: - // - let type_preference = match (kind, self.proto) { - (CandidateKind::Host, Protocol::Udp) => 126, - (CandidateKind::PeerReflexive, Protocol::Udp) => 110, - (CandidateKind::ServerReflexive, _) => 100, - (CandidateKind::Host, _) => 90, - (CandidateKind::PeerReflexive, _) => 80, - (CandidateKind::Relayed, Protocol::Udp) => 2, - (CandidateKind::Relayed, Protocol::Tcp) => 1, - (CandidateKind::Relayed, _) => 0, - }; - - // The recommended formula combines a preference for the candidate type - // (server reflexive, peer reflexive, relayed, and host), a preference - // for the IP address for which the candidate was obtained, and a - // component ID using the following formula: - // - // priority = (2^24)*(type preference) + - // (2^8)*(local preference) + - // (2^0)*(256 - component ID) - let prio = type_preference << 24 | self.local_preference() << 8 | (256 - self.component_id as u32); - - // https://datatracker.ietf.org/doc/html/rfc8445#section-5.1.2 - // MUST be a positive integer between 1 and (2**31 - 1) - assert!(prio >= 1 && prio < 2_u32.pow(31)); - - prio - } - - pub(crate) fn local_preference(&self) -> u32 { - self.local_preference - .unwrap_or_else(|| if self.addr.is_ipv6() { 65_535 } else { 65_534 }) - } - - pub(crate) fn component_id(&self) -> u16 { - self.component_id - } - - /// Returns the address for the specified ICE candidate. - pub fn addr(&self) -> SocketAddr { - self.addr - } - - /// Returns the _local_ address of this ICE candidate. - /// - /// This is an extension to the ICE spec that we use to track - /// local interfaces also for relayed candidates. - /// Specifically, for relayed candidates, the local interface - /// is the address the agent uses to communicate with the TURN - /// server using the TURN protocol. - /// - /// For all other candidates, this refers to either the - /// candidate itself (host) or the base (srflx/prflx). - pub fn local(&self) -> SocketAddr { - self.local - } - - /// Returns a reference to the String containing the transport protocol of - /// the ICE candidate. For example tcp/udp/.. - pub fn proto(&self) -> Protocol { - self.proto - } - - pub(crate) fn base(&self) -> SocketAddr { - self.base.unwrap_or(self.addr) - } - - pub(crate) fn raddr(&self) -> Option { - self.raddr - } - - /// Returns the candidate's TCP role. Refer to [`TcpType`] for more details. - pub fn tcptype(&self) -> Option { - self.tcptype - } - - /// Returns the kind of this candidate. - pub fn kind(&self) -> CandidateKind { - self.kind - } - - pub(crate) fn set_local_preference(&mut self, v: u32) { - self.local_preference = Some(v); - } - - pub(crate) fn set_discarded(&mut self, discarded: bool) { - self.discarded = discarded; - } - - pub(crate) fn discarded(&self) -> bool { - self.discarded - } - - pub fn set_ufrag(&mut self, ufrag: &str) { - self.ufrag = Some(ufrag.into()); - } - - pub fn ufrag(&self) -> Option<&str> { - self.ufrag.as_deref() - } - - pub(crate) fn clear_ufrag(&mut self) { - self.ufrag = None; - } - - /// Generates a candidate attribute string. - pub fn to_sdp_string(&self) -> String { - let mut s = format!( - "candidate:{} {} {} {} {} {} typ {}", - self.foundation(), - self.component_id, - self.proto, - self.prio(), - self.addr.ip(), - self.addr.port(), - self.kind - ); - if let Some(raddr) = &self.raddr { - s.push_str(&format!(" raddr {} rport {}", raddr.ip(), raddr.port())) - } - // https://datatracker.ietf.org/doc/html/rfc6544#section-4.5 - // the RFC requires tcptype to be defined strictly after raddr if exists. - if let Some(tcptype) = &self.tcptype { - s.push_str(&format!(" tcptype {}", tcptype)); - } - if let Some(ufrag) = &self.ufrag { - s.push_str(&format!(" ufrag {}", ufrag)); - } - s - } -} - -impl fmt::Display for Candidate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.to_sdp_string()) - } -} - -fn parse_proto(proto: impl TryInto) -> Result { - proto - .try_into() - .map_err(|_| IceError::BadCandidate("invalid protocol".into())) -} - -/// Type of candidate. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum CandidateKind { - /// Host (local network interface) - Host, - /// Prflx (Peer reflexive) - PeerReflexive, - /// Srflx (STUN) - ServerReflexive, - /// Relay (TURN) - Relayed, -} - -impl fmt::Display for CandidateKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let x = match self { - CandidateKind::Host => "host", - CandidateKind::PeerReflexive => "prflx", - CandidateKind::ServerReflexive => "srflx", - CandidateKind::Relayed => "relay", - }; - write!(f, "{x}") - } -} - -fn is_valid_ip(ip: IpAddr) -> bool { - match ip { - IpAddr::V4(v) => !v.is_link_local() && !v.is_broadcast() && !v.is_multicast() && !v.is_unspecified(), - IpAddr::V6(v) => !v.is_multicast() && !v.is_unspecified(), - } -} - -/// Serialize [Candidate] into candidate info. -/// -/// Always set `sdpMid` to null and `sdpMLineIndex` to 0, as we only support one media line. -/// -/// e.g. serde_json would produce: -/// ```json -/// { -/// "candidate": "candidate:12044049749558888150 1 udp 2130706175 1.2.3.4 1234 typ host", -/// "sdpMid": null, -/// "sdpMLineIndex": 0 -/// "usernameFragment": "ufrag" -/// } -/// ``` -impl Serialize for Candidate { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut o = serializer.serialize_struct("CandidateInfo", 4)?; - o.serialize_field("candidate", &self.to_sdp_string())?; - o.serialize_field("sdpMid", &None::<()>)?; - o.serialize_field("sdpMLineIndex", &0)?; - o.serialize_field("usernameFragment", &self.ufrag())?; - o.end() - } -} - -/// Deserialize [Candidate] from a candidate info. -/// -/// Similar to [Candidate::serialize], we drop `sdpMid` and `sdpMLineIndex` when parsing. -impl<'de> Deserialize<'de> for Candidate { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - #[derive(Deserialize)] - #[serde(rename_all = "camelCase")] - struct CandidateInfo { - candidate: String, - username_fragment: Option, - } - - let CandidateInfo { - candidate, - username_fragment, - } = CandidateInfo::deserialize(deserializer)?; - - let mut candidate = Candidate::from_sdp_string(&candidate).map_err(serde::de::Error::custom)?; - - if let Some(ufrag) = username_fragment { - candidate.set_ufrag(&ufrag); - } - - Ok(candidate) - } -} - -/// Marker for a builder requiring a protocol selection. -pub struct NoProtocol(()); - -/// State indicating a transport protocol has been assigned to the builder. -pub struct HasProtocol

{ - _marker: PhantomData

, - protocol: Protocol, -} - -/// Marker for a builder using the UDP protocol. -pub struct Udp(()); - -/// Marker for a builder using a TCP-based protocol. -pub struct Tcp(()); - -/// Marker indicating the candidate's network route (addresses and kind) is not yet defined. -pub struct NoRoute(()); - -/// State containing the network route and addresses required to build a candidate. -pub struct HasRoute { - kind: CandidateKind, - addr: SocketAddr, - base: SocketAddr, - local: SocketAddr, -} - -/// A typesafe builder for constructing a [`Candidate`]. -/// -/// This builder uses the Type State Pattern to enforce correct construction order and -/// protocol-specific constraints (such as preventing `tcptype` on UDP). -pub struct CandidateBuilder { - foundation: Option, - component_id: u16, - prio: Option, - tcptype: Option, - raddr: Option, - ufrag: Option, - local_preference: Option, - - protocol_state: P, - route_state: R, -} - -// Step 1: Protocol Selection -impl CandidateBuilder { - /// Sets the protocol to UDP. - pub fn udp(self) -> CandidateBuilder, NoRoute> { - self.into_has_protocol(Protocol::Udp) - } - - /// Sets the protocol to standard TCP. - pub fn tcp(self) -> CandidateBuilder, NoRoute> { - self.into_has_protocol(Protocol::Tcp) - } - - /// Sets the protocol to SSL-over-TCP. - pub fn ssl_tcp(self) -> CandidateBuilder, NoRoute> { - self.into_has_protocol(Protocol::SslTcp) - } - - /// Sets the protocol to TLS. - pub fn tls(self) -> CandidateBuilder, NoRoute> { - self.into_has_protocol(Protocol::Tls) - } - - fn into_has_protocol(self, p: Protocol) -> CandidateBuilder, NoRoute> { - CandidateBuilder { - protocol_state: HasProtocol { - _marker: PhantomData, - protocol: p, - }, - route_state: self.route_state, - foundation: self.foundation, - component_id: self.component_id, - prio: self.prio, - tcptype: self.tcptype, - raddr: self.raddr, - ufrag: self.ufrag, - local_preference: self.local_preference, - } - } -} - -// Step 2: Route Selection -impl

CandidateBuilder, NoRoute> { - /// Configures as a host candidate. - pub fn host(self, addr: SocketAddr) -> CandidateBuilder, HasRoute> { - self.into_has_route(CandidateKind::Host, addr, addr, addr, None) - } - - /// Configures as a Server Reflexive (STUN) candidate. - /// `base` and `addr` must use the same IP version. - pub fn server_reflexive(self, addr: SocketAddr, base: SocketAddr) -> CandidateBuilder, HasRoute> { - self.into_has_route( - CandidateKind::ServerReflexive, - addr, - base, - base, - Some(Candidate::arbitrary_raddr(addr)), - ) - } - - /// Configures as a Relayed (TURN) candidate. - /// Base is set to `addr`, and `local` is the interface address. - pub fn relayed(self, addr: SocketAddr, local: SocketAddr) -> CandidateBuilder, HasRoute> { - self.into_has_route( - CandidateKind::Relayed, - addr, - addr, - local, - Some(Candidate::arbitrary_raddr(addr)), - ) - } - - fn into_has_route( - self, - kind: CandidateKind, - addr: SocketAddr, - base: SocketAddr, - local: SocketAddr, - raddr: Option, - ) -> CandidateBuilder, HasRoute> { - CandidateBuilder { - protocol_state: self.protocol_state, - route_state: HasRoute { - kind, - addr, - base, - local, - }, - raddr, - foundation: self.foundation, - component_id: self.component_id, - prio: self.prio, - tcptype: self.tcptype, - ufrag: self.ufrag, - local_preference: self.local_preference, - } - } -} - -// Step 3: Final General Configurations and Build -impl

CandidateBuilder, HasRoute> { - /// Consumes the builder and returns a [`Candidate`]. - pub fn build(self) -> Result { - let route = &self.route_state; - if !is_valid_ip(route.addr.ip()) { - return Err(IceError::BadCandidate(format!("Invalid IP: {}", route.addr.ip()))); - } - - if route.addr.is_ipv4() != route.base.is_ipv4() { - return Err(IceError::BadCandidate(format!( - "address IP version mismatch: addr={} base={}", - route.addr.ip(), - route.base.ip(), - ))); - } - - Ok(Candidate::new( - self.foundation, - self.component_id, - self.protocol_state.protocol, - self.prio, - route.addr, - Some(route.base), - route.kind, - self.raddr, - self.tcptype, - self.ufrag, - route.local, - )) - } -} - -impl CandidateBuilder, R> { - /// Configures the TCP type (active, passive, so). - pub fn tcptype(mut self, t: TcpType) -> Self { - self.tcptype = Some(t); - self - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn basic_serialize_deserialize() { - let socket_addr = "1.2.3.4:9876".parse().unwrap(); - let candidates = [ - Candidate::host(socket_addr, Protocol::Udp).unwrap(), - Candidate::host(socket_addr, Protocol::Tcp).unwrap(), - Candidate::builder() - .tcp() - .host(socket_addr) - .tcptype(TcpType::Passive) - .build() - .unwrap(), - ]; - - for c1 in &candidates { - let json = serde_json::to_string(&c1).unwrap(); - let c2: Candidate = serde_json::from_str(&json).unwrap(); - assert_eq!(c1.proto, c2.proto); - assert_eq!(c1.tcptype, c2.tcptype); - - // Can't test equality because foundation is calculated on the fly. Use string compare instead. - assert_eq!(c1.to_string(), c2.to_string()); - } - } - - #[test] - fn serialize() { - let socket_addr = "1.2.3.4:9876".parse().unwrap(); - let mut candidate = Candidate::host(socket_addr, Protocol::Udp).unwrap(); - let json = no_hash(serde_json::to_string(&candidate).unwrap()); - let got: serde_json::Value = serde_json::from_str(&json).unwrap(); - let expected = serde_json::json!({ - "candidate": "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host", - "sdpMid": null, - "sdpMLineIndex": 0, - "usernameFragment": null - }); - assert_eq!(got, expected); - - // Add a username fragment - candidate.ufrag = Some("ufrag".to_string()); - let json = no_hash(serde_json::to_string(&candidate).unwrap()); - let got: serde_json::Value = serde_json::from_str(&json).unwrap(); - let expected = serde_json::json!({ - "candidate": "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host ufrag ufrag", - "sdpMid": null, - "sdpMLineIndex": 0, - "usernameFragment": "ufrag" - }); - assert_eq!(got, expected); - } - - fn no_hash(mut s: String) -> String { - let f = s.find("candidate:").unwrap(); - let t = s.find(" 1 ").unwrap(); - s.replace_range((f + 10)..t, "---"); - s - } - - #[test] - fn deserialize() { - let json = serde_json::json!({ - "candidate": "candidate:12044049749558888150 1 udp 2130706175 1.2.3.4 9876 typ host ufrag ufrag", - "sdpMid": "ignored", - "sdpMLineIndex": 123, - "usernameFragment": "ufrag" - }) - .to_string(); - let candidate: Candidate = serde_json::from_str(&json).unwrap(); - assert_eq!(candidate.ufrag(), Some("ufrag")); - assert_eq!(candidate.addr().to_string(), "1.2.3.4:9876"); - assert_eq!(candidate.base().to_string(), "1.2.3.4:9876"); - assert_eq!(candidate.kind(), CandidateKind::Host); - assert_eq!(candidate.proto(), Protocol::Udp); - assert_eq!(candidate.prio(), 2130706175); - assert_eq!(candidate.component_id(), 1); - assert_eq!(candidate.raddr(), None); - assert!(!candidate.discarded()); - } - - #[test] - fn to_string() { - let local_addr = "7.8.9.0:2345".parse().unwrap(); - let socket_addr = "1.2.3.4:9876".parse().unwrap(); - let mut candidate = Candidate::host(socket_addr, Protocol::Udp).unwrap(); - assert_eq!( - no_hash(candidate.to_string()), - "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host" - ); - - candidate.ufrag = Some("ufrag".into()); - assert_eq!( - no_hash(candidate.to_string()), - "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host ufrag ufrag" - ); - - candidate.raddr = Some("5.5.5.5:5555".parse().unwrap()); - assert_eq!( - no_hash(candidate.to_string()), - "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host raddr 5.5.5.5 rport 5555 ufrag ufrag" - ); - - // let base_addr = "5.6.7.8:4321".parse().unwrap(); - - let candidate = Candidate::relayed(socket_addr, local_addr, Protocol::SslTcp).unwrap(); - assert_eq!( - no_hash(candidate.to_string()), - "candidate:--- 1 ssltcp 16776959 1.2.3.4 9876 typ relay raddr 0.0.0.0 rport 0" - ); - } - - #[test] - fn new_from_sdp_string() { - let candidate = Candidate::from_sdp_string( - "candidate:fffeff7e5e895846293d220a 1 udp 2130706175 1.2.3.4 9876 typ host ufrag myuserfrag", - ) - .unwrap(); - - assert_eq!(candidate.ufrag(), Some("myuserfrag")); - assert_eq!(candidate.addr().to_string(), "1.2.3.4:9876"); - } - - #[test] - fn spoofed_raddr() { - let local_addr = "7.8.9.0:2345".parse().unwrap(); - let socket_addr = "1.2.3.4:9876".parse().unwrap(); - let base_addr = "5.6.7.8:4321".parse().unwrap(); - - let host = Candidate::host(socket_addr, Protocol::Udp).unwrap(); - assert!(host.raddr().is_none()); - - // We're not picky on the exact choice, but it must not be the private base - let relay = Candidate::relayed(socket_addr, local_addr, Protocol::Udp).unwrap(); - assert!(relay.raddr().is_some()); - let srflx = Candidate::server_reflexive(socket_addr, base_addr, Protocol::Udp).unwrap(); - assert!(srflx.raddr().is_some_and(|raddr| raddr != base_addr)); - - let prflx = Candidate::peer_reflexive(Protocol::Udp, socket_addr, base_addr, 1000, None, "ufrag".into()); - assert!(prflx.raddr().is_none()); - } - - #[test] - fn bad_candidate() { - let s = "candidate:12344 bad value"; - assert!(Candidate::from_sdp_string(s).is_err()); - } - - #[test] - fn tcp_candidates_sanity() { - let socket_addr = "1.2.3.4:9876".parse().unwrap(); - let candidates = [ - Candidate::host(socket_addr, Protocol::Tcp).unwrap(), - Candidate::builder().tcp().host(socket_addr).build().unwrap(), - Candidate::builder() - .tcp() - .host(socket_addr) - .tcptype(TcpType::Passive) - .build() - .unwrap(), - Candidate::builder() - .ssl_tcp() - .host(socket_addr) - .tcptype(TcpType::Active) - .build() - .unwrap(), - Candidate::builder() - .tls() - .host(socket_addr) - .tcptype(TcpType::So) - .build() - .unwrap(), - ]; - - assert!(!candidates[0].to_sdp_string().contains("tcptype")); - assert!(!candidates[1].to_sdp_string().contains("tcptype")); - assert!(candidates[2].to_sdp_string().contains("tcptype passive")); - assert!(candidates[3].to_sdp_string().contains("tcptype active")); - assert!(candidates[4].to_sdp_string().contains("tcptype so")); - } - - #[test] - fn lexical_ordering_of_sdp_is_follows_priority() { - let mut candidates = Vec::from([ - host("1.1.1.1:0"), - host("2.2.2.2:0"), - srflx("3.3.3.3:0", "4.4.4.4:0"), - srflx("5.5.5.5:0", "6.6.6.6:0"), - relay("8.8.8.8:0", "9.9.9.9:0"), - relay("7.7.7.7:0", "9.9.9.9:0"), - ]); - candidates.sort(); - - assert!(candidates[0].contains("relay")); - assert!(candidates[1].contains("relay")); - assert!(candidates[2].contains("srflx")); - assert!(candidates[3].contains("srflx")); - assert!(candidates[4].contains("host")); - assert!(candidates[5].contains("host")); - } - - #[test] - fn srflx_candidate_disallows_mixed_ip_versions() { - let error = Candidate::server_reflexive("10.0.0.1:1000".parse().unwrap(), "[::1]:1000".parse().unwrap(), "udp") - .unwrap_err(); - - assert_eq!( - error.to_string(), - "ICE bad candidate: addr and base are different IP versions" - ); - } - - fn host(socket: &str) -> String { - Candidate::host(socket.parse().unwrap(), "udp").unwrap().to_sdp_string() - } - - fn srflx(addr: &str, base: &str) -> String { - Candidate::server_reflexive(addr.parse().unwrap(), base.parse().unwrap(), "udp") - .unwrap() - .to_sdp_string() - } - - fn relay(addr: &str, local: &str) -> String { - Candidate::relayed(addr.parse().unwrap(), local.parse().unwrap(), "udp") - .unwrap() - .to_sdp_string() - } - - #[test] - fn builder_matches_api_host() { - let addr = "1.2.3.4:1234".parse().unwrap(); - - // UDP Host - let api = Candidate::host(addr, Protocol::Udp).unwrap(); - let builder = Candidate::builder().udp().host(addr).build().unwrap(); - assert_eq!(api, builder); - - // TCP Host - let api = Candidate::host(addr, Protocol::Tcp).unwrap(); - let builder = Candidate::builder().tcp().host(addr).build().unwrap(); - assert_eq!(api, builder); - } - - #[test] - fn builder_matches_api_server_reflexive() { - let addr = "95.1.1.1:5000".parse().unwrap(); - let base = "192.168.1.50:5000".parse().unwrap(); - - let api = Candidate::server_reflexive(addr, base, Protocol::Udp).unwrap(); - let builder = Candidate::builder().udp().server_reflexive(addr, base).build().unwrap(); - - assert_eq!(api, builder); - } - - #[test] - fn builder_matches_api_relayed() { - let addr = "1.2.3.4:3478".parse().unwrap(); // TURN relay addr - let local = "192.168.1.50:5000".parse().unwrap(); // Local interface - - let api = Candidate::relayed(addr, local, Protocol::Udp).unwrap(); - let builder = Candidate::builder().udp().relayed(addr, local).build().unwrap(); - - assert_eq!(api, builder); - } - - #[test] - fn builder_consistency_errors() { - let v4 = "1.2.3.4:1234".parse().unwrap(); - let v6 = "[2001:db8::1]:1234".parse().unwrap(); - - // API returns error on mixed versions - let api_err = Candidate::server_reflexive(v4, v6, Protocol::Udp); - // Builder should return same error type - let builder_err = Candidate::builder().udp().server_reflexive(v4, v6).build(); - - assert!(api_err.is_err()); - assert!(builder_err.is_err()); - } -} diff --git a/rs/moq-webrtc/src/vendor/is/error.rs b/rs/moq-webrtc/src/vendor/is/error.rs deleted file mode 100644 index 36c2b07852c..00000000000 --- a/rs/moq-webrtc/src/vendor/is/error.rs +++ /dev/null @@ -1,54 +0,0 @@ -use std::error::Error; -use std::fmt; -use std::io; - -/// Errors from the ICE agent. -#[allow(missing_docs)] -#[derive(Debug)] -pub enum IceError { - BadCandidate(String), -} - -impl fmt::Display for IceError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - IceError::BadCandidate(msg) => write!(f, "ICE bad candidate: {}", msg), - } - } -} - -impl Error for IceError {} - -/// A STUN message could not be parsed or processed. -#[derive(Debug)] -pub enum StunError { - /// A STUN message could not be parsed. - Parse(String), - - /// An IO error occurred while handling a STUN message. - Io(io::Error), -} - -impl fmt::Display for StunError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - StunError::Parse(msg) => write!(f, "STUN parse error: {}", msg), - StunError::Io(err) => write!(f, "STUN io: {}", err), - } - } -} - -impl Error for StunError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - StunError::Io(err) => Some(err), - _ => None, - } - } -} - -impl From for StunError { - fn from(err: io::Error) -> Self { - StunError::Io(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/is/hmac_provider.rs b/rs/moq-webrtc/src/vendor/is/hmac_provider.rs deleted file mode 100644 index e3b7c0af0df..00000000000 --- a/rs/moq-webrtc/src/vendor/is/hmac_provider.rs +++ /dev/null @@ -1,14 +0,0 @@ -/// HMAC-SHA1 for the ICE agent's own tests, from the rind provider str0m runs on. -#[cfg(test)] -#[derive(Debug)] -pub struct DefaultSha1HmacProvider; - -#[cfg(test)] -impl crate::vendor::str0m_proto::Sha1HmacProvider for DefaultSha1HmacProvider { - fn sha1_hmac(&self, key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - crate::vendor::str0m_rind::default_provider() - .unwrap() - .sha1_hmac_provider - .sha1_hmac(key, payloads) - } -} diff --git a/rs/moq-webrtc/src/vendor/is/lib.rs b/rs/moq-webrtc/src/vendor/is/lib.rs deleted file mode 100644 index babe3919749..00000000000 --- a/rs/moq-webrtc/src/vendor/is/lib.rs +++ /dev/null @@ -1,1693 +0,0 @@ -//! # is -- ICE in Sans-IO style -//! -//! Standalone [ICE][rfc8445] agent extracted from the [str0m][str0m] WebRTC library. -//! -//! ICE is the protocol used to establish peer-to-peer connectivity across -//! the internet. It coordinates STUN connectivity checks over every -//! possible network path between two peers and picks the best one, -//! handling NAT traversal along the way. -//! -//! This crate implements the ICE agent -- the state machine that drives -//! candidate pairing, connectivity checks, and nomination -- without -//! performing any I/O itself. -//! -//! # Sans-IO -//! -//! This is a [Sans-IO][sansio] implementation. The `IceAgent` never touches -//! a socket. Instead you drive it in a loop: -//! -//! 1. `poll_timeout()` -- when to wake up next. -//! 2. `handle_timeout(now)` -- advance timers. -//! 3. `poll_transmit()` -- STUN packets to send. -//! 4. `handle_packet(now, pkt)` -- feed incoming STUN. -//! 5. `poll_event()` -- state changes and nominations. -//! -//! This makes the agent easy to embed in any async runtime, event loop, or -//! test harness. -//! -//! # Quick start -//! -//! ```ignore -//! use crate::vendor::is::{IceAgent, IceCreds, Candidate}; -//! -//! // Create an agent with random credentials. -//! let mut agent = IceAgent::new(IceCreds::new()); -//! -//! // Tell the agent about a local socket. -//! let addr = "192.168.1.100:5000".parse().unwrap(); -//! agent.add_local_candidate(Candidate::host(addr, "udp").unwrap()); -//! -//! // Exchange credentials and candidates with the remote peer via your -//! // signalling channel, then run the loop above until -//! // IceConnectionState::Connected. -//! ``` -//! -//! # Address discovery is external -//! -//! The agent does not enumerate network interfaces, query STUN servers, or -//! allocate TURN relays. All of that is the caller's responsibility. -//! Discovered addresses are fed in via `add_local_candidate()` at any time -//! (trickle ICE). -//! -//! # Relationship to str0m -//! -//! This crate was extracted from [str0m][str0m] so the ICE agent can be -//! reused outside the full WebRTC stack. str0m depends on this crate with -//! default features disabled (it supplies its own HMAC provider through its -//! pluggable crypto backend). -//! -//! When used standalone the default `sha1` feature provides -//! `DefaultSha1HmacProvider` and a convenient `IceAgent::new()` constructor. -//! Disable it if you want to supply your own provider via -//! `IceAgent::with_hmac()`. -//! -//! # Design decisions -//! -//! The implementation makes several simplifying assumptions that suit -//! WebRTC usage: -//! -//! - **STUN/TURN are external** -- see above. -//! - **BUNDLE assumed** -- one agent, one data stream, one component (RTP). -//! - **Trickle ICE only** -- candidates can arrive at any time. -//! - **No frozen check state** -- single data stream means pairs go straight -//! to waiting. -//! - **Nomination is not final** -- the agent can change its nominated pair -//! as network conditions shift, without an ICE restart. -//! - **Ice-lite supported** -- the agent can act as a controlled ice-lite -//! endpoint for server-side use. -//! -//! For the full rationale and list of assumptions see the -//! [design document][design]. -//! -//! # Features -//! -//! | Feature | Default | Description | -//! |---------|---------|-------------| -//! | `sha1` | yes | Provides `DefaultSha1HmacProvider` and `IceAgent::new()` | -//! | `pii` | no | Redacts IP addresses and other PII from log output | -//! -//! [rfc8445]: https://datatracker.ietf.org/doc/html/rfc8445 -//! [str0m]: https://crates.io/crates/str0m -//! [sansio]: https://sans-io.readthedocs.io/ -//! [design]: https://github.com/algesten/str0m/blob/main/docs/ice.md - -// Avoid rewriting existing code: nested conditions are often more readable than long if-chains. -#![allow(clippy::collapsible_if)] -#![allow(clippy::new_without_default)] -#![allow(clippy::bool_to_int_with_if)] - -use tracing::info_span; -mod agent; -pub use agent::{IceAgent, IceAgentEvent, IceConnectionState, IceCreds, LocalPreference}; - -mod candidate; -pub use candidate::{Candidate, CandidateBuilder, CandidateKind}; - -mod pair; - -mod preference; -pub use preference::default_local_preference; - -mod error; -pub use error::IceError; -pub use error::StunError; - -pub mod stun; - -mod parse; - -mod hmac_provider; -pub use crate::vendor::str0m_proto::{Protocol, Sha1HmacProvider}; -#[cfg(test)] -pub use hmac_provider::DefaultSha1HmacProvider; - -#[cfg(test)] -pub(crate) mod test { - use crate::vendor::is::agent::IceAgentStats; - use crate::vendor::is::stun::{StunMessage, StunPacket}; - use crate::vendor::is::*; - use crate::vendor::str0m_proto::Protocol; - use crate::vendor::str0m_proto::Transmit; - - use std::collections::HashMap; - use std::net::IpAddr; - use std::net::SocketAddr; - use std::ops::{Deref, DerefMut}; - use std::time::{Duration, Instant}; - - use tracing::Span; - use tracing_subscriber::util::SubscriberInitExt; - - #[test] - pub fn drop_host() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - // 9999 is just dropped by propagate - let c1 = a1.add_host_candidate("1.1.1.1:9999"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_disconnected() && a2.state().is_disconnected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert_eq!( - a1.stats(), - IceAgentStats { - bind_request_sent: 9, - bind_success_recv: 0, - bind_request_recv: 0, - discovered_recv_count: 0, - nomination_send_count: 0, - } - ); - - assert_eq!( - a2.stats(), - IceAgentStats { - bind_request_sent: 9, - bind_success_recv: 0, - bind_request_recv: 0, - discovered_recv_count: 0, - nomination_send_count: 0, - } - ); - } - - #[test] - pub fn host_host_disconnect() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - a1.drop_sent_packets = true; - - loop { - if !a1.state().is_connected() && !a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - println!("{:?}", a1.events); - println!("{:?}", a2.events); - - fn assert_last_event(d: &Duration, e: &IceAgentEvent, a: &IceAgent) { - assert_eq!( - *e, - IceAgentEvent::IceConnectionStateChange(IceConnectionState::Disconnected) - ); - assert!(*d > a.ice_timeout()); - } - - let (d, e) = a1.events.last().unwrap(); - assert_last_event(d, e, &a1); - - let (d, e) = a2.events.last().unwrap(); - assert_last_event(d, e, &a2); - - assert_eq!( - a1.stats(), - IceAgentStats { - bind_request_sent: 11, - bind_success_recv: 2, - bind_request_recv: 11, - discovered_recv_count: 1, - nomination_send_count: 1, - } - ); - - assert_eq!( - a2.stats(), - IceAgentStats { - bind_request_sent: 11, - bind_success_recv: 2, - bind_request_recv: 2, - discovered_recv_count: 1, - nomination_send_count: 1, - } - ); - } - - #[test] - pub fn host_host() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert_eq!( - a1.stats(), - IceAgentStats { - bind_request_sent: 2, - bind_success_recv: 2, - bind_request_recv: 2, - discovered_recv_count: 1, - nomination_send_count: 1, - } - ); - - assert_eq!( - a2.stats(), - IceAgentStats { - bind_request_sent: 3, - bind_success_recv: 2, - bind_request_recv: 2, - discovered_recv_count: 1, - nomination_send_count: 1, - } - ); - } - - // RFC 8445 §7.3.1.1: when both agents claim the controlling role, the - // role conflict is resolved deterministically by the tiebreaker - the - // higher-tiebreaker agent keeps the role, the other yields. Tiebreakers - // here are the random ones picked by the constructor, so we cannot - // predict which side wins; we only assert that the conflict resolves: - // the connection still establishes and exactly one side ends up - // controlled. - #[test] - pub fn role_conflict_resolves_to_one_controlled_side() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(true); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert!( - a1.controlling() ^ a2.controlling(), - "role conflict must leave exactly one side controlling, got a1={} a2={}", - a1.controlling(), - a2.controlling(), - ); - assert!( - a1.stats().nomination_send_count > 0 || a2.stats().nomination_send_count > 0, - "role conflict must not block nomination", - ); - } - - // str0m performs calculations on `now` internally - // To ensure that these never panic, we run a happy-path of `host-host` that uses a very early `Instant`. - #[test] - pub fn happy_path_very_early_timestamp() { - let early_now = find_earliest_now(); - - let mut a1 = TestAgent::new(info_span!("L")); - a1.time = early_now; - let mut a2 = TestAgent::new(info_span!("R")); - a2.time = early_now; - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - } - - #[test] - pub fn no_respond_to_stun_request_on_invalidated_candidate() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1.clone()); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - a1.agent.invalidate_candidate(&c1); - - let timeout = a2.poll_timeout().unwrap(); - a2.handle_timeout(timeout); - let transmit = a2.poll_transmit().unwrap(); - - assert!(a1.poll_transmit().is_none()); - - a1.handle_packet( - Instant::now(), - StunPacket { - proto: Protocol::Udp, - source: sock("2.2.2.2:1000"), - destination: sock("1.1.1.1:1000"), - message: StunMessage::parse(&transmit.contents).unwrap(), - }, - ); - - assert!(a1.poll_transmit().is_none()); - } - - #[test] - pub fn migrates_to_new_candidates_after_invalidation_without_timeout() { - let _guard = tracing_subscriber::fmt() - .with_env_filter("debug") - .with_test_writer() - .set_default(); - - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = host("1.1.1.1:1000", "udp"); - let c1 = a1.add_local_candidate(c1).unwrap().clone(); - a2.add_remote_candidate(c1.clone()); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - let a1_time = a1.time; - let a2_time = a2.time; - let new_sock = sock("8.8.8.8:1000"); - - let c3 = Candidate::host(new_sock, Protocol::Udp).unwrap(); - let c3 = a1.add_local_candidate(c3).unwrap().clone(); - a2.add_remote_candidate(c3); - - a1.agent.invalidate_candidate(&c1); - a2.agent.invalidate_candidate(&c1); - - loop { - let a1_nominated = - a1.has_event(|e| matches!(e, IceAgentEvent::NominatedSend { source, .. } if source == &new_sock)); - let a2_nominated = a2.has_event( - |e| matches!(e, IceAgentEvent::NominatedSend { destination, .. } if destination == &new_sock), - ); - - if a1_nominated && a2_nominated { - break; - } - - progress(&mut a1, &mut a2); - } - - assert!(a1.time.duration_since(a1_time) < a1.ice_timeout()); - assert!(a2.time.duration_since(a2_time) < a2.ice_timeout()); - } - - #[test] - pub fn re_adding_invalidated_local_candidate() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1.clone()); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - a1.agent.invalidate_candidate(&c1); - - // Let time pass until it disconnects. - loop { - if a1.state().is_disconnected() && a2.state().is_disconnected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Add back the invalidated candidate - a1.add_local_candidate(c1).unwrap(); - - // progress() fails after 100 number of polls. - a1.progress_count = 0; - a2.progress_count = 0; - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - } - - #[test] - pub fn re_adding_invalidated_remote_candidate() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2.clone()); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - a1.agent.invalidate_candidate(&c2); - - // Let time pass until it disconnects. - loop { - if a1.state().is_disconnected() && a2.state().is_disconnected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Add back the invalidated candidate - a1.add_remote_candidate(c2); - - // progress() fails after 100 number of polls. - a1.progress_count = 0; - a2.progress_count = 0; - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - } - - #[test] - pub fn ice_lite_no_connection() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - // a1 acts as "server" - a1.agent.set_ice_lite(true); - - // 9999 is just dropped by propagate - let c1 = a1.add_host_candidate("1.1.1.1:9999"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - // The bug we try to avoid is that _both sides_ must reach a disconnected state eventually. - // The ice-lite (server side) should time out after roughly 8 seconds. - if a1.state().is_disconnected() && a2.state().is_disconnected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert!(a1.time - a1.start_time > Duration::from_secs(8)); - - assert_eq!( - a1.stats(), - IceAgentStats { - bind_request_sent: 0, - bind_success_recv: 0, - bind_request_recv: 0, - discovered_recv_count: 0, - nomination_send_count: 0, - } - ); - - assert_eq!( - a2.stats(), - IceAgentStats { - bind_request_sent: 9, - bind_success_recv: 0, - bind_request_recv: 0, - discovered_recv_count: 0, - nomination_send_count: 0, - } - ); - } - - /// Regression test: ice-lite agents should not disconnect immediately on first timeout. - #[test] - pub fn ice_lite_no_immediate_disconnect() { - let mut a1 = TestAgent::new(info_span!("L")); - a1.set_ice_lite(true); - - a1.add_host_candidate("1.1.1.1:1000"); - a1.add_remote_candidate(host("2.2.2.2:2000", "udp")); - - a1.span.in_scope(|| a1.agent.handle_timeout(a1.time)); - - assert!(!a1.state().is_disconnected()); - } - - #[test] - pub fn prflx_host() { - let mut a1 = TestAgent::new(info_span!("L")).with_port_restricted_nat("4.4.4.4"); - let mut a2 = TestAgent::new(info_span!("R")); - - // will be rewritten to 4.4.4.4 - let c1 = a1.add_host_candidate("3.3.3.3:1000"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert_eq!( - a1.stats(), - IceAgentStats { - bind_request_sent: 2, - bind_success_recv: 2, - bind_request_recv: 1, - discovered_recv_count: 1, - nomination_send_count: 1, - } - ); - - assert_eq!( - a2.stats(), - IceAgentStats { - bind_request_sent: 3, - bind_success_recv: 1, - bind_request_recv: 2, - discovered_recv_count: 1, - nomination_send_count: 1, - } - ); - } - - // pub fn init_log() { - // use tracing_subscriber::{fmt, prelude::*, EnvFilter}; - - // let env_filter = - // EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("trace")); - - // tracing_subscriber::registry() - // .with(fmt::layer()) - // .with(EnvFilter::from_default_env()) - // .init(); - // } - - #[test] - pub fn ice_lite_disconnect_reconnect() { - // init_log(); - - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1.clone()); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2.clone()); - - a1.set_controlling(true); - a2.set_controlling(false); - a2.set_ice_lite(true); - - // Connect. - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Disconnect - a1.drop_sent_packets = true; - - loop { - if !a1.state().is_connected() && !a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Now reconnect after disconnecting. - a1.drop_sent_packets = false; - - // Adding back the remote candidate will for new pairs to try. - // This makes a1 start sending new STUN requests. - // a2 in ice-lite mode will discover the pair from the STUN - // request and come out of disconnected. - a1.add_remote_candidate(c2); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - } - - #[test] - pub fn trickle_host_host() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - // no traffic possible - let c1 = a1.add_host_candidate("3.3.3.3:9999"); - a2.add_remote_candidate(c1); - - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - // this will be going nowhere (tested in drop-host.rs). - for _ in 0..10 { - progress(&mut a1, &mut a2); - } - - // "trickle" a possible candidate - a1.add_host_candidate("1.1.1.1:1000"); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - } - - #[test] - pub fn candidate_pair_of_same_kind_does_not_get_nominated() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")).with_port_restricted_nat("4.4.4.4"); - - let c1 = a1.add_relay_candidate("1.1.1.1:1000", "9.9.9.9:2000"); - a2.add_remote_candidate(c1); - - let c2 = a2.server_reflexive_candidate("8.8.8.8:3478", "3.3.3.3:1000"); - let c2 = a2.add_local_candidate(c2).unwrap().clone(); - a1.add_remote_candidate(c2); - let c3 = a2.add_host_candidate("3.3.3.3:1000"); - a1.add_remote_candidate(c3); - - a1.set_controlling(true); - a2.set_controlling(false); - - // loop until we're connected. - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - a2.add_remote_candidate(a1.add_relay_candidate("1.1.1.1:1001", "9.9.9.9:2000")); - - loop { - if a2.has_event( - |e| matches!(e, IceAgentEvent::DiscoveredRecv { source, .. } if source == &sock("1.1.1.1:1001")), - ) { - break; - } - - progress(&mut a1, &mut a2); - } - - assert!(!a1.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, .. } if source == &sock("1.1.1.1:1001")) - })); - assert!(!a2.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { destination, .. } - if destination == &sock("1.1.1.1:1001")) - })); - } - - #[test] - pub fn no_disconnect_when_replacing_pflx_with_real_candidate() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - // We need a 2nd pair of candidates to make sure the agent doesn't go straight into `Completed`. - - // Both agents know their local candidates - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - let c3 = a1.add_relay_candidate("2.2.2.2:1000", "9.9.9.9:2000"); - - let c2 = a2.add_host_candidate("1.1.1.1:1001"); - let c4 = a2.add_relay_candidate("2.2.2.2:1001", "9.9.9.9:2000"); - - // Agent 1 also learns about the remote candidates but agent 2 - // doesn't (imagine signalling layer being a bit slow) - a1.add_remote_candidate(c2); - a1.add_remote_candidate(c4); - - a1.set_controlling(true); - a2.set_controlling(false); - - // Wait until agent 2 is connected (based on a peer-reflexive candidate) - loop { - if a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - a2.events.clear(); - - // Candidates arrive via signalling layer - a2.add_remote_candidate(c1.clone()); - a2.add_remote_candidate(c3.clone()); - - // Continue normal operation. - for _ in 0..50 { - progress(&mut a1, &mut a2); - } - - // We expect to not disconnect as part of this, nor to go back to checking: - // the replacing pair keeps the validated path of the peer-reflexive one. - assert!(!a2.has_event(|e| matches!( - e, - IceAgentEvent::IceConnectionStateChange(IceConnectionState::Disconnected | IceConnectionState::Checking) - ))); - } - - #[test] - pub fn pair_replacement_in_attempt_window_stays_connected() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - let c2 = a2.add_host_candidate("2.2.2.2:1000"); - - // Only the controlling side initially knows the remote candidate. This makes - // the controlled side discover a peer-reflexive remote from inbound STUN. - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - // Exchange initial ICE credentials without consuming any binding requests. - progress_without_network(&mut a1, &mut a2); - progress_without_network(&mut a2, &mut a1); - - a1.events.clear(); - a2.events.clear(); - - // The controlling side starts checking the signalled host candidate. - progress_without_network(&mut a1, &mut a2); - let initial_request = progress_one_message(&mut a1, &mut a2); - assert!(initial_request.is_binding_request); - assert!(!initial_request.use_candidate); - - let initial_reply = progress_one_message(&mut a2, &mut a1); - assert!(initial_reply.is_successful_binding_response); - assert!(a1.has_event(|e| matches!(e, IceAgentEvent::NominatedSend { .. }))); - - // Now the controlling side sends the nominated USE-CANDIDATE request. - progress_without_network(&mut a1, &mut a2); - - let nominate_request = progress_one_message(&mut a1, &mut a2); - assert!(nominate_request.is_binding_request); - assert!(nominate_request.use_candidate); - - // The controlled side answers that request and then sends a reverse binding - // request to confirm the nomination. The reply is queued when the request - // arrives, then the reverse binding request is queued on the next timeout. - // The nominated pair is not valid until that request is answered (RFC 8445 - // §7.3.1.5), so the controlled side is not connected yet. - progress_without_network(&mut a2, &mut a1); - assert!(!a2.state().is_connected()); - - let nominate_reply = a2.poll_next_stun_message(); - assert!(nominate_reply.is_successful_binding_response); - let reverse_request = a2.poll_next_stun_message(); - assert!(reverse_request.is_binding_request); - - // Before the reverse binding response arrives, the signalling layer delivers the - // controller's real remote candidate. This replaces the prflx pair during Attempt. - a2.add_remote_candidate(c1); - progress_without_network(&mut a2, &mut a1); - - assert!(!a2.state().is_connected()); - assert!(!a2.has_event(|e| matches!(e, IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)))); - - // Finish the delayed round trip and ensure the controlled side stays connected. - deliver_transmit(&mut a2, &mut a1, &nominate_reply.transmit); - deliver_transmit(&mut a2, &mut a1, &reverse_request.transmit); - - let reverse_reply = progress_one_message(&mut a1, &mut a2); - assert!(reverse_reply.is_successful_binding_response); - - for _ in 0..20 { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert!(a1.state().is_connected()); - assert!(a2.state().is_connected()); - assert!(!a2.has_event(|e| matches!(e, IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)))); - } - - #[test] - pub fn identical_host_and_server_reflexive_candidates_dont_create_new_pairs_on_inbound_stun_request() { - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = a1.add_host_candidate("1.1.1.1:1000"); - a2.add_remote_candidate(c1); - let c2 = a2.server_reflexive_candidate("8.8.8.8:3478", "2.2.2.2:1000"); - let c2 = a2.add_local_candidate(c2).unwrap().clone(); - a1.add_remote_candidate(c2); - let c3 = a2.add_host_candidate("2.2.2.2:1000"); - a1.add_remote_candidate(c3); - - a1.set_controlling(true); - a2.set_controlling(false); - - // loop until we're connected. - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Each agent should only have a single candidate pair. - assert_eq!(a1.num_candidate_pairs(), 1); - assert_eq!(a2.num_candidate_pairs(), 1); - } - - // In general, ICE prefers IPv6 over IPv4. - // However, in case our only IPv6 connectivity is via a relay that we are talking to over IPv4, - // we want to prefer the IPv4 code path. - #[test] - fn prefers_ipv4_ipv4_relay_candidate_over_ipv4_ipv6_controlling() { - let _guard = tracing_subscriber::fmt() - .with_env_filter("debug") - .with_test_writer() - .set_default(); - - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - a1.set_controlling(true); - a2.set_controlling(false); - - prefer_ipv4_candidate_over_ipv6_candidate(&mut a1, &mut a2); - } - - // In general, ICE prefers IPv6 over IPv4. - // However, in case our only IPv6 connectivity is via a relay that we are talking to over IPv4, - // we want to prefer the IPv4 code path. - #[test] - fn prefers_ipv4_ipv4_relay_candidate_over_ipv4_ipv6_controlled() { - let _guard = tracing_subscriber::fmt() - .with_env_filter("debug") - .with_test_writer() - .set_default(); - - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - a1.set_controlling(false); - a2.set_controlling(true); - - prefer_ipv4_candidate_over_ipv6_candidate(&mut a1, &mut a2); - } - - fn prefer_ipv4_candidate_over_ipv6_candidate(a1: &mut TestAgent, a2: &mut TestAgent) { - // Agent 1 only has IPv4 connectivity to a relay but allocates both IPv4 and IPv6 addresses. - // Agent 2 has no relay but has full IPv4 and IPv6 connectivity. - let relay_ipv4_ipv4 = a1.add_relay_candidate("7.7.7.7:5000", "1.1.1.1:5000"); - let relay_ipv6_ipv4 = a1.add_relay_candidate("[::7]:5000", "1.1.1.1:5000"); - a2.add_remote_candidate(relay_ipv4_ipv4); - a2.add_remote_candidate(relay_ipv6_ipv4); - - let host_ipv4 = a2.add_host_candidate("5.5.5.5:3000"); - let host_ipv6 = a2.add_host_candidate("[::2]:3000"); - a1.add_remote_candidate(host_ipv4); - a1.add_remote_candidate(host_ipv6); - - // loop until we're connected. - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(a1, a2); - } - - assert!(a1.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, destination, .. } - if source == &sock("7.7.7.7:5000") && destination == &sock("5.5.5.5:3000")) - })); - assert!(a2.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, destination, .. } - if source == &sock("5.5.5.5:3000") && destination == &sock("7.7.7.7:5000")) - })); - } - - #[test] - fn changed_timing_config_takes_effect_immediately() { - let _guard = tracing_subscriber::fmt() - .with_env_filter("trace") - .with_test_writer() - .set_default(); - - const IDLE_RTO: Duration = Duration::from_secs(60); - const NORMAL_RTO: Duration = Duration::from_secs(3); - - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = host("1.1.1.1:1000", "udp"); - a1.add_local_candidate(c1.clone()); - a2.add_remote_candidate(c1); - - let c2 = host("2.2.2.2:1000", "udp"); - a2.add_local_candidate(c2.clone()); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - // loop until we're connected. - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Move to "idle" mode - a1.set_initial_stun_rto(IDLE_RTO); - a1.set_max_stun_rto(IDLE_RTO); - a2.set_initial_stun_rto(IDLE_RTO); - a2.set_max_stun_rto(IDLE_RTO); - - // Spin for a bit - for _ in 0..10 { - progress(&mut a1, &mut a2); - } - - // This is a bit of a hack because we use "insider" knowledge here - // that the next timeout is in fact `IDLE_RTO` away. - let now = a1.poll_timeout().unwrap() - IDLE_RTO; - - a1.set_initial_stun_rto(NORMAL_RTO); - a1.set_max_stun_rto(NORMAL_RTO); - - let timeout_after = a1.poll_timeout().unwrap(); - - // After applying the new timeout, it should only be `NORMAL_RTO` away. - assert_eq!(timeout_after, now + NORMAL_RTO); - } - - #[test] - fn new_candidates_after_disconnected_should_transition_to_checking() { - let _guard = tracing_subscriber::fmt() - .with_env_filter("trace") - .with_test_writer() - .set_default(); - - let mut a1 = TestAgent::new(info_span!("L")); - let mut a2 = TestAgent::new(info_span!("R")); - - let c1 = host("1.1.1.1:1000", "udp"); - a1.add_local_candidate(c1.clone()); - a2.add_remote_candidate(c1); - - let c2 = host("2.2.2.2:1000", "udp"); - a2.add_local_candidate(c2.clone()); - a1.add_remote_candidate(c2); - - a1.set_controlling(true); - a2.set_controlling(false); - - // loop until we're connected. - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // signal network outage - a1.drop_sent_packets = true; - a2.drop_sent_packets = true; - - loop { - if a1.state().is_disconnected() && a2.state().is_disconnected() { - break; - } - progress(&mut a1, &mut a2); - } - - // Reconnect with new candidates - a1.drop_sent_packets = false; - a2.drop_sent_packets = false; - - let c1 = host("5.5.5.5:1000", "udp"); - a1.add_local_candidate(c1.clone()); - a2.add_remote_candidate(c1); - - let c2 = host("6.6.6.6:1000", "udp"); - a2.add_local_candidate(c2.clone()); - a1.add_remote_candidate(c2); - - // Clear all existing events - a1.events.clear(); - a2.events.clear(); - - // Reconnect - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - assert!(a1.has_event(|e| matches!(e, IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)))); - assert!(a2.has_event(|e| matches!(e, IceAgentEvent::IceConnectionStateChange(IceConnectionState::Checking)))); - } - - #[test] - pub fn symmetric_nat_both_sides() { - let _guard = tracing_subscriber::fmt() - .with_test_writer() - .with_env_filter("trace") - .set_default(); - - // Both agents are behind symmetric NAT - let mut a1 = TestAgent::new(info_span!("L")).with_symmetric_nat("5.5.5.5"); - let mut a2 = TestAgent::new(info_span!("R")).with_symmetric_nat("6.6.6.6"); - - // Add host candidates. Those will fail behind NAT. - a2.add_remote_candidate(a1.add_host_candidate("1.1.1.1:1000")); - a1.add_remote_candidate(a2.add_host_candidate("2.2.2.2:1000")); - - // Add server-reflexive candidates, those will also fail because the NAT is symmetric - a2.add_remote_candidate(a1.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000")); - a1.add_remote_candidate(a2.server_reflexive_candidate("8.8.8.8:3478", "2.2.2.2:1000")); - - // Add relay candidates, those will work - a2.add_remote_candidate(a1.add_relay_candidate("3.3.3.3:1000", "1.1.1.1:1000")); - a1.add_remote_candidate(a2.add_relay_candidate("4.4.4.4:1000", "2.2.2.2:1000")); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // A1 sends from its host candidate with a random port getting assigned by the symmetric NAT. - assert!(a1.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, destination, .. } - if source == &sock("1.1.1.1:1000") && destination == &sock("4.4.4.4:1000")) - })); - // A2 sends from its relay candidate, towards the public IP of A1. - assert!(a2.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, destination, .. } - if source == &sock("4.4.4.4:1000") && destination.ip() == ip("5.5.5.5")) - })); - } - - #[test] - pub fn symmetric_nat_one_side() { - let _guard = tracing_subscriber::fmt() - .with_test_writer() - .with_env_filter("trace") - .set_default(); - - // Only one agent is behind symmetric NAT. - let mut a1 = TestAgent::new(info_span!("L")).with_symmetric_nat("5.5.5.5"); - let mut a2 = TestAgent::new(info_span!("R")).with_port_restricted_nat("6.6.6.6"); - - // Add host candidates. Those will fail behind NAT. - a2.add_remote_candidate(a1.add_host_candidate("1.1.1.1:1000")); - a1.add_remote_candidate(a2.add_host_candidate("2.2.2.2:1000")); - - // Add server-reflexive candidates, those will also fail due to A1's symmetric NAT. - a2.add_remote_candidate(a1.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000")); - a1.add_remote_candidate(a2.server_reflexive_candidate("8.8.8.8:3478", "2.2.2.2:1000")); - - // Add relay candidates, those will work. - a2.add_remote_candidate(a1.add_relay_candidate("3.3.3.3:1000", "1.1.1.1:1000")); - a1.add_remote_candidate(a2.add_relay_candidate("4.4.4.4:1000", "2.2.2.2:1000")); - - a1.set_controlling(true); - a2.set_controlling(false); - - loop { - if a1.state().is_connected() && a2.state().is_connected() { - break; - } - progress(&mut a1, &mut a2); - } - - // A1 sends from its host candidate with a random port getting assigned by the symmetric NAT. - assert!(a1.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, destination, .. } - if source == &sock("1.1.1.1:1000") && destination == &sock("4.4.4.4:1000")) - })); - // A2 sends from its relay candidate, towards the public IP of A1. - assert!(a2.has_event(|e| { - matches!(e, IceAgentEvent::NominatedSend { source, destination, .. } - if source == &sock("4.4.4.4:1000") && destination.ip() == ip("5.5.5.5")) - })); - } - - #[test] - fn server_reflexive_candidate_from_different_servers_have_different_ports_on_sym_nat() { - let mut agent = TestAgent::new(info_span!("A")).with_symmetric_nat("4.4.4.4"); - - let c1 = agent.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000"); - let c2 = agent.server_reflexive_candidate("9.9.9.9:3478", "1.1.1.1:1000"); - - assert_ne!(c1, c2); - } - - #[test] - fn server_reflexive_candidate_from_different_servers_are_equal_on_restricted_nat() { - let mut agent = TestAgent::new(info_span!("A")).with_port_restricted_nat("4.4.4.4"); - - let c1 = agent.server_reflexive_candidate("8.8.8.8:3478", "1.1.1.1:1000"); - let c2 = agent.server_reflexive_candidate("9.9.9.9:3478", "1.1.1.1:1000"); - - assert_eq!(c1, c2); - } - - pub struct TestStunMessage { - transmit: Transmit, - is_binding_request: bool, - is_successful_binding_response: bool, - use_candidate: bool, - } - - pub struct TestAgent { - pub start_time: Instant, - pub agent: IceAgent, - pub span: Span, - pub events: Vec<(Duration, IceAgentEvent)>, - pub progress_count: u64, - pub time: Instant, - pub drop_sent_packets: bool, - pub nat: Option, - } - - impl TestAgent { - pub fn new(span: Span) -> Self { - let now = Instant::now(); - TestAgent { - start_time: now, - agent: IceAgent::new(IceCreds::new()), - span, - events: vec![], - progress_count: 0, - time: now, - drop_sent_packets: false, - nat: None, - } - } - - pub fn with_symmetric_nat(mut self, external_ip: &str) -> Self { - self.nat = Some(Nat::new_symmetric(external_ip)); - self - } - - pub fn with_port_restricted_nat(mut self, external_ip: &str) -> Self { - self.nat = Some(Nat::new_port_restricted_cone(external_ip)); - self - } - - fn add_host_candidate(&mut self, addr: &str) -> Candidate { - self.span - .in_scope(|| self.agent.add_local_candidate(host(addr, "udp")).unwrap().clone()) - } - - fn add_relay_candidate(&mut self, addr: &str, local: &str) -> Candidate { - let local = local.parse().unwrap(); - let addr = addr.parse().unwrap(); - - self.span.in_scope(|| { - self.agent - .add_local_candidate(Candidate::relayed(addr, local, "udp").unwrap()) - .unwrap() - .clone() - }) - } - - fn add_remote_candidate(&mut self, c: Candidate) { - // Round-trip via SDP to simulate signalling protocol. - let c = Candidate::from_sdp_string(&c.to_sdp_string()).unwrap(); - - self.span.in_scope(|| self.agent.add_remote_candidate(c)) - } - - /// Simulate STUN to the given server and returned the server-reflexive candidate. - /// - /// Unlike [`TestAgent::add_host_candidate`] and [`TestAgent::add_relay_candidate`], - /// this candidate is **not** added to the agent. - /// Server-reflexive candidates are typically not added locally because one cannot - /// directly send from them. - /// The agent can only send from the base which is a host candidate. - fn server_reflexive_candidate(&mut self, stun_server: &str, base: &str) -> Candidate { - use NatType::*; - let base = base.parse().unwrap(); - let stun_server = stun_server.parse().unwrap(); - - match self.nat.as_mut() { - None => Candidate::server_reflexive(base, base, "udp"), - Some(Nat { - nat_type: PortRestrictedCone { .. }, - external_ip, - }) => Candidate::server_reflexive(SocketAddr::new(*external_ip, base.port()), base, "udp"), - Some(Nat { - nat_type: Symmetric { mappings }, - external_ip, - }) => { - let outside = symmetric_nat_lookup(base, stun_server, mappings); - - Candidate::server_reflexive(SocketAddr::new(*external_ip, outside), base, "udp") - } - } - .unwrap() - } - - fn has_event(&self, predicate: impl Fn(&IceAgentEvent) -> bool) -> bool { - self.events.iter().any(|(_, e)| predicate(e)) - } - - fn advance_time(&mut self) { - self.time = self.span.in_scope(|| self.agent.poll_timeout()).unwrap_or(self.time); - } - - fn poll_next_stun_message(&mut self) -> TestStunMessage { - let transmit = self.poll_transmit().expect("agent should emit a transmit"); - let message = StunMessage::parse(&transmit.contents).expect("IceAgent to only emit StunMessages"); - - TestStunMessage { - is_binding_request: message.is_binding_request(), - is_successful_binding_response: message.is_successful_binding_response(), - use_candidate: message.use_candidate(), - transmit, - } - } - } - - pub fn progress(a1: &mut TestAgent, a2: &mut TestAgent) { - let (f, t) = if a1.progress_count % 2 == a2.progress_count % 2 { - (a2, a1) - } else { - (a1, a2) - }; - - t.progress_count += 1; - if t.progress_count > 100 { - panic!("Test looped more than 100 times"); - } - - if let Some(trans) = f.span.in_scope(|| f.agent.poll_transmit()) { - let message = StunMessage::parse(&trans.contents).expect("IceAgent to only emit StunMessages"); - - // rewrite receive with test transforms, and potentially drop the packet. - if let Some((source, destination)) = transform(trans.source, trans.destination, f, t) { - if f.drop_sent_packets { - // drop packet - t.span.in_scope(|| t.agent.handle_timeout(t.time)); - } else { - if source != trans.source { - f.span - .in_scope(|| tracing::trace!("Outbound NAT: {} => {}", trans.source, source)); - } - - if destination != trans.destination { - t.span - .in_scope(|| tracing::trace!("Inbound NAT: {} => {}", trans.destination, destination)); - } - - let packet = StunPacket { - proto: trans.proto, - source, - destination, - message, - }; - t.span.in_scope(|| t.agent.handle_packet(t.time, packet)); - } - } else { - tracing::debug!(from = %trans.source, to = %trans.destination, "NAT: Dropping packet"); - - // drop packet - t.span.in_scope(|| t.agent.handle_timeout(t.time)); - } - } else { - t.span.in_scope(|| t.agent.handle_timeout(t.time)); - } - - let time = t.time; - - let tim_f = f.span.in_scope(|| f.agent.poll_timeout()).unwrap_or(f.time); - f.time = tim_f; - - let tim_t = t.span.in_scope(|| t.agent.poll_timeout()).unwrap_or(t.time); - t.time = tim_t; - - while let Some(v) = t.span.in_scope(|| t.agent.poll_event()) { - println!("Polled event: {v:?}"); - use IceAgentEvent::*; - f.span.in_scope(|| { - if let IceRestart(v) = &v { - f.agent.set_remote_credentials(v.clone()) - } - }); - t.events.push((time - t.start_time, v)); - } - } - - // These helpers intentionally bypass `progress()` so the regression test above - // can hold specific STUN packets and inject the signalled host candidate in the - // exact Attempt window being tested. - fn progress_without_network(from: &mut TestAgent, to: &mut TestAgent) { - let now = from.time; - from.handle_timeout(now); - drain_manual_test_events(to, from); - from.advance_time(); - to.advance_time(); - } - - fn drain_manual_test_events(from: &mut TestAgent, to: &mut TestAgent) { - let time = to.time; - while let Some(v) = to.span.in_scope(|| to.agent.poll_event()) { - println!("Polled event: {v:?}"); - use IceAgentEvent::*; - from.span.in_scope(|| { - if let IceRestart(v) = &v { - from.agent.set_remote_credentials(v.clone()) - } - }); - to.events.push((time - to.start_time, v)); - } - } - - fn progress_one_message(from: &mut TestAgent, to: &mut TestAgent) -> TestStunMessage { - let msg = from.poll_next_stun_message(); - - deliver_transmit(from, to, &msg.transmit); - - msg - } - - fn deliver_transmit(from: &mut TestAgent, to: &mut TestAgent, trans: &Transmit) { - let message = StunMessage::parse(&trans.contents).expect("IceAgent to only emit StunMessages"); - let packet = StunPacket { - proto: trans.proto, - source: trans.source, - destination: trans.destination, - message, - }; - to.span.in_scope(|| to.agent.handle_packet(to.time, packet)); - drain_manual_test_events(from, to); - from.advance_time(); - to.advance_time(); - } - - impl Deref for TestAgent { - type Target = IceAgent; - - fn deref(&self) -> &Self::Target { - &self.agent - } - } - - impl DerefMut for TestAgent { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.agent - } - } - - /// Performs a binary search for the earliest possible `Instant`. - fn find_earliest_now() -> Instant { - const ONE_YEAR: Duration = Duration::from_secs(60 * 60 * 24 * 365); - - let mut now = Instant::now(); - let mut step = ONE_YEAR; - - while step > Duration::from_secs(1) { - match now.checked_sub(step) { - Some(earlier) => { - now = earlier; - step *= 2; // Increase step-count to accelerate finding the earliest possible `Instant`. - } - None => { - step /= 2; // Decrease step-count to narrow down on the earliest possible `Instant`. - } - } - } - - now - } - - pub fn sock(s: impl Into) -> SocketAddr { - let s: String = s.into(); - s.parse().unwrap() - } - - pub fn ip(s: impl Into) -> IpAddr { - let s: String = s.into(); - s.parse().unwrap() - } - - pub fn host(s: impl Into, proto: impl TryInto) -> Candidate { - Candidate::host(sock(s), proto).unwrap() - } - - #[derive(Debug, Clone)] - enum NatType { - PortRestrictedCone { - mappings: HashMap<(SocketAddr, SocketAddr), u16>, - }, - Symmetric { - mappings: HashMap<(SocketAddr, SocketAddr), u16>, - }, - } - - #[derive(Debug, Clone)] - pub struct Nat { - external_ip: IpAddr, - nat_type: NatType, - } - - impl Nat { - fn new_port_restricted_cone(external_ip: &str) -> Self { - Self { - external_ip: external_ip.parse().expect("Invalid IP address"), - nat_type: NatType::PortRestrictedCone { - mappings: Default::default(), - }, - } - } - - fn new_symmetric(external_ip: &str) -> Self { - Self { - external_ip: external_ip.parse().expect("Invalid IP address"), - nat_type: NatType::Symmetric { - mappings: Default::default(), - }, - } - } - - fn transform_outbound(&mut self, from: SocketAddr, to: SocketAddr) -> (SocketAddr, SocketAddr) { - let external_port = match &mut self.nat_type { - NatType::Symmetric { mappings } => { - // For symmetric NATs, the key is the 4-tuple of the connection. - - symmetric_nat_lookup(from, to, mappings) - } - NatType::PortRestrictedCone { mappings } => { - // For a port-restricted-cone NAT, the key is also the 4-tuple of the connection. - // Contrary to a symmetric NAT, the source port is preserved. - *mappings.entry((from, to)).or_insert(from.port()) - } - }; - - (SocketAddr::new(self.external_ip, external_port), to) - } - - fn transform_inbound(&self, from: SocketAddr, to: SocketAddr) -> Option<(SocketAddr, SocketAddr)> { - let internal_addr = match &self.nat_type { - // For symmetric NAT, need exact source match of from == dst and only on the assigned port. - NatType::Symmetric { mappings } => { - let ((src, _), _) = mappings - .iter() - .find(|((_, dst), outside)| from == *dst && **outside == to.port())?; - - *src - } - // For restricted-cone NAT, traffic on the outside assigned port is routed back - // if we have previously contacted this IP + port combination. - NatType::PortRestrictedCone { mappings } => { - let ((src, _), _) = mappings - .iter() - .find(|((_, dst), outside)| from == *dst && **outside == to.port())?; - - *src - } - }; - - Some((from, internal_addr)) - } - } - - fn symmetric_nat_lookup( - src: SocketAddr, - dst: SocketAddr, - mappings: &mut HashMap<(SocketAddr, SocketAddr), u16>, - ) -> u16 { - let outside_port = loop { - let port = crate::vendor::str0m_proto::NonCryptographicRng::u16(); - - if mappings.values().any(|p| *p == port) { - continue; - } - - break port; - }; - - *mappings.entry((src, dst)).or_insert(outside_port) - } - - /// Transform function with flexible NAT support - fn transform( - from: SocketAddr, - to: SocketAddr, - from_agent: &mut TestAgent, - to_agent: &mut TestAgent, - ) -> Option<(SocketAddr, SocketAddr)> { - if from.port() == 9999 || to.port() == 9999 { - return None; - } - - let outgoing_is_from_relay = from_agent - .local_candidates() - .any(|c| c.addr() == from && c.kind() == CandidateKind::Relayed); - - // If NAT is present on sending agent, apply it. - let (from, to) = if let Some(nat) = &mut from_agent.nat { - // If our traffic is "from" a relay candidate, the NAT does not apply. - if outgoing_is_from_relay { - (from, to) - } else { - nat.transform_outbound(from, to) - } - } else { - (from, to) - }; - - let incoming_is_from_relay = to_agent - .local_candidates() - .any(|c| c.addr() == to && c.kind() == CandidateKind::Relayed); - - // If NAT is present on receiving agent, apply it. - if let Some(nat) = &mut to_agent.nat { - // If our traffic is "to" a relay candidate, the NAT does not apply. - if incoming_is_from_relay { - Some((from, to)) - } else { - if nat.external_ip != to.ip() { - return None; - } - - nat.transform_inbound(from, to) - } - } else { - Some((from, to)) - } - } -} diff --git a/rs/moq-webrtc/src/vendor/is/pair.rs b/rs/moq-webrtc/src/vendor/is/pair.rs deleted file mode 100644 index 56cdb02703a..00000000000 --- a/rs/moq-webrtc/src/vendor/is/pair.rs +++ /dev/null @@ -1,623 +0,0 @@ -use std::collections::VecDeque; -use std::fmt; -use std::time::{Duration, Instant}; -use tracing::{debug, trace}; - -use crate::vendor::is::Candidate; -use crate::vendor::is::CandidateKind; -use crate::vendor::is::stun::{DEFAULT_MAX_RETRANSMITS, StunTiming, TransId}; -use crate::vendor::str0m_proto::Id; -use crate::vendor::str0m_proto::Pii; - -// When running ice-lite we need a cutoff when we consider the remote definitely gone. -const RECENT_BINDING_REQUEST: Duration = Duration::from_secs(15); - -/// A pair of candidates, local and remote, in the ice agent. -pub struct CandidatePair { - id: PairId, - - /// Index into the local_candidates list in IceAgent. - local_idx: usize, - local_kind: CandidateKind, - - /// Index into the remote_candidates list in IceAgent. - remote_idx: usize, - remote_kind: CandidateKind, - - /// Index into local_candidates for the last successful - /// response. This forms the "valid pair" logic in the spec. - valid_idx: Option, - - /// Calculated prio given the candidates. - prio: u64, - - /// Current state of this pair. Start in Waiting (there is - /// no frozen state since there is only one data stream). - state: CheckState, - - /// Record of the latest STUN messages we've tried using this pair. - /// - /// This list will usually not grow beyond [`DEFAULT_MAX_RETRANSMITS`] * 2 - /// unless the user configures a very large retransmission counter. - binding_attempts: VecDeque, - - /// The next time we are to do a binding attempt, cached, since we - /// potentially recalculate this many times per second otherwise. - cached_next_attempt_time: Option, - - /// Number of remote binding requests we seen for this pair. - remote_binding_requests: u64, - - /// Last remote binding request. - remote_binding_request_time: Option, - - /// State of nomination for this candidate pair. - nomination_state: NominationState, - - /// Total number of STUN binding responses received on this pair, - /// across the whole pair lifetime (not bounded by `binding_attempts`). - responses_received: u64, - - /// Sum of all RTTs measured from successful STUN binding transactions - /// on this pair, across the whole pair lifetime. - total_round_trip_time: Duration, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum CheckState { - /// A check has not been sent for this pair. - #[default] - Waiting, - - /// A check has been sent for this pair, but the - /// transaction is in progress. - InProgress, - - /// A check has been sent for this pair, and it produced a - /// successful result. - Succeeded, - // - // Hey martin, this looks fishy you might say. Why is there no - // failed state? The reason is that agent removes the candidatepair - // straight away if it is deemed failed. - // - // /// A check has been sent for this pair, and it failed (a - // /// response to the check was never received, or a failure response - // /// was received). - // Failed, -} - -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub enum NominationState { - /// This pair has not been nominated. - #[default] - None, - /// The pair has been nominated. The binding request for the - /// nomination has not been sent. - Nominated, - /// The binding request is sent. - Attempt, - /// Successful nomination. Received a reply for the transaction id. - Success, -} - -pub struct BindingAttempt { - /// The transaction id used in the STUN binding request. - /// - /// This is how we recognize the binding response. - trans_id: TransId, - - /// The time we sent the binding request. - request_sent: Instant, - - /// The time we got a binding response, if ever. - respone_recv: Option, - - /// Whether the binding attempt is nominated. - nominated: bool, - - /// The agent's `controlling` value at request time. - /// - /// Used to decide whether a 487 (Role Conflict) response is - /// stale: if the agent has already swapped role since the - /// request was sent, the 487 must be ignored to avoid flapping - /// when in-flight requests with the old role get rejected. - controlling: bool, -} - -impl BindingAttempt { - pub fn controlling(&self) -> bool { - self.controlling - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PairId([u8; 20]); - -impl Default for PairId { - fn default() -> Self { - PairId(Id::random().into_array()) - } -} - -impl CandidatePair { - pub fn new( - local_idx: usize, - local_kind: CandidateKind, - remote_idx: usize, - remote_kind: CandidateKind, - prio: u64, - ) -> Self { - CandidatePair { - local_idx, - local_kind, - remote_idx, - remote_kind, - prio, - binding_attempts: VecDeque::with_capacity(DEFAULT_MAX_RETRANSMITS * 2), - id: Default::default(), - valid_idx: Default::default(), - state: Default::default(), - cached_next_attempt_time: Default::default(), - remote_binding_requests: Default::default(), - remote_binding_request_time: Default::default(), - nomination_state: Default::default(), - responses_received: 0, - total_round_trip_time: Duration::ZERO, - } - } - - pub fn id(&self) -> PairId { - self.id - } - - pub fn calculate_prio(controlling: bool, remote_prio: u32, local_prio: u32) -> u64 { - // The ICE agent computes a priority for each candidate pair. Let G be - // the priority for the candidate provided by the controlling agent. - // Let D be the priority for the candidate provided by the controlled - // agent. The priority for a pair is computed as follows: - // - // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0) - - let (g, d) = if controlling { - (local_prio, remote_prio) - } else { - (remote_prio, local_prio) - }; - - 2_u64.pow(32) * g.min(d) as u64 + 2 * g.max(d) as u64 + if g > d { 1 } else { 0 } - } - - pub fn local_idx(&self) -> usize { - self.local_idx - } - - pub fn remote_idx(&self) -> usize { - self.remote_idx - } - - pub fn local_candidate<'a>(&self, cs: &'a [Candidate]) -> &'a Candidate { - &cs[self.local_idx] - } - - pub fn remote_candidate<'a>(&self, cs: &'a [Candidate]) -> &'a Candidate { - &cs[self.remote_idx] - } - - pub fn prio(&self) -> u64 { - self.prio - } - - pub fn set_prio(&mut self, prio: u64) { - self.prio = prio; - } - - pub fn state(&self) -> CheckState { - self.state - } - - pub fn increase_remote_binding_requests(&mut self, now: Instant) { - self.remote_binding_requests += 1; - self.remote_binding_request_time = Some(now); - trace!("Recorded binding request: {:?}", self); - } - - pub fn remote_binding_request_time(&self) -> Option { - self.remote_binding_request_time - } - - pub fn is_ice_lite_alive(&self, now: Instant) -> bool { - let Some(t) = self.remote_binding_request_time else { - return true; // No timestamp yet = hasn't had a chance to fail - }; - now - t < RECENT_BINDING_REQUEST - } - - pub fn is_nominated(&self) -> bool { - !matches!(self.nomination_state, NominationState::None) - } - - pub fn nominate(&mut self, force_success: bool) { - assert!(self.nomination_state == NominationState::None); - if force_success { - self.nomination_state = NominationState::Success; - debug!("Force success nominated pair {:?}", Pii(&self)); - } else { - self.nomination_state = NominationState::Nominated; - debug!("Nominated pair: {:?}", Pii(&self)); - } - } - - pub fn copy_nominated_and_success_state(&mut self, other: &CandidatePair) { - match other.nomination_state { - NominationState::Nominated | NominationState::Success => { - self.nomination_state = other.nomination_state; - } - // None is the default, no need to copy - NominationState::None => {} - // The old pair had a nominated binding request in flight. We can't copy - // Attempt directly because the new pair doesn't have the corresponding - // transaction ID in its binding_attempts. Reset to Nominated so the next - // binding cycle issues a fresh attempt that can promote back to Success. - NominationState::Attempt => { - self.nomination_state = NominationState::Nominated; - } - } - - // The replacement has the same local base and remote address, so a check - // that succeeded on the old pair validated this path too. An in-progress - // check is not copied, for the same reason as Attempt above. - if other.state == CheckState::Succeeded { - self.state = CheckState::Succeeded; - } - } - - /// Records a new binding request attempt. - /// - /// Returns the transaction id to use in the STUN message. - pub fn new_attempt(&mut self, now: Instant, timing_config: &StunTiming, controlling: bool) -> TransId { - // calculate a new time - self.cached_next_attempt_time = None; - - if matches!(self.nomination_state, NominationState::Nominated) { - debug!("Nominated attempt STUN binding: {:?}", Pii(&self)); - self.nomination_state = NominationState::Attempt; - } - - let attempt = BindingAttempt { - trans_id: TransId::new(), - request_sent: now, - respone_recv: None, - nominated: self.is_nominated(), - controlling, - }; - - self.binding_attempts.push_back(attempt); - - // Never keep more than the maximum allowed retransmits. - while self.binding_attempts.len() > timing_config.max_retransmits() { - self.binding_attempts.pop_front(); - } - - if self.state == CheckState::Waiting { - trace!("Check state: {:?} -> {:?}", self.state, CheckState::InProgress); - self.state = CheckState::InProgress; - } - - trace!("Sending binding request: {:?}", self); - - let last = self.binding_attempts.back().unwrap(); - - last.trans_id - } - - /// Returns the binding attempt for the given STUN transaction id, if - /// this pair sent it. - pub fn binding_attempt(&self, trans_id: TransId) -> Option<&BindingAttempt> { - self.binding_attempts.iter().find(|b| b.trans_id == trans_id) - } - - /// Marks a binding request attempt as having a successful response. - /// - /// ### Panics - /// - /// Panics if the trans_id doesn't belong to this pair. - pub fn record_binding_response(&mut self, now: Instant, trans_id: TransId, valid_idx: usize) { - self.cached_next_attempt_time = None; - - self.valid_idx = Some(valid_idx); - - let attempt = self - .binding_attempts - .iter_mut() - .find(|b| b.trans_id == trans_id) - .expect("Binding request attempt"); - - attempt.respone_recv = Some(now); - - self.responses_received += 1; - self.total_round_trip_time += now - attempt.request_sent; - - if attempt.nominated && self.nomination_state == NominationState::Attempt { - self.nomination_state = NominationState::Success; - debug!("Nomination success: {:?}", Pii(&self)); - } - - if self.state == CheckState::InProgress { - trace!("Check state: {:?} -> {:?}", self.state, CheckState::Succeeded); - self.state = CheckState::Succeeded; - } - - trace!("Recorded binding response: {:?}", self); - } - - /// Marks the pair as validated by an incoming binding request we answered. - /// - /// This is for ice-lite only. A lite agent sends no checks of its own, so - /// [`CandidatePair::record_binding_response`] never runs for it and the - /// pair would stay `Waiting` for its entire life. - /// - /// This is weaker than [`CandidatePair::record_binding_response`] and - /// says so: a binding *response* proves return routability, while an - /// answered request proves only that the sender knows our password. An - /// ice-lite agent cannot obtain the former by construction, so the - /// alternative is not a stronger check but a permanently unusable - /// state. The caller restricts this to controlled agents, where - /// nomination - which is what governs egress - already accepts a - /// forged request without return-routability proof. - pub fn record_remote_binding_request_success(&mut self) { - if self.state != CheckState::Succeeded { - trace!("Check state: {:?} -> {:?}", self.state, CheckState::Succeeded); - self.state = CheckState::Succeeded; - } - } - - /// The time of the last binding request attempt. - /// - /// `None` means there has been no attempts. - fn last_attempt_time(&self) -> Option { - self.binding_attempts.back().map(|b| b.request_sent) - } - - /// The round-trip time of the most recent successful STUN binding - /// transaction recorded for this pair. - /// - /// `None` if no binding response has been received yet. - pub fn last_successful_rtt(&self) -> Option { - self.binding_attempts - .iter() - .rev() - .find_map(|b| b.respone_recv.map(|r| r - b.request_sent)) - } - - /// Total number of STUN binding responses received on this pair over - /// the pair's lifetime. - pub fn responses_received(&self) -> u64 { - self.responses_received - } - - /// Sum of all RTTs measured from successful STUN binding transactions - /// on this pair over the pair's lifetime. - pub fn total_round_trip_time(&self) -> Duration { - self.total_round_trip_time - } - - /// From the back of binding_attempts, go through all unanswered and find - /// the time when we started having an outage. - /// - /// The returned value is the number of unanswered attempts and the oldest time. - fn unanswered(&self) -> Option<(usize, Instant)> { - self.binding_attempts - .iter() - .rev() - .take_while(|b| b.respone_recv.is_none()) - .enumerate() - .last() - .map(|(idx, b)| (idx + 1, b.request_sent)) - } - - /// When we should do the next retry. - pub fn next_binding_attempt(&mut self, now: Instant, timing_config: &StunTiming) -> Instant { - if let Some(cached) = self.cached_next_attempt_time { - return cached; - } - - let next = if matches!(self.nomination_state, NominationState::Nominated) { - // Cheating a bit to make the nomination "skip the queue". - // Must handle underflow gracefully, machine may be running for < 60s. - now.checked_sub(Duration::from_secs(60)).unwrap_or(now) - } else if let Some(last) = self.last_attempt_time() { - // When we have unanswered for longer than STUN_MAX_RTO_MILLIS / 2, start - // checking more often. - let unanswered_count = self - .unanswered() - .filter(|(_, since)| now - *since > timing_config.max_rto() / 2) - .map(|(count, _)| count); - - let send_count = unanswered_count.unwrap_or(self.binding_attempts.len()); - - last + timing_config.stun_resend_delay(send_count) - } else { - // No previous attempt, do next retry straight away. - now - }; - - // At least do a check at this time. - let min = now + timing_config.max_rto(); - - let at_least = next.min(min); - - // keep this cached since the calculation can happen very often. - self.cached_next_attempt_time = Some(at_least); - - at_least - } - - /// Tells if this candidate pair is still possible to use for connectivity. - /// - /// Returns `false` if the candidate has failed. - pub fn is_still_possible(&self, now: Instant, timing_config: &StunTiming) -> bool { - // If we've recently received a binding request from the remote peer, the pair - // is still viable even if our own binding requests aren't getting responses. - // This handles the case where the remote peer is still sending us requests - // (indicating connectivity) but may not be responding to our requests due to - // asymmetric behavior in some browser versions (e.g., Chrome v144+). - if let Some(t) = self.remote_binding_request_time { - if now - t < RECENT_BINDING_REQUEST { - return true; - } - } - - let attempts = self.binding_attempts.len(); - let unanswered = self.unanswered().map(|b| b.0).unwrap_or(0); - - if attempts < timing_config.max_retransmits() || unanswered < timing_config.max_retransmits() { - true - } else { - // check to see if we are still waiting for the last attempt - // this unwrap is fine because unanswered count > 0 - let last = self.last_attempt_time().unwrap(); - let cutoff = last + timing_config.stun_last_resend_delay(); - now < cutoff - } - } - - pub(crate) fn copy_remote_binding_requests(&mut self, other: &CandidatePair) { - self.remote_binding_requests = other.remote_binding_requests; - self.remote_binding_request_time = other.remote_binding_request_time; - - // ICE-lite pairs are validated by incoming requests. Preserve that - // validation when a higher-priority candidate replaces the pair. - if other.state == CheckState::Succeeded { - self.state = CheckState::Succeeded; - } - } - - pub(crate) fn update_kinds(&mut self, local_candidates: &[Candidate], remote_candidates: &[Candidate]) { - self.local_kind = local_candidates[self.local_idx].kind(); - self.remote_kind = remote_candidates[self.remote_idx].kind(); - } - - pub(crate) fn reset_cached_next_attempt_time(&mut self) { - self.cached_next_attempt_time = None; - } - - #[cfg(test)] - pub fn remote_binding_requests(&self) -> (u64, Option) { - (self.remote_binding_requests, self.remote_binding_request_time) - } -} - -impl PartialEq for CandidatePair { - fn eq(&self, other: &Self) -> bool { - self.local_idx == other.local_idx && self.remote_idx == other.remote_idx && self.prio == other.prio - } -} - -impl Eq for CandidatePair {} - -impl PartialOrd for CandidatePair { - fn partial_cmp(&self, other: &Self) -> Option { - Some(Self::cmp(self, other)) - } -} - -impl Ord for CandidatePair { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - // reverse since we want highest prio first. - self.prio.cmp(&other.prio).reverse() - } -} - -impl fmt::Debug for BindingAttempt { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("BindingAttempt") - .field("request_sent", &self.request_sent) - .field("respone_recv", &self.respone_recv) - .finish() - } -} - -impl fmt::Debug for CandidatePair { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "CandidatePair(\ - {}-{} ({}-{}) prio={} state={:?} attempts={} unanswered={} remote={} nom={:?}\ - )", - self.local_idx, - self.remote_idx, - self.local_kind, - self.remote_kind, - self.prio, - self.state, - self.binding_attempts.len(), - self.unanswered().map(|b| b.0).unwrap_or(0), - self.remote_binding_requests, - self.nomination_state - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ice_timeout_after_established() { - let stun_timing = StunTiming::default(); - - let mut pair = CandidatePair::new(0, CandidateKind::Host, 0, CandidateKind::Host, 0); - - let mut now = Instant::now(); - - for _ in 0..20 { - let id = pair.new_attempt(now, &stun_timing, false); - - now += Duration::from_millis(500); - - pair.record_binding_response(now, id, 0); - } - - let offline_at = now; - - while pair.is_still_possible(now, &stun_timing) { - pair.new_attempt(now, &stun_timing, false); - now = pair.next_binding_attempt(now, &stun_timing); - } - - let duration = now.duration_since(offline_at); - - assert_eq!(duration, stun_timing.timeout()) - } - - #[test] - fn last_successful_rtt_returns_most_recent() { - let stun_timing = StunTiming::default(); - let mut pair = CandidatePair::new(0, CandidateKind::Host, 0, CandidateKind::Host, 0); - let now = Instant::now(); - - assert_eq!(pair.last_successful_rtt(), None); - assert_eq!(pair.responses_received(), 0); - assert_eq!(pair.total_round_trip_time(), Duration::ZERO); - - let id1 = pair.new_attempt(now, &stun_timing, false); - pair.record_binding_response(now + Duration::from_millis(50), id1, 0); - assert_eq!(pair.last_successful_rtt(), Some(Duration::from_millis(50))); - assert_eq!(pair.responses_received(), 1); - assert_eq!(pair.total_round_trip_time(), Duration::from_millis(50)); - - // Newer in-flight attempt without response shouldn't shadow the - // older successful one or change cumulative counters. - let _id2 = pair.new_attempt(now + Duration::from_millis(100), &stun_timing, false); - assert_eq!(pair.last_successful_rtt(), Some(Duration::from_millis(50))); - assert_eq!(pair.responses_received(), 1); - - // A newer successful attempt replaces current rtt and accumulates totals. - let id3 = pair.new_attempt(now + Duration::from_millis(200), &stun_timing, false); - pair.record_binding_response(now + Duration::from_millis(220), id3, 0); - assert_eq!(pair.last_successful_rtt(), Some(Duration::from_millis(20))); - assert_eq!(pair.responses_received(), 2); - assert_eq!(pair.total_round_trip_time(), Duration::from_millis(70)); - } -} diff --git a/rs/moq-webrtc/src/vendor/is/parse.rs b/rs/moq-webrtc/src/vendor/is/parse.rs deleted file mode 100644 index 01b95989afe..00000000000 --- a/rs/moq-webrtc/src/vendor/is/parse.rs +++ /dev/null @@ -1,109 +0,0 @@ -use std::net::{IpAddr, SocketAddr}; -use std::str::FromStr; - -use crate::vendor::is::{Candidate, CandidateKind, IceError}; -use crate::vendor::str0m_proto::TcpType; - -/// Parse a candidate string into a [Candidate]. -/// -/// Expects the format defined in RFC 5245 section 15.1, starting with `candidate:`. -/// Does not parse an `a=` prefix or trailing newline. -pub fn parse_candidate(s: &str) -> Result { - parse_candidate_inner(s).map_err(|e| IceError::BadCandidate(format!("{}: {}", s, e))) -} - -fn parse_candidate_inner(s: &str) -> Result { - let s = s.strip_prefix("candidate:").ok_or("missing 'candidate:' prefix")?; - - let mut iter = s.split_whitespace(); - - let foundation = iter.next().ok_or("missing foundation")?.to_string(); - let component_id: u16 = iter - .next() - .ok_or("missing component-id")? - .parse() - .map_err(|e| format!("bad component-id: {e}"))?; - let proto_str = iter.next().ok_or("missing protocol")?; - let proto = proto_str - .try_into() - .map_err(|_| format!("invalid protocol: {proto_str}"))?; - let prio: u32 = iter - .next() - .ok_or("missing priority")? - .parse() - .map_err(|e| format!("bad priority: {e}"))?; - let addr: IpAddr = iter - .next() - .ok_or("missing address")? - .parse() - .map_err(|e| format!("bad address: {e}"))?; - let port: u16 = iter - .next() - .ok_or("missing port")? - .parse() - .map_err(|e| format!("bad port: {e}"))?; - - // expect "typ" - match iter.next() { - Some("typ") => {} - other => return Err(format!("expected 'typ', got: {:?}", other)), - } - - let kind_str = iter.next().ok_or("missing candidate type")?; - let kind = match kind_str { - "host" => CandidateKind::Host, - "prflx" => CandidateKind::PeerReflexive, - "srflx" => CandidateKind::ServerReflexive, - "relay" => CandidateKind::Relayed, - other => return Err(format!("unknown candidate type: {other}")), - }; - - // Parse optional key-value extensions - let mut raddr = None; - let mut rport = None; - let mut tcptype = None; - let mut ufrag = None; - - while let Some(key) = iter.next() { - match key { - "raddr" => { - let v = iter.next().ok_or("missing raddr value")?; - raddr = Some(v.parse::().map_err(|e| format!("bad raddr: {e}"))?); - } - "rport" => { - let v = iter.next().ok_or("missing rport value")?; - rport = Some(v.parse::().map_err(|e| format!("bad rport: {e}"))?); - } - "tcptype" => { - let v = iter.next().ok_or("missing tcptype value")?; - tcptype = Some(TcpType::from_str(v).map_err(|e| format!("bad tcptype: {e}"))?); - } - "ufrag" => { - let v = iter.next().ok_or("missing ufrag value")?; - ufrag = Some(v.to_string()); - } - // Ignore unknown extensions (generation, network-id, network-cost, etc.) - _ => { - // consume the value - let _ = iter.next(); - } - } - } - - let raddr_sock = match (raddr, rport) { - (Some(ip), Some(port)) => Some(SocketAddr::from((ip, port))), - _ => None, - }; - - Ok(Candidate::from_parts( - foundation, - component_id, - proto, - prio, - SocketAddr::from((addr, port)), - kind, - raddr_sock, - tcptype, - ufrag, - )) -} diff --git a/rs/moq-webrtc/src/vendor/is/preference.rs b/rs/moq-webrtc/src/vendor/is/preference.rs deleted file mode 100644 index 1fbb17ddc4d..00000000000 --- a/rs/moq-webrtc/src/vendor/is/preference.rs +++ /dev/null @@ -1,347 +0,0 @@ -use crate::vendor::is::Candidate; -use crate::vendor::is::CandidateKind; - -/// Standard local preference calculation for a candidate. -/// -/// This is the default local preference calculation for a candidate. -/// -/// It is used to determine the preference of a candidate when there are multiple candidates -/// for a particular component for a particular data stream. -/// -/// The preference is calculated based on the candidate type, the IP version of the candidate, -/// and the same_kind counter. -pub fn default_local_preference(c: &Candidate, same_kind: usize) -> u32 { - let ip = c.addr(); - - // https://datatracker.ietf.org/doc/html/rfc8445#section-5.1.2.1 - // The local preference MUST be an integer from 0 (lowest preference) to - // 65535 (highest preference) inclusive. When there is only a single IP - // address, this value SHOULD be set to 65535. If there are multiple - // candidates for a particular component for a particular data stream - // that have the same type, the local preference MUST be unique for each - // one. - // ... - // If an ICE agent is multihomed and has multiple IP addresses, the - // recommendations in [RFC8421] SHOULD be followed. If multiple TURN - // servers are used, local priorities for the candidates obtained from - // the TURN servers are chosen in a similar fashion as for multihomed - // local candidates: the local preference value is used to indicate a - // preference among different servers, but the preference MUST be unique - // for each one. - // ================ - // - // The above presupposes that we know all the candidates when we start - // the ice agent. That doesn't work for us, so we deliberately do not - // follow spec. We assign the following intervals for the different - // types of candidates: - // - // 0 - 16384 => relay - // 16384 - 32768 => srflx - // 32768 - 49152 => prflx - // 49152 - 65536 => host - // - // And furthermore we subdivide these to interleave IPv6 with IPv4 - // so that odd numbers are ipv6 and even are ipv4. - // - // For host candidates this means: - // 65535 - first ipv6 - // 65534 - first ipv4 - // 65533 - second ipv6 - // 65432 - second ipv4 - let counter_start: u32 = { - use CandidateKind::*; - let x = match c.kind() { - Host => 65_535, - PeerReflexive => 49_151, - ServerReflexive => 32_767, - Relayed => 16_383, - }; - x - if ip.is_ipv6() { 0 } else { 1 } - }; - - // For relayed candidates, we add a "punishment" to the local preference - // if the base address differs in the IP version from the allocated address - // of the candidate. - // This punishment ensures that we prefer relayed within the same IP version, - // e.g. IPv4 <> IPv4 over ones that translate between IP version, e.g. IPv4 <> IPv6. - let relay_across_ip_version_punishment = if c.kind() == CandidateKind::Relayed { - if c.local().is_ipv4() != ip.is_ipv4() { 1000 } else { 0 } - } else { - 0 - }; - - counter_start - same_kind as u32 * 2 - relay_across_ip_version_punishment -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::is::Candidate; - use std::net::SocketAddr; - - fn ipv4_addr(ip: &str) -> SocketAddr { - format!("{}:1234", ip).parse().unwrap() - } - - fn ipv6_addr(ip: &str) -> SocketAddr { - format!("[{}]:1234", ip).parse().unwrap() - } - - #[test] - fn test_host_candidates_ipv4() { - let addr = ipv4_addr("192.168.1.1"); - let candidate = Candidate::host(addr, "udp").unwrap(); - - // First host candidate (same_kind = 0) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 65534); // 65535 - 1 (IPv4) - 0 * 2 - - // Second host candidate (same_kind = 1) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 65532); // 65535 - 1 (IPv4) - 1 * 2 - - // Third host candidate (same_kind = 2) - let pref = default_local_preference(&candidate, 2); - assert_eq!(pref, 65530); // 65535 - 1 (IPv4) - 2 * 2 - } - - #[test] - fn test_host_candidates_ipv6() { - let addr = ipv6_addr("2001:db8::1"); - let candidate = Candidate::host(addr, "udp").unwrap(); - - // First host candidate (same_kind = 0) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 65535); // 65535 - 0 (IPv6) - 0 * 2 - - // Second host candidate (same_kind = 1) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 65533); // 65535 - 0 (IPv6) - 1 * 2 - - // Third host candidate (same_kind = 2) - let pref = default_local_preference(&candidate, 2); - assert_eq!(pref, 65531); // 65535 - 0 (IPv6) - 2 * 2 - } - - #[test] - fn test_server_reflexive_candidates_ipv4() { - let addr = ipv4_addr("203.0.113.1"); - let base = ipv4_addr("192.168.1.1"); - let candidate = Candidate::server_reflexive(addr, base, "udp").unwrap(); - - // First srflx candidate (same_kind = 0) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 32766); // 32767 - 1 (IPv4) - 0 * 2 - - // Second srflx candidate (same_kind = 1) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 32764); // 32767 - 1 (IPv4) - 1 * 2 - } - - #[test] - fn test_server_reflexive_candidates_ipv6() { - let addr = ipv6_addr("2001:db8::100"); - let base = ipv6_addr("2001:db8::1"); - let candidate = Candidate::server_reflexive(addr, base, "udp").unwrap(); - - // First srflx candidate (same_kind = 0) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 32767); // 32767 - 0 (IPv6) - 0 * 2 - - // Second srflx candidate (same_kind = 1) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 32765); // 32767 - 0 (IPv6) - 1 * 2 - } - - #[test] - fn test_peer_reflexive_candidates_ipv4() { - let addr = ipv4_addr("198.51.100.1"); - let base = ipv4_addr("192.168.1.1"); - let candidate = Candidate::test_peer_rflx(addr, base, "udp"); - - // First prflx candidate (same_kind = 0) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 49150); // 49151 - 1 (IPv4) - 0 * 2 - - // Second prflx candidate (same_kind = 1) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 49148); // 49151 - 1 (IPv4) - 1 * 2 - } - - #[test] - fn test_peer_reflexive_candidates_ipv6() { - let addr = ipv6_addr("2001:db8::200"); - let base = ipv6_addr("2001:db8::1"); - let candidate = Candidate::test_peer_rflx(addr, base, "udp"); - - // First prflx candidate (same_kind = 0) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 49151); // 49151 - 0 (IPv6) - 0 * 2 - - // Second prflx candidate (same_kind = 1) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 49149); // 49151 - 0 (IPv6) - 1 * 2 - } - - #[test] - fn test_relayed_candidates_ipv4_same_ip_version() { - let addr = ipv4_addr("192.0.2.1"); - let local = ipv4_addr("192.168.1.1"); - let candidate = Candidate::relayed(addr, local, "udp").unwrap(); - - // First relay candidate (same_kind = 0, no IP version punishment) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 16382); // 16383 - 1 (IPv4) - 0 * 2 - 0 (no punishment) - - // Second relay candidate (same_kind = 1, no IP version punishment) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 16380); // 16383 - 1 (IPv4) - 1 * 2 - 0 (no punishment) - } - - #[test] - fn test_relayed_candidates_ipv6_same_ip_version() { - let addr = ipv6_addr("2001:db8::300"); - let local = ipv6_addr("2001:db8::1"); - let candidate = Candidate::relayed(addr, local, "udp").unwrap(); - - // First relay candidate (same_kind = 0, no IP version punishment) - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 16383); // 16383 - 0 (IPv6) - 0 * 2 - 0 (no punishment) - - // Second relay candidate (same_kind = 1, no IP version punishment) - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 16381); // 16383 - 0 (IPv6) - 1 * 2 - 0 (no punishment) - } - - #[test] - fn test_relayed_candidates_cross_ip_version_punishment() { - // IPv4 allocated address with IPv6 local address - let addr = ipv4_addr("192.0.2.1"); - let local = ipv6_addr("2001:db8::1"); - let candidate = Candidate::relayed(addr, local, "udp").unwrap(); - - // First relay candidate with IP version punishment - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 15382); // 16383 - 1 (IPv4) - 0 * 2 - 1000 (punishment) - - // Second relay candidate with IP version punishment - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 15380); // 16383 - 1 (IPv4) - 1 * 2 - 1000 (punishment) - } - - #[test] - fn test_relayed_candidates_cross_ip_version_punishment_reverse() { - // IPv6 allocated address with IPv4 local address - let addr = ipv6_addr("2001:db8::300"); - let local = ipv4_addr("192.168.1.1"); - let candidate = Candidate::relayed(addr, local, "udp").unwrap(); - - // First relay candidate with IP version punishment - let pref = default_local_preference(&candidate, 0); - assert_eq!(pref, 15383); // 16383 - 0 (IPv6) - 0 * 2 - 1000 (punishment) - - // Second relay candidate with IP version punishment - let pref = default_local_preference(&candidate, 1); - assert_eq!(pref, 15381); // 16383 - 0 (IPv6) - 1 * 2 - 1000 (punishment) - } - - #[test] - fn test_candidate_type_ordering() { - // Test that different candidate types maintain proper ordering - let ipv4_addr = ipv4_addr("192.168.1.1"); - let ipv6_addr = ipv6_addr("2001:db8::1"); - let local = ipv4_addr; - - let host_ipv4 = Candidate::host(ipv4_addr, "udp").unwrap(); - let host_ipv6 = Candidate::host(ipv6_addr, "udp").unwrap(); - let srflx_ipv4 = Candidate::server_reflexive(ipv4_addr, local, "udp").unwrap(); - let srflx_ipv6 = Candidate::server_reflexive(ipv6_addr, ipv6_addr, "udp").unwrap(); - let prflx_ipv4 = Candidate::test_peer_rflx(ipv4_addr, local, "udp"); - let prflx_ipv6 = Candidate::test_peer_rflx(ipv6_addr, ipv6_addr, "udp"); - let relay_ipv4 = Candidate::relayed(ipv4_addr, local, "udp").unwrap(); - let relay_ipv6 = Candidate::relayed(ipv6_addr, ipv6_addr, "udp").unwrap(); - - let same_kind = 0; - - let host_ipv4_pref = default_local_preference(&host_ipv4, same_kind); - let host_ipv6_pref = default_local_preference(&host_ipv6, same_kind); - let srflx_ipv4_pref = default_local_preference(&srflx_ipv4, same_kind); - let srflx_ipv6_pref = default_local_preference(&srflx_ipv6, same_kind); - let prflx_ipv4_pref = default_local_preference(&prflx_ipv4, same_kind); - let prflx_ipv6_pref = default_local_preference(&prflx_ipv6, same_kind); - let relay_ipv4_pref = default_local_preference(&relay_ipv4, same_kind); - let relay_ipv6_pref = default_local_preference(&relay_ipv6, same_kind); - - // Host candidates should have highest preference - assert!(host_ipv4_pref > srflx_ipv4_pref); - assert!(host_ipv6_pref > srflx_ipv6_pref); - assert!(host_ipv4_pref > prflx_ipv4_pref); - assert!(host_ipv6_pref > prflx_ipv6_pref); - assert!(host_ipv4_pref > relay_ipv4_pref); - assert!(host_ipv6_pref > relay_ipv6_pref); - - // Peer reflexive candidates should have higher preference than server reflexive - assert!(prflx_ipv4_pref > srflx_ipv4_pref); - assert!(prflx_ipv6_pref > srflx_ipv6_pref); - - // Server reflexive candidates should have higher preference than relayed - assert!(srflx_ipv4_pref > relay_ipv4_pref); - assert!(srflx_ipv6_pref > relay_ipv6_pref); - - // Peer reflexive candidates should have higher preference than relayed - assert!(prflx_ipv4_pref > relay_ipv4_pref); - assert!(prflx_ipv6_pref > relay_ipv6_pref); - - // IPv6 should have higher preference than IPv4 within the same type - assert!(host_ipv6_pref > host_ipv4_pref); - assert!(srflx_ipv6_pref > srflx_ipv4_pref); - assert!(prflx_ipv6_pref > prflx_ipv4_pref); - assert!(relay_ipv6_pref > relay_ipv4_pref); - } - - #[test] - fn test_ipv4_ipv6_interleaving() { - // Test that IPv6 gets odd numbers and IPv4 gets even numbers - let ipv4_addr = ipv4_addr("192.168.1.1"); - let ipv6_addr = ipv6_addr("2001:db8::1"); - - let host_ipv4 = Candidate::host(ipv4_addr, "udp").unwrap(); - let host_ipv6 = Candidate::host(ipv6_addr, "udp").unwrap(); - - let ipv4_pref = default_local_preference(&host_ipv4, 0); - let ipv6_pref = default_local_preference(&host_ipv6, 0); - - // IPv4 should get even number (65534), IPv6 should get odd number (65535) - assert_eq!(ipv4_pref % 2, 0, "IPv4 preference should be even"); - assert_eq!(ipv6_pref % 2, 1, "IPv6 preference should be odd"); - assert_eq!(ipv6_pref - ipv4_pref, 1, "IPv6 should be exactly 1 higher than IPv4"); - } - - #[test] - fn test_same_kind_counter_effect() { - let addr = ipv4_addr("192.168.1.1"); - let candidate = Candidate::host(addr, "udp").unwrap(); - - // Test that same_kind counter decreases preference by 2 each time - let pref0 = default_local_preference(&candidate, 0); - let pref1 = default_local_preference(&candidate, 1); - let pref2 = default_local_preference(&candidate, 2); - let pref3 = default_local_preference(&candidate, 3); - - assert_eq!( - pref0 - pref1, - 2, - "Preference should decrease by 2 for each same_kind increment" - ); - assert_eq!( - pref1 - pref2, - 2, - "Preference should decrease by 2 for each same_kind increment" - ); - assert_eq!( - pref2 - pref3, - 2, - "Preference should decrease by 2 for each same_kind increment" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/is/stun.rs b/rs/moq-webrtc/src/vendor/is/stun.rs deleted file mode 100644 index 7ffa8faf76a..00000000000 --- a/rs/moq-webrtc/src/vendor/is/stun.rs +++ /dev/null @@ -1,1973 +0,0 @@ -use std::fmt; -use std::fmt::Formatter; -use std::io::Write; -use std::net::IpAddr; -use std::net::SocketAddr; -use std::time::Duration; -use tracing::{trace, warn}; - -use crc::{CRC_32_ISO_HDLC, Crc}; -use serde::{Deserialize, Serialize}; -use subtle::ConstantTimeEq; - -pub const DEFAULT_MAX_RETRANSMITS: usize = 9; - -#[derive(Debug)] // Purposely not `Clone` / `Copy` to ensure we always use the latest one everywhere. -pub struct StunTiming { - pub initial_rto: Duration, - pub max_retransmits: usize, - pub max_rto: Duration, -} - -impl StunTiming { - /// Calculate the ICE timeout of a successful pair. - pub fn timeout(&self) -> Duration { - let base_timeout = (2..=self.max_retransmits) - .map(|n| self.stun_resend_delay(n)) - .sum::(); - - base_timeout + self.stun_resend_delay(self.max_retransmits) - } - - /// Calculate the send delay given how many times we tried. - /// - // Technically RTO should be calculated as per https://datatracker.ietf.org/doc/html/rfc2988, and - // modified by https://datatracker.ietf.org/doc/html/rfc5389#section-7.2.1, - // but chrome does it like this. - // https://webrtc.googlesource.com/src/+/refs/heads/main/p2p/base/stun_request.cc - pub fn stun_resend_delay(&self, send_count: usize) -> Duration { - if send_count == 0 { - return Duration::ZERO; - } - - let retrans = (send_count - 1).min(self.max_retransmits); - - let rto = self.initial_rto.as_millis() << retrans; - let capped = rto.min(self.max_rto.as_millis()); - - Duration::from_millis(capped as u64) - } - - pub fn stun_last_resend_delay(&self) -> Duration { - self.stun_resend_delay(self.max_retransmits) - } - - pub fn max_retransmits(&self) -> usize { - self.max_retransmits - } - - pub fn max_rto(&self) -> Duration { - self.max_rto - } -} - -// Consult libwebrtc for default values here. -impl Default for StunTiming { - fn default() -> Self { - Self { - initial_rto: Duration::from_millis(250), - max_retransmits: DEFAULT_MAX_RETRANSMITS, - // libwebrtc uses 8000 here but we want faster detection of gone peers. - max_rto: Duration::from_millis(3000), - } - } -} - -pub use super::error::StunError; - -/// STUN transaction ID. -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct TransId([u8; 12]); - -impl fmt::Debug for TransId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - DebugHex(&self.0).fmt(f) - } -} - -#[allow(clippy::new_without_default)] -impl TransId { - /// A new random transaction id. - pub fn new() -> Self { - let mut t = [0_u8; 12]; - for v in &mut t { - *v = NonCryptographicRng::u8(); - } - TransId(t) - } - - fn from_slice(s: &[u8]) -> Self { - let mut t = [0_u8; 12]; - t[..].copy_from_slice(s); - TransId(t) - } -} - -/// Represents a STUN message as fit for our purposes. -/// -/// STUN is a very flexible protocol. -/// This implementations only provides what we need for our ICE implementation. -#[derive(Clone, Copy, Serialize, Deserialize)] -pub struct StunMessage<'a> { - method: Method, - class: Class, - trans_id: TransId, - attrs: Attributes<'a>, - integrity: &'a [u8], - integrity_len: u16, -} - -impl<'a> StunMessage<'a> { - /// Parse a STUN message from a slice of bytes. - pub fn parse(buf: &'a [u8]) -> Result, StunError> { - if buf.len() < 4 { - return Err(StunError::Parse("Buffer too short".into())); - } - - let typ = (buf[0] as u16 & 0b0011_1111) << 8 | buf[1] as u16; - let len = (buf[2] as u16) << 8 | buf[3] as u16; - if len & 0b0000_0011 > 0 { - return Err(StunError::Parse("len is not a multiple of 4".into())); - } - // Use addition here to avoid panic! if the UDP packet is under 20 bytes long. - if (len as usize + 20) != buf.len() { - return Err(StunError::Parse("STUN length vs UDP packet mismatch".into())); - } - if &buf[4..8] != MAGIC { - return Err(StunError::Parse("magic cookie mismatch".into())); - } - // typ is method and class - // |M11|M10|M9|M8|M7|C1|M6|M5|M4|C0|M3|M2|M1|M0| - // |11 |10 |9 |8 |7 |1 |6 |5 |4 |0 |3 |2 |1 |0 | - let class = Class::from_typ(typ); - let method = Method::from_typ(typ); - let trans_id = TransId::from_slice(&buf[8..20]); - - let mut message_integrity_offset = None; - - let attrs = Attributes::parse(&buf[20..], trans_id, &mut message_integrity_offset)?; - - // length including message integrity attribute - let (integrity_len, integrity) = if let Some(off) = message_integrity_offset { - let integrity_len = (off + 4 + 20) as u16; - - // password as key is called "short-term credentials" - // buffer from beginning including header (+20) to where message-integrity starts. - let integrity = &buf[0..(off + 20)]; - - (integrity_len, integrity) - } else { - (0_u16, [].as_slice()) - }; - - if method == Method::Binding && class == Class::Success { - // // message-integrity only includes the length up until and including - // // the message-integrity attribute. - if message_integrity_offset.is_none() { - return Err(StunError::Parse( - "No message integrity in incoming STUN binding reply".into(), - )); - } - - if attrs.xor_mapped_address.is_none() { - return Err(StunError::Parse("STUN packet missing mapped addr".into())); - } - } else if method == Method::Binding && class == Class::Request { - // // message-integrity only includes the length up until and including - // // the message-integrity attribute. - if message_integrity_offset.is_none() { - return Err(StunError::Parse( - "No message integrity in incoming STUN binding request".into(), - )); - } - - if attrs.split_username().is_none() { - return Err(StunError::Parse("STUN packet missing username".into())); - } - if attrs.priority.is_none() { - return Err(StunError::Parse("STUN packet missing priority".into())); - } - } - - Ok(StunMessage { - class, - method, - trans_id, - attrs, - integrity, - integrity_len, - }) - } - - pub fn method(&self) -> Method { - self.method - } - - pub fn class(&self) -> Class { - self.class - } - - /// Whether this STUN message is a BINDING request. - pub fn is_binding_request(&self) -> bool { - self.method == Method::Binding && self.class == Class::Request - } - - /// Whether this STUN message is a _successful_ BINDING response. - pub fn is_successful_binding_response(&self) -> bool { - self.method == Method::Binding && self.class == Class::Success - } - - /// Whether this STUN message is a _failed_ BINDING response. - /// - /// In ICE, this is used for 487 Role Conflict (RFC 8445 §7.3.1.1). - pub fn is_failed_binding_response(&self) -> bool { - self.method == Method::Binding && self.class == Class::Failure - } - - /// Whether this STUN message is an ALLOCATE request (TURN). - pub fn is_allocate_request(&self) -> bool { - self.method == Method::Allocate && self.class == Class::Request - } - - /// Whether this STUN message is a CREATE_PERMISSION request (TURN). - pub fn is_create_permission_request(&self) -> bool { - self.method == Method::CreatePermission && self.class == Class::Request - } - - /// Whether this STUN message is a CHANNEL_BIND request (TURN). - pub fn is_channel_bind_request(&self) -> bool { - self.method == Method::ChannelBind && self.class == Class::Request - } - - /// Whether this STUN message is a REFRESH request (TURN). - pub fn is_refresh_request(&self) -> bool { - self.method == Method::Refresh && self.class == Class::Request - } - - /// Whether this STUN message is a SEND indication (TURN). - pub fn is_send_indication(&self) -> bool { - self.method == Method::Send && self.class == Class::Indication - } - - /// The transaction ID of this STUN message. - pub fn trans_id(&self) -> TransId { - self.trans_id - } - - /// Returns the value of the USERNAME attribute, if present. - pub fn username(&self) -> Option<&'a str> { - self.attrs.username - } - - /// If present, splits the value of the USERNAME attribute into local and remote (separated by `:`). - pub fn split_username(&self) -> Option<(&str, &str)> { - self.attrs.split_username() - } - - /// Returns the value of the XOR-MAPPED-ADDRESS attribute, if present. - pub fn mapped_address(&self) -> Option { - self.attrs.xor_mapped_address - } - - /// Returns the value of the PRIORITY attribute (ICE), if present. - pub fn prio(&self) -> Option { - self.attrs.priority - } - - /// Returns whether the USE-CANDIDATE attribute (ICE) is present. - pub fn use_candidate(&self) -> bool { - self.attrs.use_candidate - } - - /// Returns the value of the ERROR_CODE attribute, if present. - pub fn error_code(&self) -> Option<(u16, &'a str)> { - self.attrs.error_code - } - - /// Returns the value of the CHANNEL_NUMBER attribute (TURN), if present. - pub fn channel_number(&self) -> Option { - self.attrs.channel_number - } - - /// Returns the value of the LIFETIME attribute (TURN), if present. - pub fn lifetime(&self) -> Option { - self.attrs.lifetime - } - - /// Returns the value of the XOR_PEER_ADDRESS attribute (TURN), if present. - pub fn xor_peer_address(&self) -> Option { - self.attrs.xor_peer_address - } - - /// Returns the value of the DATA attribute (TURN), if present. - pub fn data(&self) -> Option<&'a [u8]> { - self.attrs.data - } - - /// Returns the value of the REALM attribute, if present. - pub fn realm(&self) -> Option<&'a str> { - self.attrs.realm - } - - /// Returns the value of the NONCE attribute, if present. - pub fn nonce(&self) -> Option<&'a str> { - self.attrs.nonce - } - - /// Returns the value of the XOR_RELAYED_ADDRESS attribute (TURN), if present. - pub fn xor_relayed_address(&self) -> Option { - self.attrs.xor_relayed_address - } - - /// Returns the value of the SOFTWARE attribute, if present. - pub fn software(&self) -> Option<&'a str> { - self.attrs.software - } - - /// Returns the value of the ICE_CONTROLLED attribute (ICE), if present. - pub fn ice_controlled(&self) -> Option { - self.attrs.ice_controlled - } - - /// Returns the value of the ICE_CONTROLLING attribute (ICE), if present. - pub fn ice_controlling(&self) -> Option { - self.attrs.ice_controlling - } - - /// Returns the value of the NETWORK_COST attribute (ICE), if present. - pub fn network_cost(&self) -> Option<(u16, u16)> { - self.attrs.network_cost - } - - /// Constructs a new BINDING request using the provided data. - pub fn binding_request( - username: &'a str, - trans_id: TransId, - controlling: bool, - control_tie_breaker: u64, - prio: u32, - use_candidate: bool, - ) -> Self { - let mut builder = StunMessageBuilder::new() - .binding() - .request() - .username(username) - .prio(prio); - - if use_candidate { - builder = builder.use_candidate(); - } - - if controlling { - builder = builder.ice_controlling(control_tie_breaker); - } else { - builder = builder.ice_controlled(control_tie_breaker); - } - - builder.build(trans_id) - } - - /// Constructs a new STUN BINDING success reply using the builder. - pub fn binding_reply(trans_id: TransId, mapped_address: SocketAddr) -> StunMessage<'a> { - StunMessageBuilder::new() - .binding() - .success() - .xor_mapped_address(mapped_address) - .build(trans_id) - } - - /// Constructs a STUN BINDING error reply with a 487 Role Conflict - /// error code (RFC 8445 §7.3.1.1). - pub fn binding_role_conflict_reply(trans_id: TransId) -> StunMessage<'a> { - StunMessageBuilder::new() - .binding() - .failure() - .error_code(487, "Role Conflict") - .build(trans_id) - } - - /// Verify the integrity of this message against the provided password. - #[must_use] - pub fn verify(&self, password: &[u8], sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20]) -> bool { - let (Some(integ), Some(typ), Some(rest)) = ( - self.attrs.message_integrity, - self.integrity.get(..2), - self.integrity.get(4..), - ) else { - return false; - }; - - let comp = sha1_hmac(password, &[typ, &self.integrity_len.to_be_bytes(), rest]); - - comp[..].ct_eq(integ).into() - } - - /// Serialize this message into the provided buffer, returning the final length of the message. - /// - /// The provided password is used to authenticate the message if provided, otherwise no - /// `MESSAGE-INTEGRITY` attribute will be present. - pub fn to_bytes( - self, - password: Option<&[u8]>, - buf: &mut [u8], - sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20], - ) -> Result { - const MSG_HEADER_LEN: usize = 20; - const MSG_INTEGRITY_LEN: usize = 20; - const FPRINT_LEN: usize = 4; - const ATTR_TLV_LENGTH: usize = 4; - - let include_message_integrity = password.is_some(); - let message_integrity_len = if include_message_integrity { - MSG_INTEGRITY_LEN + ATTR_TLV_LENGTH - } else { - 0 - }; - - let attr_len = self.attrs.padded_len() + message_integrity_len + FPRINT_LEN + ATTR_TLV_LENGTH; - - let mut buf = io::Cursor::new(buf); - - // Message header - { - let typ = self.class.to_u16() | self.method.to_u16(); - buf.write_all(&typ.to_be_bytes())?; - - // -8 for fingerprint - buf.write_all(&((attr_len - 8) as u16).to_be_bytes())?; - buf.write_all(MAGIC)?; - buf.write_all(&self.trans_id.0)?; - } - - // Custom attributes - self.attrs.to_bytes(&mut buf, &self.trans_id)?; - - if include_message_integrity { - // Message integrity - buf.write_all(&Attributes::MESSAGE_INTEGRITY.to_be_bytes())?; - buf.write_all(&(MSG_INTEGRITY_LEN as u16).to_be_bytes())?; - buf.write_all(&[0; MSG_INTEGRITY_LEN])?; // placeholder - } - let integrity_value_offset = MSG_HEADER_LEN + self.attrs.padded_len() + ATTR_TLV_LENGTH; - - // Fingerprint - buf.write_all(&Attributes::FINGERPRINT.to_be_bytes())?; - buf.write_all(&(FPRINT_LEN as u16).to_be_bytes())?; - buf.write_all(&[0; FPRINT_LEN])?; // placeholder - let fingerprint_value_offest = integrity_value_offset + message_integrity_len; - - let buf = buf.into_inner(); - - if let Some(password) = password { - // Compute and fill in message integrity - let hmac = sha1_hmac(password, &[&buf[0..(integrity_value_offset - ATTR_TLV_LENGTH)]]); - buf[integrity_value_offset..(integrity_value_offset + MSG_INTEGRITY_LEN)].copy_from_slice(&hmac); - } - - // Fill in total message length - buf[2..4].copy_from_slice(&(attr_len as u16).to_be_bytes()); - - // Compute and fill in fingerprint - let crc = Crc::::new(&CRC_32_ISO_HDLC).checksum(&buf[0..(fingerprint_value_offest - ATTR_TLV_LENGTH)]) - ^ 0x5354_554e; - buf[fingerprint_value_offest..(fingerprint_value_offest + FPRINT_LEN)].copy_from_slice(&crc.to_be_bytes()); - - Ok(MSG_HEADER_LEN + attr_len) - } -} - -const MAGIC: &[u8; 4] = &[0x21, 0x12, 0xA4, 0x42]; - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub enum Class { - Request, - Indication, - Success, - Failure, - Unknown, -} - -impl Class { - fn from_typ(typ: u16) -> Self { - use Class::*; - match typ & 0b0000_0001_0001_0000 { - 0b0000_0000_0000_0000 => Request, - 0b0000_0000_0001_0000 => Indication, - 0b0000_0001_0000_0000 => Success, - 0b0000_0001_0001_0000 => Failure, - _ => Unknown, - } - } - - fn to_u16(self) -> u16 { - use Class::*; - match self { - Request => 0b0000_0000_0000_0000, - Indication => 0b0000_0000_0001_0000, - Success => 0b0000_0001_0000_0000, - Failure => 0b0000_0001_0001_0000, - _ => panic!("Unknown class"), - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub enum Method { - Binding, - // TURN specific - Allocate, - Refresh, - Send, - Data, - CreatePermission, - ChannelBind, - Unknown, -} - -impl Method { - fn from_typ(typ: u16) -> Self { - use Method::*; - match typ & 0b0011_1110_1110_1111 { - 0b0000_0000_0000_0001 => Binding, - 0b0000_0000_0000_0011 => Allocate, - 0b0000_0000_0000_0100 => Refresh, - 0b0000_0000_0000_0110 => Send, - 0b0000_0000_0000_0111 => Data, - 0b0000_0000_0000_1000 => CreatePermission, - 0b0000_0000_0000_1001 => ChannelBind, - _ => Unknown, - } - } - - #[rustfmt::skip] - fn to_u16(self) -> u16 { - use Method::*; - match self { - Binding => 0b0000_0000_0000_0001, - Allocate => 0b0000_0000_0000_0011, - Refresh => 0b0000_0000_0000_0100, - Send => 0b0000_0000_0000_0110, - Data => 0b0000_0000_0000_0111, - CreatePermission => 0b0000_0000_0000_1000, - ChannelBind => 0b0000_0000_0000_1001, - _ => panic!("Unknown method"), - } - } -} - -#[derive(Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] -#[rustfmt::skip] -pub struct Attributes<'a> { - username: Option<&'a str>, // < 128 utf8 chars - message_integrity: Option<&'a [u8]>, // 20 bytes sha-1 - error_code: Option<(u16, &'a str)>, // 300-699 and reason phrase < 128 utf8 chars - channel_number: Option, // 0x000C https://tools.ietf.org/html/rfc5766#section-14.1 - lifetime: Option, // 0x000D https://tools.ietf.org/html/rfc5766#section-14.2 - xor_peer_address: Option, // 0x0012 - data: Option<&'a [u8]>, // 0x0013 - realm: Option<&'a str>, // < 128 utf8 chars, 0x0014 - nonce: Option<&'a str>, // < 128 utf8 chars, 0x0015 - xor_relayed_address: Option, // 0x0016 - xor_mapped_address: Option, // 0x0020 - software: Option<&'a str>, // 0x0022 - fingerprint: Option, // crc32 - priority: Option, // 0x0024 https://tools.ietf.org/html/rfc8445 - use_candidate: bool, // 0x0025 - ice_controlled: Option, // 0x8029 - ice_controlling: Option, // 0x802a - // 0xc057 https://tools.ietf.org/html/draft-thatcher-ice-network-cost-00 - network_cost: Option<(u16, u16)>, -} - -impl<'a> fmt::Debug for Attributes<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let debug_struct = &mut f.debug_struct("Attributes"); - - if let Some(value) = self.username { - debug_struct.field("username", &value); - } - if let Some(value) = self.message_integrity { - debug_struct.field("message_integrity", &DebugHex(value)); - } - if let Some(value) = self.error_code { - debug_struct.field("error_code", &value); - } - if let Some(value) = self.channel_number { - debug_struct.field("channel_number", &value); - } - if let Some(value) = self.lifetime { - debug_struct.field("lifetime", &value); - } - if let Some(value) = self.xor_peer_address { - debug_struct.field("xor_peer_address", &value); - } - if let Some(value) = self.data { - debug_struct.field("data", &value); - } - if let Some(value) = self.realm { - debug_struct.field("realm", &value); - } - if let Some(value) = self.nonce { - debug_struct.field("nonce", &value); - } - if let Some(value) = self.xor_relayed_address { - debug_struct.field("xor_relayed_address", &value); - } - if let Some(value) = self.xor_mapped_address { - debug_struct.field("xor_mapped_address", &value); - } - if let Some(value) = self.software { - debug_struct.field("software", &value); - } - if let Some(value) = self.fingerprint { - debug_struct.field("fingerprint", &value); - } - if let Some(value) = self.priority { - debug_struct.field("priority", &value); - } - if self.use_candidate { - debug_struct.field("use_candidate", &true); - } - if let Some(value) = self.ice_controlled { - debug_struct.field("ice_controlled", &value); - } - if let Some(value) = self.ice_controlling { - debug_struct.field("ice_controlling", &value); - } - if let Some(value) = self.network_cost { - debug_struct.field("network_cost", &value); - } - - debug_struct.finish() - } -} - -impl<'a> Attributes<'a> { - fn split_username(&self) -> Option<(&'a str, &'a str)> { - // usernames are on the form gfNK:062g where - // gfNK is my local sdp ice username and - // 062g is the remote. - - let v = self.username?; - let idx = v.find(':')?; - - if idx + 1 >= v.len() { - return None; - } - - let local = &v[..idx]; - let remote = &v[(idx + 1)..]; - - Some((local, remote)) - } -} - -use std::{io, str}; - -use crate::vendor::str0m_proto::NonCryptographicRng; - -const PAD: [u8; 4] = [0, 0, 0, 0]; -impl<'a> Attributes<'a> { - const ALTERNATE_SERVER: u16 = 0x8023; - const FINGERPRINT: u16 = 0x8028; - const ICE_CONTROLLED: u16 = 0x8029; - const ICE_CONTROLLING: u16 = 0x802a; - - const MAPPED_ADDRESS: u16 = 0x0001; - const USERNAME: u16 = 0x0006; - const MESSAGE_INTEGRITY: u16 = 0x0008; - const ERROR_CODE: u16 = 0x0009; - const UNKNOWN_ATTRIBUTES: u16 = 0x000a; - const CHANNEL_NUMBER: u16 = 0x000c; - const LIFETIME: u16 = 0x000d; - const XOR_PEER_ADDRESS: u16 = 0x0012; - const DATA: u16 = 0x0013; - const REALM: u16 = 0x0014; - const NONCE: u16 = 0x0015; - const XOR_RELAYED_ADDRESS: u16 = 0x0016; - const XOR_MAPPED_ADDRESS: u16 = 0x0020; - const SOFTWARE: u16 = 0x0022; - const PRIORITY: u16 = 0x0024; - const USE_CANDIDATE: u16 = 0x0025; - - const NETWORK_COST: u16 = 0xc057; - - fn padded_len(&self) -> usize { - const ATTR_TLV_LENGTH: usize = 4; - - let username = self - .username - .map(|v| ATTR_TLV_LENGTH + v.len() + calculate_pad(v.len())) - .unwrap_or_default(); - let ice_controlled = self.ice_controlled.map(|_| ATTR_TLV_LENGTH + 8).unwrap_or_default(); - let ice_controlling = self.ice_controlling.map(|_| ATTR_TLV_LENGTH + 8).unwrap_or_default(); - let priority = self - .priority - .map(|p| ATTR_TLV_LENGTH + p.to_le_bytes().len()) - .unwrap_or_default(); - let address = self - .xor_mapped_address - .map(|a| ATTR_TLV_LENGTH + if a.is_ipv4() { 8 } else { 20 }) - .unwrap_or_default(); - let use_candidate = if self.use_candidate { ATTR_TLV_LENGTH } else { 0 }; - let xor_peer_address = self - .xor_peer_address - .map(|a| ATTR_TLV_LENGTH + if a.is_ipv4() { 8 } else { 20 }) - .unwrap_or_default(); - let xor_relayed_address = self - .xor_relayed_address - .map(|a| ATTR_TLV_LENGTH + if a.is_ipv4() { 8 } else { 20 }) - .unwrap_or_default(); - let data = self - .data - .map(|d| ATTR_TLV_LENGTH + d.len() + calculate_pad(d.len())) - .unwrap_or_default(); - let channel_number = self.channel_number.map(|_| ATTR_TLV_LENGTH + 4).unwrap_or_default(); - let lifetime = self.lifetime.map(|_| ATTR_TLV_LENGTH + 4).unwrap_or_default(); - let realm = self - .realm - .map(|v| ATTR_TLV_LENGTH + v.len() + calculate_pad(v.len())) - .unwrap_or_default(); - let nonce = self - .nonce - .map(|v| ATTR_TLV_LENGTH + v.len() + calculate_pad(v.len())) - .unwrap_or_default(); - let error_code = self - .error_code - .map(|(_, reason)| ATTR_TLV_LENGTH + 4 + reason.len() + calculate_pad(reason.len())) - .unwrap_or_default(); - - username - + ice_controlled - + ice_controlling - + priority - + address + use_candidate - + xor_peer_address - + xor_relayed_address - + data + channel_number - + lifetime - + realm + nonce - + error_code - } - - fn to_bytes(self, out: &mut dyn Write, trans_id: &TransId) -> io::Result<()> { - if let Some(v) = self.username { - out.write_all(&Self::USERNAME.to_be_bytes())?; - encode_str(Self::USERNAME, v, out)?; - let pad = calculate_pad(v.len()); - out.write_all(&PAD[0..pad])?; - } - if let Some(v) = self.ice_controlled { - out.write_all(&Self::ICE_CONTROLLED.to_be_bytes())?; - out.write_all(&8_u16.to_be_bytes())?; - out.write_all(&v.to_be_bytes())?; - } - if let Some(v) = self.ice_controlling { - out.write_all(&Self::ICE_CONTROLLING.to_be_bytes())?; - out.write_all(&8_u16.to_be_bytes())?; - out.write_all(&v.to_be_bytes())?; - } - if let Some(v) = self.priority { - out.write_all(&Self::PRIORITY.to_be_bytes())?; - out.write_all(&4_u16.to_be_bytes())?; - out.write_all(&v.to_be_bytes())?; - } - if let Some(v) = self.xor_mapped_address { - let mut buf = [0_u8; 20]; - let len = encode_xor(v, &mut buf, trans_id); - out.write_all(&Self::XOR_MAPPED_ADDRESS.to_be_bytes())?; - out.write_all(&((len as u16).to_be_bytes()))?; - out.write_all(&buf[0..len])?; - } - if self.use_candidate { - out.write_all(&Self::USE_CANDIDATE.to_be_bytes())?; - out.write_all(&0_u16.to_be_bytes())?; - } - if let Some(d) = self.data { - if d.len() > u16::MAX as usize { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "Data attribute too long, max 65535 bytes", - )); - } - - out.write_all(&Self::DATA.to_be_bytes())?; - out.write_all(&(d.len() as u16).to_be_bytes())?; - out.write_all(d)?; - - let pad = calculate_pad(d.len()); - out.write_all(&PAD[0..pad])?; - } - if let Some(v) = self.xor_relayed_address { - let mut buf = [0_u8; 20]; - let len = encode_xor(v, &mut buf, trans_id); - out.write_all(&Self::XOR_RELAYED_ADDRESS.to_be_bytes())?; - out.write_all(&((len as u16).to_be_bytes()))?; - out.write_all(&buf[0..len])?; - } - if let Some(v) = self.xor_peer_address { - let mut buf = [0_u8; 20]; - let len = encode_xor(v, &mut buf, trans_id); - out.write_all(&Self::XOR_PEER_ADDRESS.to_be_bytes())?; - out.write_all(&((len as u16).to_be_bytes()))?; - out.write_all(&buf[0..len])?; - } - if let Some(v) = self.channel_number { - out.write_all(&Self::CHANNEL_NUMBER.to_be_bytes())?; - out.write_all(&4_u16.to_be_bytes())?; - out.write_all(&v.to_be_bytes())?; - // RFU bytes - out.write_all(&[0, 0])?; - } - if let Some(v) = self.lifetime { - out.write_all(&Self::LIFETIME.to_be_bytes())?; - out.write_all(&4_u16.to_be_bytes())?; - out.write_all(&v.to_be_bytes())?; - } - if let Some(v) = self.realm { - out.write_all(&Self::REALM.to_be_bytes())?; - encode_str(Self::REALM, v, out)?; - let pad = calculate_pad(v.len()); - out.write_all(&PAD[0..pad])?; - } - if let Some(v) = self.nonce { - out.write_all(&Self::NONCE.to_be_bytes())?; - encode_str(Self::NONCE, v, out)?; - let pad = calculate_pad(v.len()); - out.write_all(&PAD[0..pad])?; - } - if let Some((code, reason)) = self.error_code { - out.write_all(&Self::ERROR_CODE.to_be_bytes())?; - // Length - out.write_all(&(4_u16 + reason.len() as u16).to_be_bytes())?; - // Reserved 16 bits - out.write_all(&((0_u16).to_be_bytes()))?; - // Reserved 5 high bits, class 3 bits - out.write_all(&((0x7_u8 & (code / 100) as u8).to_be_bytes()))?; - // code 8 bits - out.write_all(&(((code % 100) as u8).to_be_bytes()))?; - // Total written 8 bytes 4 byte aligned - encode_str_no_len(Self::ERROR_CODE, reason, out)?; - - // Need to ensure padding is correct only with respect to reason since the - // prior length was 4 byte aligned. - let pad = calculate_pad(reason.len()); - out.write_all(&PAD[0..pad])?; - } - - Ok(()) - } - - fn parse( - mut buf: &'a [u8], - trans_id: TransId, - msg_integrity_off: &mut Option, - ) -> Result, StunError> { - let mut attributes = Attributes::default(); - - let mut off = 0; - // With the exception of the FINGERPRINT - // attribute, which appears after MESSAGE-INTEGRITY, agents MUST ignore - // all other attributes that follow MESSAGE-INTEGRITY - let mut ignore_rest = false; - loop { - if buf.is_empty() { - break; - } - let typ = u16::from_le_bytes([buf[1], buf[0]]); - let len = u16::from_le_bytes([buf[3], buf[2]]) as usize; - // trace!( - // "STUN attribute typ 0x{:04x?} len {}: {:02x?}", - // typ, - // len, - // buf - // ); - if len > buf.len() - 4 { - return Err(StunError::Parse(format!( - "Bad STUN attribute length: {} > {}", - len, - buf.len() - 4, - ))); - } - if !ignore_rest || typ == Self::FINGERPRINT { - match typ { - Self::MAPPED_ADDRESS => { - warn!("STUN got MappedAddress"); - } - Self::USERNAME => { - // It MUST contain a UTF-8 [RFC3629] encoded sequence of less than 513 bytes - attributes.username = Some(decode_str(typ, 513, &buf[4..], len)?); - } - Self::MESSAGE_INTEGRITY => { - if len != 20 { - return Err(StunError::Parse("Expected message integrity to have length 20".into())); - } - // message integrity is up until, but not including the message - // integrity attribute. - *msg_integrity_off = Some(off); - ignore_rest = true; - attributes.message_integrity = Some(&buf[4..24]); - } - Self::ERROR_CODE => { - if len < 4 { - return Err(StunError::Parse("Error code length must be at least 4".into())); - } - - if buf[4] != 0 || buf[5] != 0 || buf[6] & 0b1111_1000 != 0 { - return Err(StunError::Parse("Expected 0 at top of error code".into())); - } - let class = buf[6] as u16 * 100; - if !(300..=699).contains(&class) { - return Err(StunError::Parse(format!("Error class is not in range: {class}"))); - } - let code = class + (buf[7] % 100) as u16; - // The reason phrase MUST be a UTF-8 [RFC3629] encoded sequence of less - // than 128 characters (which can be as long as 763 bytes). - attributes.error_code = Some((code, decode_str(typ, 763, &buf[8..], len - 4)?)); - } - Self::CHANNEL_NUMBER => { - if len != 4 { - return Err(StunError::Parse(format!( - "Channel number that isn't 4 in length, was {}", - len - ))); - } - let bytes = [buf[4], buf[5]]; - let channel = u16::from_be_bytes(bytes); - // Channel numbers must be between 0x4000 and 0x7FFF inclusive - // https://tools.ietf.org/html/rfc5766#section-2.5 - if !(0x4000..=0x7FFF).contains(&channel) { - return Err(StunError::Parse(format!( - "Channel number {channel} is not in valid range 0x4000-0x7FFF" - ))); - } - attributes.channel_number = Some(channel); - } - Self::LIFETIME => { - if len != 4 { - return Err(StunError::Parse("Lifetime that isn't 4 in length".into())); - } - let bytes = [buf[4], buf[5], buf[6], buf[7]]; - attributes.lifetime = Some(u32::from_be_bytes(bytes)); - } - Self::UNKNOWN_ATTRIBUTES => { - warn!("STUN got UnknownAttributes"); - } - Self::XOR_PEER_ADDRESS => attributes.xor_peer_address = Some(decode_xor(&buf[4..], trans_id)?), - Self::DATA => { - attributes.data = Some(&buf[4..len + 4]); - } - Self::REALM => { - // It MUST be a UTF-8 [RFC3629] encoded sequence of less than - // 128 characters (which can be as long as 763 bytes) - attributes.realm = Some(decode_str(typ, 763, &buf[4..], len)?); - } - Self::NONCE => { - // It MUST be less than 128 characters (which can be as long as 763 bytes). - attributes.nonce = Some(decode_str(typ, 763, &buf[4..], len)?); - } - Self::XOR_RELAYED_ADDRESS => { - attributes.xor_relayed_address = Some(decode_xor(&buf[4..], trans_id)?); - } - Self::XOR_MAPPED_ADDRESS => { - attributes.xor_mapped_address = Some(decode_xor(&buf[4..], trans_id)?); - } - Self::SOFTWARE => { - // It MUST be a UTF-8 [RFC3629] encoded sequence of less than - // 128 characters (which can be as long as 763 bytes) - attributes.software = Some(decode_str(typ, 763, &buf[4..], len)?); - } - Self::PRIORITY => { - if len != 4 { - return Err(StunError::Parse("Priority that isnt 4 in length".into())); - } - let bytes = [buf[4], buf[5], buf[6], buf[7]]; - attributes.priority = Some(u32::from_be_bytes(bytes)); - } - Self::USE_CANDIDATE => { - if len != 0 { - return Err(StunError::Parse("UseCandidate that isnt 0 in length".into())); - } - attributes.use_candidate = true; - } - Self::ALTERNATE_SERVER => { - warn!("STUN got AlternateServer"); - } - Self::FINGERPRINT => { - if len != 4 { - return Err(StunError::Parse("Fingerprint length must be 4".into())); - } - let bytes = [buf[4], buf[5], buf[6], buf[7]]; - attributes.fingerprint = Some(u32::from_be_bytes(bytes)); - } - Self::ICE_CONTROLLED => { - if len != 8 { - return Err(StunError::Parse("IceControlled that isnt 8 in length".into())); - } - let mut bytes = [0_u8; 8]; - bytes.copy_from_slice(&buf[4..(4 + 8)]); - attributes.ice_controlled = Some(u64::from_be_bytes(bytes)); - } - Self::ICE_CONTROLLING => { - if len != 8 { - return Err(StunError::Parse("IceControlling that isnt 8 in length".into())); - } - let mut bytes = [0_u8; 8]; - bytes.copy_from_slice(&buf[4..(4 + 8)]); - attributes.ice_controlling = Some(u64::from_be_bytes(bytes)); - } - Self::NETWORK_COST => { - if len != 4 { - warn!("NetworkCost that isnt 4 in length"); - } else { - let net_id = (buf[4] as u16) << 8 | buf[5] as u16; - let cost = (buf[6] as u16) << 8 | buf[7] as u16; - attributes.network_cost = Some((net_id, cost)); - } - } - _ => {} - } - } - // attributes are on even 32 bit boundaries - let pad = calculate_pad(len); - let pad_len = len + pad; - buf = &buf[(4 + pad_len)..]; - off += 4 + pad_len; - } - Ok(attributes) - } -} - -fn calculate_pad(len: usize) -> usize { - (4 - (len % 4)) % 4 -} - -fn encode_str(typ: u16, s: &str, out: &mut dyn Write) -> io::Result<()> { - out.write_all(&(s.len() as u16).to_be_bytes())?; - - encode_str_no_len(typ, s, out) -} - -fn encode_str_no_len(typ: u16, s: &str, out: &mut dyn Write) -> io::Result<()> { - if s.len() > 128 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!("0x{typ:04x?} too long str len: {}", s.len()), - )); - } - out.write_all(s.as_bytes())?; - Ok(()) -} - -fn decode_str(typ: u16, max_bytes: usize, buf: &[u8], len: usize) -> Result<&str, StunError> { - if len > max_bytes { - return Err(StunError::Parse(format!( - "0x{typ:04x?} too long str len: {len} (max {max_bytes})" - ))); - } - match str::from_utf8(&buf[0..len]).ok() { - Some(v) => Ok(v), - None => Err(StunError::Parse(format!("0x{typ:04x?} malformed utf-8"))), - } -} - -fn encode_xor(addr: SocketAddr, buf: &mut [u8; 20], trans_id: &TransId) -> usize { - let port = addr.port() ^ 0x2112; - buf[2..4].copy_from_slice(&port.to_be_bytes()); - buf[1] = if addr.is_ipv4() { 1 } else { 2 }; - let ip_buf = &mut buf[4..]; - match addr { - SocketAddr::V4(v) => { - let bytes = v.ip().octets(); - for i in 0..4 { - ip_buf[i] = bytes[i] ^ MAGIC[i]; - } - 8 - } - SocketAddr::V6(v) => { - let bytes = v.ip().octets(); - for i in 0..4 { - ip_buf[i] = bytes[i] ^ MAGIC[i]; - } - for i in 4..16 { - ip_buf[i] = bytes[i] ^ trans_id.0[i - 4]; - } - 20 - } - } -} - -fn decode_xor(buf: &[u8], trans_id: TransId) -> Result { - if buf.len() < 4 { - return Err(StunError::Parse(format!("XOR buffer is too short: {} < 4", buf.len()))); - } - let port = u16::from_be_bytes([buf[2], buf[3]]) ^ 0x2112; - let ip_buf = &buf[4..]; - let ip = match buf[1] { - 1 if ip_buf.len() >= 4 => { - let mut bytes = [0_u8; 4]; - for i in 0..4 { - bytes[i] = ip_buf[i] ^ MAGIC[i]; - } - IpAddr::V4(bytes.into()) - } - 2 if ip_buf.len() >= 16 => { - let mut bytes = [0_u8; 16]; - for i in 0..4 { - bytes[i] = ip_buf[i] ^ MAGIC[i]; - } - for i in 4..16 { - bytes[i] = ip_buf[i] ^ trans_id.0[i - 4]; - } - IpAddr::V6(bytes.into()) - } - v => { - return Err(StunError::Parse(format!( - "Unknown IP version ({v}) or insufficient buffer length for it ({})", - ip_buf.len() - ))); - } - }; - - Ok(SocketAddr::new(ip, port)) -} - -impl<'a> fmt::Debug for StunMessage<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("StunMessage") - .field("method", &self.method) - .field("class", &self.class) - .field("id", &self.trans_id) - .field("attrs", &self.attrs) - .field("integrity_len", &self.integrity.len()) - .finish() - } -} - -pub use builder::Builder as StunMessageBuilder; - -mod builder { - use super::{Attributes, Class, Method, StunMessage, TransId}; - use std::net::SocketAddr; - - /// Type state representing a builder where the STUN method has not yet been set. - #[derive(Default, Debug, Clone)] - pub struct NoMethod; - - /// Type state representing a builder where the STUN method has been set, but the class has not. - #[derive(Debug, Clone)] - pub struct HasMethod { - method: Method, - } - - /// Type state representing a builder where both the STUN method and class have been set. - /// Attributes can now be added. - #[derive(Debug, Clone)] - pub struct HasClass { - method: Method, - class: Class, - } - - /// A type-state builder for creating [`StunMessage`] instances. - /// - /// This builder guides the user through the required steps: - /// 1. Set the STUN method (e.g., `binding()`, `allocate()`). - /// 2. Set the STUN class (e.g., `request()`, `success()`). - /// 3. Optionally set attributes (e.g., `username()`, `priority()`). - /// 4. Call `build()` with a [`TransId`]. - #[derive(Default, Debug, Clone)] - pub struct Builder<'a, State> { - attrs: Attributes<'a>, - state: State, - } - - impl<'a> Builder<'a, NoMethod> { - /// Creates a new STUN message builder, starting in the initial state - /// where the method needs to be set. - pub fn new() -> Self { - Builder { - attrs: Attributes::default(), - state: NoMethod, - } - } - } - - // Method Setters (Transition from NoMethod to HasMethod) --- - impl<'a> Builder<'a, NoMethod> { - fn set_method(self, method: Method) -> Builder<'a, HasMethod> { - Builder { - attrs: self.attrs, - state: HasMethod { method }, - } - } - - /// Sets the STUN method to BINDING. - pub fn binding(self) -> Builder<'a, HasMethod> { - self.set_method(Method::Binding) - } - - /// Sets the STUN method to ALLOCATE (TURN). - pub fn allocate(self) -> Builder<'a, HasMethod> { - self.set_method(Method::Allocate) - } - - /// Sets the STUN method to REFRESH (TURN). - pub fn refresh(self) -> Builder<'a, HasMethod> { - self.set_method(Method::Refresh) - } - - /// Sets the STUN method to SEND (TURN). - pub fn send(self) -> Builder<'a, HasMethod> { - self.set_method(Method::Send) - } - - /// Sets the STUN method to DATA (TURN). - pub fn data(self) -> Builder<'a, HasMethod> { - self.set_method(Method::Data) - } - - /// Sets the STUN method to CREATE_PERMISSION (TURN). - pub fn create_permission(self) -> Builder<'a, HasMethod> { - self.set_method(Method::CreatePermission) - } - - /// Sets the STUN method to CHANNEL_BIND (TURN). - pub fn channel_bind(self) -> Builder<'a, HasMethod> { - self.set_method(Method::ChannelBind) - } - } - - // Class Setters (Transition from HasMethod to HasClass) --- - impl<'a> Builder<'a, HasMethod> { - fn set_class(self, class: Class) -> Builder<'a, HasClass> { - Builder { - attrs: self.attrs, - state: HasClass { - method: self.state.method, - class, - }, - } - } - - /// Sets the STUN class to Request. - pub fn request(self) -> Builder<'a, HasClass> { - self.set_class(Class::Request) - } - - /// Sets the STUN class to Indication. - pub fn indication(self) -> Builder<'a, HasClass> { - self.set_class(Class::Indication) - } - - /// Sets the STUN class to Success Response. - pub fn success(self) -> Builder<'a, HasClass> { - self.set_class(Class::Success) - } - - /// Sets the STUN class to Error Response. - pub fn failure(self) -> Builder<'a, HasClass> { - self.set_class(Class::Failure) - } - } - - // Attribute Setters (Only on HasClass state) --- - impl<'a> Builder<'a, HasClass> { - /// Sets the USERNAME attribute. - pub fn username(mut self, username: &'a str) -> Self { - self.attrs.username = Some(username); - self - } - - /// Sets the ERROR_CODE attribute. - pub fn error_code(mut self, code: u16, reason: &'a str) -> Self { - self.attrs.error_code = Some((code, reason)); - self - } - - /// Sets the CHANNEL_NUMBER attribute (TURN). - pub fn channel_number(mut self, number: u16) -> Self { - self.attrs.channel_number = Some(number); - self - } - - /// Sets the LIFETIME attribute (TURN). - pub fn lifetime(mut self, lifetime: u32) -> Self { - self.attrs.lifetime = Some(lifetime); - self - } - - /// Sets the XOR_PEER_ADDRESS attribute (TURN). - pub fn xor_peer_address(mut self, addr: SocketAddr) -> Self { - self.attrs.xor_peer_address = Some(addr); - self - } - - /// Sets the DATA attribute (TURN). - pub fn data(mut self, data: &'a [u8]) -> Self { - self.attrs.data = Some(data); - self - } - - /// Sets the REALM attribute. - pub fn realm(mut self, realm: &'a str) -> Self { - self.attrs.realm = Some(realm); - self - } - - /// Sets the NONCE attribute. - pub fn nonce(mut self, nonce: &'a str) -> Self { - self.attrs.nonce = Some(nonce); - self - } - - /// Sets the XOR_RELAYED_ADDRESS attribute (TURN). - pub fn xor_relayed_address(mut self, addr: SocketAddr) -> Self { - self.attrs.xor_relayed_address = Some(addr); - self - } - - /// Sets the XOR_MAPPED_ADDRESS attribute. - pub fn xor_mapped_address(mut self, addr: SocketAddr) -> Self { - self.attrs.xor_mapped_address = Some(addr); - self - } - - /// Sets the SOFTWARE attribute. - pub fn software(mut self, software: &'a str) -> Self { - self.attrs.software = Some(software); - self - } - - /// Sets the PRIORITY attribute (ICE). - pub fn prio(mut self, prio: u32) -> Self { - self.attrs.priority = Some(prio); - self - } - - /// Adds the USE_CANDIDATE attribute (ICE). - pub fn use_candidate(mut self) -> Self { - self.attrs.use_candidate = true; - self - } - - /// Sets the ICE_CONTROLLED attribute (ICE). - pub fn ice_controlled(mut self, tie_breaker: u64) -> Self { - self.attrs.ice_controlled = Some(tie_breaker); - self - } - - /// Sets the ICE_CONTROLLING attribute (ICE). - pub fn ice_controlling(mut self, tie_breaker: u64) -> Self { - self.attrs.ice_controlling = Some(tie_breaker); - self - } - - /// Sets the NETWORK_COST attribute (ICE). - pub fn network_cost(mut self, net_id: u16, cost: u16) -> Self { - self.attrs.network_cost = Some((net_id, cost)); - self - } - - /// Builds the final [`StunMessage`]. - /// - /// This method consumes the builder and requires a transaction ID. - /// Note that `MESSAGE_INTEGRITY` and `FINGERPRINT` attributes are not - /// added here; they are calculated and added during serialization in - /// [`StunMessage::to_bytes()`]. - pub fn build(self, trans_id: TransId) -> StunMessage<'a> { - StunMessage { - method: self.state.method, - class: self.state.class, - trans_id, - attrs: self.attrs, - integrity: &[], // Calculated during serialization - integrity_len: 0, // Calculated during serialization - } - } - } -} - -struct DebugHex<'a>(&'a [u8]); - -impl fmt::Debug for DebugHex<'_> { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - for b in self.0 { - write!(f, "{:x}", b)?; - } - - Ok(()) - } -} - -/// An incoming STUN packet. -#[derive(Debug)] -pub struct StunPacket<'a> { - /// The protocol the socket this received data originated from is using. - pub proto: crate::vendor::str0m_proto::Protocol, - /// The socket this received data originated from. - pub source: SocketAddr, - /// The destination socket of the datagram. - pub destination: SocketAddr, - /// The STUN message. - pub message: StunMessage<'a>, -} - -#[cfg(test)] -mod test { - use super::*; - use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; - - fn sha1_hmac(key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - use rind::hmac; - let key = hmac::Key::new(&hmac::legacy::HMAC_SHA1, key); - let mut ctx = hmac::Context::with_key(&key); - for p in payloads { - ctx.update(p); - } - ctx.sign().as_ref().try_into().unwrap() - } - - #[test] - fn parse_stun_message() { - const PACKET: &[u8] = &[ - 0x00, 0x01, 0x00, 0x50, 0x21, 0x12, 0xa4, 0x42, 0x6a, 0x75, 0x63, 0x31, 0x35, 0x75, 0x78, 0x55, 0x6e, 0x67, - 0x47, 0x63, 0x00, 0x06, 0x00, 0x09, 0x70, 0x39, 0x4b, 0x41, 0x3a, 0x53, 0x51, 0x41, 0x74, 0x00, 0x00, 0x00, - 0xc0, 0x57, 0x00, 0x04, 0x00, 0x01, 0x00, 0x0a, 0x80, 0x2a, 0x00, 0x08, 0x6e, 0xee, 0xc6, 0xe9, 0x7d, 0x18, - 0x39, 0x5c, 0x00, 0x25, 0x00, 0x00, 0x00, 0x24, 0x00, 0x04, 0x6e, 0x7f, 0x1e, 0xff, 0x00, 0x08, 0x00, 0x14, - 0x5d, 0x04, 0x25, 0xa0, 0x20, 0x7a, 0xb1, 0xe0, 0x54, 0x10, 0x22, 0x99, 0xaa, 0xf9, 0x83, 0x9c, 0xa0, 0x76, - 0xc6, 0xd5, 0x80, 0x28, 0x00, 0x04, 0x36, 0x0e, 0x21, 0x9f, - ]; - - let packet = PACKET.to_vec(); - let message = StunMessage::parse(&packet).unwrap(); - assert!(message.verify(b"xJcE9AQAR7kczUDVOXRUCl", sha1_hmac)); - } - - #[test] - fn minimal_debug_print() { - let attrs = Attributes { - username: Some("foo"), - ..Default::default() - }; - - let dbg_print = format!("{attrs:?}"); - - assert_eq!(dbg_print, r#"Attributes { username: "foo" }"#); - } - - // README: IF YOU NEED TO ADJUST THIS TEST BECAUSE YOU ADDED AN ATTRIBUTE, - // MAKE SURE TO ADJUST THE `fmt::Debug` impl. - #[test] - fn all_attributes_are_printed() { - let attrs = Attributes { - username: Some("foo"), - message_integrity: Some(b"0000"), - error_code: Some((401, "Unauthorized")), - channel_number: Some(0x4000), - lifetime: Some(3600), - xor_peer_address: Some(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))), - data: Some(&[0xDE, 0xAD, 0xBE, 0xEF]), - realm: Some("baz"), - nonce: Some("abcd"), - xor_relayed_address: Some(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))), - xor_mapped_address: Some(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))), - software: Some("str0m"), - fingerprint: Some(9999), - priority: Some(1), - use_candidate: true, - ice_controlled: Some(10), - ice_controlling: Some(100), - network_cost: Some((10, 10)), - }; - - let dbg_print = format!("{attrs:?}"); - - assert_eq!( - dbg_print, - "\ -Attributes { \ -username: \"foo\", \ -message_integrity: 30303030, \ -error_code: (401, \"Unauthorized\"), \ -channel_number: 16384, \ -lifetime: 3600, \ -xor_peer_address: 127.0.0.1:0, \ -data: [222, 173, 190, 239], \ -realm: \"baz\", \ -nonce: \"abcd\", \ -xor_relayed_address: 127.0.0.1:0, \ -xor_mapped_address: 127.0.0.1:0, \ -software: \"str0m\", \ -fingerprint: 9999, \ -priority: 1, \ -use_candidate: true, \ -ice_controlled: 10, \ -ice_controlling: 100, \ -network_cost: (10, 10) \ -}" - ); - } - - #[test] - fn test_username_4_bytes_no_padding() { - let attrs = Attributes { - username: Some("abcd"), - ..Default::default() - }; - let mut buf = vec![]; - let trans_id = TransId::new(); - attrs.to_bytes(&mut buf, &trans_id).expect("To serialize attributes"); - assert_eq!( - buf.len(), - 8, - "A 4 byte username attribute should be 8 bytes, 4 for TVL and 4 for the username" - ); - } - - #[test] - fn parse_zero_length_buffer() { - let result = StunMessage::parse(&[]); - - assert!(result.is_err()); - } - - #[test] - fn parse_allocate_request() { - let trans_id = TransId::new(); - let message = StunMessage { - method: Method::Allocate, - class: Class::Request, - trans_id, - attrs: Attributes { - username: Some("user"), - realm: Some("example.org"), - nonce: Some("dcd98b7102dd2f0e8b11d0f600bfb0c093"), - lifetime: Some(3600), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::Allocate); - assert_eq!(parsed.class, Class::Request); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.username, Some("user")); - assert_eq!(parsed.attrs.realm, Some("example.org")); - assert_eq!(parsed.attrs.nonce, Some("dcd98b7102dd2f0e8b11d0f600bfb0c093")); - assert_eq!(parsed.attrs.lifetime, Some(3600)); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn parse_allocate_response() { - let trans_id = TransId::new(); - let relayed_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1234)); - let message = StunMessage { - method: Method::Allocate, - class: Class::Success, - trans_id, - attrs: Attributes { - xor_relayed_address: Some(relayed_addr), - lifetime: Some(1800), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::Allocate); - assert_eq!(parsed.class, Class::Success); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.xor_relayed_address, Some(relayed_addr)); - assert_eq!(parsed.attrs.lifetime, Some(1800)); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn parse_allocate_failure_no_integrity() { - let trans_id = TransId::new(); - let message = StunMessage { - method: Method::Allocate, - class: Class::Failure, - trans_id, - attrs: Attributes { - error_code: Some((401, "Unauthorized")), - realm: Some("example.org"), - nonce: Some("dcd98b7102dd2f0e8b11d0f600bfb0c093"), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(None, &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::Allocate); - assert_eq!(parsed.class, Class::Failure); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.error_code, Some((401, "Unauthorized"))); - assert_eq!(parsed.attrs.realm, Some("example.org")); - assert_eq!(parsed.attrs.nonce, Some("dcd98b7102dd2f0e8b11d0f600bfb0c093")); - } - - #[test] - fn parse_send_request() { - // Data length of 3 bytes (0xDEADBE) requires 1 byte of padding - let trans_id = TransId::new(); - let message = StunMessage { - method: Method::Send, - class: Class::Indication, - trans_id, - attrs: Attributes { - username: Some("user"), - realm: Some("example.org"), - nonce: Some("dcd98b7102dd2f0e8b11d0f600bfb0c093"), - // Data length of 3 bytes (0xDEADBE) requires 1 byte of padding - data: Some(&[0xDE, 0xAD, 0xBE]), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::Send); - assert_eq!(parsed.class, Class::Indication); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.username, Some("user")); - assert_eq!(parsed.attrs.realm, Some("example.org")); - assert_eq!(parsed.attrs.nonce, Some("dcd98b7102dd2f0e8b11d0f600bfb0c093")); - assert_eq!(parsed.attrs.data, Some(&[0xDE, 0xAD, 0xBE][..])); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn verify_integrity_as_first_attribute() { - let message = StunMessage { - method: Method::Binding, - class: Class::Failure, - trans_id: TransId::new(), - attrs: Attributes::default(), - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - // Header followed directly by MESSAGE-INTEGRITY. - assert_eq!(&serialized[20..22], &[0x00, 0x08]); - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert!(parsed.verify(b"password", sha1_hmac)); - assert!(!parsed.verify(b"wrong", sha1_hmac)); - } - - #[test] - fn verify_without_covered_bytes_is_false() { - let message = StunMessage { - method: Method::Binding, - class: Class::Failure, - trans_id: TransId::new(), - attrs: Attributes { - message_integrity: Some(&[0; 20]), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - assert!(!message.verify(b"password", sha1_hmac)); - } - - #[test] - fn parse_data_indication() { - // Data length of 5 bytes (0xDEADBEEF00) requires 3 bytes of padding - let trans_id = TransId::new(); - let message = StunMessage { - method: Method::Data, - class: Class::Indication, - trans_id, - attrs: Attributes { - data: Some(&[0xDE, 0xAD, 0xBE, 0xEF, 0xF7]), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::Data); - assert_eq!(parsed.class, Class::Indication); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.data, Some(&[0xDE, 0xAD, 0xBE, 0xEF, 0xF7][..])); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn parse_refresh_request() { - let trans_id = TransId::new(); - let message = StunMessage { - method: Method::Refresh, - class: Class::Request, - trans_id, - attrs: Attributes { - username: Some("user"), - realm: Some("example.org"), - nonce: Some("dcd98b7102dd2f0e8b11d0f600bfb0c093"), - lifetime: Some(600), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::Refresh); - assert_eq!(parsed.class, Class::Request); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.username, Some("user")); - assert_eq!(parsed.attrs.realm, Some("example.org")); - assert_eq!(parsed.attrs.nonce, Some("dcd98b7102dd2f0e8b11d0f600bfb0c093")); - assert_eq!(parsed.attrs.lifetime, Some(600)); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn parse_create_permission_request() { - let trans_id = TransId::new(); - let peer_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 1), 8080)); - let message = StunMessage { - method: Method::CreatePermission, - class: Class::Request, - trans_id, - attrs: Attributes { - username: Some("user"), - realm: Some("example.org"), - nonce: Some("dcd98b7102dd2f0e8b11d0f600bfb0c093"), - xor_peer_address: Some(peer_addr), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::CreatePermission); - assert_eq!(parsed.class, Class::Request); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.username, Some("user")); - assert_eq!(parsed.attrs.realm, Some("example.org")); - assert_eq!(parsed.attrs.nonce, Some("dcd98b7102dd2f0e8b11d0f600bfb0c093")); - assert_eq!(parsed.attrs.xor_peer_address, Some(peer_addr)); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn parse_channel_bind_request() { - let trans_id = TransId::new(); - let peer_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 1), 8080)); - let message = StunMessage { - method: Method::ChannelBind, - class: Class::Request, - trans_id, - attrs: Attributes { - username: Some("user"), - realm: Some("example.org"), - nonce: Some("dcd98b7102dd2f0e8b11d0f600bfb0c093"), - channel_number: Some(0x4000), - xor_peer_address: Some(peer_addr), - ..Default::default() - }, - integrity: &[], - integrity_len: 0, - }; - - let mut buf = [0u8; 1024]; - let len = message.to_bytes(Some(b"password"), &mut buf, sha1_hmac).unwrap(); - let serialized = &buf[..len]; - - let parsed = StunMessage::parse(serialized).unwrap(); - - assert_eq!(parsed.method, Method::ChannelBind); - assert_eq!(parsed.class, Class::Request); - assert_eq!(parsed.trans_id, trans_id); - assert_eq!(parsed.attrs.username, Some("user")); - assert_eq!(parsed.attrs.realm, Some("example.org")); - assert_eq!(parsed.attrs.nonce, Some("dcd98b7102dd2f0e8b11d0f600bfb0c093")); - assert_eq!(parsed.attrs.channel_number, Some(0x4000)); - assert_eq!(parsed.attrs.xor_peer_address, Some(peer_addr)); - assert!(parsed.verify(b"password", sha1_hmac)); - } - - #[test] - fn build_stun_binding_request_with_attrs() { - let trans_id = TransId::new(); - let username = "test:user"; - let tie_breaker = 1234567890; - let prio = 9876; - - let message = StunMessageBuilder::new() - .binding() - .request() - .username(username) - .prio(prio) - .ice_controlling(tie_breaker) - .use_candidate() - .build(trans_id); - - assert_eq!(message.method(), Method::Binding); - assert_eq!(message.class(), Class::Request); - assert_eq!(message.trans_id(), trans_id); - assert_eq!(message.attrs.username, Some(username)); - assert_eq!(message.attrs.priority, Some(prio)); - assert_eq!(message.attrs.ice_controlling, Some(tie_breaker)); - assert!(message.attrs.use_candidate); - assert!(message.attrs.ice_controlled.is_none()); // Ensure others aren't set - } - - #[test] - fn build_stun_binding_success_with_attrs() { - let trans_id = TransId::new(); - let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 5678)); - - let message = StunMessageBuilder::new() - .binding() - .success() - .xor_mapped_address(addr) - .build(trans_id); - - assert_eq!(message.method(), Method::Binding); - assert_eq!(message.class(), Class::Success); - assert_eq!(message.trans_id(), trans_id); - assert_eq!(message.attrs.xor_mapped_address, Some(addr)); - } - - #[test] - fn build_stun_data_indication_with_attrs() { - let trans_id = TransId::new(); - let data_payload: &[u8] = &[0xca, 0xfe, 0xba, 0xbe]; - - let message = StunMessageBuilder::new() - .data() - .indication() - .data(data_payload) - .build(trans_id); - - assert_eq!(message.method(), Method::Data); - assert_eq!(message.class(), Class::Indication); - assert_eq!(message.trans_id(), trans_id); - assert_eq!(message.attrs.data, Some(data_payload)); - } - - #[test] - fn decode_xor_buffer_shorter_than_4_is_error() { - let trans_id = TransId::new(); - for buf in [&[][..], &[0x00][..], &[0x00, 0x01, 0x02][..]] { - let err = decode_xor(buf, trans_id).expect_err("short buffer must error"); - assert!(matches!(err, StunError::Parse(_)), "expected Parse error, got {err:?}"); - } - } - - #[test] - fn decode_xor_ipv4_family_with_short_ip_buf_is_error() { - let trans_id = TransId::new(); - // Family = IPv4 (0x01), valid port bytes, but fewer than 4 IP octets. - for buf in [ - &[0x00, 0x01, 0x11, 0x22][..], - &[0x00, 0x01, 0x11, 0x22, 0xaa][..], - &[0x00, 0x01, 0x11, 0x22, 0xaa, 0xbb, 0xcc][..], - ] { - let err = decode_xor(buf, trans_id).expect_err("short ipv4 payload must error"); - assert!(matches!(err, StunError::Parse(_)), "expected Parse error, got {err:?}"); - } - } - - #[test] - fn decode_xor_ipv6_family_with_short_ip_buf_is_error() { - let trans_id = TransId::new(); - // Family = IPv6 (0x02), valid port bytes, but fewer than 16 IP octets. - let mut buf = vec![0x00, 0x02, 0x11, 0x22]; - buf.extend_from_slice(&[0xaa; 15]); - let err = decode_xor(&buf, trans_id).expect_err("short ipv6 payload must error"); - assert!(matches!(err, StunError::Parse(_)), "expected Parse error, got {err:?}"); - - // Zero IP bytes for IPv6 family is also insufficient. - let err = decode_xor(&[0x00, 0x02, 0x11, 0x22], trans_id).expect_err("empty ipv6 payload must error"); - assert!(matches!(err, StunError::Parse(_))); - } - - #[test] - fn decode_xor_unknown_family_is_error() { - let trans_id = TransId::new(); - let buf = [0x00, 0x03, 0x11, 0x22, 0xaa, 0xbb, 0xcc, 0xdd]; - let err = decode_xor(&buf, trans_id).expect_err("unknown family must error"); - assert!(matches!(err, StunError::Parse(_))); - } - - #[test] - fn encode_decode_xor_ipv4_roundtrip() { - let trans_id = TransId::new(); - let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 15), 54321)); - let mut buf = [0u8; 20]; - let len = encode_xor(addr, &mut buf, &trans_id); - assert_eq!(len, 8); - let decoded = decode_xor(&buf[..len], trans_id).expect("ipv4 roundtrip"); - assert_eq!(decoded, addr); - } - - #[test] - fn encode_decode_xor_ipv6_roundtrip() { - let trans_id = TransId::new(); - let addr = SocketAddr::V6(SocketAddrV6::new( - Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x1234), - 54321, - 0, - 0, - )); - let mut buf = [0u8; 20]; - let len = encode_xor(addr, &mut buf, &trans_id); - assert_eq!(len, 20); - let decoded = decode_xor(&buf[..len], trans_id).expect("ipv6 roundtrip"); - assert_eq!(decoded, addr); - } -} diff --git a/rs/moq-webrtc/src/vendor/mod.rs b/rs/moq-webrtc/src/vendor/mod.rs deleted file mode 100644 index 40b3ecdecac..00000000000 --- a/rs/moq-webrtc/src/vendor/mod.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! The WebRTC stack moq-webrtc runs on: str0m (SDP, RTP/RTCP, SRTP, the `Rtc` -//! state machine) with its ICE agent `is`, and DTLS from dimpl. Each lives here -//! as a private module, trimmed to what MoQ uses, so fixes land in normal MoQ -//! PRs. str0m's data channels (SCTP over DTLS) are cut: an offered -//! `m=application` line is answered rejected. -//! -//! # Upstream -//! -//! Vendored on 2026-11-07, each module keeping its upstream layout and its -//! license (MIT OR Apache-2.0). The `LICENSE-*` files sit beside `str0m` (whose -//! file covers the other crates from its repository, which ship none of their -//! own) and `dimpl`, and `str0m/packet/LICENSE-APACHE.txt` keeps webrtc-rs's -//! notice on `str0m::packet`: -//! - `str0m` (0.24.1+), `str0m_proto` (0.7.0), `is` (0.11.1), and the test-only -//! `netem` (0.4.0): -//! at [`dc317173`](https://github.com/algesten/str0m/commit/dc317173b16fc6ed86633e6b08b229c9195deb87) -//! (2026-10-26), the main-branch revision on dimpl 0.9 with str0m's pluggable -//! crypto provider. -//! - `dimpl`: 0.9.0 -//! ([`c17b3b8`](https://github.com/algesten/dimpl/commit/c17b3b8b971b6eb2ecf7284f5dc0ecb86680ac4d)). -//! - `str0m_rind` and dimpl's `crypto::rind`, the stack's crypto providers: -//! 's `rind-str0m` (as of -//! [`86567aad`](https://github.com/kixel-ai/rind/commit/86567aadabc22d2b2ac23ea534598a0fffc66538), -//! which targeted the str0m revision above) and `rind-dimpl` 0.1.12, ported to -//! the rind release the workspace pins. -//! -//! Nobody merges upstream automatically: the release-cut vendor audit reads each -//! upstream's changes since these revisions and ports the fixes MoQ needs. -//! -//! Kept close to upstream (its own tests included), so the vendored modules opt -//! out of the workspace's lints rather than churning them to satisfy ours. -#![allow(warnings, reason = "vendored upstream code")] -#![allow(clippy::all, reason = "vendored upstream code")] -#![allow(clippy::pedantic, reason = "vendored upstream code")] -#![allow(clippy::nursery, reason = "vendored upstream code")] -#![allow(rustdoc::all, reason = "vendored upstream code")] -#![allow( - clippy::disallowed_methods, - clippy::disallowed_types, - reason = "the stack reads std::time::Instant until it takes kio::clock time" -)] - -#[path = "dimpl/lib.rs"] -mod dimpl; -#[path = "is/lib.rs"] -mod is; -#[cfg(test)] -#[path = "netem/lib.rs"] -mod netem; -#[path = "str0m/lib.rs"] -pub(crate) mod str0m; -#[path = "str0m_proto/lib.rs"] -mod str0m_proto; -#[path = "str0m_rind/lib.rs"] -mod str0m_rind; diff --git a/rs/moq-webrtc/src/vendor/netem/config.rs b/rs/moq-webrtc/src/vendor/netem/config.rs deleted file mode 100644 index 906bd2f517c..00000000000 --- a/rs/moq-webrtc/src/vendor/netem/config.rs +++ /dev/null @@ -1,584 +0,0 @@ -use std::time::Duration; - -pub use crate::vendor::str0m_proto::{Bitrate, DataSize}; - -/// Configuration for the network emulator. -/// -/// Use the builder pattern to configure the emulator: -/// -/// ```ignore -/// use std::time::Duration; -/// use str0m_netem::{NetemConfig, LossModel, GilbertElliot}; -/// -/// let config = NetemConfig::new() -/// .latency(Duration::from_millis(50)) -/// .jitter(Duration::from_millis(10)) -/// .loss(GilbertElliot::wifi()) -/// .seed(42); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct NetemConfig { - pub(crate) latency: Duration, - pub(crate) jitter: Duration, - pub(crate) delay_correlation: Probability, - pub(crate) loss: LossModel, - pub(crate) duplicate: Probability, - pub(crate) reorder_gap: Option, - pub(crate) link: Option, - pub(crate) seed: u64, -} - -/// A bottleneck link with rate limiting and finite buffer. -/// -/// When packets arrive faster than the link rate, they queue up. -/// When the queue exceeds the buffer size, packets are dropped (tail drop). -#[derive(Debug, Clone, Copy)] -pub struct Link { - /// Link capacity in bits per second. - pub(crate) rate: Bitrate, - /// Buffer size in bytes. When exceeded, packets are dropped. - pub(crate) buffer: DataSize, -} - -impl Default for NetemConfig { - fn default() -> Self { - Self::new() - } -} - -impl NetemConfig { - /// Create a new network emulator configuration with default values. - /// - /// Default: no delay, no loss, no rate limit, seed 0. - pub const fn new() -> Self { - Self { - latency: Duration::ZERO, - jitter: Duration::ZERO, - delay_correlation: Probability::ZERO, - loss: LossModel::None, - duplicate: Probability::ZERO, - reorder_gap: None, - link: None, - seed: 0, - } - } - - // --- Preset constructors for common network environments --- - - /// Good WiFi: low latency, minimal loss, high bandwidth. - /// - /// Simulates a typical home/office WiFi connection with good signal. - /// - Latency: 5ms (local network) - /// - Jitter: 2ms - /// - Loss: ~1% bursty (GilbertElliot::wifi) - /// - Bandwidth: 100 Mbps with 200 KB buffer - pub fn wifi() -> Self { - Self::new() - .latency(Duration::from_millis(5)) - .jitter(Duration::from_millis(2)) - .loss(GilbertElliot::wifi()) - .link(Bitrate::mbps(100), DataSize::kbytes(200)) - } - - /// Lossy WiFi: poor signal, more interference and loss. - /// - /// Simulates WiFi with weak signal or interference. - /// - Latency: 15ms - /// - Jitter: 10ms - /// - Loss: ~5% bursty (GilbertElliot::wifi_lossy) - /// - Bandwidth: 50 Mbps with 100 KB buffer - pub fn wifi_lossy() -> Self { - Self::new() - .latency(Duration::from_millis(15)) - .jitter(Duration::from_millis(10)) - .loss(GilbertElliot::wifi_lossy()) - .link(Bitrate::mbps(50), DataSize::kbytes(100)) - } - - /// Congested WiFi: shared connection with competing traffic. - /// - /// Simulates a home WiFi where others are streaming video, - /// causing buffer bloat and bandwidth contention. - /// - Latency: 10ms - /// - Jitter: 20ms (high due to competing traffic) - /// - Loss: ~10% (buffer overflow from congestion) - /// - Bandwidth: 5 Mbps with 30 KB buffer (your share of the link) - pub fn wifi_congested() -> Self { - Self::new() - .latency(Duration::from_millis(10)) - .jitter(Duration::from_millis(20)) - .loss(GilbertElliot::congested()) - .link(Bitrate::mbps(5), DataSize::kbytes(30)) - } - - /// Cellular/4G: moderate latency with occasional handoff loss. - /// - /// Simulates a mobile LTE/4G connection. - /// - Latency: 50ms - /// - Jitter: 15ms - /// - Loss: ~2% bursty (handoffs, signal fading) - /// - Bandwidth: 30 Mbps with 100 KB buffer - pub fn cellular() -> Self { - Self::new() - .latency(Duration::from_millis(50)) - .jitter(Duration::from_millis(15)) - .loss(GilbertElliot::cellular()) - .link(Bitrate::mbps(30), DataSize::kbytes(100)) - } - - /// Satellite (GEO): very high latency, weather-related loss bursts. - /// - /// Simulates a geostationary satellite link (e.g., Viasat, HughesNet). - /// - Latency: 600ms (round-trip to GEO orbit) - /// - Jitter: 30ms - /// - Loss: ~3% bursty (weather, atmospheric) - /// - Bandwidth: 15 Mbps with 500 KB buffer (large buffer for high BDP) - pub fn satellite() -> Self { - Self::new() - .latency(Duration::from_millis(600)) - .jitter(Duration::from_millis(30)) - .loss(GilbertElliot::satellite()) - .link(Bitrate::mbps(15), DataSize::kbytes(500)) - } - - /// Congested network: high latency/jitter, frequent loss, throttled. - /// - /// Simulates a severely congested network path. - /// - Latency: 80ms - /// - Jitter: 40ms - /// - Loss: ~10% (queue overflow) - /// - Bandwidth: 10 Mbps with 50 KB buffer (small buffer causes loss) - pub fn congested() -> Self { - Self::new() - .latency(Duration::from_millis(80)) - .jitter(Duration::from_millis(40)) - .loss(GilbertElliot::congested()) - .link(Bitrate::mbps(10), DataSize::kbytes(50)) - } - - /// Set fixed delay added to every packet. - /// - /// This simulates the propagation delay of a network link. For example: - /// - LAN: 0-1ms - /// - Same city: 5-20ms - /// - Cross-country: 30-70ms - /// - Intercontinental: 100-200ms - /// - Satellite (GEO): 500-700ms - /// - /// The actual send time is: `arrival_time + latency + random_jitter` - pub fn latency(mut self, latency: Duration) -> Self { - self.latency = latency; - self - } - - /// Set random variation added to the latency (uniform distribution). - /// - /// Each packet gets a random delay in the range `[-jitter, +jitter]` added - /// to its base latency. This simulates the variable queuing delays in routers. - /// - /// For example, with `latency(50ms)` and `jitter(10ms)`, packets will have - /// delays uniformly distributed between 40ms and 60ms. - /// - /// Real networks typically have jitter of 1-30ms depending on congestion. - pub fn jitter(mut self, jitter: Duration) -> Self { - self.jitter = jitter; - self - } - - /// Set correlation between consecutive delay values. - /// - /// Controls how similar each packet's delay is to the previous packet's delay. - /// This models the fact that network conditions change gradually, not randomly. - /// - /// - `0.0`: Each packet's jitter is completely independent (unrealistic) - /// - `0.25`: Low correlation, delays vary somewhat smoothly - /// - `0.5`: Medium correlation, delays change gradually - /// - `0.75`: High correlation, delays are very similar to previous - /// - `1.0`: Perfect correlation, all packets get the same jitter (no variation) - /// - /// Formula: `next_jitter = random * (1 - correlation) + last_jitter * correlation` - /// - /// A value around 0.25-0.5 is realistic for most networks. - pub fn delay_correlation(mut self, correlation: Probability) -> Self { - self.delay_correlation = correlation; - self - } - - /// Set the loss model. - /// - /// See [`LossModel`] for available options. - pub fn loss(mut self, loss: impl Into) -> Self { - self.loss = loss.into(); - self - } - - /// Set probability that each packet is duplicated. - /// - /// When a packet is duplicated, both the original and the copy are sent - /// with the same delay. This simulates network equipment bugs or - /// misconfigured routing that causes packets to be sent twice. - /// - /// - `0.0`: No duplication (normal) - /// - `0.01`: 1% of packets are duplicated (rare but happens) - /// - `0.1`: 10% duplication (severe misconfiguration) - pub fn duplicate(mut self, probability: Probability) -> Self { - self.duplicate = probability; - self - } - - /// Set reordering by sending every Nth packet immediately. - /// - /// Every Nth packet bypasses the delay queue and is sent immediately, - /// causing it to arrive before packets that were sent earlier. - /// This simulates multi-path routing where packets take different routes. - /// - /// - `3`: Every 3rd packet is sent immediately - /// - `10`: Every 10th packet is sent immediately - /// - /// Combined with latency, this creates realistic reordering patterns. - pub fn reorder_gap(mut self, gap: u32) -> Self { - self.reorder_gap = Some(gap); - self - } - - /// Set a bottleneck link with rate limiting and finite buffer. - /// - /// Simulates a network link with limited capacity. When packets arrive faster - /// than the link can transmit, they queue up. When the queue (buffer) is full, - /// packets are dropped (tail drop), simulating congestion-induced loss. - /// - /// # Example - /// - /// ```ignore - /// use std::time::Duration; - /// use str0m_netem::{NetemConfig, Bitrate, DataSize}; - /// - /// // 10 Mbps link with 200KB buffer (~160ms at full rate) - /// let config = NetemConfig::new() - /// .latency(Duration::from_millis(50)) - /// .link(Bitrate::mbps(10), DataSize::bytes(200_000)); - /// ``` - /// - /// # Behavior - /// - /// - Below capacity: packets flow with minimal queuing delay - /// - At capacity: queuing delay increases as buffer fills - /// - Over capacity: buffer fills, then excess packets are dropped - pub fn link(mut self, rate: Bitrate, buffer: DataSize) -> Self { - self.link = Some(Link { rate, buffer }); - self - } - - /// Set seed for the random number generator. - /// - /// Using the same seed produces identical packet loss/delay patterns, - /// which is essential for reproducible tests. Different seeds produce - /// different (but deterministic) random sequences. - /// - /// - Use a fixed seed (e.g., `42`) for reproducible tests - /// - Use `std::time::SystemTime::now().duration_since(UNIX_EPOCH).as_nanos() as u64` - /// for random behavior in production - pub fn seed(mut self, seed: u64) -> Self { - self.seed = seed; - self - } -} - -/// Probability in range 0.0..=1.0 -#[derive(Debug, Clone, Copy, PartialEq, Default)] -pub struct Probability(pub f32); - -impl Probability { - pub const ZERO: Probability = Probability(0.0); - pub const ONE: Probability = Probability(1.0); - - pub fn new(value: f32) -> Self { - debug_assert!((0.0..=1.0).contains(&value), "Probability must be in 0.0..=1.0"); - Probability(value.clamp(0.0, 1.0)) - } - - pub fn value(self) -> f32 { - self.0 - } -} - -/// Loss model for packet dropping. -/// -/// Real networks rarely have uniform random loss. Instead, losses tend to come -/// in bursts due to congestion, interference, or route changes. This enum -/// provides different models to simulate various loss patterns. -#[derive(Debug, Clone, Copy, Default)] -pub enum LossModel { - /// No packet loss. All packets are delivered. - #[default] - None, - - /// Probability-based random loss with optional correlation. - /// - /// See [`RandomLoss`] for configuration options. - Random(RandomLoss), - - /// Gilbert-Elliot model for realistic bursty packet loss. - /// - /// This 2-state Markov model alternates between GOOD (low loss) and BAD - /// (high loss) states, producing realistic burst patterns where losses - /// cluster together rather than being spread evenly. - /// - /// Use the builder methods or presets on [`GilbertElliot`]: - /// - `GilbertElliot::wifi()` - occasional short bursts - /// - `GilbertElliot::cellular()` - moderate bursts from handoffs - /// - `GilbertElliot::satellite()` - rare but longer bursts - /// - `GilbertElliot::congested()` - frequent drops - GilbertElliot(GilbertElliot), -} - -/// Random loss model configuration. -/// -/// Each packet has the given probability of being dropped. By default, each -/// decision is independent (Bernoulli process), producing unrealistic "spread out" -/// loss patterns. -/// -/// Use [`correlation`](RandomLoss::correlation) to make losses more bursty, or -/// prefer [`GilbertElliot`] for more realistic bursty loss with finer control. -/// -/// # Example -/// -/// ```ignore -/// use str0m_netem::{RandomLoss, Probability}; -/// -/// // 5% loss, independent -/// let simple = RandomLoss::new(Probability::new(0.05)); -/// -/// // 5% loss, bursty (losses cluster together) -/// let bursty = RandomLoss::new(Probability::new(0.05)) -/// .correlation(Probability::new(0.5)); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct RandomLoss { - /// Probability of dropping each packet. - pub(crate) probability: f32, - - /// Correlation between consecutive loss decisions. - pub(crate) correlation: f32, -} - -impl RandomLoss { - /// Create a new random loss model with the given drop probability. - /// - /// Loss decisions are independent by default (no correlation). - pub fn new(probability: Probability) -> Self { - Self { - probability: probability.0, - correlation: 0.0, - } - } - - /// Set correlation between consecutive loss decisions. - /// - /// Controls how "bursty" random loss is: - /// - /// - `0.0`: Each loss decision is independent (Bernoulli process) - /// - `0.5`: If a packet was lost, next packet is more likely to be lost too - /// - `0.9`: Very bursty - losses come in clusters - /// - /// For realistic bursty loss, consider using [`GilbertElliot`] instead, - /// which provides more control over burst characteristics. - pub fn correlation(mut self, correlation: Probability) -> Self { - self.correlation = correlation.0; - self - } -} - -/// Gilbert-Elliot loss model with two states: GOOD and BAD. -/// -/// This is a 2-state Markov chain that models bursty packet loss: -/// -/// ```text -/// p (enter burst) -/// ┌──────────────────────┐ -/// │ ▼ -/// ┌───────┐ ┌───────┐ -/// │ GOOD │ │ BAD │ -/// │(k=0%) │ │(h=100%)│ -/// └───────┘ └───────┘ -/// ▲ │ -/// └──────────────────────┘ -/// r (exit burst) -/// ``` -/// -/// **How it works:** -/// 1. Start in GOOD state (low/no loss) -/// 2. Each packet, roll dice to potentially transition to BAD state (probability `p`) -/// 3. In BAD state, packets are lost with probability `h` (default 100%) -/// 4. Each packet in BAD, roll dice to return to GOOD (probability `r`) -/// -/// **Key insight:** The average number of packets before transitioning is `1/probability`. -/// So `p = 0.01` means ~100 packets in GOOD before entering BAD, -/// and `r = 0.5` means ~2 packets in BAD before returning to GOOD. -/// -/// # Example -/// -/// ```ignore -/// use str0m_netem::GilbertElliot; -/// -/// // Custom: lose ~3 packets every ~50 packets -/// let ge = GilbertElliot::new() -/// .good_duration(50.0) // stay in GOOD for ~50 packets -/// .bad_duration(3.0); // stay in BAD for ~3 packets (burst length) -/// -/// // Or use a preset -/// let wifi = GilbertElliot::wifi(); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct GilbertElliot { - /// Probability of transitioning from GOOD to BAD state (per packet). - /// Average packets in GOOD = 1/p - pub(crate) p: f32, - - /// Probability of transitioning from BAD to GOOD state (per packet). - /// Average packets in BAD (burst length) = 1/r - pub(crate) r: f32, - - /// Probability of loss when in BAD state (default 1.0 = 100%). - pub(crate) h: f32, - - /// Probability of loss when in GOOD state (default 0.0 = 0%). - pub(crate) k: f32, -} - -impl Default for GilbertElliot { - fn default() -> Self { - Self::new() - } -} - -impl GilbertElliot { - /// Create a new Gilbert-Elliot model with default parameters. - /// - /// Defaults produce **no loss**: stays in GOOD forever (p=0). - /// Use the builder methods to configure loss behavior. - pub fn new() -> Self { - Self { - p: 0.0, // never transition to BAD - r: 1.0, // immediately return to GOOD - h: 1.0, // 100% loss in BAD - k: 0.0, // 0% loss in GOOD - } - } - - /// Set average number of packets in GOOD state before transitioning to BAD. - /// - /// This controls how often bursts occur. Higher values = rarer bursts. - /// - /// - `50.0`: Burst starts every ~50 packets on average - /// - `100.0`: Burst starts every ~100 packets on average - /// - `200.0`: Burst starts every ~200 packets on average - /// - /// Internally sets `p = 1 / avg_packets`. - pub fn good_duration(mut self, avg_packets: f32) -> Self { - self.p = if avg_packets > 0.0 { 1.0 / avg_packets } else { 0.0 }; - self - } - - /// Set average number of packets in BAD state (burst length). - /// - /// This controls how long each burst lasts. Higher values = longer bursts. - /// - /// - `1.0`: Single packet losses (not really bursty) - /// - `2.0`: ~2 packets lost per burst - /// - `5.0`: ~5 packets lost per burst - /// - `10.0`: ~10 packets lost per burst (severe) - /// - /// Internally sets `r = 1 / avg_packets`. - pub fn bad_duration(mut self, avg_packets: f32) -> Self { - self.r = if avg_packets > 0.0 { 1.0 / avg_packets } else { 1.0 }; - self - } - - /// Set loss probability when in BAD state. - /// - /// Default is `1.0` (100% loss in BAD state). - /// - /// Setting this below 1.0 means some packets survive even during a burst, - /// which can model partial outages or congestion that drops some but not - /// all packets. - pub fn loss_in_bad(mut self, prob: Probability) -> Self { - self.h = prob.0; - self - } - - /// Set loss probability when in GOOD state. - /// - /// Default is `0.0` (no loss in GOOD state). - /// - /// Setting this above 0.0 adds a baseline random loss even outside of - /// bursts, simulating a network that always has some background loss. - pub fn loss_in_good(mut self, prob: Probability) -> Self { - self.k = prob.0; - self - } - - // --- Preset constructors for common environments --- - - /// Good WiFi: rare short bursts (~1% loss). - /// - /// Models occasional interference causing brief packet loss. - pub fn wifi() -> Self { - Self::new() - .good_duration(200.0) // ~200 packets between bursts - .bad_duration(2.0) // ~2 packets lost per burst - .loss_in_bad(Probability::ONE) - } - - /// Lossy WiFi: frequent short bursts (~5% loss). - /// - /// Models poor WiFi signal with frequent interference. - pub fn wifi_lossy() -> Self { - Self::new() - .good_duration(40.0) // ~40 packets between bursts - .bad_duration(2.0) // ~2 packets lost per burst - .loss_in_bad(Probability::ONE) - } - - /// Mobile/cellular: moderate bursts from handoffs (~2% loss). - /// - /// Models cellular network with occasional handoffs and signal issues. - pub fn cellular() -> Self { - Self::new() - .good_duration(100.0) // ~100 packets between bursts - .bad_duration(2.0) // ~2 packets lost per burst - .loss_in_bad(Probability::ONE) - } - - /// Satellite: rare but longer bursts (~3% loss). - /// - /// Models satellite link with weather-related outages. - pub fn satellite() -> Self { - Self::new() - .good_duration(100.0) // ~100 packets between bursts - .bad_duration(3.0) // ~3 packets lost per burst - .loss_in_bad(Probability::ONE) - } - - /// Congested network: frequent drops (~10% loss). - /// - /// Models a heavily loaded network with queue overflow. - pub fn congested() -> Self { - Self::new() - .good_duration(20.0) // ~20 packets between bursts - .bad_duration(2.0) // ~2 packets lost per burst - .loss_in_bad(Probability::ONE) - } -} - -impl From for LossModel { - fn from(value: RandomLoss) -> Self { - LossModel::Random(value) - } -} - -impl From for LossModel { - fn from(value: GilbertElliot) -> Self { - LossModel::GilbertElliot(value) - } -} diff --git a/rs/moq-webrtc/src/vendor/netem/lib.rs b/rs/moq-webrtc/src/vendor/netem/lib.rs deleted file mode 100644 index 5c85be2fc27..00000000000 --- a/rs/moq-webrtc/src/vendor/netem/lib.rs +++ /dev/null @@ -1,718 +0,0 @@ -//! Sans-IO network emulator inspired by Linux netem. -//! -//! This crate provides a network emulator that can simulate: -//! - Latency and jitter -//! - Packet loss (random or bursty via Gilbert-Elliot model) -//! - Packet duplication -//! - Packet reordering -//! - Rate limiting -//! -//! # Sans-IO Pattern -//! -//! This implementation follows the Sans-IO pattern: packets go in with timestamps, -//! and decisions come out (drop, delay, duplicate). The caller handles actual I/O -//! and timing. -//! -//! # Example -//! -//! ```ignore -//! use std::time::{Duration, Instant}; -//! use str0m_netem::{Netem, NetemConfig, Input, Output, LossModel, RandomLoss, Probability}; -//! -//! let config = NetemConfig::new() -//! .latency(Duration::from_millis(50)) -//! .jitter(Duration::from_millis(10)) -//! .loss(RandomLoss::new(Probability::new(0.01))) -//! .seed(42); -//! -//! let mut netem: Netem> = Netem::new(config); -//! -//! // Send a packet -//! let now = Instant::now(); -//! netem.handle_input(Input::Packet(now, vec![1, 2, 3])); -//! -//! // Poll for output -//! while let Some(output) = netem.poll_output() { -//! match output { -//! Output::Timeout(when) => { -//! // Wait until `when` and call handle_input with Input::Timeout -//! } -//! Output::Packet(data) => { -//! // Send the packet -//! } -//! } -//! } -//! ``` - -// Avoid rewriting existing code: nested conditions are often more readable than long if-chains. -#![allow(clippy::collapsible_if)] - -mod config; -mod loss; - -pub use config::{Bitrate, DataSize, GilbertElliot, Link}; -pub use config::{LossModel, NetemConfig, Probability, RandomLoss}; - -use std::cmp::{Ordering, Reverse}; -use std::collections::BinaryHeap; -use std::time::{Duration, Instant}; - -use fastrand::Rng; - -use loss::LossState; - -/// Sans-IO network emulator. -pub struct Netem { - config: NetemConfig, - rng: Rng, - loss_state: LossState, - - /// Priority queue of packets, ordered by send time (earliest first). - /// Using Reverse to make BinaryHeap a min-heap. - queue: BinaryHeap>>, - - /// Last delay value for correlation. - last_delay: Duration, - - /// Virtual time when the last packet would finish transmitting (for rate limiting). - rate_virtual_time: Option, - - /// Counter for reordering (every N packets, one gets reordered). - reorder_counter: u32, - - /// Current time from the last input. - current_time: Option, - - /// Number of packets for the current time. - packet_count: u64, - - /// Whether we've already returned a timeout for the next packet. - timeout_pending: bool, - - /// Send time of the last queued packet (for reordering). - last_send_at: Option, - - /// Total bytes currently queued (for buffer overflow detection). - queued_bytes: usize, -} - -impl Netem { - /// Create a new network emulator with the given configuration. - pub fn new(config: NetemConfig) -> Self { - let rng = Rng::with_seed(config.seed); - - let loss_state = LossState::new(&config.loss); - - Self { - config, - rng, - loss_state, - queue: BinaryHeap::new(), - last_delay: Duration::ZERO, - rate_virtual_time: None, - reorder_counter: 0, - current_time: None, - packet_count: 0, - timeout_pending: false, - last_send_at: None, - queued_bytes: 0, - } - } - - /// Handle an input event. - pub fn handle_input(&mut self, input: Input) { - match input { - Input::Timeout(now) => { - self.progress_time(now); - self.timeout_pending = false; - } - Input::Packet(now, data) => { - self.progress_time(now); - self.process_packet(now, data); - } - } - } - - fn progress_time(&mut self, now: Instant) { - if let Some(last_time) = self.current_time { - if now < last_time { - // Time does not go backwards. - return; - } - } - self.current_time = Some(now); - } - - /// Poll for the next output event. - /// - /// Returns `None` when there are no more events to process. - pub fn poll_output(&mut self) -> Option> { - let now = self.current_time?; - - // Check if the next packet is ready to send - if let Some(Reverse(packet)) = self.queue.peek() { - if packet.send_at <= now { - let Reverse(packet) = self.queue.pop().unwrap(); - // Decrement queued bytes when packet is dequeued - self.queued_bytes = self.queued_bytes.saturating_sub(packet.data.len()); - return Some(Output::Packet(packet.data)); - } - - // Need to wait for the packet - if !self.timeout_pending { - self.timeout_pending = true; - return Some(Output::Timeout(packet.send_at)); - } - } - - None - } - - /// Returns when the next packet will be ready, if any. - /// - /// This can be used to decide which of multiple Netem instances - /// should be polled next. - pub fn poll_timeout(&self) -> Instant { - self.queue - .peek() - .map(|Reverse(p)| p.send_at) - .unwrap_or_else(not_happening) - } - - /// Process an incoming packet. - fn process_packet(&mut self, now: Instant, data: T) { - // Check for packet loss - if self.loss_state.should_lose(&self.config.loss, &mut self.rng) { - return; // Packet dropped - } - - // Check for duplication (process original first, then maybe duplicate) - let should_duplicate = self.rng.f32() < self.config.duplicate.0; - - // Process the original packet - self.enqueue_packet(now, data.clone()); - - // Duplicate if needed - if should_duplicate { - self.enqueue_packet(now, data); - } - } - - /// Calculate delay and enqueue a packet. - fn enqueue_packet(&mut self, now: Instant, data: T) { - // Calculate delay with jitter - let delay = self.calculate_delay(); - - // Calculate base send time - let mut send_at = now + delay; - - // Handle link rate limiting and buffer overflow - let transmission_time = if let Some(link) = self.config.link { - let packet_size = DataSize::from(data.len()); - let tx_time = packet_size / link.rate; - - // Apply rate limiting: packet can't be sent until previous finishes - if let Some(virtual_time) = self.rate_virtual_time { - if virtual_time > send_at { - send_at = virtual_time; - } - } - - // Check buffer overflow (tail drop) using actual queued bytes - if self.queued_bytes + data.len() > link.buffer.as_bytes_usize() { - // Buffer overflow - drop packet - return; - } - - Some(tx_time) - } else { - None - }; - - // Determine if this packet should be reordered - let should_reorder = if let Some(gap) = self.config.reorder_gap { - self.reorder_counter += 1; - if self.reorder_counter >= gap { - self.reorder_counter = 0; - // Can only reorder if we have a previous packet to reorder before - self.last_send_at.is_some() && self.packet_count > 0 - } else { - false - } - } else { - false - }; - - let gap = self.config.reorder_gap.unwrap_or(1) as u64; - let packet_index; - - if should_reorder { - // Reordered packet: use previous packet's send_at and a lower index - send_at = self.last_send_at.unwrap(); - // Index slots before the previous packet: count * gap - 1 - // Previous packet had index = count * gap - packet_index = self.packet_count * gap - 1; - // Don't update rate_virtual_time or last_send_at - } else { - // Normal packet: use calculated send_at with gaps for index - packet_index = (self.packet_count + 1) * gap; - - // Update rate_virtual_time for next packet - if let Some(tx_time) = transmission_time { - self.rate_virtual_time = Some(send_at + tx_time); - } - - // Track this packet's send_at for potential future reordering - self.last_send_at = Some(send_at); - } - - self.packet_count += 1; - - // Track queued bytes for buffer overflow detection - self.queued_bytes += data.len(); - - let packet = QueuedPacket { - send_at, - data, - packet_index, - }; - self.queue.push(Reverse(packet)); - - // Reset timeout pending since queue changed - self.timeout_pending = false; - } - - /// Calculate delay with jitter and correlation. - fn calculate_delay(&mut self) -> Duration { - let base = self.config.latency; - let jitter = self.config.jitter; - - if jitter.is_zero() { - return base; - } - - // Generate correlated jitter - let rho = self.config.delay_correlation.0; - let jitter_nanos = jitter.as_nanos() as f32; - - // Random value in [-1, 1] - let fresh_random = self.rng.f32() * 2.0 - 1.0; - let last_normalized = if self.last_delay >= base { - (self.last_delay - base).as_nanos() as f32 / jitter_nanos - } else { - -((base - self.last_delay).as_nanos() as f32 / jitter_nanos) - }; - - let jitter_factor = if rho == 0.0 { - fresh_random - } else { - fresh_random * (1.0 - rho) + last_normalized.clamp(-1.0, 1.0) * rho - }; - - let jitter_nanos = (jitter_factor * jitter_nanos) as i64; - let delay = if jitter_nanos >= 0 { - base + Duration::from_nanos(jitter_nanos as u64) - } else { - base.saturating_sub(Duration::from_nanos((-jitter_nanos) as u64)) - }; - - self.last_delay = delay; - delay - } - - /// Returns the number of packets currently queued. - pub fn queue_len(&self) -> usize { - self.queue.len() - } - - /// Returns true if the queue is empty. - pub fn is_empty(&self) -> bool { - self.queue.is_empty() - } - - /// Update the configuration without dropping queued packets. - /// - /// Resets loss state and correlation tracking, but preserves timing state - /// (rate limiting, reorder counter, pending timeouts) to avoid disrupting - /// packets already in the queue. - pub fn set_config(&mut self, config: NetemConfig) { - self.rng = Rng::with_seed(config.seed); - self.loss_state = LossState::new(&config.loss); - self.last_delay = Duration::ZERO; - self.last_send_at = None; - // Don't reset: rate_virtual_time, reorder_counter, timeout_pending, current_time - // These affect packets already queued - self.config = config; - } -} - -/// Trait for getting the length of packet data (used for rate limiting). -pub trait WithLen { - fn len(&self) -> usize; - - fn is_empty(&self) -> bool { - self.len() == 0 - } -} - -impl> WithLen for T { - fn len(&self) -> usize { - self.as_ref().len() - } -} - -/// Input events to the network emulator. -#[derive(Debug)] -pub enum Input { - /// A timeout has occurred at the given instant. - Timeout(Instant), - - /// A packet arrived at the given instant with the given data. - Packet(Instant, T), -} - -/// Output events from the network emulator. -#[derive(Debug)] -pub enum Output { - /// Request a timeout at the given instant. - Timeout(Instant), - - /// A packet is ready to be sent. - Packet(T), -} - -/// A queued packet waiting to be sent. -#[derive(Debug)] -struct QueuedPacket { - /// When this packet should be sent. - send_at: Instant, - - /// The packet data. - data: T, - - /// Ever increasing counter to break ties when send_at is the same. - packet_index: u64, -} - -fn not_happening() -> Instant { - Instant::now() + Duration::from_secs(3600 * 24 * 365 * 10) -} - -impl PartialEq for QueuedPacket { - fn eq(&self, other: &Self) -> bool { - self.send_at == other.send_at && self.packet_index == other.packet_index - } -} - -impl Eq for QueuedPacket {} - -impl PartialOrd for QueuedPacket { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for QueuedPacket { - fn cmp(&self, other: &Self) -> Ordering { - self.packet_index - .cmp(&other.packet_index) - .then(self.send_at.cmp(&other.send_at)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn instant() -> Instant { - Instant::now() - } - - #[test] - fn test_passthrough() { - let config = NetemConfig::default(); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - netem.handle_input(Input::Packet(now, vec![1, 2, 3])); - - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(data)) if data == vec![1, 2, 3])); - assert!(netem.poll_output().is_none()); - } - - #[test] - fn test_latency() { - let config = NetemConfig::new().latency(Duration::from_millis(100)).seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - netem.handle_input(Input::Packet(now, vec![1, 2, 3])); - - // Should get a timeout, not the packet - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Timeout(t)) if t > now)); - - // After the timeout, packet should be ready - let later = now + Duration::from_millis(100); - netem.handle_input(Input::Timeout(later)); - - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(data)) if data == vec![1, 2, 3])); - } - - #[test] - fn test_total_loss() { - let config = NetemConfig::new().loss(RandomLoss::new(Probability::ONE)).seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - netem.handle_input(Input::Packet(now, vec![1, 2, 3])); - - assert!(netem.poll_output().is_none()); - assert!(netem.is_empty()); - } - - #[test] - fn test_duplication() { - let config = NetemConfig::new().duplicate(Probability::ONE).seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - netem.handle_input(Input::Packet(now, vec![1, 2, 3])); - - // Should get two packets - assert!(matches!(netem.poll_output(), Some(Output::Packet(_)))); - assert!(matches!(netem.poll_output(), Some(Output::Packet(_)))); - assert!(netem.poll_output().is_none()); - } - - #[test] - fn test_rate_limiting() { - // 8 kbps = 1000 bytes/sec, large buffer to avoid drops - let config = NetemConfig::new().link(Bitrate::kbps(8), DataSize::kbytes(10)).seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - - // Send 100 bytes - netem.handle_input(Input::Packet(now, vec![0; 100])); - - // First packet should be immediate - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(_)))); - - // Send another 100 bytes immediately after - netem.handle_input(Input::Packet(now, vec![0; 100])); - - // Second packet should require a timeout (rate limited) - let output = netem.poll_output(); - match output { - Some(Output::Timeout(t)) => { - // Should be delayed by ~100ms (100 bytes at 1000 bytes/sec) - let delay = t - now; - assert!(delay >= Duration::from_millis(90)); - assert!(delay <= Duration::from_millis(110)); - } - _ => panic!("Expected timeout, got {:?}", output), - } - } - - #[test] - fn test_reordering() { - let config = NetemConfig::new() - .latency(Duration::from_millis(100)) - .reorder_gap(3) // Every 3rd packet is reordered - .seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - - // Send 3 packets - netem.handle_input(Input::Packet(now, vec![1])); - netem.handle_input(Input::Packet(now, vec![2])); - netem.handle_input(Input::Packet(now, vec![3])); // This one should be reordered before packet 2 - - // All packets are delayed by latency, so we get a timeout first - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Timeout(t)) if t == now + Duration::from_millis(100))); - - // After the timeout, packets should be ready in reordered sequence: 1, 3, 2 - let later = now + Duration::from_millis(100); - netem.handle_input(Input::Timeout(later)); - - // Packet 1 comes first (lowest index) - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(data)) if data == vec![1])); - - // Packet 3 comes second (reordered before packet 2) - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(data)) if data == vec![3])); - - // Packet 2 comes last - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(data)) if data == vec![2])); - } - - #[test] - fn test_reordering_with_rate_limiting() { - // 8 kbps = 1024 bytes/sec, large buffer to avoid drops - let config = NetemConfig::new() - .link(Bitrate::kbps(8), DataSize::kbytes(10)) - .reorder_gap(3) // Every 3rd packet is reordered - .seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - - // Send 3 packets of 100 bytes each - netem.handle_input(Input::Packet(now, vec![0; 100])); - netem.handle_input(Input::Packet(now, vec![0; 100])); - netem.handle_input(Input::Packet(now, vec![0; 100])); // Reordered - - // First packet should be immediate (no latency configured) - let output = netem.poll_output(); - assert!(matches!(output, Some(Output::Packet(_)))); - - // Next output should be a timeout (rate limited) - // The reordered packet (3rd) shares the slot with packet 2 - let output = netem.poll_output(); - match output { - Some(Output::Timeout(t)) => { - // Should be delayed by ~100ms (100 bytes at 1000 bytes/sec) - let delay = t - now; - assert!( - delay >= Duration::from_millis(90), - "Reordered packet should respect rate limiting, got delay {:?}", - delay - ); - } - _ => panic!("Expected timeout for rate-limited reordered packet, got {:?}", output), - } - } - - #[test] - fn test_gilbert_elliot_preset() { - let config = NetemConfig::new() - .loss(LossModel::GilbertElliot(GilbertElliot::wifi())) - .seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - let mut received = 0; - let total = 1000; - - for i in 0..total { - netem.handle_input(Input::Packet(now, vec![i as u8])); - while let Some(output) = netem.poll_output() { - if matches!(output, Output::Packet(_)) { - received += 1; - } - } - } - - // WiFi preset should have ~1% loss, so ~990 received - let loss_ratio = 1.0 - (received as f32 / total as f32); - assert!((0.005..=0.05).contains(&loss_ratio), "Loss ratio: {}", loss_ratio); - } - - #[test] - fn test_buffer_overflow_drops_packets() { - // 80 kbps = 10KB/sec, tiny 100 byte buffer - // This means only ~1 packet of 100 bytes can be queued - let config = NetemConfig::new() - .link(Bitrate::kbps(80), DataSize::bytes(100)) - .seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - - // Send 5 packets of 100 bytes each at once - // Only the first should be accepted, rest should be dropped due to buffer overflow - for i in 0..5 { - netem.handle_input(Input::Packet(now, vec![i; 100])); - } - - // Count how many packets we actually receive - let mut received = 0; - while let Some(output) = netem.poll_output() { - match output { - Output::Packet(_) => received += 1, - Output::Timeout(t) => { - // Advance time to release next packet - netem.handle_input(Input::Timeout(t)); - } - } - } - - // With a 100 byte buffer and 100 byte packets, only 1-2 should fit - assert!( - received < 5, - "Expected buffer overflow to drop packets, but received all {received}" - ); - assert!( - received >= 1, - "Expected at least one packet to be delivered, got {received}" - ); - } - - #[test] - fn test_congestion_causes_delay_then_loss() { - // 80 kbps = 10KB/sec, 500 byte buffer (~50ms worth at this rate) - // This allows ~5 packets of 100 bytes each to be queued - let config = NetemConfig::new() - .link(Bitrate::kbps(80), DataSize::bytes(500)) - .seed(42); - let mut netem: Netem> = Netem::new(config); - - let now = instant(); - - // Send many packets to cause congestion and buffer overflow - // 20 packets * 100 bytes = 2000 bytes, but buffer is only 500 bytes - for i in 0..20 { - netem.handle_input(Input::Packet(now, vec![i; 100])); - } - - // First packet should be immediate (no queue yet) - let first = netem.poll_output(); - assert!(matches!(first, Some(Output::Packet(_)))); - - // Next should be a timeout (queued due to rate limiting) - let second = netem.poll_output(); - match second { - Some(Output::Timeout(t)) => { - // Delay should be positive (congestion causing queue buildup) - assert!(t > now, "Expected queuing delay"); - } - _ => panic!("Expected timeout due to rate limiting"), - } - - // Advance time to release all remaining packets - // Send a dummy packet at a far future time to advance current_time - let far_future = now + Duration::from_secs(10); - netem.handle_input(Input::Packet(far_future, vec![])); - - // Count total packets received (including the first one we already got) - let mut received = 1; - while let Some(output) = netem.poll_output() { - if matches!(output, Output::Packet(_)) { - received += 1; - } - } - - // Should have lost some packets due to buffer overflow - // With 500 byte buffer and 100 byte packets: - // - First packet sent immediately (no queue) - // - 5 more packets can be buffered (500 bytes) - // - Remaining 14 packets should be dropped - // Expected: ~6 packets total (plus the dummy 0-byte packet) - assert!( - received < 20, - "Expected buffer overflow to cause loss, but received all {received}" - ); - assert!( - received >= 5, - "Expected some packets to get through, only got {received}" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/netem/loss.rs b/rs/moq-webrtc/src/vendor/netem/loss.rs deleted file mode 100644 index fbbb0531ed9..00000000000 --- a/rs/moq-webrtc/src/vendor/netem/loss.rs +++ /dev/null @@ -1,165 +0,0 @@ -use fastrand::Rng; - -use crate::vendor::netem::config::{GilbertElliot, LossModel, RandomLoss}; - -/// State for the loss model evaluation. -#[derive(Debug, Clone)] -pub(crate) enum LossState { - /// No loss - no state needed. - None, - - /// State for random loss with correlation. - Random { - /// Last random value for correlated loss. - last_random: f32, - }, - - /// State for Gilbert-Elliot loss model. - GilbertElliot { - /// Current state in the Markov chain (true = Good, false = Bad). - in_good_state: bool, - }, -} - -impl LossState { - pub fn new(model: &LossModel) -> Self { - match model { - LossModel::None => LossState::None, - LossModel::Random(_) => LossState::Random { last_random: 0.0 }, - LossModel::GilbertElliot(_) => LossState::GilbertElliot { in_good_state: true }, - } - } - - /// Evaluate whether a packet should be lost. - /// - /// Returns `true` if the packet should be dropped. - pub fn should_lose(&mut self, model: &LossModel, rng: &mut Rng) -> bool { - match (self, model) { - (LossState::None, LossModel::None) => false, - (LossState::Random { last_random }, LossModel::Random(random)) => evaluate_random(last_random, random, rng), - (LossState::GilbertElliot { in_good_state }, LossModel::GilbertElliot(ge)) => { - evaluate_gilbert_elliot(in_good_state, ge, rng) - } - _ => false, - } - } -} - -/// Evaluate the random loss model with optional correlation. -fn evaluate_random(last_random: &mut f32, random: &RandomLoss, rng: &mut Rng) -> bool { - let rho = random.correlation; - - let value = if rho == 0.0 { - let v = rng.f32(); - *last_random = v; - v - } else { - let fresh = rng.f32(); - let v = fresh * (1.0 - rho) + *last_random * rho; - *last_random = v; - v - }; - - value < random.probability -} - -/// Evaluate the Gilbert-Elliot loss model. -/// -/// First, potentially transition between GOOD and BAD states. -/// Then, decide whether to lose the packet based on current state. -fn evaluate_gilbert_elliot(in_good_state: &mut bool, ge: &GilbertElliot, rng: &mut Rng) -> bool { - // State transition - if *in_good_state { - if rng.f32() < ge.p { - *in_good_state = false; - } - } else if rng.f32() < ge.r { - *in_good_state = true; - } - - // Loss decision based on current state - if *in_good_state { - rng.f32() < ge.k - } else { - rng.f32() < ge.h - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::netem::config::Probability; - - #[test] - fn test_no_loss() { - let model = LossModel::None; - let mut state = LossState::new(&model); - let mut rng = Rng::with_seed(42); - - for _ in 0..100 { - assert!(!state.should_lose(&model, &mut rng)); - } - } - - #[test] - fn test_random_loss_zero() { - let model = LossModel::Random(RandomLoss::new(Probability::ZERO)); - let mut state = LossState::new(&model); - let mut rng = Rng::with_seed(42); - - for _ in 0..100 { - assert!(!state.should_lose(&model, &mut rng)); - } - } - - #[test] - fn test_random_loss_one() { - let model = LossModel::Random(RandomLoss::new(Probability::ONE)); - let mut state = LossState::new(&model); - let mut rng = Rng::with_seed(42); - - for _ in 0..100 { - assert!(state.should_lose(&model, &mut rng)); - } - } - - #[test] - fn test_random_loss_half() { - let model = LossModel::Random(RandomLoss::new(Probability::new(0.5))); - let mut state = LossState::new(&model); - let mut rng = Rng::with_seed(42); - - let mut lost = 0; - let total = 10000; - - for _ in 0..total { - if state.should_lose(&model, &mut rng) { - lost += 1; - } - } - - // Should be roughly 50% with some tolerance - let ratio = lost as f32 / total as f32; - assert!((0.45..=0.55).contains(&ratio), "Loss ratio: {}", ratio); - } - - #[test] - fn test_gilbert_elliot_wifi() { - let model = LossModel::GilbertElliot(GilbertElliot::wifi()); - let mut state = LossState::new(&model); - let mut rng = Rng::with_seed(42); - - let mut lost = 0; - let total = 10000; - - for _ in 0..total { - if state.should_lose(&model, &mut rng) { - lost += 1; - } - } - - // WiFi preset should be around 1% loss - let ratio = lost as f32 / total as f32; - assert!((0.005..=0.03).contains(&ratio), "Loss ratio: {}", ratio); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/LICENSE-MIT.txt b/rs/moq-webrtc/src/vendor/str0m/LICENSE-MIT.txt deleted file mode 100644 index 235abe2ca4c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/LICENSE-MIT.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2022 Martin Algesten - -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. diff --git a/rs/moq-webrtc/src/vendor/str0m/change/direct.rs b/rs/moq-webrtc/src/vendor/str0m/change/direct.rs deleted file mode 100644 index cd2deca7063..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/change/direct.rs +++ /dev/null @@ -1,322 +0,0 @@ -use std::sync::Arc; - -use crate::vendor::str0m::Candidate; -use crate::vendor::str0m::IceCreds; -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::crypto::Fingerprint; -use crate::vendor::str0m::crypto::dtls::ProtocolVersion; -use crate::vendor::str0m::media::{Media, MediaKind}; -use crate::vendor::str0m::poll::RtcMut; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::{Mid, Rid, Ssrc}; -use crate::vendor::str0m::streams::{DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP, StreamRx, StreamTx}; - -/// Direct change strategy. -/// -/// Makes immediate changes to the Rtc session without any SDP OFFER/ANSWER. This -/// is an alternative to [`Rtc::sdp_api()`] for use cases when you don’t want to use SDP -/// (or when you want to write RTP directly). -/// -/// To use the Direct API together with a browser client, you would need to make -/// the equivalent changes on the browser side by manually generating the correct -/// SDP OFFER/ANSWER to make the `RTCPeerConnection` match str0m's state. -/// -/// To change str0m's state through the Direct API followed by the SDP API produce -/// an SDP OFFER is not a supported use case. Either pick SDP API and let str0m handle -/// the OFFER/ANSWER or use Direct API and deal with SDP manually. Not both. -/// -///

This is a low level API. -/// -/// str0m normally guarantees that user input cannot cause panics. -/// However as an exception, the Direct API does allow the user to configure the -/// session in a way that is internally inconsistent. Such situations can -/// result in panics. -///
-pub struct DirectApi<'a> { - // `RtcMut` arms the readiness on mutable deref only, so the `&mut self` - // methods below re-poll the tree while the `&self` readers do not - with no - // per-method call to forget. See [`crate::vendor::str0m::poll`]. - rtc: RtcMut<'a>, -} - -impl<'a> DirectApi<'a> { - /// Creates a new instance of the `DirectApi` struct with the specified `Rtc` instance. - /// - /// The `DirectApi` struct provides a high-level API for interacting with a WebRTC peer connection, - /// and the `Rtc` instance provides low-level access to the underlying WebRTC functionality. - pub fn new(rtc: &'a mut Rtc) -> Self { - DirectApi { rtc: RtcMut::new(rtc) } - } - - /// Sets the ICE controlling flag for this peer connection. - /// - /// If `controlling` is `true`, this peer connection is set as the ICE controlling agent, - /// meaning it will take the initiative to send connectivity checks and control the pace of - /// connectivity checks sent between two peers during the ICE session. - /// - /// If `controlling` is `false`, this peer connection is set as the ICE controlled agent, - /// meaning it will respond to connectivity checks sent by the controlling agent. - pub fn set_ice_controlling(&mut self, controlling: bool) { - self.rtc.ice.set_controlling(controlling); - } - - /// Returns a reference to the local ICE credentials used by this peer connection. - /// - /// The ICE credentials consist of the username and password used by the ICE agent during - /// the ICE session to authenticate and exchange connectivity checks with the remote peer. - pub fn local_ice_credentials(&self) -> IceCreds { - self.rtc.ice.local_credentials().clone() - } - - /// Sets the local ICE credentials. - pub fn set_local_ice_credentials(&mut self, local_ice_credentials: IceCreds) { - self.rtc.ice.set_local_credentials(local_ice_credentials); - } - - /// Sets the remote ICE credentials. - pub fn set_remote_ice_credentials(&mut self, remote_ice_credentials: IceCreds) { - self.rtc.ice.set_remote_credentials(remote_ice_credentials); - } - - /// Invalidate a candidate and remove it from the connection. - /// - /// This is done for host candidates disappearing due to changes in the network - /// interfaces like a WiFi disconnecting or changing IPs. - /// - /// It can also be used to invalidate _remote_ candidates, i.e. if the remote - /// has signalled us that they have invalidated one of their candidates. - /// - /// Returns `true` if the candidate was found and invalidated. - pub fn invalidate_candidate(&mut self, c: &Candidate) -> bool { - self.rtc.ice.invalidate_candidate(c) - } - - /// Returns a reference to the local DTLS fingerprint used by this peer connection. - /// - /// The DTLS fingerprint is a hash of the local SSL/TLS certificate used to authenticate the - /// peer connection and establish a secure communication channel between the peers. - pub fn local_dtls_fingerprint(&self) -> &Fingerprint { - self.rtc.dtls.local_fingerprint() - } - - /// Returns a reference to the remote DTLS fingerprint used by this peer connection. - pub fn remote_dtls_fingerprint(&self) -> Option<&Fingerprint> { - self.rtc.dtls.remote_fingerprint() - } - - /// Returns the negotiated DTLS protocol version. - /// - /// Call this after receiving [`crate::vendor::str0m::Event::Connected`] - /// to learn the negotiated DTLS version. Before the handshake completes, - /// this may return `None` - pub fn dtls_protocol_version(&self) -> Option { - self.rtc.dtls.protocol_version() - } - - /// Sets the remote DTLS fingerprint. - pub fn set_remote_fingerprint(&mut self, dtls_fingerprint: Fingerprint) { - self.rtc.remote_fingerprint = Some(dtls_fingerprint); - } - - /// Start the DTLS subsystem. - pub fn start_dtls(&mut self, active: bool) -> Result<(), RtcError> { - self.rtc.init_dtls(active) - } - - /// Set whether to enable ice-lite. - pub fn set_ice_lite(&mut self, ice_lite: bool) { - self.rtc.ice.set_ice_lite(ice_lite); - } - - /// Enable twcc feedback. - pub fn enable_twcc_feedback(&mut self) { - self.rtc.session.enable_twcc_feedback() - } - - /// Generate a ssrc that is not already used in session - pub fn new_ssrc(&self) -> Ssrc { - self.rtc.session.streams.new_ssrc() - } - - /// Create a new `Media`. - /// - /// All streams belong to a media identified by a `mid`. This creates the media without - /// doing any SDP dance. - pub fn declare_media(&mut self, mid: Mid, kind: MediaKind) -> &mut Media { - let max_index = self.rtc.session.medias.iter().map(|m| m.index()).max(); - - let next_index = if let Some(max_index) = max_index { - max_index + 1 - } else { - 0 - }; - - let exts = self.rtc.session.exts.cloned_with_type(kind.is_audio()); - let m = Media::from_direct_api(mid, next_index, kind, exts); - - self.rtc.session.medias.push(m); - self.rtc.session.medias.last_mut().unwrap() - } - - /// Remove `Media`. - /// - /// Removes media and all streams belong to a media identified by a `mid`. - pub fn remove_media(&mut self, mid: Mid) { - self.rtc.session.remove_media(mid); - } - - /// Allow incoming traffic from remote peer for the given SSRC. - /// - /// Can be called multiple times if the `rtx` is discovered later via RTP header extensions. - pub fn expect_stream_rx(&mut self, ssrc: Ssrc, rtx: Option, mid: Mid, rid: Option) -> &mut StreamRx { - let Some(_media) = self.rtc.session.media_by_mid(mid) else { - panic!("No media declared for mid: {}", mid); - }; - - // By default we do not suppress nacks, this has to be called explicitly by the user of direct API. - let suppress_nack = false; - - let midrid = MidRid(mid, rid); - - self.rtc - .session - .streams - .expect_stream_rx(ssrc, rtx, midrid, suppress_nack) - } - - /// Remove the receive stream for the given SSRC. - /// - /// Returns true if stream existed and was removed. - pub fn remove_stream_rx(&mut self, ssrc: Ssrc) -> bool { - self.rtc.session.streams.remove_stream_rx(ssrc) - } - - /// Obtain a receive stream. - /// - /// In RTP mode, the receive stream is used to signal keyframe requests. - /// - /// The stream must first be declared using [`DirectApi::expect_stream_rx`]. - pub fn stream_rx(&mut self, ssrc: &Ssrc) -> Option<&mut StreamRx> { - self.rtc.session.streams.stream_rx(ssrc) - } - - /// Obtain a recv stream by looking it up via mid/rid. - pub fn stream_rx_by_mid(&mut self, mid: Mid, rid: Option) -> Option<&mut StreamRx> { - let midrid = MidRid(mid, rid); - self.rtc.session.streams.stream_rx_by_midrid(midrid) - } - - /// Declare the intention to send data using the given SSRC. - /// - /// * The resend RTX is optional but necessary to do resends. str0m does not do - /// resends without RTX. - /// - /// Can be called multiple times without changing any internal state. However - /// the RTX value is only picked up the first ever time we see a new SSRC. - pub fn declare_stream_tx(&mut self, ssrc: Ssrc, rtx: Option, mid: Mid, rid: Option) -> &mut StreamTx { - // One arming deref, then split-borrow the real `&mut Rtc`. - let rtc = &mut *self.rtc; - - let Some(media) = rtc.session.media_by_mid_mut(mid) else { - panic!("No media declared for mid: {}", mid); - }; - - let is_audio = media.kind().is_audio(); - - let midrid = MidRid(mid, rid); - - // If there is a RID tx, declare it so we an use it in Writer API - if let Some(rid) = rid { - media.add_to_rid_tx(rid); - } - - let stream = rtc.session.streams.declare_stream_tx(ssrc, rtx, midrid); - - let size = if is_audio { - rtc.session.send_buffer_audio - } else { - rtc.session.send_buffer_video - }; - - stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP); - - stream - } - - /// Remove the transmit stream for the given SSRC. - /// - /// Returns true if stream existed and was removed. - pub fn remove_stream_tx(&mut self, ssrc: Ssrc) -> bool { - self.rtc.session.streams.remove_stream_tx(ssrc) - } - - /// Obtain a send stream to write RTP data directly. - /// - /// The stream must first be declared using [`DirectApi::declare_stream_tx`]. - pub fn stream_tx(&mut self, ssrc: &Ssrc) -> Option<&mut StreamTx> { - self.rtc.session.streams.stream_tx(ssrc) - } - - /// Obtain a send stream by looking it up via mid/rid. - pub fn stream_tx_by_mid(&mut self, mid: Mid, rid: Option) -> Option<&mut StreamTx> { - let midrid = MidRid(mid, rid); - self.rtc.session.streams.stream_tx_by_midrid(midrid) - } - - /// Reset a transmit stream to use a new SSRC and optionally a new RTX SSRC. - /// - /// This changes the SSRC of an existing stream and resets all relevant state. - /// Use this when you need to change the SSRC of an existing stream without creating a new one. - /// - /// If the stream has an RTX SSRC, `new_rtx` must be provided. If the stream doesn't - /// have an RTX SSRC, `new_rtx` is ignored. - /// - /// Returns a reference to the updated stream or None if: - /// - No stream was found for the given mid/rid - /// - The new SSRC is the same as the current one (no change needed) - /// - The new RTX SSRC is the same as the current one (no change needed) - pub fn reset_stream_tx( - &mut self, - mid: Mid, - rid: Option, - new_ssrc: Ssrc, - new_rtx: Option, - ) -> Option<&mut StreamTx> { - let midrid = MidRid(mid, rid); - - // Find the stream by mid/rid - let stream = self.rtc.session.streams.stream_tx_by_midrid(midrid)?; - - // Don't change to the same SSRC - if stream.ssrc() == new_ssrc { - return None; - } - - // If the stream has an RTX SSRC, New RTX must be provided and differ. - // But it is allowed to start or turn off RTX. - if stream.rtx().is_some() && stream.rtx() == new_rtx { - return None; - } - - // Reset the stream with the new SSRC and RTX - stream.reset_ssrc(new_ssrc, new_rtx); - - // Return a reference to the updated stream - Some(stream) - } - - /// Send a Picture Loss Indication (PLI, PT=206 FMT=1) for a media stream, - /// choosing the `sender_ssrc` of the outgoing RTCP feedback. - /// - /// The PLI is queued into the regular RTCP compound packet. The `sender_ssrc` - /// sets the feedback packet's sender SSRC. `media_ssrc` is the SSRC of the - /// stream a keyframe is requested for. - /// - /// Unlike requesting a keyframe on a local receive stream, this does not require a - /// receive stream for `media_ssrc` and lets the caller choose the sender SSRC, so it - /// can relay a keyframe request for a stream sourced by the remote peer. - pub fn send_pli_feedback(&mut self, sender_ssrc: Ssrc, media_ssrc: Ssrc) { - self.rtc.session.send_pli_feedback(sender_ssrc, media_ssrc); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/change/mod.rs b/rs/moq-webrtc/src/vendor/str0m/change/mod.rs deleted file mode 100644 index 369f297d2d2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/change/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! Ways to change the [`Rtc`][crate::vendor::str0m::Rtc] session. SDP or Direct. -//! -//! str0m has two main APIs for changing the WebRTC session. -//! -//! 1. SDP API. The common way to talk to browsers using SDP OFFER/ANSWER negotiations. -//! [`Rtc::sdp_api()`][crate::vendor::str0m::Rtc::sdp_api] -//! 2. Direct API. Makes changes directly to the session without any negotiation. -//! [`Rtc::direct_api()`][crate::vendor::str0m::Rtc::direct_api] -//! -//! ## Direct API -//! -//! The direct API is a lower level API which typically can't be mixed with the SDP API. If you make -//! changes directly to the session, the remote side would not be aware of them unless you construct -//! some "other way" keeping the two peers in sync. -mod sdp; -pub(crate) use sdp::AddMedia; -pub use sdp::{SdpAnswer, SdpApi, SdpOffer, SdpPendingOffer}; - -mod direct; -pub use direct::DirectApi; diff --git a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs deleted file mode 100644 index 72bb13ccee2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs +++ /dev/null @@ -1,2066 +0,0 @@ -//! Strategy that amends the [`Rtc`] via SDP OFFER/ANSWER negotiation. - -use std::fmt; -use std::ops::{Deref, DerefMut}; -use tracing::{debug, warn}; - -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::crypto::Fingerprint; -use crate::vendor::str0m::format::CodecConfig; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::media::{Media, Rids, Simulcast}; -use crate::vendor::str0m::packet::MediaKind; -use crate::vendor::str0m::poll::RtcMut; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::Rid; -use crate::vendor::str0m::rtp_::{Direction, Extension, ExtensionMap, Mid, Pt, Ssrc}; -use crate::vendor::str0m::sdp::{self, MediaAttribute, MediaLine, MediaType, Msid, Sdp}; -use crate::vendor::str0m::sdp::{Proto, SessionAttribute, Setup, SimulcastGroups}; -use crate::vendor::str0m::session::Session; -use crate::vendor::str0m::{Candidate, IceCreds}; -use crate::vendor::str0m_proto::Id; - -pub use crate::vendor::str0m::sdp::{SdpAnswer, SdpOffer}; -use crate::vendor::str0m::streams::{DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP, Streams}; - -/// Changes to the Rtc via SDP Offer/Answer dance. -/// -/// Only one local offer/answer exchange can be pending at a time. Applications must track -/// queued changes outside str0m and wait for the current exchange to finish before creating -/// another offer. If an incoming offer interrupts the exchange, recreate the desired local -/// changes against the updated session after answering that offer. -pub struct SdpApi<'a> { - // `RtcMut` arms the readiness on mutable deref only; see [`crate::vendor::str0m::poll`]. - rtc: RtcMut<'a>, - changes: Changes, -} - -impl<'a> SdpApi<'a> { - pub(crate) fn new(rtc: &'a mut Rtc) -> Self { - SdpApi { - rtc: RtcMut::new(rtc), - changes: Changes::default(), - } - } - - fn new_mid(&self) -> Mid { - loop { - let mid = self.rtc.new_mid(); - if !self.changes.has_mid(mid) { - break mid; - } - } - } - - /// Accept an [`SdpOffer`] from the remote peer. If this call returns successfully, the - /// changes will have been made to the session. The resulting [`SdpAnswer`] should be - /// sent to the remote peer. - /// - /// Note. Pending changes from a previous non-completed [`SdpApi`][super::SdpApi] will be - /// considered rolled back when calling this function. Any outstanding [`SdpPendingOffer`] - /// is invalidated, even if this call returns an error. The application must track and - /// recreate any local changes it still wants to negotiate. - /// - /// The incoming SDP is validated in various ways which can cause this call to fail. - /// Example of such problems would be an SDP without any m-lines, missing `a=fingerprint` - /// or if `a=group` doesn't match the number of m-lines. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::change::{SdpOffer}; - /// // obtain offer from remote peer. - /// let json_offer: &[u8] = todo!(); - /// let offer: SdpOffer = serde_json::from_slice(json_offer).unwrap(); - /// - /// let mut rtc = Rtc::new(Instant::now()); - /// let answer = rtc.sdp_api().accept_offer(offer).unwrap(); - /// - /// // send json_answer to remote peer. - /// let json_answer = serde_json::to_vec(&answer).unwrap(); - /// ``` - pub fn accept_offer(mut self, offer: SdpOffer) -> Result { - debug!("Accept offer"); - - // Invalidate any outstanding PendingOffer. - self.rtc.next_change_id(); - - if offer.media_lines.is_empty() { - return Err(RtcError::RemoteSdp("No m-lines in offer".into())); - } - - if self.rtc.ice.ice_lite() && offer.session.ice_lite() { - return Err(RtcError::RemoteSdp("Both peers being ICE-Lite not supported".into())); - } - - add_ice_details(&mut self.rtc, &offer, None)?; - - if self.rtc.remote_fingerprint.is_none() { - if let Some(f) = offer.fingerprint() { - self.rtc.remote_fingerprint = Some(f); - } else { - self.rtc.disconnect(); - return Err(RtcError::RemoteSdp("missing a=fingerprint".into())); - } - } - - if !self.rtc.dtls.is_inited() { - // The side that makes the first offer is the controlling side, unless they - // are ICE Lite, in which case the roles are reversed (see RFC 5245). - self.rtc.ice.set_controlling(offer.session.ice_lite()); - } - - // Ensure setup=active/passive is corresponding remote and init dtls. - init_dtls(&mut self.rtc, &offer)?; - - // Modify session with offer. An m=application line is answered rejected. - apply_offer(&mut self.rtc.session, offer)?; - - let params = AsSdpParams::new(&self.rtc, None); - let sdp = as_sdp(&self.rtc.session, params); - - debug!("Create answer"); - Ok(sdp.into()) - } - - /// Accept an answer to a previously created [`SdpOffer`]. - /// - /// This function returns an [`RtcError::ChangesOutOfOrder`] if we have created and applied another - /// [`SdpApi`][super::SdpApi] before calling this. The same also happens if we use - /// [`SdpApi::accept_offer()`] before using this pending instance. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::media::{MediaKind, Direction}; - /// # use crate::vendor::str0m::change::SdpAnswer; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let mut changes = rtc.sdp_api(); - /// let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - /// let (offer, pending) = changes.apply().unwrap(); - /// - /// // send offer to remote peer, receive answer back - /// let answer: SdpAnswer = todo!(); - /// - /// rtc.sdp_api().accept_answer(pending, answer).unwrap(); - /// ``` - pub fn accept_answer(mut self, pending: SdpPendingOffer, answer: SdpAnswer) -> Result<(), RtcError> { - debug!("Accept answer"); - - // Ensure we don't use the wrong changes below. We must use that of pending. - drop(self.changes); - - if !self.rtc.is_correct_change_id(pending.change_id) { - return Err(RtcError::ChangesOutOfOrder); - } - - if self.rtc.ice.ice_lite() && answer.session.ice_lite() { - return Err(RtcError::RemoteSdp("Both peers being ICE-Lite not supported".into())); - } - - add_ice_details(&mut self.rtc, &answer, Some(&pending))?; - - // Ensure setup=active/passive is corresponding remote and init dtls. - init_dtls(&mut self.rtc, &answer)?; - - if self.rtc.remote_fingerprint.is_none() { - if let Some(f) = answer.fingerprint() { - self.rtc.remote_fingerprint = Some(f); - } else { - self.rtc.disconnect(); - return Err(RtcError::RemoteSdp("missing a=fingerprint".into())); - } - } - - // Modify session with answer - apply_answer(&mut self.rtc.session, pending.changes, answer)?; - - Ok(()) - } - - /// Test if any changes have been made. - /// - /// If changes have been made, nothing happens until we call [`SdpApi::apply()`]. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{Rtc, media::MediaKind, media::Direction}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let mut changes = rtc.sdp_api(); - /// assert!(!changes.has_changes()); - /// - /// let mid = changes.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - /// assert!(changes.has_changes()); - /// # } - /// ``` - pub fn has_changes(&self) -> bool { - !self.changes.0.is_empty() - } - - /// Add audio or video media and get the `mid` that will be used. - /// - /// Each call will result in a new m-line in the offer identified by the [`Mid`]. - /// - /// The mid is not valid to use until the SDP offer-answer dance is complete and - /// the mid been advertised via [`Event::MediaAdded`][crate::vendor::str0m::Event::MediaAdded]. - /// - /// * `stream_id` is used to synchronize media. It is `a=msid-semantic: WMS ` line in SDP. - /// * `track_id` is becomes both the track id in `a=msid ` as well as the - /// CNAME in the RTP SDES. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{Rtc, media::MediaKind, media::Direction}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let mut changes = rtc.sdp_api(); - /// - /// let mid = changes.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - /// # } - /// ``` - pub fn add_media( - &mut self, - kind: MediaKind, - dir: Direction, - stream_id: Option, - track_id: Option, - simulcast: Option, - ) -> Mid { - let mid = self.new_mid(); - - // https://www.rfc-editor.org/rfc/rfc8830 - // msid-id = 1*64token-char - fn is_token_char(c: &char) -> bool { - // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 - // / %x41-5A / %x5E-7E - let u = *c as u32; - u == 0x21 - || (0x23..=0x27).contains(&u) - || (0x2a..=0x2b).contains(&u) - || (0x2d..=0x2e).contains(&u) - || (0x30..=0x39).contains(&u) - || (0x41..=0x5a).contains(&u) - || (0x5e..0x7e).contains(&u) - } - - let stream_id = if let Some(stream_id) = stream_id { - stream_id.chars().filter(is_token_char).take(64).collect() - } else { - Id::<20>::random().to_string() - }; - - let track_id = if let Some(track_id) = track_id { - track_id.chars().filter(is_token_char).take(64).collect() - } else { - Id::<20>::random().to_string() - }; - - let mut ssrcs = Vec::new(); - - // Main SSRC, not counting RTX. - let main_ssrc_count = simulcast.as_ref().map(|s| s.send.len()).unwrap_or(1); - - for _ in 0..main_ssrc_count { - let rtx = kind.is_video().then(|| self.rtc.session.streams.new_ssrc()); - ssrcs.push((self.rtc.session.streams.new_ssrc(), rtx)); - } - - // TODO: let user configure stream/track name. - let msid = Msid { - stream_id, - track_id: track_id.clone(), - }; - - let add = AddMedia { - mid, - cname: track_id, - msid, - kind, - dir, - ssrcs, - simulcast, - - // Added later - pts: vec![], - exts: ExtensionMap::empty(), - index: 0, - }; - - self.changes.0.push(Change::AddMedia(add)); - mid - } - - /// Change the direction of an already existing media. - /// - /// All media have a direction. The media can be added by this side via - /// [`SdpApi::add_media()`] or by the remote peer. Either way, the direction - /// of the line can be changed at any time. - /// - /// It's possible to set the direction [`Direction::Inactive`] for media that - /// will not be used by the session anymore. - /// - /// If the direction is set for media that doesn't exist, or if the direction is - /// the same that's already set [`SdpApi::apply()`] not require a negotiation. - pub fn set_direction(&mut self, mid: Mid, dir: Direction) { - let changed = self.rtc.session.set_direction(mid, dir); - - if changed { - self.changes.0.push(Change::Direction(mid, dir)); - } - } - - /// Stop an already existing media. - /// - /// The next generated offer emits the m-line with port 0 and excludes - /// it from the BUNDLE group, per [RFC 8843] §7.5.3. The remote - /// transceiver transitions to the "stopped" state and the m-line slot - /// becomes eligible for recycling. - /// - /// Unlike [`SdpApi::set_direction()`] with [`Direction::Inactive`], - /// a stopped m-line cannot be reactivated. - /// - /// If the media doesn't exist, or is already stopped, [`SdpApi::apply()`] - /// will not require a negotiation. - /// - /// [RFC 8843]: https://datatracker.ietf.org/doc/html/rfc8843#section-7.5.3 - pub fn stop_media(&mut self, mid: Mid) { - let changed = self.rtc.session.stop_media(mid); - - if changed { - self.changes.0.push(Change::Direction(mid, Direction::Inactive)); - } - } - - /// Perform an ICE restart. - /// - /// Only one ICE restart can be pending at the time. Calling this repeatedly removes any other - /// pending ICE restart. - /// - /// The local ICE candidates can be kept as is, or be cleared out, in which case new ice - /// candidates must be added via [`Rtc::add_local_candidate`] before connectivity can be - /// re-established. - /// - /// Returns the new ICE credentials that will be used going forward. - pub fn ice_restart(&mut self, keep_local_candidates: bool) -> IceCreds { - self.changes.retain(|c| !matches!(c, Change::IceRestart(_, _))); - - let new_creds = IceCreds::new(); - self.changes - .push(Change::IceRestart(new_creds.clone(), keep_local_candidates)); - - new_creds - } - - /// Attempt to apply the changes made. - /// - /// If this returns [`SdpOffer`], the caller the changes are - /// not happening straight away, and the caller is expected to do a negotiation with the remote - /// peer and apply the answer using [`SdpPendingOffer`]. - /// - /// In case this returns `None`, there were no changes. - /// - /// The [`SdpPendingOffer`] is valid until the next time we call this function, at which - /// point using it will raise an error. Using [`SdpApi::accept_offer()`] will also invalidate - /// the current [`SdpPendingOffer`]. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let changes = rtc.sdp_api(); - /// assert!(changes.apply().is_none()); - /// # } - /// ``` - pub fn apply(mut self) -> Option<(SdpOffer, SdpPendingOffer)> { - if self.changes.is_empty() { - return None; - } - - let change_id = self.rtc.next_change_id(); - - let offer = create_offer(&mut self.rtc, &self.changes); - let pending = SdpPendingOffer { - change_id, - changes: self.changes, - }; - debug!("Create offer"); - Some((offer, pending)) - } -} - -/// Pending offer from a previous [`Rtc::sdp_api()`] call. -/// -/// Represents one local negotiation change set, which can contain multiple media -/// changes, and allows accepting its remote answer. It is not a queue of pending negotiations. -/// Creating another offer with [`SdpApi::apply()`] invalidates it, as does calling -/// [`SdpApi::accept_offer()`]. Invalidated changes cannot be reapplied through this token. -/// Applications must track queued changes outside str0m and recreate any desired changes -/// after an interrupted negotiation against the current session state. -/// -/// No changes have been made to the session -/// before we call [`SdpApi::accept_answer()`], which means that rolling back a -/// change is as simple as dropping this instance. -/// -/// ```ignore -/// # use std::time::Instant; -/// # use crate::vendor::str0m::Rtc; -/// # use crate::vendor::str0m::media::{MediaKind, Direction}; -/// # use crate::vendor::str0m::change::SdpAnswer; -/// let mut rtc = Rtc::new(Instant::now()); -/// -/// let mut changes = rtc.sdp_api(); -/// let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); -/// let (offer, pending) = changes.apply().unwrap(); -/// -/// // send offer to remote peer, receive answer back -/// let answer: SdpAnswer = todo!(); -/// -/// rtc.sdp_api().accept_answer(pending, answer).unwrap(); -/// ``` -pub struct SdpPendingOffer { - change_id: usize, - changes: Changes, -} - -#[derive(Default)] -pub(crate) struct Changes(pub Vec); - -impl Changes { - /// Details of the active ICE restart, if any. - /// - /// Returns the new local ICE credentials and the whether to keep local ICE candidates if an - /// ICE restart has been initiated in the offer, otherwise [`None`]. - fn ice_restart(&self) -> Option<(IceCreds, bool)> { - self.iter().find_map(|c| match c { - Change::IceRestart(creds, keep_local_candidates) => Some((creds.clone(), *keep_local_candidates)), - _ => None, - }) - } -} - -#[derive(Debug)] -#[allow(clippy::large_enum_variant)] -pub(crate) enum Change { - AddMedia(AddMedia), - Direction(Mid, Direction), - IceRestart(IceCreds, bool), -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct AddMedia { - pub mid: Mid, - pub cname: String, - pub msid: Msid, - pub kind: MediaKind, - pub dir: Direction, - pub ssrcs: Vec<(Ssrc, Option)>, - pub simulcast: Option, - - // pts and index are filled in when creating the SDP OFFER. - // The default PT order is set by the Session (BUNDLE). - // TODO: We can make this configurable here too. - pub pts: Vec, - pub exts: ExtensionMap, - pub index: usize, -} - -impl Deref for Changes { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for Changes { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -fn create_offer(rtc: &mut Rtc, changes: &Changes) -> SdpOffer { - if !rtc.dtls.is_inited() { - // The side that makes the first offer is the controlling side, unless they - // are ICE Lite, in which case the roles are reversed (see RFC 5245). - rtc.ice.set_controlling(!rtc.ice.ice_lite()); - } - - let params = AsSdpParams::new(rtc, Some(changes)); - let sdp = as_sdp(&rtc.session, params); - - sdp.into() -} - -fn add_ice_details(rtc: &mut Rtc, sdp: &Sdp, pending: Option<&SdpPendingOffer>) -> Result<(), RtcError> { - let Some(creds) = sdp.ice_creds() else { - return Err(RtcError::RemoteSdp("missing a=ice-ufrag/pwd".into())); - }; - - // If we are handling an **offer** from the remote, differing ICE credentials indicate an ICE - // restart initiated by the remote. - // - // If we are handling an **answer** from the remote, differing ICE credentials indicate an - // acceptance of an ICE restart we requested. - let ice_restart = match rtc.ice.remote_credentials() { - Some(v) => *v != creds, - None => false, - }; - if ice_restart { - let (new_local_creds, keep_local_candidates) = if let Some(pending) = pending { - // Since we have a pending, this is an answer to our offer. - pending.changes.ice_restart().ok_or_else(|| - // Answer contained changed remote creds, indicating an ice restart - // but since we have no pending ice-creds, we didn't initiate it - // Ice restart in an ANSWER breaks spec. - RtcError::RemoteSdp( - "Ice restart in answer without one in the preceeding offer".into(), - ))? - } else { - // The remote OFFER had an ice restart, and we need to respond with - // new credentials in the ANSWER. - (IceCreds::new(), true) - }; - - rtc.ice.ice_restart(new_local_creds.clone(), keep_local_candidates); - } - - rtc.ice.set_remote_credentials(creds); - - for r in sdp.ice_candidates() { - rtc.ice.add_remote_candidate(r.clone()); - } - - Ok(()) -} - -fn init_dtls(rtc: &mut Rtc, remote_sdp: &Sdp) -> Result<(), RtcError> { - let setup = match remote_sdp.setup() { - Some(v) => match v { - // Remote being ActPass, we take Passive role. - Setup::ActPass => Setup::Passive, - _ => v.invert(), - }, - - None => { - warn!("Missing a=setup line"); - Setup::Passive - } - }; - - let active = setup == Setup::Active; - rtc.init_dtls(active)?; - - Ok(()) -} - -fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp { - let (media_lines, mids, stream_ids) = { - let mut v = as_media_lines(session); - - let mut new_lines = vec![]; - - // When creating new m-lines from the pending changes, the m-line index starts from this. - let new_index_start = v.len(); - - // If there are additions in the pending changes, prepend them now. - if let Some(pending) = params.pending { - new_lines = pending - .as_new_medias(new_index_start, &session.codec_config, &session.exts) - .collect(); - } - - // Add potentially new m-lines to the existing ones. - v.extend(new_lines.iter().map(|n| n as &dyn AsSdpMediaLine)); - - // Turn into sdp::MediaLine (m-line). - let mut lines = v - .iter() - .map(|m| { - // Candidates go on the first accepted line, added below. - let attrs = params.media_attributes(false); - - // Already made send stream SSRCs - let mut ssrcs = session.streams.ssrcs_tx(m.mid()); - - // Merged with pending stream SSRCs - if let Some(pending) = params.pending { - ssrcs.extend(pending.ssrcs_for_mid(m.mid())) - } - - let params: Vec<_> = session.codec_config.all_for_kind(m.kind()).cloned().collect(); - - m.as_media_line(attrs, &ssrcs, &session.exts, ¶ms) - }) - .collect::>(); - - if let Some(pending) = params.pending { - pending.apply_to(&mut lines); - } - - // Candidates belong in the first BUNDLE mid, which is the first accepted line: a - // rejected line ahead of it, such as an offered data channel, is out of the group. - let first = lines.iter().position(|l| !l.disabled).unwrap_or(0); - if let Some(line) = lines.get_mut(first) { - let candidates = params.candidates.iter().map(|c| MediaAttribute::Candidate(c.clone())); - line.attrs.splice(0..0, candidates); - } - - // Mids go into the session part of the SDP. - // Rejected (disabled) m-lines must not be part of the BUNDLE group. - let mids = lines.iter().filter(|l| !l.disabled).map(|l| l.mid()).collect(); - - let mut stream_ids = vec![]; - for msid in v.iter().filter_map(|v| v.msid()) { - if !stream_ids.contains(&msid.stream_id) { - stream_ids.push(msid.stream_id.clone()); - } - } - - (lines, mids, stream_ids) - }; - - // AllowMixedExts adds "a=extmap-allow-mixed" at session level to signal - // support for mixing one-byte and two-byte RTP header extensions. - // TODO: It would make sense to perform an actual negotiation, however - // just adding this line should work fine: - // https://github.com/meetecho/janus-gateway/blob/d2e74fdf9bb8aa7a39ed68ed28394afe1e0cd22d/src/sdp.c#L1519 - let mut attrs = vec![ - SessionAttribute::Group { - typ: "BUNDLE".into(), - mids, - }, - SessionAttribute::AllowMixedExts, - SessionAttribute::MsidSemantic { - semantic: "WMS".to_string(), - stream_ids, - }, - ]; - - if session.ice_lite { - attrs.push(SessionAttribute::IceLite); - } - - Sdp { - session: sdp::Session { - id: session.id(), - bw: None, - attrs, - }, - media_lines, - } -} - -fn apply_offer(session: &mut Session, offer: SdpOffer) -> Result<(), RtcError> { - offer.assert_consistency()?; - - update_session(session, &offer); - - let bundle_mids = offer.bundle_mids(); - let new_lines = sync_medias(session, &offer, true).map_err(RtcError::RemoteSdp)?; - - add_new_lines(session, &new_lines, true, bundle_mids).map_err(RtcError::RemoteSdp)?; - - ensure_stream_tx(session); - - Ok(()) -} - -fn apply_answer(session: &mut Session, pending: Changes, answer: SdpAnswer) -> Result<(), RtcError> { - answer.assert_consistency()?; - - update_session(session, &answer); - - let bundle_mids = answer.bundle_mids(); - let new_lines = sync_medias(session, &answer, false).map_err(RtcError::RemoteSdp)?; - - // The new_lines from the answer must correspond to what we sent in the offer. - if let Some(err) = pending.ensure_correct_answer(&new_lines) { - return Err(RtcError::RemoteSdp(err)); - } - - add_new_lines(session, &new_lines, false, bundle_mids).map_err(RtcError::RemoteSdp)?; - - // Add all pending changes (since we pre-allocated SSRC communicated in the Offer). - add_pending_changes(session, pending); - - ensure_stream_tx(session); - - Ok(()) -} - -fn ensure_stream_tx(session: &mut Session) { - for media in &session.medias { - // Only make send streams when we have to. - if !media.direction().is_sending() { - continue; - } - - let mut rids: Vec> = vec![]; - - if let Some(sim) = media.simulcast() { - for layer in &*sim.send { - let rid: Rid = layer.restriction_id.0.as_str().into(); - rids.push(Some(rid)); - } - } else { - rids.push(None); - } - - // If any payload param has RTX, we need to prepare for RTX. This is because we always - // communicate a=ssrc lines, which need to be complete with main and RTX SSRC. - let has_rtx = session - .codec_config - .iter() - .filter(|p| media.remote_pts().contains(&p.pt)) - .any(|p| p.resend().is_some()); - - for rid in rids { - let midrid = MidRid(media.mid(), rid); - - // If we already have the stream, we don't make any new one. - let has_stream = session.streams.stream_tx_by_midrid(midrid).is_some(); - - if has_stream { - continue; - } - - let (ssrc, rtx) = if has_rtx { - let (ssrc, rtx) = session.streams.new_ssrc_pair(); - (ssrc, Some(rtx)) - } else { - let ssrc = session.streams.new_ssrc(); - (ssrc, None) - }; - - let stream = session.streams.declare_stream_tx(ssrc, rtx, midrid); - - // Configure cache size - let size = if media.kind().is_audio() { - session.send_buffer_audio - } else { - session.send_buffer_video - }; - - stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP); - } - } -} - -fn add_pending_changes(session: &mut Session, pending: Changes) { - // For pending AddMedia, we have outgoing SSRC communicated that needs to be added. - for change in pending.0 { - let add_media = match change { - Change::AddMedia(v) => v, - _ => continue, - }; - - let media = session - .medias - .iter_mut() - .find(|m| m.mid() == add_media.mid) - .expect("Media to be added for pending mid"); - - // the cname/msid has already been communicated in the offer, we need to kep - // it the same once the m-line is created. - media.set_cname(add_media.cname); - media.set_msid(add_media.msid); - - // If there are RIDs, the SSRC order matches that of the rid order. - let layers = add_media.simulcast.map(|x| x.send).unwrap_or(vec![]); - - for (i, (ssrc, rtx)) in add_media.ssrcs.into_iter().enumerate() { - let maybe_layer = layers.get(i).cloned(); - let midrid = MidRid(add_media.mid, maybe_layer.map(|layer| layer.rid)); - - let stream = session.streams.declare_stream_tx(ssrc, rtx, midrid); - - let size = if media.kind().is_audio() { - session.send_buffer_audio - } else { - session.send_buffer_video - }; - - stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP); - } - } -} - -/// Compares m-lines in Sdp with that already in the session. -/// -/// * Existing m-lines can apply changes (such as direction change). -/// * New m-lines are returned to the caller paired with the session -/// index they should occupy. The index is normally the next free slot, -/// but can be a recycled slot (RFC 8829 §5.2.2) when the remote has -/// replaced a previously disabled Media with a new mid. -fn sync_medias<'a>(session: &mut Session, sdp: &'a Sdp, is_offer: bool) -> Result, String> { - let mut new_lines = Vec::with_capacity(sdp.media_lines.len()); - let bundle_mids = sdp.bundle_mids(); - - for (idx, m) in sdp.media_lines.iter().enumerate() { - // First, match existing m-lines. - match m.typ { - MediaType::Application => { - if let Some((_, index)) = session.app() { - if idx != *index { - return index_err(m.mid()); - } - continue; - } - } - MediaType::Audio | MediaType::Video => { - if let Some(media) = session.medias.iter_mut().find(|l| l.mid() == m.mid()) { - if idx != media.index() { - return index_err(m.mid()); - } - - update_media( - media, - m, - &session.codec_config, - &session.exts, - &mut session.streams, - bundle_mids, - ); - - continue; - } - - // Unknown mid at an index held by a disabled Media means - // the remote has recycled the slot (RFC 8829 §5.2.2). - // Recycling is only permitted in offers; an answer that - // rewires a mid at a stopped slot is malformed. - if let Some(pos) = session.medias.iter().position(|l| l.index() == idx) { - if !is_offer { - return Err(format!( - "Answer recycles stopped m-line (not permitted per RFC 8829 §5.2.2): {}", - m.mid() - )); - } - if !session.medias[pos].disabled() { - return index_err(m.mid()); - } - let retired_mid = session.medias[pos].mid(); - session.medias.swap_remove(pos); - session.streams.remove_streams_by_mid(retired_mid); - } - } - _ => { - continue; - } - } - - // Second, discover new m-lines. - new_lines.push((idx, m)); - } - - fn index_err(mid: Mid) -> Result { - Err(format!("Changed order for m-line with mid: {mid}")) - } - - Ok(new_lines) -} - -/// Adds new m-lines as found in an offer or answer. -/// -/// Each entry in `new_lines` pairs an m-line with the session index it -/// should occupy. -fn add_new_lines( - session: &mut Session, - new_lines: &[(usize, &MediaLine)], - is_offer: bool, - bundle_mids: Option<&[Mid]>, -) -> Result<(), String> { - for (idx, m) in new_lines { - let idx = *idx; - - if m.typ.is_media() { - let mut media = Media::from_remote_media_line(m, idx, is_offer); - - // For disabled (rejected) m-lines, don't fire open event - // and the direction will be set to Inactive by update_media. - // In max-bundle, port=0 with the MID in BUNDLE group is NOT rejected. - let is_in_bundle = bundle_mids.map(|mids| mids.contains(&m.mid())).unwrap_or(false); - let is_rejected = m.disabled && !is_in_bundle; - media.need_open_event = is_offer && !is_rejected; - - // Match/remap remote params. - session.codec_config.update_params(&m.rtp_params(), m.direction()); - - // Remap the extension to that of the answer. - session.exts.remap(&m.extmaps()); - - update_media( - &mut media, - m, - &session.codec_config, - &session.exts, - &mut session.streams, - bundle_mids, - ); - - session.add_media(media); - } else if m.typ.is_channel() { - session.set_app(m.mid(), idx)?; - } else { - return Err(format!("New m-line is neither media nor channel: {}", m.mid())); - } - } - - Ok(()) -} - -/// Update session level properties like -/// Extensions from offer or answer. -fn update_session(session: &mut Session, sdp: &Sdp) { - // Does any m-line contain a a=rtcp-fb:xx transport-cc? - let has_transport_cc = sdp - .media_lines - .iter() - .any(|m| m.rtp_params().iter().any(|p| p.fb_transport_cc)); - - // Is the session level sequence number enabled? - let has_twcc_header = session.exts.id_of(Extension::TransportSequenceNumber).is_some(); - - // Since twcc feedback is session wide we enable it if there are _any_ - // m-line with a a=rtcp-fb transport-cc parameter and the sequence number - // header is enabled. It can later be disabled for specific m-lines based - // on the extensions map. - if has_transport_cc && has_twcc_header { - session.enable_twcc_feedback(); - } -} - -/// Returns all media/channels as `AsMediaLine` trait. -fn as_media_lines(session: &Session) -> Vec<&dyn AsSdpMediaLine> { - let mut v = vec![]; - - if let Some(app) = session.app() { - v.push(app as &dyn AsSdpMediaLine); - } - v.extend(session.medias().iter().map(|m| m as &dyn AsSdpMediaLine)); - v.sort_by_key(|f| f.index()); - v -} - -fn update_media( - media: &mut Media, - m: &MediaLine, - config: &CodecConfig, - exts: &ExtensionMap, - streams: &mut Streams, - bundle_mids: Option<&[Mid]>, -) { - // If the m-line has port=0, it could mean: - // 1. The m-line is rejected (not in BUNDLE group) - // 2. The m-line is bundled with another m-line (max-bundle format, RFC 8843) - // - // In max-bundle, secondary m-lines use port=0 to indicate they share transport - // with the first m-line. This is NOT a rejection. - let is_in_bundle = bundle_mids.map(|mids| mids.contains(&m.mid())).unwrap_or(false); - let is_rejected = m.disabled && !is_in_bundle; - - if is_rejected { - if !media.disabled() { - debug!( - "Mid ({}) is rejected (port=0, not in BUNDLE), setting to Inactive", - media.mid() - ); - } - media.mark_stopped(); - media.set_direction(Direction::Inactive); - return; - } - - // Direction changes - // - // All changes come from the other side, either via an incoming OFFER - // or a ANSWER from our OFFER. Either way, the direction is inverted to - // how we have it locally. - let new_dir = m.direction().invert(); - // - let change_direction_disallowed = - !media.remote_created() && media.direction() == Direction::Inactive && new_dir == Direction::SendOnly; - - if change_direction_disallowed { - debug!( - "Ignore attempt to change inactive to recvonly by remote peer for locally created mid: {}", - media.mid() - ); - } else { - media.set_direction(new_dir); - } - - if new_dir.is_sending() { - // The other side has declared how it EXPECTING to receive. We must only send - // the RIDs declared in the answer. - let rids = m.rids(); - let rid_tx = if rids.is_empty() { - Rids::None - } else { - Rids::Specific(rids) - }; - media.set_rid_tx(rid_tx); - } - if new_dir.is_receiving() { - // The other side has declared what it proposes to send. We are accepting it. - let rids = m.rids(); - let rid_rx = if rids.is_empty() { - Rids::Any - } else { - Rids::Specific(rids) - }; - media.set_rid_rx(rid_rx); - } - - // Narrowing/ordering of of PT - let pts: Vec = m - .rtp_params() - .into_iter() - .filter_map(|p| config.sdp_match_remote(p, m.direction())) - .collect(); - media.set_remote_pts(pts); - - let mut remote_extmap = ExtensionMap::empty(); - for (id, ext) in m.extmaps().into_iter() { - // The remapping of extensions should already have happened, which - // means the ID are matching in the session to the remote. - - // Does the ID exist in session? - let in_session = match exts.lookup(id) { - Some(v) => v, - None => continue, - }; - - if in_session != ext { - // Don't set any extensions that aren't enabled in Session. - continue; - } - - // Use the Extension from session, since there might be a special - // serializer for cases like VLA. - remote_extmap.set(id, in_session.clone()); - } - media.set_remote_extmap(remote_extmap); - - // Simulcast configuration. This applies to both directions: every later SDP for the - // m-line is generated from the Media, and must repeat the negotiated a=rid and - // a=simulcast lines (RFC 8829 5.2.2, RFC 8853 5.3.4). - if let Some(s) = m.simulcast() { - if s.is_munged { - warn!("Not supporting simulcast via munging SDP"); - } else if media.simulcast().is_none() { - // Invert before setting, since it has a recv and send config. - media.set_simulcast(s.invert()); - } - } - - // SSRC changes - // This will always be for ReceiverSource since any incoming a=ssrc line will be - // about the remote side's SSRC. - if !new_dir.is_receiving() { - return; - } - - // Only use pre-communicated SSRC if we are running without simulcast. - // We found a bug in FF where the order of the simulcast lines does not - // correspond to the order of the simulcast declarations. In this case - // it's better to fall back on mid/rid dynamic mapping. - if m.simulcast().is_some() { - return; - } - - let infos = m.ssrc_info(); - let main = infos.iter().filter(|i| i.repairs.is_none()); - - for i in main { - // TODO: If the remote is communicating _BOTH_ rid and a=ssrc this will fail. - debug!("Adding pre-communicated SSRC: {:?}", i); - let repair_ssrc = infos.iter().find(|r| r.repairs == Some(i.ssrc)).map(|r| r.ssrc); - - // If remote communicated a main a=ssrc, but no RTX, we will not send nacks. - let midrid = MidRid(media.mid(), None); - let suppress_nack = repair_ssrc.is_none(); - streams.expect_stream_rx(i.ssrc, repair_ssrc, midrid, suppress_nack); - } -} - -trait AsSdpMediaLine { - fn mid(&self) -> Mid; - fn msid(&self) -> Option<&Msid>; - fn index(&self) -> usize; - fn kind(&self) -> MediaKind; - fn as_media_line( - &self, - attrs: Vec, - ssrcs_tx: &[(Ssrc, Option)], - exts: &ExtensionMap, - params: &[PayloadParams], - ) -> MediaLine; -} - -impl AsSdpMediaLine for (Mid, usize) { - fn mid(&self) -> Mid { - self.0 - } - fn msid(&self) -> Option<&Msid> { - None - } - fn index(&self) -> usize { - self.1 - } - fn kind(&self) -> MediaKind { - MediaKind::Audio // doesn't matter for App - } - fn as_media_line( - &self, - mut attrs: Vec, - _ssrcs_tx: &[(Ssrc, Option)], - _exts: &ExtensionMap, - _params: &[PayloadParams], - ) -> MediaLine { - attrs.push(MediaAttribute::Mid(self.0)); - - // No SCTP runs here, so a remote data channel line is always rejected. - MediaLine { - typ: sdp::MediaType::Application, - disabled: true, - proto: Proto::Sctp, - pts: vec![], - bw: None, - attrs, - } - } -} - -impl AsSdpMediaLine for Media { - fn mid(&self) -> Mid { - Media::mid(self) - } - fn msid(&self) -> Option<&Msid> { - (!self.disabled()).then(|| Media::msid(self)) - } - fn index(&self) -> usize { - Media::index(self) - } - fn kind(&self) -> MediaKind { - Media::kind(self) - } - fn as_media_line( - &self, - mut attrs: Vec, - ssrcs_tx: &[(Ssrc, Option)], - exts: &ExtensionMap, - params: &[PayloadParams], - ) -> MediaLine { - attrs.push(MediaAttribute::Mid(self.mid())); - - let audio = self.kind() == MediaKind::Audio; - for (id, ext) in self.remote_extmap().iter_by_media_type(audio) { - attrs.push(MediaAttribute::ExtMap { id, ext: ext.clone() }); - } - - attrs.push(self.direction().into()); - if !self.disabled() { - attrs.push(MediaAttribute::Msid(self.msid().clone())); - } - attrs.push(MediaAttribute::RtcpMux); - - // The effective params start from the Session::codec_config to retain the - // user's configured preferred order, however they are narrowed only include - // those the remote peer wants. - let effective_params = params.iter().filter(|p| self.remote_pts().contains(&p.pt)); - - let mut pts = vec![]; - - for p in effective_params { - let p = *p; - p.as_media_attrs(&mut attrs); - - // The pts that will be advertised in the SDP. - pts.push(p.pt()); - if let Some(rtx) = p.resend() { - pts.push(rtx); - } - } - - if let Some(s) = self.simulcast() { - fn to_rids<'a>( - gs: &'a SimulcastGroups, - direction: &'static str, - ) -> impl Iterator + 'a { - gs.iter().map(move |layer| MediaAttribute::Rid { - id: layer.restriction_id.clone(), - direction, - pt: vec![], - restriction: layer.attributes.clone().unwrap_or_default(), - }) - } - attrs.extend(to_rids(&s.recv, "recv")); - attrs.extend(to_rids(&s.send, "send")); - attrs.push(MediaAttribute::Simulcast(s.clone())); - } - - // Outgoing SSRCs - let ssrcs_tx: &[(Ssrc, Option)] = if self.disabled() { &[] } else { ssrcs_tx }; - let msid = format!("{} {}", self.msid().stream_id, self.msid().track_id); - for (ssrc, ssrc_rtx) in ssrcs_tx { - attrs.push(MediaAttribute::Ssrc { - ssrc: *ssrc, - attr: "cname".to_string(), - value: self.cname().to_string(), - }); - attrs.push(MediaAttribute::Ssrc { - ssrc: *ssrc, - attr: "msid".to_string(), - value: msid.clone(), - }); - if let Some(ssrc_rtx) = ssrc_rtx { - attrs.push(MediaAttribute::Ssrc { - ssrc: *ssrc_rtx, - attr: "cname".to_string(), - value: self.cname().to_string(), - }); - attrs.push(MediaAttribute::Ssrc { - ssrc: *ssrc_rtx, - attr: "msid".to_string(), - value: msid.clone(), - }); - } - } - - for (ssrc, ssrc_rtx) in ssrcs_tx { - if let Some(ssrc_rtx) = ssrc_rtx { - attrs.push(MediaAttribute::SsrcGroup { - semantics: "FID".to_string(), - ssrcs: vec![*ssrc, *ssrc_rtx], - }); - } - } - - MediaLine { - typ: self.kind().into(), - disabled: self.disabled(), - proto: Proto::Srtp, - pts, - bw: None, - attrs, - } - } -} - -impl From for MediaType { - fn from(value: MediaKind) -> Self { - match value { - MediaKind::Audio => MediaType::Audio, - MediaKind::Video => MediaType::Video, - } - } -} - -struct AsSdpParams<'a, 'b> { - pub candidates: Vec, - pub creds: IceCreds, - pub fingerprint: &'a Fingerprint, - pub setup: Setup, - pub pending: Option<&'b Changes>, -} - -impl<'a, 'b> AsSdpParams<'a, 'b> { - pub fn new(rtc: &'a Rtc, pending: Option<&'b Changes>) -> Self { - let (creds, candidates) = - if let Some((new_creds, keep_local_candidates)) = pending.and_then(|p| p.ice_restart()) { - if keep_local_candidates { - // If we are performing an ICE restart and we are keeping the same - // candidates we need to use ufrag from the new ICE credentials - // in our offer. - let mut new_candidates = rtc.ice.local_candidates().collect::>(); - for c in &mut new_candidates { - c.set_ufrag(&new_creds.ufrag); - } - - (new_creds, new_candidates) - } else { - (new_creds, vec![]) - } - } else { - ( - rtc.ice.local_credentials().clone(), - rtc.ice.local_candidates().collect::>(), - ) - }; - - // RFC 8842 Section 5.2/5.5: Offerers MUST always use a=setup:actpass. - // Answerers use the negotiated role (active/passive). - // We distinguish offer vs answer by the presence of `pending` (Some = offer). - let setup = if pending.is_some() { - // This is an offer - always actpass per RFC 8842 - Setup::ActPass - } else { - // This is an answer - use the negotiated DTLS role - match rtc.dtls.is_active() { - Some(true) => Setup::Active, - Some(false) => Setup::Passive, - None => Setup::ActPass, - } - }; - - AsSdpParams { - candidates, - creds, - fingerprint: rtc.dtls.local_fingerprint(), - setup, - pending, - } - } - - fn media_attributes(&self, include_candidates: bool) -> Vec { - use MediaAttribute::*; - - let mut v = if include_candidates { - self.candidates.iter().map(|c| Candidate(c.clone())).collect() - } else { - vec![] - }; - - v.push(IceUfrag(self.creds.ufrag.clone())); - v.push(IcePwd(self.creds.pass.clone())); - v.push(IceOptions("trickle".into())); - v.push(Fingerprint(self.fingerprint.clone())); - v.push(Setup(self.setup)); - - v - } -} - -impl fmt::Debug for SdpPendingOffer { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SdpPendingOffer").finish() - } -} - -impl Changes { - fn has_mid(&self, mid: Mid) -> bool { - self.0.iter().any(|c| match c { - Change::AddMedia(v) => v.mid == mid, - Change::Direction(_, _) | Change::IceRestart(_, _) => false, - }) - } - - /// Tests the given lines (from answer) corresponds to changes. - fn ensure_correct_answer(&self, lines: &[(usize, &MediaLine)]) -> Option { - if self.count_new_medias() != lines.len() { - return Some(format!( - "Differing m-line count in offer vs answer: {} != {}", - self.count_new_medias(), - lines.len() - )); - } - - 'next: for (_, l) in lines { - let mid = l.mid(); - - for m in &self.0 { - use Change::*; - match m { - AddMedia(v) if v.mid == mid => { - if !l.typ.is_media() { - return Some(format!( - "Answer m-line for mid ({}) is not of media type: {:?}", - mid, l.typ - )); - } - continue 'next; - } - _ => {} - } - } - - return Some(format!("Mid in answer is not in offer: {mid}")); - } - - None - } - - fn count_new_medias(&self) -> usize { - self.0.iter().filter(|c| matches!(c, Change::AddMedia(_))).count() - } - - pub fn as_new_medias<'a, 'b: 'a>( - &'a self, - index_start: usize, - config: &'b CodecConfig, - exts: &'b ExtensionMap, - ) -> impl Iterator + 'a { - // Use a separate counter that only advances for entries that actually produce - // an m-line (AddMedia). Non-media entries (Direction, IceRestart) - // must not consume an index slot, otherwise the resulting m-line - // indices would be non-contiguous and out of sync with their array positions. - let mut media_idx = 0usize; - self.0.iter().filter_map(move |c| { - let result = c.as_new_media(index_start + media_idx, config, exts); - if result.is_some() { - media_idx += 1; - } - result - }) - } - - pub(crate) fn apply_to(&self, lines: &mut [MediaLine]) { - for change in &self.0 { - if let Change::Direction(mid, dir) = change { - if let Some(line) = lines.iter_mut().find(|l| l.mid() == *mid) { - if let Some(dir_pos) = line.attrs.iter().position(|a| a.is_direction()) { - line.attrs[dir_pos] = (*dir).into(); - } - } - } - } - } - - fn ssrcs_for_mid(&self, mid: Mid) -> &[(Ssrc, Option)] { - let maybe_add_media = self - .0 - .iter() - .filter_map(|c| if let Change::AddMedia(m) = c { Some(m) } else { None }) - .find(|m| m.mid == mid); - - let Some(m) = maybe_add_media else { - return &[]; - }; - - &m.ssrcs - } -} - -impl Change { - fn as_new_media(&self, index: usize, config: &CodecConfig, exts: &ExtensionMap) -> Option { - use Change::*; - match self { - AddMedia(v) => { - // TODO can we avoid all this cloning? - let mut add = v.clone(); - add.pts = config.all_for_kind(v.kind).map(|p| p.pt()).collect(); - add.exts = exts.cloned_with_type(v.kind.is_audio()); - add.index = index; - - Some(Media::from_add_media(add)) - } - _ => None, - } - } -} - -#[cfg(test)] -mod test { - use std::time::Instant; - - use sdp::RestrictionId; - use sdp::SimulcastLayer as SdpSimulcastLayer; - - use crate::vendor::str0m::format::Codec; - use crate::vendor::str0m::media::{Simulcast, SimulcastLayer}; - use crate::vendor::str0m::sdp::RtpMap; - - use super::*; - - fn resolve_pt(m_line: &MediaLine, needle: Pt) -> RtpMap { - m_line - .attrs - .iter() - .find_map(|attr| match attr { - MediaAttribute::RtpMap { pt, value } if *pt == needle => Some(*value), - _ => None, - }) - .unwrap_or_else(|| panic!("Expected to find RtpMap for {needle}")) - } - - fn count_lines(lines: &str, what: &str) -> usize { - lines.lines().filter(|l| l == &what).count() - } - - fn get_setup_from_media_line(line: &MediaLine) -> Setup { - line.setup().expect("Expected a=setup attribute in SDP") - } - - /// RFC 8842 §5.2: an offer MUST use a=setup:actpass regardless of DTLS role. - #[test] - fn offer_uses_actpass() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc = Rtc::new(now); - - let mut change = rtc.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, _pending) = change.apply().unwrap(); - - let setup = get_setup_from_media_line(&offer.media_lines[0]); - assert_eq!( - setup, - Setup::ActPass, - "Offer must use a=setup:actpass per RFC 8842 §5.2" - ); - } - - /// RFC 8842 §5.5: the answerer uses the negotiated DTLS role (active or passive). - /// When the offerer uses actpass, the answerer picks passive (DTLS server) and the - /// offerer becomes active (DTLS client). The answerer's SDP must reflect passive. - #[test] - fn answer_uses_negotiated_dtls_role() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut offerer = Rtc::new(now); - let mut answerer = Rtc::new(now); - - // Offerer creates the offer. - let mut change = offerer.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - // Verify the offer itself is actpass. - assert_eq!( - get_setup_from_media_line(&offer.media_lines[0]), - Setup::ActPass, - "Offer must use a=setup:actpass" - ); - - // Answerer accepts and generates the answer. - let answer = answerer.sdp_api().accept_offer(offer).unwrap(); - - // When the offerer sends actpass, the answerer takes the passive DTLS role - // (see init_dtls: ActPass from remote → local takes Passive). - // The answerer's SDP must reflect that with a=setup:passive. - assert_eq!( - get_setup_from_media_line(&answer.media_lines[0]), - Setup::Passive, - "Answerer's SDP must use a=setup:passive when responding to an actpass offer" - ); - - // Complete the exchange on the offerer side. - offerer.sdp_api().accept_answer(pending, answer).unwrap(); - - // Now generate a subsequent offer from the offerer (re-offer). - // Even after the DTLS role is settled (offerer is now passive), a new offer - // must still carry a=setup:actpass per RFC 8842 §5.2. - let mut change = offerer.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (reoffer, _) = change.apply().unwrap(); - - assert_eq!( - get_setup_from_media_line(&reoffer.media_lines[0]), - Setup::ActPass, - "Re-offer must still use a=setup:actpass even after DTLS role is settled" - ); - } - - #[test] - fn test_out_of_order_error() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc1 = Rtc::new(now); - let mut rtc2 = Rtc::new(now); - - let mut change1 = rtc1.sdp_api(); - change1.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer1, pending1) = change1.apply().unwrap(); - - let mut change2 = rtc2.sdp_api(); - change2.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer2, _) = change2.apply().unwrap(); - - // invalidates pending1 - let _ = rtc1.sdp_api().accept_offer(offer2).unwrap(); - let answer2 = rtc2.sdp_api().accept_offer(offer1).unwrap(); - - let r = rtc1.sdp_api().accept_answer(pending1, answer2); - - assert!(matches!(r, Err(RtcError::ChangesOutOfOrder))); - } - - // The indices assigned to Media objects by as_new_medias() must be contiguous starting - // from index_start. Only entries that produce m-lines (AddMedia) should consume an - // index slot – non-media entries (Direction, IceRestart) must not advance the counter. - // - // We test this by building a Changes vector directly and inspecting the indices - // returned by as_new_medias(). - #[test] - fn as_new_medias_contiguous_indices_with_non_media_changes() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let rtc = Rtc::new(now); - - let add = |mid: Mid, kind: MediaKind| { - Change::AddMedia(AddMedia { - mid, - cname: "test".into(), - msid: Msid { - stream_id: "stream".into(), - track_id: "track".into(), - }, - kind, - dir: Direction::SendOnly, - ssrcs: vec![], - simulcast: None, - pts: vec![], - exts: ExtensionMap::empty(), - index: 0, // will be overwritten by as_new_media() - }) - }; - - // Changes = [AddMedia(audio), IceRestart, AddMedia(video)] - let mut changes = Changes::default(); - changes.0.push(add(rtc.new_mid(), MediaKind::Audio)); - changes.0.push(Change::IceRestart(IceCreds::new(), true)); - changes.0.push(add(rtc.new_mid(), MediaKind::Video)); - - let config = CodecConfig::new_with_defaults(); - let exts = ExtensionMap::standard(); - - let medias: Vec = changes.as_new_medias(0, &config, &exts).collect(); - - assert_eq!(medias.len(), 2, "Expected 2 media-producing entries"); - assert_eq!(medias[0].index(), 0, "AddMedia(audio) should have index 0"); - // Index 2 would result from counting the non-media IceRestart entry as a slot. - assert_eq!( - medias[1].index(), - 1, - "AddMedia(video) should have contiguous index 1, not 2" - ); - } - - /// No SCTP runs here, so an offered data channel is answered rejected and left out of - /// the BUNDLE group, while the media beside it is accepted. - #[test] - fn an_offered_data_channel_is_answered_rejected() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut offerer = Rtc::new(now); - let mut change = offerer.sdp_api(); - let audio = change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - let (offer, _) = change.apply().unwrap(); - let offer = offer.to_sdp_string().replace( - &format!("a=group:BUNDLE {audio}\r\n"), - &format!("a=group:BUNDLE {audio} dc\r\n"), - ) + "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:dc\r\n\ - a=sctp-port:5000\r\n"; - let offer = SdpOffer::from_sdp_string(&offer).expect("offer with a data channel"); - - let answer = Rtc::new(now).sdp_api().accept_offer(offer).unwrap(); - - let app = answer.media_lines.iter().find(|m| m.typ.is_channel()).unwrap(); - assert!(app.disabled, "the data channel was accepted"); - let media = answer.media_lines.iter().find(|m| m.mid() == audio).unwrap(); - assert!(!media.disabled, "the audio was rejected"); - let answer = answer.to_sdp_string(); - assert!( - answer.contains("m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\n"), - "{answer}" - ); - assert!(answer.contains(&format!("a=group:BUNDLE {audio}\r\n")), "{answer}"); - } - - /// An offer that puts its data channel first still gets the answer's candidates on the - /// accepted media, since the rejected data channel line is out of the BUNDLE group. - #[test] - fn candidates_skip_a_rejected_first_line() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut offerer = Rtc::new(now); - let mut change = offerer.sdp_api(); - let audio = change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - let (offer, _) = change.apply().unwrap(); - let offer = offer.to_sdp_string(); - let (session, media) = offer.split_at(offer.find("m=audio").unwrap()); - let session = session.replace( - &format!("a=group:BUNDLE {audio}\r\n"), - &format!("a=group:BUNDLE dc {audio}\r\n"), - ); - let offer = format!( - "{session}m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:dc\r\n\ - a=sctp-port:5000\r\n{media}" - ); - let offer = SdpOffer::from_sdp_string(&offer).expect("offer with a data channel first"); - - let mut answerer = Rtc::new(now); - let candidate = Candidate::host((std::net::Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - answerer.add_local_candidate(candidate).unwrap(); - let answer = answerer.sdp_api().accept_offer(offer).unwrap(); - - let has_candidate = |m: &MediaLine| m.attrs.iter().any(|a| matches!(a, MediaAttribute::Candidate(_))); - assert!(answer.media_lines[0].disabled, "the data channel was accepted"); - assert!( - !has_candidate(&answer.media_lines[0]), - "a candidate sits on the rejected line" - ); - assert_eq!(answer.media_lines[1].mid(), audio); - assert!( - has_candidate(&answer.media_lines[1]), - "the accepted audio has no candidate" - ); - } - - #[test] - fn twcc_negotiation_uses_first_media_section_for_each_pt() { - crate::vendor::str0m::init_crypto_default(); - for enabled_audio in [1, 2] { - let expected_audio = enabled_audio == 1; - let now = Instant::now(); - let mut local = Rtc::builder().build(now); - let mut remote = Rtc::builder().build(now); - let mut change = local.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let mut section = 0; - let sdp = offer - .to_sdp_string() - .lines() - .filter(|line| { - if line.starts_with("m=") { - section += 1; - } - section == enabled_audio || !line.contains("transport-cc") - }) - .collect::>() - .join("\r\n") - + "\r\n"; - let offer = SdpOffer::from_sdp_string(&sdp).unwrap(); - let answer = remote.sdp_api().accept_offer(offer).unwrap(); - // Both audio sections use the first section's negotiated result. - for m in &answer.media_lines[..2] { - assert!(m.rtp_params().iter().all(|p| p.fb_transport_cc() == expected_audio)); - } - assert!(answer.media_lines[2].rtp_params().iter().all(|p| !p.fb_transport_cc())); - local.sdp_api().accept_answer(pending, answer).unwrap(); - for rtc in [&local, &remote] { - assert!( - rtc.codec_config() - .params() - .iter() - .filter(|p| p.spec().codec.is_audio()) - .all(|p| p.fb_transport_cc() == expected_audio) - ); - assert!( - rtc.codec_config() - .params() - .iter() - .filter(|p| p.spec().codec.is_video()) - .all(|p| !p.fb_transport_cc()) - ); - } - - // Existing m-lines retain their negotiated codec parameters. - let sdp = - sdp.lines() - .filter(|line| !line.contains("transport-cc")) - .collect::>() - .join("\r\n") + "\r\n"; - let offer = SdpOffer::from_sdp_string(&sdp).unwrap(); - let answer = remote.sdp_api().accept_offer(offer).unwrap(); - for m in &answer.media_lines[..2] { - assert!(m.rtp_params().iter().all(|p| p.fb_transport_cc() == expected_audio)); - } - } - } - - #[test] - fn test_rtp_payload_priority() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc1 = Rtc::builder() - .clear_codecs() - .enable_h264(true) - .enable_vp8(true) - .enable_vp9(true) - .build(now); - let mut rtc2 = Rtc::builder() - .clear_codecs() - .enable_vp8(true) - .enable_h264(true) - .build(now); - - let mut change1 = rtc1.sdp_api(); - change1.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer1, _) = change1.apply().unwrap(); - - let answer = rtc2.sdp_api().accept_offer(offer1).unwrap(); - assert_eq!(answer.media_lines.len(), 1, "There should be one mline only"); - - let first_mline = &answer.media_lines[0]; - let first_pt = resolve_pt(first_mline, first_mline.pts[0]); - - assert_eq!( - first_pt.codec, - Codec::Vp8, - "The first PT returned should be the highest priority PT from the answer that is supported." - ); - - let vp9_unsupported = first_mline - .pts - .iter() - .any(|pt| resolve_pt(first_mline, *pt).codec == Codec::Vp9); - - assert!( - !vp9_unsupported, - "VP9 was not offered, so it should not be present in the answer" - ); - } - - #[test] - fn non_simulcast_rids() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc1 = Rtc::new(now); - let mut rtc2 = Rtc::new(now); - - // Test initial media creation - let mid = { - let mut changes = rtc1.sdp_api(); - let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - let (offer, pending) = changes.apply().unwrap(); - let answer = rtc2.sdp_api().accept_offer(offer).unwrap(); - rtc1.sdp_api().accept_answer(pending, answer).unwrap(); - - assert!(matches!(rtc1.media(mid).unwrap().rids_rx(), Rids::Any)); - assert!(matches!(rtc1.media(mid).unwrap().rids_tx(), Rids::None)); - assert!(matches!(rtc2.media(mid).unwrap().rids_rx(), Rids::Any)); - assert!(matches!(rtc2.media(mid).unwrap().rids_tx(), Rids::None)); - - mid - }; - - // Test later updates to that media - { - let mut changes = rtc1.sdp_api(); - changes.set_direction(mid, Direction::Inactive); - let (offer, pending) = changes.apply().unwrap(); - let answer = rtc2.sdp_api().accept_offer(offer).unwrap(); - rtc1.sdp_api().accept_answer(pending, answer).unwrap(); - - assert!(matches!(rtc1.media(mid).unwrap().rids_rx(), Rids::Any)); - assert!(matches!(rtc1.media(mid).unwrap().rids_tx(), Rids::None)); - assert!(matches!(rtc2.media(mid).unwrap().rids_rx(), Rids::Any)); - assert!(matches!(rtc2.media(mid).unwrap().rids_tx(), Rids::None)); - } - } - - #[test] - fn simulcast_ssrc_allocation() { - crate::vendor::str0m::init_crypto_default(); - - let mut rtc1 = Rtc::new(Instant::now()); - - let mut simulcast = Simulcast::new(); - - simulcast.add_send_layer(SimulcastLayer::new("h")); - simulcast.add_send_layer(SimulcastLayer::new("m")); - simulcast.add_send_layer(SimulcastLayer::new("l")); - - let mut change = rtc1.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, Some(simulcast)); - - let Change::AddMedia(am) = &change.changes[0] else { - panic!("Not AddMedia?!"); - }; - - // these should be organized in order: m, h, l - let pending_ssrcs = am.ssrcs.clone(); - assert_eq!(pending_ssrcs.len(), 3); - - for p in &pending_ssrcs { - assert!(p.1.is_some()); // all should have rtx - } - - let (offer, _) = change.apply().unwrap(); - let sdp = offer.into_inner(); - let line = &sdp.media_lines[0]; - - assert_eq!( - line.simulcast().unwrap().send, - SimulcastGroups(vec![ - SdpSimulcastLayer { - restriction_id: RestrictionId("h".into(), true), - attributes: None, - }, - SdpSimulcastLayer { - restriction_id: RestrictionId("m".into(), true), - attributes: None, - }, - SdpSimulcastLayer { - restriction_id: RestrictionId("l".into(), true), - attributes: None, - }, - ]) - ); - - // Each SSRC, both regular and RTX get their own a=ssrc line. - assert_eq!(line.ssrc_info().len(), pending_ssrcs.len() * 2); - - let fids: Vec<_> = line - .attrs - .iter() - .filter_map(|a| { - if let MediaAttribute::SsrcGroup { semantics, ssrcs } = a { - // We don't have any other semantics right now. - assert_eq!(semantics, "FID"); - assert_eq!(ssrcs.len(), 2); - Some((ssrcs[0], ssrcs[1])) - } else { - None - } - }) - .collect(); - - assert_eq!(fids.len(), pending_ssrcs.len()); - - for (a, b) in fids.iter().zip(pending_ssrcs.iter()) { - assert_eq!(a.0, b.0); - assert_eq!(Some(a.1), b.1); - } - - let line_string = line.to_string(); - - // The SDP offer should contain layers without any attributes - assert_eq!(count_lines(&line_string, "a=rid:h send"), 1); - assert_eq!(count_lines(&line_string, "a=rid:m send"), 1); - assert_eq!(count_lines(&line_string, "a=rid:l send"), 1); - } - - #[test] - fn simulcast_attributes() { - crate::vendor::str0m::init_crypto_default(); - - let mut rtc1 = Rtc::new(Instant::now()); - - let mut simulcast = Simulcast::new(); - - // High layer - simulcast.add_send_layer( - SimulcastLayer::new_with_attributes("high") - .max_width(1280) - .max_height(720) - .max_br(1100000) - .max_br(1300000) - .max_br(1500000) // the last one wins - .max_fps(30) - .build(), - ); - - // Medium layer - simulcast.add_send_layer( - SimulcastLayer::new_with_attributes("medium") - .max_width(640) - .max_height(360) - .max_br(600000) - // No max_fps - .build(), - ); - - // Low layer - simulcast.add_send_layer( - SimulcastLayer::new_with_attributes("low") - // No max_width - .max_height(180) - .max_br(200000) - .max_fps(15) - .build(), - ); - - // Custom attribute - simulcast.add_send_layer( - SimulcastLayer::new_with_attributes("custom") - .custom("foo", "bar") - .build(), - ); - - // No attributes - simulcast.add_send_layer(SimulcastLayer::new_with_attributes("no_attrs").build()); - - let mut change = rtc1.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, Some(simulcast)); - - let (offer, _) = change.apply().unwrap(); - let sdp = offer.into_inner(); - let line = &sdp.media_lines[0]; - - fn pairs_to_some_vec(pairs: &[(&str, &str)]) -> Option> { - Some(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()) - } - - assert_eq!( - line.simulcast().unwrap().send, - SimulcastGroups(vec![ - SdpSimulcastLayer { - restriction_id: RestrictionId("high".into(), true), - attributes: pairs_to_some_vec(&[ - ("max-width", "1280"), - ("max-height", "720"), - ("max-br", "1500000"), - ("max-fps", "30"), - ]), - }, - SdpSimulcastLayer { - restriction_id: RestrictionId("medium".into(), true), - attributes: pairs_to_some_vec( - &[("max-width", "640"), ("max-height", "360"), ("max-br", "600000"),] - ), - }, - SdpSimulcastLayer { - restriction_id: RestrictionId("low".into(), true), - attributes: pairs_to_some_vec(&[("max-height", "180"), ("max-br", "200000"), ("max-fps", "15"),]), - }, - SdpSimulcastLayer { - restriction_id: RestrictionId("custom".into(), true), - attributes: pairs_to_some_vec(&[("foo", "bar"),]), - }, - SdpSimulcastLayer { - restriction_id: RestrictionId("no_attrs".into(), true), - attributes: None, - }, - ]) - ); - - // The SDP offer should contain layers with our attributes - let line_string = line.to_string(); - assert_eq!( - count_lines( - &line_string, - "a=rid:high send max-width=1280;max-height=720;max-br=1500000;max-fps=30" - ), - 1 - ); - assert_eq!( - count_lines( - &line_string, - "a=rid:medium send max-width=640;max-height=360;max-br=600000" - ), - 1 - ); - assert_eq!( - count_lines(&line_string, "a=rid:low send max-height=180;max-br=200000;max-fps=15"), - 1 - ); - assert_eq!(count_lines(&line_string, "a=rid:custom send foo=bar"), 1); - // No space at the end - assert_eq!(count_lines(&line_string, "a=rid:no_attrs send"), 1); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/config.rs b/rs/moq-webrtc/src/vendor/str0m/config.rs deleted file mode 100644 index e4aefdd8f7b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/config.rs +++ /dev/null @@ -1,712 +0,0 @@ -use std::ops::RangeInclusive; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::config::DtlsCert; -use crate::vendor::str0m::crypto::CryptoProvider; -use crate::vendor::str0m::format::CodecConfig; -use crate::vendor::str0m::format::Vp9PacketizerMode; -use crate::vendor::str0m::ice::IceCreds; -use crate::vendor::str0m::io::DATAGRAM_MTU_TARGET; -use crate::vendor::str0m::io::DATAGRAM_MTU_TARGET_MAX; -use crate::vendor::str0m::io::DATAGRAM_MTU_TARGET_MIN; -use crate::vendor::str0m::io::DATAGRAM_MTU_WARN; -use crate::vendor::str0m::rtp_::{Bitrate, Extension, ExtensionMap}; - -/// Customized config for creating an [`Rtc`] instance. -/// -/// ```ignore -/// # #[cfg(any())] { -/// use std::time::Instant; -/// use crate::vendor::str0m::RtcConfig; -/// -/// let rtc = RtcConfig::new() -/// .set_ice_lite(true) -/// .build(Instant::now()); -/// # } -/// ``` -/// -/// Configs implement [`Clone`] to help create multiple `Rtc` instances. -#[derive(Debug, Clone)] -pub struct RtcConfig { - pub(crate) local_ice_credentials: Option, - pub(crate) crypto_provider: Option>, - pub(crate) dtls_cert: Option, - pub(crate) fingerprint_verification: bool, - pub(crate) ice_lite: bool, - pub(crate) initial_stun_rto: Option, - pub(crate) max_stun_rto: Option, - pub(crate) max_stun_retransmits: Option, - pub(crate) codec_config: CodecConfig, - pub(crate) exts: ExtensionMap, - pub(crate) intervals: RtcpReportIntervals, - pub(crate) reordering_size_audio: usize, - pub(crate) reordering_size_video: usize, - pub(crate) reordering_timeout_audio: Option, - pub(crate) pause_threshold: Duration, - pub(crate) send_buffer_audio: usize, - pub(crate) send_buffer_video: usize, - pub(crate) rtp_mode: bool, - pub(crate) enable_raw_packets: bool, - pub(crate) vp9_packetizer_mode: Vp9PacketizerMode, - pub(crate) mtu: RangeInclusive, -} - -#[derive(Debug, Clone, Copy)] -pub(crate) struct RtcpReportIntervals { - pub(crate) audio: Duration, - pub(crate) video: Duration, -} - -impl RtcpReportIntervals { - pub(crate) fn for_audio(self, audio: bool) -> Duration { - if audio { self.audio } else { self.video } - } -} - -impl RtcConfig { - /// Creates a new default config. - pub fn new() -> Self { - RtcConfig::default() - } - - /// Get the local ICE credentials, if set. - /// - /// If not specified, local credentials will be randomly generated when - /// building the [`Rtc`] instance. - pub fn local_ice_credentials(&self) -> &Option { - &self.local_ice_credentials - } - - /// Explicitly sets local ICE credentials. - pub fn set_local_ice_credentials(mut self, local_ice_credentials: IceCreds) -> Self { - self.local_ice_credentials = Some(local_ice_credentials); - self - } - - /// Set the crypto provider. - /// - /// This overrides what is set in [`crate::vendor::str0m::crypto::CryptoProvider::install_process_default()`]. - pub fn set_crypto_provider(mut self, p: Arc) -> Self { - self.crypto_provider = Some(p); - self - } - - /// The configured crypto provider, if explicitly set. - /// - /// Returns `None` if not explicitly set via [`Self::set_crypto_provider()`]. - /// When `None`, the process default will be checked when building the [`Rtc`] instance. - pub fn crypto_provider(&self) -> Option<&Arc> { - self.crypto_provider.as_ref() - } - - /// Returns the configured DTLS certificate, if set. - /// - /// If not set, a certificate will be generated automatically. - pub fn dtls_cert(&self) -> Option<&DtlsCert> { - self.dtls_cert.as_ref() - } - - /// Set a pregenerated DTLS certificate. - /// - /// If not set, a certificate will be generated automatically using - /// the configured crypto provider. - /// - /// ```ignore - /// # use crate::vendor::str0m::RtcConfig; - /// # use crate::vendor::str0m::crypto; - /// - /// let provider = crypto::from_feature_flags(); - /// let cert = provider.dtls_provider.generate_certificate().unwrap(); - /// let rtc_config = RtcConfig::default() - /// .set_dtls_cert(cert); - /// ``` - pub fn set_dtls_cert(mut self, cert: DtlsCert) -> Self { - self.dtls_cert = Some(cert); - self - } - - /// Toggle ice lite. Ice lite is a mode for WebRTC servers with public IP address. - /// An [`Rtc`] instance in ice lite mode will not make STUN binding requests, but only - /// answer to requests from the remote peer. - /// - /// See [ICE RFC][1] - /// - /// [1]: https://www.rfc-editor.org/rfc/rfc8445#page-13 - pub fn set_ice_lite(mut self, enabled: bool) -> Self { - self.ice_lite = enabled; - self - } - - /// Sets the initial STUN retransmission timeout (RTO). - /// - /// This is the initial wait time before a STUN request is retransmitted. - /// The timeout will double with each retry, starting from this value. - /// - /// Defaults to 250ms. - pub fn set_initial_stun_rto(&mut self, rto: Duration) { - self.initial_stun_rto = Some(rto); - } - - /// Sets the maximum STUN retransmission timeout for the ICE agent. - /// - /// This is the upper bound for how long to wait between retransmissions. - /// It also controls how often successful bindings are checked. - /// - /// Defaults to 3000ms. - pub fn set_max_stun_rto(&mut self, rto: Duration) { - self.max_stun_rto = Some(rto); - } - - /// Sets the maximum number of retransmits for STUN messages. - /// - /// Defaults to 9. - pub fn set_max_stun_retransmits(&mut self, num: usize) { - self.max_stun_retransmits = Some(num); - } - - /// Get fingerprint verification mode. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to true. - /// assert!(config.fingerprint_verification()); - /// ``` - pub fn fingerprint_verification(&self) -> bool { - self.fingerprint_verification - } - - /// Toggle certificate fingerprint verification. - /// - /// By default the certificate fingerprint is verified. - pub fn set_fingerprint_verification(mut self, enabled: bool) -> Self { - self.fingerprint_verification = enabled; - self - } - - /// Tells whether ice lite is enabled. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to false. - /// assert_eq!(config.ice_lite(), false); - /// # } - /// ``` - pub fn ice_lite(&self) -> bool { - self.ice_lite - } - - /// Lower level access to precise configuration of codecs (payload types). - pub fn codec_config(&mut self) -> &mut CodecConfig { - &mut self.codec_config - } - - /// Clear all configured codecs. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use std::time::Instant; - /// # use crate::vendor::str0m::RtcConfig; - /// // For the session to use only OPUS and VP8. - /// let mut rtc = RtcConfig::default() - /// .clear_codecs() - /// .enable_opus(true) - /// .enable_vp8(true) - /// .build(Instant::now()); - /// # } - /// ``` - pub fn clear_codecs(mut self) -> Self { - self.codec_config.clear(); - self - } - - /// Enable opus audio codec. - /// - /// Enabled by default. - pub fn enable_opus(mut self, enabled: bool) -> Self { - self.codec_config.enable_opus(enabled); - self - } - - /// Enable AMR-WB audio codec. - /// - /// Disabled by default. - pub fn enable_amr_wb(mut self, enabled: bool) -> Self { - self.codec_config.enable_amr_wb(enabled); - self - } - - /// Enable VP8 video codec. - /// - /// Enabled by default. - pub fn enable_vp8(mut self, enabled: bool) -> Self { - self.codec_config.enable_vp8(enabled); - self - } - - /// Enable H264 video codec. - /// - /// Enabled by default. - pub fn enable_h264(mut self, enabled: bool) -> Self { - self.codec_config.enable_h264(enabled); - self - } - - /// Enable H265 video codec. - /// - /// Enabled by default. - pub fn enable_h265(mut self, enabled: bool) -> Self { - self.codec_config.enable_h265(enabled); - self - } - - /// Enable VP9 video codec. - /// - /// Enabled by default. - pub fn enable_vp9(mut self, enabled: bool) -> Self { - self.codec_config.enable_vp9(enabled); - self - } - - /// Enable AV1 video codec. - /// - /// Enabled by default. - pub fn enable_av1(mut self, enabled: bool) -> Self { - self.codec_config.enable_av1(enabled); - self - } - - /// Configure the RTP extension mappings. - /// - /// The default extension map is - /// - /// ```ignore - /// # use crate::vendor::str0m::rtp::{Extension, ExtensionMap}; - /// let exts = ExtensionMap::standard(); - /// - /// assert_eq!(exts.id_of(Extension::AudioLevel), Some(1)); - /// assert_eq!(exts.id_of(Extension::AbsoluteSendTime), Some(2)); - /// assert_eq!(exts.id_of(Extension::TransportSequenceNumber), Some(3)); - /// assert_eq!(exts.id_of(Extension::RtpMid), Some(4)); - /// assert_eq!(exts.id_of(Extension::RtpStreamId), Some(10)); - /// assert_eq!(exts.id_of(Extension::RepairedRtpStreamId), Some(11)); - /// assert_eq!(exts.id_of(Extension::VideoOrientation), Some(13)); - /// ``` - pub fn extension_map(&mut self) -> &mut ExtensionMap { - &mut self.exts - } - - /// Set the extension map replacing the existing. - pub fn set_extension_map(mut self, exts: ExtensionMap) -> Self { - self.exts = exts; - self - } - - /// Clear out the standard extension mappings. - pub fn clear_extension_map(mut self) -> Self { - self.exts.clear(); - - self - } - - /// Set an extension mapping on session level. - /// - /// The media level will be capped by the extension enabled on session level. - /// - /// The id must be 1-14 inclusive (1-indexed). - pub fn set_extension(mut self, id: u8, ext: Extension) -> Self { - self.exts.set(id, ext); - self - } - - /// Sets the interval between RTCP sender/receiver reports for audio streams. - /// - /// Defaults to 5 seconds. - /// - /// # Panics - /// - /// Panics if `interval` is zero. - pub fn set_rtcp_report_interval_audio(mut self, interval: Duration) -> Self { - assert!(!interval.is_zero()); - self.intervals.audio = interval; - self - } - - /// Returns the interval between RTCP sender/receiver reports for audio streams. - pub fn rtcp_report_interval_audio(&self) -> Duration { - self.intervals.audio - } - - /// Sets the interval between RTCP sender/receiver reports for video streams. - /// - /// Defaults to 1 second. - /// - /// # Panics - /// - /// Panics if `interval` is zero. - pub fn set_rtcp_report_interval_video(mut self, interval: Duration) -> Self { - assert!(!interval.is_zero()); - self.intervals.video = interval; - self - } - - /// Returns the interval between RTCP sender/receiver reports for video streams. - pub fn rtcp_report_interval_video(&self) -> Duration { - self.intervals.video - } - - /// Sets the number of packets held back for reordering audio packets. - /// - /// Str0m tries to deliver the frames in order. This number determines how many - /// packets to "wait" before releasing media - /// [`contiguous: false`][crate::vendor::str0m::media::MediaData::contiguous]. - /// - /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP - /// packets can arrive out of order. - pub fn set_reordering_size_audio(mut self, size: usize) -> Self { - self.reordering_size_audio = size; - - self - } - - /// Returns the setting for audio reordering size. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to 15. - /// assert_eq!(config.reordering_size_audio(), 15); - /// ``` - /// - /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP - /// packets can arrive out of order. - pub fn reordering_size_audio(&self) -> usize { - self.reordering_size_audio - } - - /// Sets how long the oldest audio frame may wait to finish or for missing earlier packets. - /// - /// On expiry, an incomplete frame is dropped; a complete frame can move past a gap. - /// Later frames stay buffered and retain their own deadlines. The default is 1 second. - /// `None` disables this deadline and keeps count-based waiting only. - /// Applies to audio streams in frame mode, not RTP mode. - pub fn set_reordering_timeout_audio(mut self, timeout: Option) -> Self { - self.reordering_timeout_audio = timeout; - self - } - - /// Returns the configured audio reordering timeout. - pub fn reordering_timeout_audio(&self) -> Option { - self.reordering_timeout_audio - } - - /// Sets the number of packets held back for reordering video packets. - /// - /// Str0m tries to deliver the frames in order. This number determines how many - /// packets to "wait" before releasing media with gaps. - /// - /// This must be at least as big as the number of packets the biggest keyframe - /// can be split over. - /// - /// WARNING: video is very different to audio. Setting this value too low will result in - /// missing video data. The 0 (as described for audio) is not relevant for video. - /// - /// Video recovery waits for a complete successor and missing packets' NACK attempts - /// plus three RTTs. When NACK timing is unavailable, it waits three RTTs from the - /// complete candidate's earliest receipt instead (100 ms RTT until measured). - /// An incomplete frame without a complete successor has no age deadline. - /// - /// Default: 30 - /// - /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP - /// packets can arrive out of order. - pub fn set_reordering_size_video(mut self, size: usize) -> Self { - self.reordering_size_video = size; - - self - } - - /// Returns the setting for video reordering size. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to 30. - /// assert_eq!(config.reordering_size_video(), 30); - /// ``` - /// - /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP - /// packets can arrive out of order. - pub fn reordering_size_video(&self) -> usize { - self.reordering_size_video - } - - /// Sets how long an incoming stream may receive no packets before it is reported paused. - /// Defaults to 1.5 seconds and applies to all incoming streams created by this `Rtc`. - pub fn set_pause_threshold(mut self, threshold: Duration) -> Self { - self.pause_threshold = threshold; - self - } - - /// Returns the incoming stream pause threshold. - pub fn pause_threshold(&self) -> Duration { - self.pause_threshold - } - - /// Sets the buffer size for outgoing audio packets. - /// - /// This must be larger than 0. The value configures an internal ring buffer used as a temporary - /// holding space between calling [`Writer::write`][crate::vendor::str0m::media::Writer::write()] and - /// [`Rtc::poll_output`]. - /// - /// For audio one call to `write()` typically results in one RTP packet since the entire - /// payload fits in one. If you can guarantee that every `write()` is a single RTP packet, - /// and is always followed by a `poll_output()`, it might be possible to set this value to 1. - /// But that would give no margins for unexpected patterns. - /// - /// panics if set to 0. - pub fn set_send_buffer_audio(mut self, size: usize) -> Self { - assert!(size > 0); - self.send_buffer_audio = size; - self - } - - /// Returns the setting for audio resend size. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to 50. - /// assert_eq!(config.send_buffer_audio(), 50); - /// ``` - pub fn send_buffer_audio(&self) -> usize { - self.send_buffer_audio - } - - /// Sets the buffer size for outgoing video packets and resends. - /// - /// This must be larger than 0. The value configures an internal ring buffer that is both - /// used as a temporary holding space between calling - /// [`Writer::write`][crate::vendor::str0m::media::Writer::write()] and [`Rtc::poll_output`] as well as for - /// fulfilling resends. - /// - /// For video, this buffer is used for more than for audio. First, a call to `write()` often - /// results in multiple RTP packets since large frames don't fit in one payload. That means - /// the buffer must be at least as large to hold all those packets. Second, when the remote - /// requests resends (NACK), those are fulfilled from this buffer. - pub fn set_send_buffer_video(mut self, size: usize) -> Self { - self.send_buffer_video = size; - self - } - - /// Returns the setting for video resend size. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to 1000. - /// assert_eq!(config.send_buffer_video(), 1000); - /// ``` - pub fn send_buffer_video(&self) -> usize { - self.send_buffer_video - } - - /// Make the entire Rtc be in RTP mode. - /// - /// This means all media, read from [`RtpPacket`][crate::vendor::str0m::rtp::RtpPacket] and written to - /// [`StreamTx::write_rtp`][crate::vendor::str0m::rtp::StreamTx::write_rtp] are RTP packetized. - /// It bypasses all internal packetization/depacketization inside str0m. - /// - /// WARNING: This is a low level API and is not str0m's primary use case. - pub fn set_rtp_mode(mut self, enabled: bool) -> Self { - self.rtp_mode = enabled; - - self - } - - /// Checks if RTP mode is set. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to false. - /// assert_eq!(config.rtp_mode(), false); - /// ``` - pub fn rtp_mode(&self) -> bool { - self.rtp_mode - } - - /// Enable the [`Event::RawPacket`][crate::vendor::str0m::Event::RawPacket] event. - /// - /// This clones data, and is therefore expensive. - /// Should not be enabled outside of tests and troubleshooting. - pub fn enable_raw_packets(mut self, enabled: bool) -> Self { - self.enable_raw_packets = enabled; - self - } - - /// Set the MTU as a `target..=warn` inclusive range. - /// - /// * `*range.start()` is the **target** MTU: the size str0m aims for when - /// fragmenting outgoing packets. Must be within - /// `[DATAGRAM_MTU_TARGET_MIN, DATAGRAM_MTU_TARGET_MAX]`. - /// * `*range.end()` is the **warn** threshold: packets whose length - /// exceeds the target trigger a warning. - /// - /// Set as `target..=target` to warn packets bigger than target. - /// Set as `target..=usize::MAX` to disable warning. - /// - /// Defaults to `DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN`. - pub fn set_mtu(mut self, range: RangeInclusive) -> Self { - let (start, end) = (*range.start(), *range.end()); - assert!( - DATAGRAM_MTU_TARGET_MIN <= start && start <= DATAGRAM_MTU_TARGET_MAX, - "mtu target {} out of bounds [{}, {}]", - start, - DATAGRAM_MTU_TARGET_MIN, - DATAGRAM_MTU_TARGET_MAX, - ); - assert!(start <= end, "mtu range start must be <= end, got {}..={}", start, end,); - self.mtu = range; - self - } - - /// Get the configured target MTU (the value str0m aims for). - pub fn mtu(&self) -> usize { - *self.mtu.start() - } - - /// Get the configured warn threshold above which outgoing packets - /// trigger a warning trace. - pub fn mtu_warn(&self) -> usize { - *self.mtu.end() - } - - /// Set the VP9 packetizer mode. - /// - /// VP9 supports two RTP payload descriptor formats: - /// - /// * [`Vp9PacketizerMode::NonFlexible`] (default) - 5-6 byte header with layer indices - /// and scalability structure. Compatible with all major browsers including Safari. - /// * [`Vp9PacketizerMode::Flexible`] - minimal 3-byte header. Simpler but may cause - /// issues with Safari which drops inter-frames. - pub fn set_vp9_packetizer_mode(mut self, mode: Vp9PacketizerMode) -> Self { - self.vp9_packetizer_mode = mode; - self - } - - /// Returns the configured VP9 packetizer mode. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::format::Vp9PacketizerMode; - /// let config = Rtc::builder(); - /// - /// // Defaults to NonFlexible. - /// assert_eq!(config.vp9_packetizer_mode(), Vp9PacketizerMode::NonFlexible); - /// ``` - pub fn vp9_packetizer_mode(&self) -> Vp9PacketizerMode { - self.vp9_packetizer_mode - } - - /// Create a [`Rtc`] from the configuration. - pub fn build(self, start: Instant) -> Rtc { - Rtc::new_from_config(self, start).expect("Failed to create Rtc from config") - } -} - -impl Default for RtcConfig { - fn default() -> Self { - Self { - local_ice_credentials: None, - crypto_provider: None, - dtls_cert: None, - fingerprint_verification: true, - ice_lite: false, - initial_stun_rto: None, - max_stun_rto: None, - max_stun_retransmits: None, - codec_config: CodecConfig::new_with_defaults(), - exts: ExtensionMap::standard(), - intervals: RtcpReportIntervals { - audio: Duration::from_secs(5), - video: Duration::from_secs(1), - }, - reordering_size_audio: 15, - reordering_size_video: 30, - reordering_timeout_audio: Some(Duration::from_secs(1)), - pause_threshold: Duration::from_millis(1500), - send_buffer_audio: 50, - send_buffer_video: 1000, - rtp_mode: false, - enable_raw_packets: false, - vp9_packetizer_mode: Vp9PacketizerMode::default(), - mtu: DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn default_mtu_is_datagram_mtu_target() { - let cfg = RtcConfig::default(); - assert_eq!(cfg.mtu(), DATAGRAM_MTU_TARGET); - assert_eq!(cfg.mtu_warn(), DATAGRAM_MTU_WARN); - } - - #[test] - fn set_mtu_round_trips() { - let cfg = RtcConfig::default().set_mtu(900..=1400); - assert_eq!(cfg.mtu(), 900); - assert_eq!(cfg.mtu_warn(), 1400); - - let cfg = RtcConfig::default().set_mtu(900..=usize::MAX); - assert_eq!(cfg.mtu(), 900); - assert_eq!(cfg.mtu_warn(), usize::MAX); - } - - #[test] - fn set_mtu_accepts_equal_bounds() { - let cfg = RtcConfig::default().set_mtu(1200..=1200); - assert_eq!(cfg.mtu(), 1200); - assert_eq!(cfg.mtu_warn(), 1200); - - let cfg = RtcConfig::default().set_mtu(DATAGRAM_MTU_TARGET_MIN..=DATAGRAM_MTU_TARGET_MIN); - assert_eq!(cfg.mtu(), DATAGRAM_MTU_TARGET_MIN); - - let cfg = RtcConfig::default().set_mtu(DATAGRAM_MTU_TARGET_MAX..=DATAGRAM_MTU_TARGET_MAX); - assert_eq!(cfg.mtu(), DATAGRAM_MTU_TARGET_MAX); - } - - #[test] - #[should_panic(expected = "mtu target")] - fn set_mtu_panics_on_target_below_min() { - let _ = RtcConfig::default().set_mtu((DATAGRAM_MTU_TARGET_MIN - 1)..=usize::MAX); - } - - #[test] - #[should_panic(expected = "mtu target")] - fn set_mtu_panics_on_target_above_max() { - let _ = RtcConfig::default().set_mtu((DATAGRAM_MTU_TARGET_MAX + 1)..=usize::MAX); - } - - #[test] - #[should_panic(expected = "mtu range start must be <= end")] - fn set_mtu_panics_on_inverted_range() { - let _ = RtcConfig::default().set_mtu(RangeInclusive::new(1300, 1299)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/crypto/finger.rs b/rs/moq-webrtc/src/vendor/str0m/crypto/finger.rs deleted file mode 100644 index b745832a87e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/crypto/finger.rs +++ /dev/null @@ -1,124 +0,0 @@ -use core::fmt; - -use subtle::ConstantTimeEq; - -use super::CryptoProvider; - -/// Certificate fingerprint. -/// -/// DTLS uses self signed certificates, and the fingerprint is communicated via -/// SDP to let the remote peer verify who is connecting. -#[derive(Debug, Clone)] -pub struct Fingerprint { - /// Hash function used to produce the `bytes`. - /// - /// This is normally `sha-256`. - pub hash_func: String, - - /// Digest of the certificate by the algorithm in `hash_func`. - pub bytes: Vec, -} - -impl Fingerprint { - /// Prefer SHA-256 to SHA-1, and supported algorithms to unsupported ones. - /// Lower values mean higher preference (RFC 8122 §5.1). - pub(crate) fn hash_preference(&self) -> u8 { - if self.hash_func.eq_ignore_ascii_case("sha-256") { - 0 - } else if self.hash_func.eq_ignore_ascii_case("sha-1") { - 1 - } else { - 2 - } - } - - /// The fingerprint of a DER certificate made with `hash_func`, the hash - /// function the remote SDP names (RFC 8122 §5, case-insensitive). Only - /// `sha-256` and `sha-1` are supported; `None` for any other. - /// - /// The result keeps `hash_func` as given, so it compares equal to the - /// remote fingerprint when the digests match. - pub(crate) fn of_certificate(der: &[u8], hash_func: &str, provider: &CryptoProvider) -> Option { - let bytes = if hash_func.eq_ignore_ascii_case("sha-256") { - provider.sha256_provider.sha256(der).to_vec() - } else if hash_func.eq_ignore_ascii_case("sha-1") { - provider.sha1_provider.sha1(der).to_vec() - } else { - return None; - }; - Some(Fingerprint { - hash_func: hash_func.to_owned(), - bytes, - }) - } -} - -impl PartialEq for Fingerprint { - fn eq(&self, other: &Self) -> bool { - // Use constant-time comparison for the bytes to prevent timing attacks - self.hash_func == other.hash_func && self.bytes[..].ct_eq(&other.bytes[..]).into() - } -} - -impl Eq for Fingerprint {} - -impl std::hash::Hash for Fingerprint { - fn hash(&self, state: &mut H) { - self.hash_func.hash(state); - self.bytes.hash(state); - } -} - -// DO NOT CHANGE! -// This format is exactly what's needed in n SDP. -impl fmt::Display for Fingerprint { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} ", self.hash_func)?; - for (i, b) in self.bytes.iter().enumerate() { - if i > 0 { - write!(f, ":")?; - } - write!(f, "{:02X}", b)?; - } - Ok(()) - } -} - -impl std::str::FromStr for Fingerprint { - type Err = String; - - fn from_str(hex_string: &str) -> Result { - let (hash_func, hex_with_colons) = hex_string - .split_once(' ') - .ok_or_else(|| "Failed to split once".to_owned())?; - - let mut bytes = Vec::new(); - for hex in hex_with_colons.split(':') { - let byte = u8::from_str_radix(hex, 16).map_err(|e| format!("Failed to parse fingerprint: {}", e))?; - bytes.push(byte); - } - - Ok(Self { - hash_func: hash_func.to_owned(), - bytes, - }) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn fingerprint_format() { - let f = Fingerprint { - hash_func: "foo".to_string(), - bytes: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], - }; - - assert_eq!( - f.to_string(), - "foo 00:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F:10:11" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs b/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs deleted file mode 100644 index f6c1347b77b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/crypto/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -use crate::vendor::str0m_proto::crypto as provider; - -pub use provider::{AeadAes128Gcm, AeadAes128GcmCipher, AeadAes256Gcm, AeadAes256GcmCipher}; -pub use provider::{Aes128CmSha1_80, Aes128CmSha1_80Cipher, CryptoProvider, CryptoSafe}; -pub use provider::{Sha1HmacProvider, Sha1Provider, Sha256Provider}; -pub use provider::{SrtpProvider, SupportedAeadAes128Gcm}; -pub use provider::{SupportedAeadAes256Gcm, SupportedAes128CmSha1_80}; - -/// DTLS related types and traits. -pub mod dtls { - pub use super::provider::dtls::{DtlsInstance, DtlsProvider}; - - pub use crate::vendor::dimpl::DtlsCertificate as DtlsCert; - pub use crate::vendor::dimpl::KeyingMaterial; - pub use crate::vendor::dimpl::ProtocolVersion; - pub use crate::vendor::dimpl::SrtpProfile; - // Note: crate::vendor::dimpl::Error is renamed to DtlsImplError to avoid conflict with str0m's DtlsError - pub use crate::vendor::dimpl::{Error as DtlsImplError, Output as DtlsOutput}; -} - -#[cfg(test)] -#[allow(unused)] -pub(crate) fn test_default_provider() -> &'static CryptoProvider { - use std::sync::OnceLock; - static TEST_PROVIDER: OnceLock = OnceLock::new(); - TEST_PROVIDER.get_or_init(from_feature_flags) -} - -/// The default crypto provider: rind, the only backend kept in the vendored copy. -/// -/// Panics on a CPU rind refuses, so moq-webrtc checks the CPU before building an `Rtc`. -pub fn from_feature_flags() -> CryptoProvider { - crate::vendor::str0m_rind::default_provider().expect("rind refuses this CPU") -} - -mod finger; -pub use finger::Fingerprint; - -pub use crate::vendor::str0m_proto::crypto::{CryptoError, DtlsError}; diff --git a/rs/moq-webrtc/src/vendor/str0m/docs/chrome-sdp.json b/rs/moq-webrtc/src/vendor/str0m/docs/chrome-sdp.json deleted file mode 100644 index f8137918cee..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/docs/chrome-sdp.json +++ /dev/null @@ -1,193 +0,0 @@ -{ - "direction": "Send", - "reason": "negotiate", - "type": "offer", - "time": "2022-08-18T18:42:04.008Z", - "sdp": [ - "v=0", - "o=- 2954344436352400798 4 IN IP4 127.0.0.1", - "s=-", - "t=0 0", - "a=group:BUNDLE 0 1 2", - "a=extmap-allow-mixed", - "a=msid-semantic: WMS bce3d790-a073-42ae-89e6-6a8979f4e203", - "m=application 64356 UDP/DTLS/SCTP webrtc-datachannel", - "c=IN IP4 192.168.115.173", - "a=candidate:1669605774 1 udp 2122260223 192.168.115.173 64356 typ host generation 0 network-id 1 network-cost 10", - "a=candidate:755488126 1 tcp 1518280447 192.168.115.173 9 typ host tcptype active generation 0 network-id 1 network-cost 10", - "a=ice-ufrag:v8Lx", - "a=ice-pwd:GdpW980Caww9WWsbg6jJ5pGu", - "a=ice-options:trickle", - "a=fingerprint:sha-256 7A:D7:C9:33:94:8D:8A:BA:10:EB:93:21:7C:B4:91:6D:40:F7:56:07:CA:9D:42:D3:80:32:2D:10:D9:AC:8E:15", - "a=setup:actpass", - "a=mid:0", - "a=sctp-port:5000", - "a=max-message-size:262144", - "m=audio 9 UDP/TLS/RTP/SAVPF 111 63 103 104 9 0 8 106 105 13 110 112 113 126", - "c=IN IP4 0.0.0.0", - "a=rtcp:9 IN IP4 0.0.0.0", - "a=ice-ufrag:v8Lx", - "a=ice-pwd:GdpW980Caww9WWsbg6jJ5pGu", - "a=ice-options:trickle", - "a=fingerprint:sha-256 7A:D7:C9:33:94:8D:8A:BA:10:EB:93:21:7C:B4:91:6D:40:F7:56:07:CA:9D:42:D3:80:32:2D:10:D9:AC:8E:15", - "a=setup:actpass", - "a=mid:1", - "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level", - "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time", - "a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01", - "a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid", - "a=sendonly", - "a=msid:bce3d790-a073-42ae-89e6-6a8979f4e203 37d89104-03a9-4be0-8cf4-50310d61b211", - "a=rtcp-mux", - "a=rtpmap:111 opus/48000/2", - "a=rtcp-fb:111 transport-cc", - "a=fmtp:111 minptime=10;useinbandfec=1", - "a=rtpmap:63 red/48000/2", - "a=fmtp:63 111/111", - "a=rtpmap:103 ISAC/16000", - "a=rtpmap:104 ISAC/32000", - "a=rtpmap:9 G722/8000", - "a=rtpmap:0 PCMU/8000", - "a=rtpmap:8 PCMA/8000", - "a=rtpmap:106 CN/32000", - "a=rtpmap:105 CN/16000", - "a=rtpmap:13 CN/8000", - "a=rtpmap:110 telephone-event/48000", - "a=rtpmap:112 telephone-event/32000", - "a=rtpmap:113 telephone-event/16000", - "a=rtpmap:126 telephone-event/8000", - "a=ssrc:2096647523 cname:XafHSPS71ySwVueL", - "a=ssrc:2096647523 msid:bce3d790-a073-42ae-89e6-6a8979f4e203 37d89104-03a9-4be0-8cf4-50310d61b211", - "m=video 9 UDP/TLS/RTP/SAVPF 96 97 127 121 125 107 108 109 124 120 123 119 35 36 41 42 98 99 100 101 114 115 116 117 118", - "c=IN IP4 0.0.0.0", - "a=rtcp:9 IN IP4 0.0.0.0", - "a=ice-ufrag:v8Lx", - "a=ice-pwd:GdpW980Caww9WWsbg6jJ5pGu", - "a=ice-options:trickle", - "a=fingerprint:sha-256 7A:D7:C9:33:94:8D:8A:BA:10:EB:93:21:7C:B4:91:6D:40:F7:56:07:CA:9D:42:D3:80:32:2D:10:D9:AC:8E:15", - "a=setup:actpass", - "a=mid:2", - "a=extmap:14 urn:ietf:params:rtp-hdrext:toffset", - "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time", - "a=extmap:13 urn:3gpp:video-orientation", - "a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01", - "a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay", - "a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type", - "a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing", - "a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space", - "a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid", - "a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id", - "a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id", - "a=sendonly", - "a=msid:bce3d790-a073-42ae-89e6-6a8979f4e203 a7fb716d-5759-4f9c-80a7-3a3d1833b429", - "a=rtcp-mux", - "a=rtcp-rsize", - "a=rtpmap:96 VP8/90000", - "a=rtcp-fb:96 goog-remb", - "a=rtcp-fb:96 transport-cc", - "a=rtcp-fb:96 ccm fir", - "a=rtcp-fb:96 nack", - "a=rtcp-fb:96 nack pli", - "a=rtpmap:97 rtx/90000", - "a=fmtp:97 apt=96", - "a=rtpmap:127 H264/90000", - "a=rtcp-fb:127 goog-remb", - "a=rtcp-fb:127 transport-cc", - "a=rtcp-fb:127 ccm fir", - "a=rtcp-fb:127 nack", - "a=rtcp-fb:127 nack pli", - "a=fmtp:127 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f", - "a=rtpmap:121 rtx/90000", - "a=fmtp:121 apt=127", - "a=rtpmap:125 H264/90000", - "a=rtcp-fb:125 goog-remb", - "a=rtcp-fb:125 transport-cc", - "a=rtcp-fb:125 ccm fir", - "a=rtcp-fb:125 nack", - "a=rtcp-fb:125 nack pli", - "a=fmtp:125 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f", - "a=rtpmap:107 rtx/90000", - "a=fmtp:107 apt=125", - "a=rtpmap:108 H264/90000", - "a=rtcp-fb:108 goog-remb", - "a=rtcp-fb:108 transport-cc", - "a=rtcp-fb:108 ccm fir", - "a=rtcp-fb:108 nack", - "a=rtcp-fb:108 nack pli", - "a=fmtp:108 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", - "a=rtpmap:109 rtx/90000", - "a=fmtp:109 apt=108", - "a=rtpmap:124 H264/90000", - "a=rtcp-fb:124 goog-remb", - "a=rtcp-fb:124 transport-cc", - "a=rtcp-fb:124 ccm fir", - "a=rtcp-fb:124 nack", - "a=rtcp-fb:124 nack pli", - "a=fmtp:124 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f", - "a=rtpmap:120 rtx/90000", - "a=fmtp:120 apt=124", - "a=rtpmap:123 H264/90000", - "a=rtcp-fb:123 goog-remb", - "a=rtcp-fb:123 transport-cc", - "a=rtcp-fb:123 ccm fir", - "a=rtcp-fb:123 nack", - "a=rtcp-fb:123 nack pli", - "a=fmtp:123 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f", - "a=rtpmap:119 rtx/90000", - "a=fmtp:119 apt=123", - "a=rtpmap:35 H264/90000", - "a=rtcp-fb:35 goog-remb", - "a=rtcp-fb:35 transport-cc", - "a=rtcp-fb:35 ccm fir", - "a=rtcp-fb:35 nack", - "a=rtcp-fb:35 nack pli", - "a=fmtp:35 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f", - "a=rtpmap:36 rtx/90000", - "a=fmtp:36 apt=35", - "a=rtpmap:41 AV1/90000", - "a=rtcp-fb:41 goog-remb", - "a=rtcp-fb:41 transport-cc", - "a=rtcp-fb:41 ccm fir", - "a=rtcp-fb:41 nack", - "a=rtcp-fb:41 nack pli", - "a=rtpmap:42 rtx/90000", - "a=fmtp:42 apt=41", - "a=rtpmap:98 VP9/90000", - "a=rtcp-fb:98 goog-remb", - "a=rtcp-fb:98 transport-cc", - "a=rtcp-fb:98 ccm fir", - "a=rtcp-fb:98 nack", - "a=rtcp-fb:98 nack pli", - "a=fmtp:98 profile-id=0", - "a=rtpmap:99 rtx/90000", - "a=fmtp:99 apt=98", - "a=rtpmap:100 VP9/90000", - "a=rtcp-fb:100 goog-remb", - "a=rtcp-fb:100 transport-cc", - "a=rtcp-fb:100 ccm fir", - "a=rtcp-fb:100 nack", - "a=rtcp-fb:100 nack pli", - "a=fmtp:100 profile-id=2", - "a=rtpmap:101 rtx/90000", - "a=fmtp:101 apt=100", - "a=rtpmap:114 H264/90000", - "a=rtcp-fb:114 goog-remb", - "a=rtcp-fb:114 transport-cc", - "a=rtcp-fb:114 ccm fir", - "a=rtcp-fb:114 nack", - "a=rtcp-fb:114 nack pli", - "a=fmtp:114 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f", - "a=rtpmap:115 rtx/90000", - "a=fmtp:115 apt=114", - "a=rtpmap:116 red/90000", - "a=rtpmap:117 rtx/90000", - "a=fmtp:117 apt=116", - "a=rtpmap:118 ulpfec/90000", - "a=ssrc-group:FID 2796837875 1979944319", - "a=ssrc:2796837875 cname:XafHSPS71ySwVueL", - "a=ssrc:2796837875 msid:bce3d790-a073-42ae-89e6-6a8979f4e203 a7fb716d-5759-4f9c-80a7-3a3d1833b429", - "a=ssrc:1979944319 cname:XafHSPS71ySwVueL", - "a=ssrc:1979944319 msid:bce3d790-a073-42ae-89e6-6a8979f4e203 a7fb716d-5759-4f9c-80a7-3a3d1833b429", - "" - ] -} diff --git a/rs/moq-webrtc/src/vendor/str0m/dtls.rs b/rs/moq-webrtc/src/vendor/str0m/dtls.rs deleted file mode 100644 index fca90a2f469..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/dtls.rs +++ /dev/null @@ -1,232 +0,0 @@ -use std::collections::VecDeque; -use std::io; -use std::ops::RangeInclusive; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::time::Instant; -use tracing::{debug, warn}; - -use crate::vendor::str0m::crypto::Fingerprint; -use crate::vendor::str0m::crypto::Sha256Provider; -use crate::vendor::str0m::crypto::dtls::{DtlsCert, DtlsOutput, ProtocolVersion}; -use crate::vendor::str0m::crypto::dtls::{DtlsInstance, DtlsProvider}; -use crate::vendor::str0m::crypto::{CryptoError, DtlsError}; -use crate::vendor::str0m::io::DatagramSend; -use crate::vendor::str0m::util::{already_happened, not_happening}; - -/// Encapsulation of DTLS. -/// -/// This is a thin wrapper around `DtlsInstance` that adds fingerprint tracking -/// and active/passive state management. The API follows dimpl's sans-IO pattern. -pub struct Dtls { - /// The underlying DTLS instance. - instance: Box, - - /// The fingerprint of the local certificate. - fingerprint: Fingerprint, - - /// Remote fingerprint (set when received via poll_output). - remote_fingerprint: Option, - - /// Whether set_active has been called. - active_state: Option, - - /// Packets to be sent. - pending_packets: VecDeque, - - /// Target MTU (start) and warn threshold (end). The target is forwarded to - /// the backend's fragmenter; outgoing records larger than the warn - /// threshold log a warning. - mtu: RangeInclusive, -} - -pub(crate) fn is_would_block(error: &DtlsError) -> bool { - match error { - DtlsError::Io(e) => e.kind() == io::ErrorKind::WouldBlock, - DtlsError::CryptoError(crypto_err) => match crypto_err { - CryptoError::Io(e) => e.kind() == io::ErrorKind::WouldBlock, - #[allow(unreachable_patterns)] - _ => false, - }, - } -} - -impl UnwindSafe for Dtls {} -impl RefUnwindSafe for Dtls {} - -impl Dtls { - /// Creates a new DTLS instance. - pub fn new( - cert: &DtlsCert, - dtls_provider: &dyn DtlsProvider, - sha256_provider: &dyn Sha256Provider, - now: Instant, - mtu: RangeInclusive, - ) -> Result { - let instance = dtls_provider - .new_dtls(cert, now, Some(*mtu.start())) - .map_err(DtlsError::CryptoError)?; - - // Compute fingerprint from the certificate DER bytes - let fingerprint = Fingerprint { - hash_func: "sha-256".to_string(), - bytes: sha256_provider.sha256(&cert.certificate).to_vec(), - }; - - Ok(Self { - instance, - fingerprint, - remote_fingerprint: None, - active_state: None, - pending_packets: VecDeque::new(), - mtu, - }) - } - - /// Threshold above which an outgoing DTLS record triggers an MTU warning. - pub fn mtu_warn(&self) -> usize { - *self.mtu.end() - } - - /// Tells if this instance has been inited (set_active called). - pub fn is_inited(&self) -> bool { - self.active_state.is_some() - } - - /// Set whether this instance is active (client) or passive (server). - pub fn set_active(&mut self, active: bool) { - self.active_state = Some(active); - self.instance.set_active(active) - } - - /// If set_active was called, returns what was set. - pub fn is_active(&self) -> Option { - self.active_state - } - - /// The local certificate fingerprint. - pub fn local_fingerprint(&self) -> &Fingerprint { - &self.fingerprint - } - - /// Remote fingerprint, if received. - pub fn remote_fingerprint(&self) -> Option<&Fingerprint> { - self.remote_fingerprint.as_ref() - } - - /// The negotiated DTLS protocol version, or `None` before handshake completion. - pub fn protocol_version(&self) -> Option { - self.instance.protocol_version() - } - - pub fn is_closed(&self) -> bool { - self.pending_packets.is_empty() && self.instance.is_closed() - } - - /// Set the remote fingerprint (extracted from peer certificate). - pub fn set_remote_fingerprint(&mut self, fingerprint: Fingerprint) { - self.remote_fingerprint = Some(fingerprint); - } - - /// Poll for output from the DTLS instance. - pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a> { - if !self.is_inited() { - return DtlsOutput::Timeout(not_happening()); - } - - let next = self.instance.poll_output(buf); - - if let DtlsOutput::Packet(packet) = next { - if packet.len() > self.mtu_warn() { - warn!("DTLS above MTU {}: {}", self.mtu_warn(), packet.len()); - } - self.pending_packets.push_back(packet.to_vec().into()); - - // Return timeout indicating we want another poll straight away - return DtlsOutput::Timeout(already_happened()); - } - - next - } - - pub fn poll_packet(&mut self) -> Option { - self.pending_packets.pop_front() - } - - /// Handle an incoming DTLS packet. - pub fn handle_receive(&mut self, packet: &[u8]) -> Result<(), DtlsError> { - if !self.is_inited() { - debug!("Ignoring DTLS datagram prior to DTLS start"); - return Ok(()); - } - - self.instance - .handle_packet(packet) - .map_err(|e| DtlsError::CryptoError(CryptoError::DtlsImpl(e))) - } - - /// Send application data over DTLS. - pub fn handle_input(&mut self, data: &[u8]) -> Result<(), DtlsError> { - fn make_handshake_pending_err() -> DtlsError { - DtlsError::Io(io::Error::new(io::ErrorKind::WouldBlock, "DTLS handshake pending")) - } - - // Don't rely on the inner instance for proper pre-init behavior. - if !self.is_inited() { - return Err(make_handshake_pending_err()); - } - - let accepted = self - .instance - .send_application_data(data) - .map_err(|e| DtlsError::CryptoError(CryptoError::DtlsImpl(e)))?; - - if accepted != data.len() { - return Err(make_handshake_pending_err()); - } - - Ok(()) - } - - /// Handle a timeout event. - pub fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsError> { - if !self.is_inited() { - return Ok(()); - } - - self.instance - .handle_timeout(now) - .map_err(|e| DtlsError::CryptoError(CryptoError::DtlsImpl(e))) - } - - /// Initiate graceful shutdown by sending a close_notify alert. - pub fn close(&mut self) -> Result<(), DtlsError> { - self.instance - .close() - .map_err(|e| DtlsError::CryptoError(CryptoError::DtlsImpl(e))) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn new_dtls(now: Instant) -> Dtls { - let provider = crate::vendor::str0m::crypto::test_default_provider(); - let cert = provider.dtls_provider.generate_certificate().unwrap(); - Dtls::new( - &cert, - provider.dtls_provider, - provider.sha256_provider, - now, - 1200..=1500, - ) - .unwrap() - } - - #[test] - fn input_before_initialization_would_block() { - let mut dtls = new_dtls(Instant::now()); - let err = dtls.handle_input(b"application data").unwrap_err(); - assert!(is_would_block(&err)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/error.rs b/rs/moq-webrtc/src/vendor/str0m/error.rs deleted file mode 100644 index d3cbf8b9fc1..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/error.rs +++ /dev/null @@ -1,166 +0,0 @@ -//! Various error types. - -use std::error::Error; -use std::fmt; - -// Re-export all error types for convenience -pub use crate::vendor::is::IceError; -pub use crate::vendor::str0m::crypto::DtlsError; -pub use crate::vendor::str0m::io::NetError; -pub use crate::vendor::str0m::packet::{PacketError, Vp8DescriptorError, Vp8PatchError}; -pub use crate::vendor::str0m::rtp_::RtpError; -pub use crate::vendor::str0m::sdp::SdpError; - -use crate::vendor::str0m::{Direction, KeyframeRequestKind, Mid, Pt, Rid}; - -/// Errors for the whole Rtc engine. -#[derive(Debug)] -#[non_exhaustive] -pub enum RtcError { - /// Some problem with the remote SDP. - RemoteSdp(String), - - /// SDP errors. - Sdp(SdpError), - - /// RTP errors. - Rtp(RtpError), - - /// Other IO errors. - Io(std::io::Error), - - /// DTLS errors - Dtls(DtlsError), - - /// RTP packetization, depacketization, or payload validation error. - Packet(Mid, Pt, PacketError), - - /// The PT attempted to write to is not known. - UnknownPt(Pt), - - /// The Rid attempted to write is not known. - UnknownRid(Rid), - - /// If MediaWriter.write fails because we can't find an SSRC to use. - NoSenderSource, - - /// Using `write_rtp` for a stream with RTX without providing a rtx_pt. - ResendRequiresRtxPt, - - /// Direction does not allow sending of Media data. - NotSendingDirection(Direction), - - /// Direction does not allow receiving media data. - NotReceivingDirection, - - /// If MediaWriter.request_keyframe fails because we can't find an SSRC to use. - NoReceiverSource(Option), - - /// The keyframe request failed because the kind of request is not enabled - /// in the media. - FeedbackNotEnabled(KeyframeRequestKind), - - /// Parser errors from network packet parsing. - Net(NetError), - - /// ICE agent errors. - Ice(IceError), - - /// [`crate::vendor::str0m::change::SdpApi`] was not done in a correct order. - /// - /// For [`crate::vendor::str0m::change::SdpApi`]: - /// - /// 1. We created an [`crate::vendor::str0m::change::SdpOffer`]. - /// 2. The remote side created an [`crate::vendor::str0m::change::SdpOffer`] at the same time. - /// 3. We applied the remote side [`crate::vendor::str0m::change::SdpApi::accept_offer`]. - /// 4. The we used the [`crate::vendor::str0m::change::SdpPendingOffer`] created in step 1. - ChangesOutOfOrder, - - /// The [`crate::vendor::str0m::media::Writer`] was used twice without doing [`crate::vendor::str0m::Rtc::poll_output`] in between. This - /// is an incorrect usage pattern of the str0m API. - WriteWithoutPoll, -} - -impl fmt::Display for RtcError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - RtcError::RemoteSdp(msg) => write!(f, "remote sdp: {}", msg), - RtcError::Sdp(err) => write!(f, "{}", err), - RtcError::Rtp(err) => write!(f, "{}", err), - RtcError::Io(err) => write!(f, "{}", err), - RtcError::Dtls(err) => write!(f, "{}", err), - RtcError::Packet(mid, pt, err) => write!(f, "{} {} {}", mid, pt, err), - RtcError::UnknownPt(pt) => write!(f, "PT is unknown {}", pt), - RtcError::UnknownRid(rid) => write!(f, "RID is unknown {}", rid), - RtcError::NoSenderSource => write!(f, "No sender source"), - RtcError::ResendRequiresRtxPt => write!( - f, - "When outgoing stream has RTX, write_rtp must be called with rtp_pt set" - ), - RtcError::NotSendingDirection(dir) => { - write!(f, "Direction does not allow sending: {}", dir) - } - RtcError::NotReceivingDirection => write!(f, "Direction does not allow receiving"), - RtcError::NoReceiverSource(rid) => write!(f, "No receiver source (rid: {:?})", rid), - RtcError::FeedbackNotEnabled(kind) => { - write!(f, "Requested feedback is not enabled: {:?}", kind) - } - RtcError::Net(err) => write!(f, "{}", err), - RtcError::Ice(err) => write!(f, "{}", err), - RtcError::ChangesOutOfOrder => write!(f, "Changes made out of order"), - RtcError::WriteWithoutPoll => write!(f, "Consecutive calls to write() without poll_output() in between"), - } - } -} - -impl Error for RtcError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - RtcError::Sdp(err) => Some(err), - RtcError::Rtp(err) => Some(err), - RtcError::Io(err) => Some(err), - RtcError::Dtls(err) => Some(err), - RtcError::Packet(_, _, err) => Some(err), - RtcError::Net(err) => Some(err), - RtcError::Ice(err) => Some(err), - _ => None, - } - } -} - -// From implementations for error conversions -impl From for RtcError { - fn from(err: SdpError) -> Self { - RtcError::Sdp(err) - } -} - -impl From for RtcError { - fn from(err: RtpError) -> Self { - RtcError::Rtp(err) - } -} - -impl From for RtcError { - fn from(err: std::io::Error) -> Self { - RtcError::Io(err) - } -} - -impl From for RtcError { - fn from(err: DtlsError) -> Self { - RtcError::Dtls(err) - } -} - -impl From for RtcError { - fn from(err: NetError) -> Self { - RtcError::Net(err) - } -} - -impl From for RtcError { - fn from(err: IceError) -> Self { - RtcError::Ice(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/format/codec.rs b/rs/moq-webrtc/src/vendor/str0m/format/codec.rs deleted file mode 100644 index 3e4f808568c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/format/codec.rs +++ /dev/null @@ -1,103 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::fmt; - -use crate::vendor::str0m::packet::MediaKind; -use crate::vendor::str0m::rtp_::Frequency; - -use super::format_params::FormatParams; - -/// Codec specification -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct CodecSpec { - /// The codec identifier. - pub codec: Codec, - - /// Clock rate of the codec. - pub clock_rate: Frequency, - - /// Number of audio channels (if any). - pub channels: Option, - - /// Codec specific format parameters. This might carry additional config for - /// things like h264. - pub format: FormatParams, -} - -/// Known codecs and RTP payload formats. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[non_exhaustive] -#[allow(missing_docs)] -pub enum Codec { - Opus, - AmrWb, - H264, - // TODO show this when we support h265. - H265, - Vp8, - Vp9, - // TODO show this when we support Av1. - Av1, - /// Technically not a codec, but used in places where codecs go - /// in `a=rtpmap` lines. - Rtx, - /// For RTP mode. No codec. - Null, - Unknown, -} - -impl Codec { - /// Tells if codec is audio. - pub fn is_audio(&self) -> bool { - use Codec::*; - matches!(self, Opus | AmrWb) - } - - /// Tells if codec is video. - pub fn is_video(&self) -> bool { - use Codec::*; - matches!(self, H265 | H264 | Vp8 | Vp9 | Av1) - } - - /// Audio/Video. - pub fn kind(&self) -> MediaKind { - if self.is_audio() { - MediaKind::Audio - } else { - MediaKind::Video - } - } -} - -impl<'a> From<&'a str> for Codec { - fn from(v: &'a str) -> Self { - let lc = v.to_ascii_lowercase(); - match &lc[..] { - "opus" => Codec::Opus, - "amr-wb" => Codec::AmrWb, - "h264" => Codec::H264, - "h265" => Codec::H265, - "vp8" => Codec::Vp8, - "vp9" => Codec::Vp9, - "av1" => Codec::Av1, - "rtx" => Codec::Rtx, // resends - _ => Codec::Unknown, - } - } -} - -impl fmt::Display for Codec { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Codec::Opus => write!(f, "opus"), - Codec::AmrWb => write!(f, "AMR-WB"), - Codec::H264 => write!(f, "H264"), - Codec::H265 => write!(f, "H265"), - Codec::Vp8 => write!(f, "VP8"), - Codec::Vp9 => write!(f, "VP9"), - Codec::Av1 => write!(f, "AV1"), - Codec::Rtx => write!(f, "rtx"), - Codec::Null => write!(f, "null"), - Codec::Unknown => write!(f, "unknown"), - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/format/codec_config.rs b/rs/moq-webrtc/src/vendor/str0m/format/codec_config.rs deleted file mode 100644 index de37e02e63b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/format/codec_config.rs +++ /dev/null @@ -1,1079 +0,0 @@ -use std::collections::HashSet; -use std::ops::{Deref, DerefMut}; -use tracing::debug; - -use crate::vendor::str0m::packet::MediaKind; -use crate::vendor::str0m::rtp_::Pt; -use crate::vendor::str0m::rtp_::{Direction, Frequency}; - -use super::codec::{Codec, CodecSpec}; -use super::format_params::FormatParams; -use super::payload_params::{Claimed, PREFERED_RANGES, PayloadParams}; - -/// Default payload type for VP8. -pub(crate) const PT_VP8: Pt = Pt::new_with_value(96); - -/// Default payload type for VP8 RTX. -pub(crate) const PT_VP8_RTX: Pt = Pt::new_with_value(97); - -/// Default payload type for VP9 profile 0. -pub(crate) const PT_VP9: Pt = Pt::new_with_value(98); - -/// Default payload type for VP9 profile 0 RTX. -pub(crate) const PT_VP9_RTX: Pt = Pt::new_with_value(99); - -/// Default payload type for AV1. -pub(crate) const PT_AV1: Pt = Pt::new_with_value(45); - -/// Default payload type for AV1 RTX. -pub(crate) const PT_AV1_RTX: Pt = Pt::new_with_value(46); - -/// Default payload type for H265. -pub(crate) const PT_H265: Pt = Pt::new_with_value(102); - -/// Default payload type for H265 RTX. -pub(crate) const PT_H265_RTX: Pt = Pt::new_with_value(103); - -/// Default payload type for Opus. -pub(crate) const PT_OPUS: Pt = Pt::new_with_value(111); - -/// Default payload type for AMR-WB. -pub(crate) const PT_AMR_WB: Pt = Pt::new_with_value(122); - -/// Session config for all codecs. -#[derive(Debug, Clone, Default)] -pub struct CodecConfig { - params: Vec, -} - -impl CodecConfig { - /// Creates a new empty config. - pub fn empty() -> Self { - CodecConfig::default() - } - - /// Creates a new config from payload params - pub fn new_from_payload_params(payload_params: Vec) -> Self { - CodecConfig { - params: payload_params, - ..Default::default() - } - } - - /// Creates a new config with all default configurations enabled. - pub fn new_with_defaults() -> Self { - let mut c = Self::empty(); - c.enable_opus(true); - - c.enable_vp8(true); - c.enable_h264(true); - c.enable_h265(true); - c.enable_vp9(true); - c.enable_av1(true); - - c - } - - /// Returns a reference to the payload parameters. - pub fn params(&self) -> &[PayloadParams] { - &self.params - } - - /// Clear all configured configs. - pub fn clear(&mut self) { - self.params.clear(); - } - - /// Manually configure a payload type. - pub fn add_config( - &mut self, - pt: Pt, - resend: Option, - codec: Codec, - clock_rate: Frequency, - channels: Option, - format: FormatParams, - ) { - let (fb_transport_cc, fb_fir, fb_nack, fb_pli, fb_remb) = if codec.is_video() { - (true, true, true, true, true) - } else { - (true, false, false, false, false) - }; - - let p = PayloadParams { - pt, - spec: CodecSpec { - codec, - clock_rate, - channels, - format, - }, - resend, - fb_transport_cc, - fb_fir, - fb_nack, - fb_pli, - fb_remb, - locked: false, - }; - - self.params.push(p); - } - - /// Convenience for adding a h264 payload type. - pub fn add_h264(&mut self, pt: Pt, resend: Option, packetization_mode: bool, profile_level_id: u32) { - self.add_config( - pt, - resend, - Codec::H264, - Frequency::NINETY_KHZ, - None, - FormatParams { - level_asymmetry_allowed: Some(true), - packetization_mode: if packetization_mode { Some(1) } else { Some(0) }, - profile_level_id: Some(profile_level_id), - ..Default::default() - }, - ) - } - - /// Convenience for adding a h265 payload type. - pub fn add_h265(&mut self, pt: Pt, resend: Option, profile_id: u8, tier_flag: u8, level_id: u8) { - use crate::vendor::str0m::packet::H265ProfileTierLevel; - - let ptl = H265ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap_or(H265ProfileTierLevel::FALLBACK); - - self.add_config( - pt, - resend, - Codec::H265, - Frequency::NINETY_KHZ, - None, - FormatParams { - h265_profile_tier_level: Some(ptl), - ..Default::default() - }, - ) - } - - /// Add a default AMR-WB payload type. - pub fn enable_amr_wb(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::AmrWb); - if !enabled { - return; - } - self.add_config( - PT_AMR_WB, - None, - Codec::AmrWb, - Frequency::SIXTEEN_KHZ, - Some(1), - FormatParams { - octet_align: Some(true), - ..Default::default() - }, - ); - } - - /// Add a default OPUS payload type. - pub fn enable_opus(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::Opus); - if !enabled { - return; - } - self.add_config( - PT_OPUS, - None, - Codec::Opus, - Frequency::FORTY_EIGHT_KHZ, - Some(2), - FormatParams { - min_p_time: Some(10), - use_inband_fec: Some(true), - ..Default::default() - }, - ); - } - - /// Add a default VP8 payload type. - pub fn enable_vp8(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::Vp8); - if !enabled { - return; - } - self.add_config( - PT_VP8, - Some(PT_VP8_RTX), - Codec::Vp8, - Frequency::NINETY_KHZ, - None, - FormatParams::default(), - ) - } - - /// Add a default H264 payload type. - pub fn enable_h264(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::H264); - if !enabled { - return; - } - const PARAMS: &[(u8, u8, bool, u32)] = &[ - (127, 121, true, 0x42001f), - (125, 107, false, 0x42001f), - (108, 109, true, 0x42e01f), - (124, 120, false, 0x42e01f), - (123, 119, true, 0x4d001f), - (35, 36, false, 0x4d001f), - (114, 115, true, 0x64001f), - ]; - - for p in PARAMS { - self.add_h264(p.0.into(), Some(p.1.into()), p.2, p.3) - } - } - - /// Add a default H265 payload type. - /// This enables H265 as a video codec (clock rate 90kHz) with default RTX payload type. - /// Note: H265 is still considered an experimental/hidden codec in parts of the public API, - /// but it is supported internally for packetization/depacketization. - pub fn enable_h265(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::H265); - if !enabled { - return; - } - - // Start with single default configuration - // Profile/tier/level negotiation will happen via SDP fmtp parameters - // - // Level 6.0 (level_id=180) - a high capability level well supported by modern browsers. - // Level-id formula per ITU-T H.265 Annex A: level_id = (a*10 + b) * 3 - // e.g. Level 6.0 → (6*10 + 0) * 3 = 180 - // - // Chromium H265Level enum definition (kLevel6 = 180): - // https://source.chromium.org/chromium/chromium/src/+/main: - // third_party/webrtc/api/video_codecs/h265_profile_tier_level.h - self.add_h265(PT_H265, Some(PT_H265_RTX), 1, 0, 180); // Main, Main tier, Level 6.0 - } - - /// Add a default VP9 payload type. - pub fn enable_vp9(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::Vp9); - if !enabled { - return; - } - self.add_config( - PT_VP9, - Some(PT_VP9_RTX), - Codec::Vp9, - Frequency::NINETY_KHZ, - None, - FormatParams { - profile_id: Some(0), - ..Default::default() - }, - ); - self.add_config( - 100.into(), - Some(101.into()), - Codec::Vp9, - Frequency::NINETY_KHZ, - None, - FormatParams { - profile_id: Some(2), - ..Default::default() - }, - ); - } - - /// Add a default AV1 payload type. - pub fn enable_av1(&mut self, enabled: bool) { - self.params.retain(|c| c.spec.codec != Codec::Av1); - if !enabled { - return; - } - self.add_config( - PT_AV1, - Some(PT_AV1_RTX), - Codec::Av1, - Frequency::NINETY_KHZ, - None, - FormatParams::default(), - ); - } - - /// Match the given parameters to the configured parameters. - /// - /// In a server scenario, a certain codec configuration might not have the same - /// payload type (PT) for two different peers. We will have incoming data with one - /// PT and need to match that against the PT of the outgoing. - /// - /// This call performs matching and if a match is found, returns the _local_ PT - /// that can be used for sending media. - pub fn match_params(&self, params: PayloadParams) -> Option<&PayloadParams> { - let c = self.params.iter().max_by_key(|p| p.match_score(¶ms))?; - c.match_score(¶ms)?; // avoid None, which isn't a match. - Some(c) - } - - /// When we get remote payload parameters, we need to match differently depending on direction. - pub(crate) fn sdp_match_remote(&self, remote_params: PayloadParams, remote_dir: Direction) -> Option { - // If we have no matching parameters locally, we can't accept the remote in any way. - let our_params = self.match_params(remote_params)?; - - if remote_dir.sdp_is_receiving() { - // The remote is talking about its own receive requirements. The PTs are not suggestions. - Some(remote_params.pt()) - } else { - // We can override the remote with our local config. We would have adjusted to - // the remote earlier if we can. - Some(our_params.pt()) - } - } - - /// Find a payload parameter using a finder function. - pub fn find(&self, mut f: impl FnMut(&PayloadParams) -> bool) -> Option<&PayloadParams> { - self.params.iter().find(move |p| f(p)) - } - - /// Return configured payloads for a media kind. - pub(crate) fn all_for_kind(&self, kind: MediaKind) -> impl Iterator { - self.params.iter().filter(move |p| { - if kind == MediaKind::Video { - p.spec.codec.is_video() - } else { - p.spec.codec.is_audio() - } - }) - } - - pub(crate) fn update_params(&mut self, remote_params: &[PayloadParams], remote_dir: Direction) { - // 0-128 of "claimed" PTs. I.e. PTs that we already allocated to something. - let mut claimed: [bool; 128] = [false; 128]; - - // Make a pass with all that are definitely confirmed by the remote, since these can't change. - for p in self.params.iter() { - if !p.locked { - continue; - } - - claimed.assert_claim_once(p.pt); - - if let Some(rtx) = p.resend { - claimed.assert_claim_once(rtx); - } - } - - // Collect all currently unlocked PTs since we will need to avoid them when reassigning. - let mut unlocked = self - .params - .iter() - .filter(|p| !p.locked) - .flat_map(|p| [Some(p.pt()), p.resend()]) - .flatten() - .collect::>(); - - // Now lock potential new parameters to remote. - // - // If the remote is doing `SendOnly`, we are receiving, so the PTs are suggestions, - // and we are allowed to ANSWER with our own allocations as overrides. - // If SendRecv or RecvOnly, the remote is talking about its own receiving capabilities - // and we are not allowed to change it in the ANSWER. - let local_is_controlling = !remote_dir.sdp_is_receiving(); - - for p in self.params.iter_mut() { - p.update_param(remote_params, &mut claimed, local_is_controlling, &mut unlocked); - } - - // Make a pass to reassign unconfirmed payloads that have PT which are now claimed. - for p in self.params.iter_mut() { - if p.locked { - continue; - } - - if claimed.is_claimed(p.pt) { - let Some(pt) = claimed.find_unclaimed(PREFERED_RANGES, &unlocked) else { - // TODO: handle this gracefully. - panic!("Exhausted all PT ranges, inconsistent PayloadParam state"); - }; - - debug!("Reassigned PT {} => {}", p.pt, pt); - p.pt = pt; - - claimed.assert_claim_once(pt); - unlocked.remove(&pt); - } - - let Some(rtx) = p.resend else { - continue; - }; - - if claimed.is_claimed(rtx) { - let Some(rtx) = claimed.find_unclaimed(PREFERED_RANGES, &unlocked) else { - // TODO: handle this gracefully. - panic!("Exhausted all PT ranges, inconsistent PayloadParam state"); - }; - - debug!("Reassigned RTX PT {:?} => {:?}", p.resend, rtx); - p.resend = Some(rtx); - - claimed.assert_claim_once(rtx); - unlocked.remove(&rtx); - } - } - } - - pub(crate) fn has_pt(&self, pt: Pt) -> bool { - self.params.iter().any(|p| p.pt() == pt) - } -} - -impl Deref for CodecConfig { - type Target = [PayloadParams]; - - fn deref(&self) -> &Self::Target { - &self.params - } -} - -impl DerefMut for CodecConfig { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.params - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::io::MultiplexKind; - use crate::vendor::str0m::packet::MediaKind; - use crate::vendor::str0m::rtp_::Direction; - use crate::vendor::str0m::rtp_::Frequency; - - use super::*; - use crate::vendor::str0m::format::{CodecSpec, FormatParams}; - - #[test] - fn transport_cc_uses_first_section_and_preserves_local_capability() { - for direction in [Direction::SendOnly, Direction::RecvOnly] { - for local_enabled in [false, true] { - for sections in [[false, false], [false, true], [true, false]] { - let mut config = CodecConfig::empty(); - config.enable_vp8(true); - config.params[0].set_fb_transport_cc(local_enabled); - let mut remote = config.params[0]; - let expected = local_enabled && sections[0]; - for enabled in sections { - remote.set_fb_transport_cc(enabled); - config.update_params(&[remote], direction); - assert_eq!(config.params()[0].fb_transport_cc(), expected); - } - } - } - } - } - - #[test] - fn collision_preserves_configured_primary_and_rtx_pts() { - let mut claimed = PayloadParams::new( - 96.into(), - Some(97.into()), - CodecSpec { - codec: Codec::H264, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams::default(), - }, - ); - claimed.locked = true; - - let vp8 = CodecSpec { - codec: Codec::Vp8, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams::default(), - }; - let local_vp8 = PayloadParams::new(110.into(), Some(111.into()), vp8); - let remote_vp8 = PayloadParams::new(96.into(), Some(97.into()), vp8); - - let mut config = CodecConfig::new_from_payload_params(vec![claimed, local_vp8]); - config.update_params(&[remote_vp8], Direction::SendOnly); - - let vp8 = config - .iter() - .find(|p| p.spec().codec == Codec::Vp8) - .expect("configured VP8 payload"); - assert_eq!((*vp8.pt(), vp8.resend().map(|pt| *pt)), (110, Some(111))); - } - - #[test] - fn enable_amr_wb_uses_a_free_default_pt() { - let mut config = CodecConfig::new_with_defaults(); - - config.enable_amr_wb(true); - - let amr_wb = config - .params() - .iter() - .find(|p| p.spec().codec == Codec::AmrWb) - .expect("AMR-WB should be enabled"); - assert_eq!(amr_wb.pt(), PT_AMR_WB); - - let mut seen = std::collections::HashSet::new(); - for pt in config - .params() - .iter() - .flat_map(|p| [Some(p.pt()), p.resend()]) - .flatten() - { - assert!(seen.insert(pt), "duplicate PT {pt}"); - } - } - - #[test] - fn test_pt_conflict_different_directions() { - // Simulates: - // 1. str0m OFFER sendonly H264 PT 108, RTX PT 109 - // 2. FF ANSWER recvonly (locks PT 109 as H264 RTX) - // 3. FF OFFER sendonly Opus PT 109 - // 4. Crash on PT 109 conflict - - let mut config = CodecConfig::empty(); - - // Initial local config: H264 with PT 108, RTX 109 and Opus with PT 111 - config.add_config( - 108.into(), - Some(109.into()), - Codec::H264, - Frequency::NINETY_KHZ, - None, - FormatParams { - packetization_mode: Some(1), - profile_level_id: Some(0x42e01f), - ..Default::default() - }, - ); - config.add_config( - 111.into(), - None, - Codec::Opus, - Frequency::FORTY_EIGHT_KHZ, - Some(2), - FormatParams::default(), - ); - - // Step 2: Remote answers recvonly with our H264 PT 108/109 - // This locks PT 109 as RTX - let remote_h264_params = vec![PayloadParams::new( - 108.into(), - Some(109.into()), - CodecSpec { - codec: Codec::H264, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - packetization_mode: Some(1), - profile_level_id: Some(0x42e01f), - ..Default::default() - }, - }, - )]; - - config.update_params(&remote_h264_params, Direction::RecvOnly); - - // Verify PT 109 is now locked as RTX for H264 - assert!( - config - .params() - .iter() - .any(|p| p.resend() == Some(109.into()) && p.locked) - ); - - // Step 3: Remote offers sendonly Opus PT 109 - // This should NOT crash - PT 109 should be remapped to 111 (Opus default) - let remote_opus_params = vec![PayloadParams::new( - 109.into(), - None, - CodecSpec { - codec: Codec::Opus, - clock_rate: Frequency::FORTY_EIGHT_KHZ, - channels: Some(2), - format: FormatParams::default(), - }, - )]; - - config.update_params(&remote_opus_params, Direction::SendOnly); - - // Verify the fix: Opus should be remapped to PT_OPUS (its default) - let opus_param = config.params().iter().find(|p| p.spec().codec == Codec::Opus); - assert!(opus_param.is_some(), "Opus param should exist"); - assert_eq!( - opus_param.unwrap().pt(), - PT_OPUS, - "Opus should be remapped to PT_OPUS (default)" - ); - assert!(opus_param.unwrap().locked, "Opus param should be locked"); - - // Verify H264 RTX PT 109 is still locked - assert!( - config - .params() - .iter() - .any(|p| p.resend() == Some(109.into()) && p.locked) - ); - } - - #[test] - fn test_pt_conflict_same_mline_multiple_codecs() { - // Reproduces a bug we have had where reassigned PTs were conflicting with unlocked PTs. - // - // SCENARIO & ROOT CAUSE: - // This test reproduces the exact bug from sdp.json using str0m's default config. - // - // 1. str0m starts with DEFAULT codec configuration: - // - VP8 at PT 96/97 (unlocked) - // - H264 High (0x64001f) at PT 114/115 (unlocked) - // - Many other H264 profiles at various PTs (127, 125, 108, 124, 123, 35) - // - // 2. Chrome (peer A) offers video with H264 only - PTs: 103/104, 109/114, 117/118 - // Chrome's OFFER direction: sendonly (Chrome sends video to us) - // **CRITICAL**: Chrome uses PT 114 as RTX for H264 42e01f (PT 109) - // - // 3. str0m ANSWERs accepting Chrome's H264 offer: - // - Chrome's H264 PTs (103, 109, 117) are LOCKED - // - Chrome's RTX PTs (104, 114, 118) are LOCKED - // - VP8 at PT 96 remains UNLOCKED (Chrome didn't negotiate it) - // - H264 High at PT 114 CONFLICTS with Chrome's RTX usage of PT 114! - // - // 4. THE BUG (before fix): update_params reassigns H264 High from PT 114: - // - Searches for available PT starting from 96 - // - PT 96 appears "unclaimed" because it only checked LOCKED PTs - // - VP8 is at PT 96 but UNLOCKED, so wasn't checked! - // - H264 High gets reassigned to PT 96 - // - Now BOTH VP8 and H264 High are at PT 96! ❌ - // - // 5. Later, Firefox (peer B) joins - str0m creates NEW video m-line (mid KvE) - // When generating SDP, str0m collects ALL video codecs from codec_config - // Result (before fix): PT 96 appears TWICE in the same m-line! - // - Line 729 in sdp.json: a=rtpmap:96 VP8/90000 - // - Line 791 in sdp.json: a=rtpmap:96 H264/90000 profile-level-id=64001f - // - // EXPECTED: Each PT in an m-line must be unique - // THE FIX: Now checks BOTH locked and unlocked PTs when reassigning - - // Start with str0m's default codec configuration - // This includes VP8 at 96/97 and H264 High at 114/115 (among others) - let mut config = CodecConfig::new_with_defaults(); - - // Verify H264 High starts at its default PT 114 BEFORE Chrome's offer - let h264_high_before = config - .params() - .iter() - .find(|p| p.spec().codec == Codec::H264 && p.spec().format.profile_level_id == Some(0x64001f)) - .expect("H264 High should exist"); - assert_eq!(h264_high_before.pt(), 114.into(), "H264 High should start at PT 114"); - - // Simulate Chrome's OFFER with H264 only (sendonly from Chrome's perspective) - // Chrome is sending video to us, so we're receiving - // Direction::SendOnly means the remote is sending (we receive) - let chrome_h264_params = vec![ - PayloadParams::new( - 103.into(), - Some(104.into()), - CodecSpec { - codec: Codec::H264, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - packetization_mode: Some(1), - profile_level_id: Some(0x42001f), - ..Default::default() - }, - }, - ), - PayloadParams::new( - 109.into(), - Some(114.into()), - CodecSpec { - codec: Codec::H264, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - packetization_mode: Some(1), - profile_level_id: Some(0x42e01f), - ..Default::default() - }, - }, - ), - PayloadParams::new( - 117.into(), - Some(118.into()), - CodecSpec { - codec: Codec::H264, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - packetization_mode: Some(1), - profile_level_id: Some(0x4d001f), - ..Default::default() - }, - }, - ), - ]; - - // Process Chrome's offer - this locks the H264 PTs that Chrome offered - // Chrome is SendOnly, so from our perspective we're receiving (recvonly) - config.update_params(&chrome_h264_params, Direction::SendOnly); - - // Verify: Chrome's H264 profiles are locked at their specific PTs - assert!( - config.params().iter().any(|p| p.pt() == 103.into() - && p.spec().codec == Codec::H264 - && p.spec().format.profile_level_id == Some(0x42001f) - && p.locked), - "H264 42001f should be locked at PT 103" - ); - assert!( - config.params().iter().any(|p| p.pt() == 109.into() - && p.spec().codec == Codec::H264 - && p.spec().format.profile_level_id == Some(0x42e01f) - && p.locked), - "H264 42e01f should be locked at PT 109" - ); - assert!( - config.params().iter().any(|p| p.pt() == 117.into() - && p.spec().codec == Codec::H264 - && p.spec().format.profile_level_id == Some(0x4d001f) - && p.locked), - "H264 4d001f should be locked at PT 117" - ); - - // Verify: VP8 at PT 96 is NOT locked (Chrome didn't negotiate it) - let vp8_param = config.params().iter().find(|p| p.spec().codec == Codec::Vp8); - assert!(vp8_param.is_some(), "VP8 should still exist"); - assert_eq!(vp8_param.unwrap().pt(), 96.into(), "VP8 should be at PT 96"); - assert!(!vp8_param.unwrap().locked, "VP8 should NOT be locked"); - - // THE FIX VERIFICATION: - // H264 64001f was originally at PT 114, but Chrome used PT 114 for RTX - // update_params should reassign H264 64001f to a PT that avoids BOTH: - // - Locked PTs (103, 104, 109, 114, 117, 118) - // - Unlocked PTs already in use (96 for VP8, 97 for VP8 RTX) - let h264_high_param = config - .params() - .iter() - .find(|p| p.spec().codec == Codec::H264 && p.spec().format.profile_level_id == Some(0x64001f)); - assert!(h264_high_param.is_some(), "H264 64001f should still exist"); - let h264_pt = h264_high_param.unwrap().pt(); - - // Should NOT be at PT 96 (VP8 is there) - assert_ne!( - h264_pt, - 96.into(), - "FIX WORKING: H264 64001f should NOT be at PT 96 (VP8 is there)" - ); - - // Should NOT be at any of the locked PTs - assert!( - ![103, 104, 109, 114, 117, 118].contains(&{ *h264_pt }), - "H264 64001f should not conflict with locked PTs" - ); - - assert!( - !h264_high_param.unwrap().locked, - "H264 64001f should NOT be locked (Chrome didn't offer it)" - ); - - // Now simulate creating a new video m-line (for Firefox's camera) - // This is where the bug manifests: we collect ALL video codecs from config - let all_video_params: Vec<_> = config.all_for_kind(MediaKind::Video).collect(); - - // Extract just the PTs (including RTX PTs) - let mut all_pts = Vec::new(); - for p in all_video_params { - all_pts.push(p.pt()); - if let Some(rtx) = p.resend() { - all_pts.push(rtx); - } - } - - // THE FIX: With the bug fixed, no PT should appear multiple times - // Check for duplicate PTs - this should now PASS - let mut seen = std::collections::HashSet::new(); - let mut duplicates = Vec::new(); - for pt in &all_pts { - if !seen.insert(pt) { - duplicates.push(*pt); - } - } - - assert!( - duplicates.is_empty(), - "FAILED: Found duplicate PTs in same m-line: {:?}\nAll PTs: {:?}\n - This creates invalid SDP with multiple a=rtpmap lines for the same PT!", - duplicates, - all_pts - ); - } - - // ── H.265 direction-based negotiation tests ────────────────────────── - - /// Helper: build a CodecConfig containing only H.265 at the given PTL. - fn h265_config(profile_id: u8, tier_flag: u8, level_id: u8) -> CodecConfig { - let mut config = CodecConfig::empty(); - config.add_h265(102.into(), Some(103.into()), profile_id, tier_flag, level_id); - config - } - - /// Helper: build a single-element remote PayloadParams for H.265 with full PTL. - fn h265_remote_ptl(profile_id: u8, tier_flag: u8, level_id: u8) -> Vec { - use crate::vendor::str0m::packet::H265ProfileTierLevel; - vec![PayloadParams::new( - 102.into(), - Some(103.into()), - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - h265_profile_tier_level: Some(H265ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap()), - ..Default::default() - }, - }, - )] - } - - /// Helper: build a single-element remote PayloadParams for H.265 with profile-id only. - fn h265_remote_profile_only(profile_id: u32) -> Vec { - vec![PayloadParams::new( - 102.into(), - Some(103.into()), - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - profile_id: Some(profile_id), - ..Default::default() - }, - }, - )] - } - - /// Helper: build a single-element remote PayloadParams for H.265 with no fmtp. - fn h265_remote_no_fmtp() -> Vec { - vec![PayloadParams::new( - 102.into(), - Some(103.into()), - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams::default(), - }, - )] - } - - /// Helper: extract the H.265 param from a config (panics if missing). - fn get_h265(config: &CodecConfig) -> &PayloadParams { - config - .params() - .iter() - .find(|p| p.spec().codec == Codec::H265) - .expect("H.265 param missing") - } - - // ── recvonly: remote sends to us ───────────────────────────────────── - - /// Remote sends at Level 5.2, we can receive at Level 6.0. - /// Negotiated level should narrow to min(6.0, 5.2) = 5.2. - #[test] - fn test_h265_recvonly_remote_level_lower() { - let mut config = h265_config(1, 0, 180); // Main, Main tier, Level 6.0 - let remote = h265_remote_ptl(1, 0, 156); // Level 5.2 - - // Direction::SendOnly = remote is sending (we receive) - config.update_params(&remote, Direction::SendOnly); - - let ptl = get_h265(&config).spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 156, "Should narrow to min(180,156) = Level 5.2"); - assert_eq!(ptl.profile_id(), 1, "Profile should be preserved"); - assert_eq!(ptl.tier_flag(), 0, "Tier should be preserved"); - } - - /// Remote sends at Level 6.0, we can receive at Level 5.2. - /// Negotiated level should narrow to min(5.2, 6.0) = 5.2. - #[test] - fn test_h265_recvonly_local_level_lower() { - let mut config = h265_config(1, 0, 156); // Level 5.2 - let remote = h265_remote_ptl(1, 0, 180); // Level 6.0 - - config.update_params(&remote, Direction::SendOnly); - - let ptl = get_h265(&config).spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 156, "Should narrow to min(156,180) = Level 5.2"); - } - - // ── sendrecv: both sides send and receive ──────────────────────────── - - /// Both sides sendrecv. Local Level 6.0, remote Level 5.2. - /// Effective level should narrow to min(6.0, 5.2) = 5.2. - #[test] - fn test_h265_sendrecv_remote_level_lower() { - let mut config = h265_config(1, 0, 180); // Level 6.0 - let remote = h265_remote_ptl(1, 0, 156); // Level 5.2 - - config.update_params(&remote, Direction::SendRecv); - - let ptl = get_h265(&config).spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 156, "sendrecv: should narrow to Level 5.2"); - } - - /// Both sides sendrecv. Local Level 5.2, remote Level 6.0. - /// Effective level should narrow to min(5.2, 6.0) = 5.2. - #[test] - fn test_h265_sendrecv_local_level_lower() { - let mut config = h265_config(1, 0, 156); // Level 5.2 - let remote = h265_remote_ptl(1, 0, 180); // Level 6.0 - - config.update_params(&remote, Direction::SendRecv); - - let ptl = get_h265(&config).spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 156, "sendrecv: should narrow to Level 5.2"); - } - - /// Same level on both sides. Should remain unchanged. - #[test] - fn test_h265_sendrecv_same_level() { - let mut config = h265_config(1, 0, 156); // Level 5.2 - let remote = h265_remote_ptl(1, 0, 156); // Level 5.2 - - config.update_params(&remote, Direction::SendRecv); - - let ptl = get_h265(&config).spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 156, "Same levels should stay at Level 5.2"); - } - - // ── sendonly: we send, remote receives ─────────────────────────────── - - /// Remote declares recvonly at Level 5.2, we offer sendonly at Level 6.0. - /// Negotiated level should narrow to 5.2 (receiver wins). - #[test] - fn test_h265_sendonly_receiver_level_lower() { - let mut config = h265_config(1, 0, 180); // Level 6.0 - let remote = h265_remote_ptl(1, 0, 156); // Level 5.2 - - // Direction::RecvOnly = remote is receiving (we send) - config.update_params(&remote, Direction::RecvOnly); - - let ptl = get_h265(&config).spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 156, "sendonly: should narrow to receiver's Level 5.2"); - } - - /// Remote offers only profile-id=1, no tier/level. - /// Local should drop its full PTL and echo back profile-id only. - #[test] - fn test_h265_profile_only_remote_mirrors() { - let mut config = h265_config(1, 0, 180); // Full PTL - let remote = h265_remote_profile_only(1); // profile-id only - - config.update_params(&remote, Direction::SendRecv); - - let h265 = get_h265(&config); - assert!( - h265.spec().format.h265_profile_tier_level.is_none(), - "Full PTL should be cleared when remote only offers profile-id" - ); - assert_eq!( - h265.spec().format.profile_id, - Some(1), - "profile_id should mirror the remote's value" - ); - } - - // ── no-fmtp remote ────────────────────────────────────────────────── - - /// Remote has no H.265 fmtp at all. Local should clear both fields. - #[test] - fn test_h265_no_fmtp_remote_clears() { - let mut config = h265_config(1, 0, 180); // Full PTL - let remote = h265_remote_no_fmtp(); - - config.update_params(&remote, Direction::SendRecv); - - let h265 = get_h265(&config); - assert!( - h265.spec().format.h265_profile_tier_level.is_none(), - "PTL should be cleared when remote has no fmtp" - ); - assert!( - h265.spec().format.profile_id.is_none(), - "profile_id should be cleared when remote has no fmtp" - ); - } - - // ── profile_id field cleanup ───────────────────────────────────────── - - /// When remote has full PTL, the `profile_id` field must be None - /// to avoid duplicate serialization (profile-id appears in both - /// h265_profile_tier_level AND the VP9-style profile_id field). - #[test] - fn test_h265_profile_id_cleared_on_ptl_match() { - let mut config = CodecConfig::empty(); - // Artificially set both fields to simulate a misconfigured state - config.add_config( - 102.into(), - Some(103.into()), - Codec::H265, - Frequency::NINETY_KHZ, - None, - FormatParams { - h265_profile_tier_level: Some( - crate::vendor::str0m::packet::H265ProfileTierLevel::new(1, 0, 180).unwrap(), - ), - profile_id: Some(1), // should be cleared after negotiation - ..Default::default() - }, - ); - let remote = h265_remote_ptl(1, 0, 156); - - config.update_params(&remote, Direction::SendRecv); - - let h265 = get_h265(&config); - assert!( - h265.spec().format.profile_id.is_none(), - "profile_id field must be None when full PTL is present" - ); - assert!( - h265.spec().format.h265_profile_tier_level.is_some(), - "PTL should still be present" - ); - } - - // ── default level ──────────────────────────────────────────────────── - - /// `enable_h265` should produce Level 6.0 (level_id = 180). - #[test] - fn test_h265_default_level_is_6_0() { - let mut config = CodecConfig::empty(); - config.enable_h265(true); - - let h265 = get_h265(&config); - let ptl = h265.spec().format.h265_profile_tier_level.unwrap(); - assert_eq!(ptl.level_id(), 180, "Default H.265 level should be 6.0 (180)"); - assert_eq!(ptl.profile_id(), 1, "Default H.265 profile should be Main (1)"); - assert_eq!(ptl.tier_flag(), 0, "Default H.265 tier should be Main (0)"); - } - - // H.266 direction-based negotiation tests. - - // recvonly: remote sends to us. - - // sendrecv: both sides send and receive. - - // sendonly: we send, remote receives. - - // no-fmtp remote. - - // profile_id field cleanup. - - // H.266 default level. -} diff --git a/rs/moq-webrtc/src/vendor/str0m/format/format_params.rs b/rs/moq-webrtc/src/vendor/str0m/format/format_params.rs deleted file mode 100644 index 7d4feb094b9..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/format/format_params.rs +++ /dev/null @@ -1,338 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::fmt; -use tracing::debug; - -use super::Codec; -use crate::vendor::str0m::sdp::FormatParam; - -/// Codec specific format parameters. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] -pub struct FormatParams { - /// Opus specific parameter. - /// - /// The minimum duration of media represented by a packet. - pub min_p_time: Option, - - /// Opus specific parameter. - /// - /// Decoder-side preference for stereo audio. Default is mono per - /// RFC 7587 Section 7.1: - pub stereo: Option, - - /// Opus specific parameter. - /// - /// Sender-side stereo hint for Opus. When set, it signals the intent to - /// transmit stereo from the sender, matching the symmetric m-line model. - pub sprop_stereo: Option, - - /// Opus specific parameter. - /// - /// Specifies that the decoder can do Opus in-band FEC - pub use_inband_fec: Option, - - /// Opus specific parameter. - /// - /// Specifies that the decoder prefers DTX (Discontinuous Transmission) such that - /// the packet rate is greatly lowered during periods of silence. - pub use_dtx: Option, - - /// Whether h264 sending media encoded at a different level in the offerer-to-answerer - /// direction than the level in the answerer-to-offerer direction, is allowed. - pub level_asymmetry_allowed: Option, - - /// What h264 packetization mode is used. - /// - /// * 0 - single nal. - /// * 1 - STAP-A, FU-A is allowed. Non-interleaved. - pub packetization_mode: Option, - - /// H264 profile level. - /// - /// * 42 00 1f - 4200=baseline (B) 1f=level 3.1 - /// * 42 e0 1f - 42e0=constrained baseline (CB) 1f=level 3.1 - /// * 4d 00 1f - 4d00=main (M) 1f=level 3.1 - /// * 64 00 1f - 6400=high (H) 1f=level 3.1 - pub profile_level_id: Option, - - /// VP9 profile id. - pub profile_id: Option, - - /// AV1 profile. - /// - /// Indicates the highest AV1 profile that may have been used to generate - /// the bitstream or that the receiver supports. The range of possible values - /// is identical to the seq_profile syntax element specified in AV1. If the - /// parameter is not present, it MUST be inferred to be 0 ("Main" profile). - /// - /// 0 8-bit or 10-bit 4:2:0 - /// 1 8-bit or 10-bit 4:4:4 - /// 2 8-bit or 10-bit 4:2:2 - /// 2 12-bit 4:2:0, 4:2:2, 4:4:4 - pub profile: Option, - - /// AV1 level-idx. - /// - /// Indicates the highest AV1 level that may have been used to generate the - /// bitstream or that the receiver supports. The range of possible values - /// is identical to the seq_level_idx syntax element specified in AV1. If - /// the parameter is not present, it MUST be inferred to be 5 (level 3.1). - pub level_idx: Option, - - /// AV1 tier. - /// - /// Indicates the highest tier that may have been used to generate the bitstream - /// or that the receiver supports. The range of possible values is identical - /// to the seq_tier syntax element specified in AV1. If the parameter is not - /// present, the tier MUST be inferred to be 0. - pub tier: Option, - - /// H.265/HEVC profile, tier, and level. - /// - /// Contains: - /// * profile: Main, Main10, Main Still Picture, etc. - /// * tier: Main or High. - /// * level: 3.1, 4.0, 5.0, etc. - /// - /// See ITU-T H.265 Annex A for complete definitions. - pub h265_profile_tier_level: Option, - - /// H.265 sprop-max-don-diff parameter (RFC 7798 §7.1). - /// When > 0, DONL fields are included in H.265 RTP packets to support - /// out-of-order NAL unit decoding. - pub sprop_max_don_diff: Option, - - /// AMR-WB `octet-align`. `Some(true)` selects the octet-aligned payload - /// layout, otherwise bandwidth-efficient is used. - pub octet_align: Option, - - /// AMR-WB `mode-set`, a bitmask of the allowed speech modes 0..=8. - /// - /// A mode set from either peer applies to both directions, so only write - /// frames in these modes. - pub mode_set: Option, -} - -impl FormatParams { - pub(crate) fn from_sdp_fmtp<'a>(codec: Codec, mut lines: impl Iterator) -> Option { - let mut params = Self::default(); - for line in lines { - for param in line { - // Decline AMR-WB payload types that need features str0m lacks. - if codec == Codec::AmrWb && *param == FormatParam::AmrWbUnsupported { - return None; - } - params.set_param(param); - } - } - Some(params) - } - - /// Parse an fmtp line to create a FormatParams. - /// - /// Example `minptime=10;useinbandfec=1`. - pub fn parse_line(line: &str) -> Self { - let mut p = FormatParams::default(); - let key_vals: Vec<_> = line - .split(';') - .filter_map(|pair| { - let mut kv = pair.split('='); - match (kv.next(), kv.next()) { - (Some(k), Some(v)) => Some((k.trim().to_string(), v.trim().to_string())), - (Some(value), None) => { - let value = value.trim(); - if !value.is_empty() { - debug!("Ignoring unsupported fmtp value: {value}"); - } - None - } - (None, _) => None, - } - }) - .collect(); - - for param in FormatParam::parse_pairs(key_vals) { - p.set_param(¶m); - } - - p - } - - pub(crate) fn set_param(&mut self, param: &FormatParam) { - use FormatParam::*; - match param { - MinPTime(v) => self.min_p_time = Some(*v), - Stereo(v) => self.stereo = Some(*v), - SpropStereo(v) => self.sprop_stereo = Some(*v), - UseInbandFec(v) => self.use_inband_fec = Some(*v), - UseDtx(v) => self.use_dtx = Some(*v), - LevelAsymmetryAllowed(v) => self.level_asymmetry_allowed = Some(*v), - PacketizationMode(v) => self.packetization_mode = Some(*v), - ProfileLevelId(v) => self.profile_level_id = Some(*v), - ProfileId(v) => self.profile_id = Some(*v), - Profile(v) => self.profile = Some(*v), - LevelIdx(v) => self.level_idx = Some(*v), - Tier(v) => self.tier = Some(*v), - H265ProfileTierLevel(v) => self.h265_profile_tier_level = Some(*v), - SpropMaxDonDiff(v) => self.sprop_max_don_diff = Some(*v), - OctetAlign(v) => self.octet_align = Some(*v), - ModeSet(v) => self.mode_set = Some(*v), - AmrWbUnsupported => {} - Apt(_) => {} - Unknown => {} - } - } - - pub(crate) fn to_format_param(self) -> Vec { - use FormatParam::*; - let mut r = Vec::with_capacity(5); - - if let Some(v) = self.min_p_time { - r.push(MinPTime(v)); - } - if let Some(v) = self.stereo { - r.push(Stereo(v)); - } - if let Some(v) = self.sprop_stereo { - r.push(SpropStereo(v)); - } - if let Some(v) = self.use_inband_fec { - r.push(UseInbandFec(v)); - } - if let Some(v) = self.use_dtx { - r.push(UseDtx(v)); - } - if let Some(v) = self.level_asymmetry_allowed { - r.push(LevelAsymmetryAllowed(v)); - } - if let Some(v) = self.packetization_mode { - r.push(PacketizationMode(v)); - } - if let Some(v) = self.profile_level_id { - r.push(ProfileLevelId(v)); - } - if let Some(v) = self.profile_id { - r.push(ProfileId(v)); - } - if let Some(v) = self.profile { - r.push(Profile(v)); - } - if let Some(v) = self.level_idx { - r.push(LevelIdx(v)); - } - if let Some(v) = self.tier { - r.push(Tier(v)); - } - // H.265 Profile/Tier/Level: Keep as composite, it serializes all three params - if let Some(ptl) = self.h265_profile_tier_level { - r.push(H265ProfileTierLevel(ptl)); - } - if let Some(v) = self.sprop_max_don_diff { - r.push(SpropMaxDonDiff(v)); - } - if let Some(v) = self.octet_align { - r.push(OctetAlign(v)); - } - if let Some(v) = self.mode_set { - r.push(ModeSet(v)); - } - - r - } -} - -impl fmt::Display for FormatParams { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = self - .to_format_param() - .into_iter() - .map(|f| f.to_string()) - .collect::>() - .join(";"); - write!(f, "{s}") - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn sprop_max_don_diff_roundtrip() { - // Test that sprop-max-don-diff parameter round-trips correctly - let f = FormatParams { - sprop_max_don_diff: Some(32), - ..Default::default() - }; - - // Serialize to string - let fmtp_str = f.to_string(); - assert_eq!(fmtp_str, "sprop-max-don-diff=32"); - - // Parse back - let parsed = FormatParams::parse_line(&fmtp_str); - assert_eq!(parsed.sprop_max_don_diff, Some(32)); - } - - #[test] - fn sprop_stereo_roundtrip() { - let f = FormatParams { - sprop_stereo: Some(true), - ..Default::default() - }; - - let fmtp_str = f.to_string(); - assert_eq!(fmtp_str, "sprop-stereo=1"); - - let parsed = FormatParams::parse_line(&fmtp_str); - assert_eq!(parsed.sprop_stereo, Some(true)); - } - - #[test] - fn h265_combined_params_roundtrip() { - use crate::vendor::str0m::packet::H265ProfileTierLevel; - - // Test H.265 with both profile/tier/level and sprop-max-don-diff - let ptl = H265ProfileTierLevel::new(1, 0, 93).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(ptl), - sprop_max_don_diff: Some(32), - ..Default::default() - }; - - // Serialize to string - let fmtp_str = f.to_string(); - assert!(fmtp_str.contains("profile-id=1")); - assert!(fmtp_str.contains("tier-flag=0")); - assert!(fmtp_str.contains("level-id=93")); - assert!(fmtp_str.contains("sprop-max-don-diff=32")); - - // Parse back - let parsed = FormatParams::parse_line(&fmtp_str); - assert_eq!(parsed.h265_profile_tier_level, Some(ptl)); - assert_eq!(parsed.sprop_max_don_diff, Some(32)); - } - - #[test] - fn amr_wb_fmtp() { - let f = FormatParams::parse_line("octet-align=1; mode-set=0, 1,2;max-red=220"); - assert_eq!(f.to_string(), "octet-align=1;mode-set=0,1,2"); - assert_eq!(FormatParams::parse_line("mode-set=0,9"), FormatParams::default()); - - let declined = |codec, k: &str, v: &str| { - let line = [FormatParam::parse(k, v)]; - FormatParams::from_sdp_fmtp(codec, [&line[..]].into_iter()).is_none() - }; - for (k, v) in [ - ("crc", "1"), - ("robust-sorting", "1"), - ("interleaving", "30"), - ("mode-change-period", "2"), - ] { - assert!(declined(Codec::AmrWb, k, v), "{k}={v}"); - assert!(!declined(Codec::Opus, k, v), "{k}={v}"); - } - for (k, v) in [("crc", "0"), ("robust-sorting", "0"), ("mode-change-period", "1")] { - assert!(!declined(Codec::AmrWb, k, v), "{k}={v}"); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/format/mod.rs b/rs/moq-webrtc/src/vendor/str0m/format/mod.rs deleted file mode 100644 index 7d8232f6f09..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/format/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Media formats and parameters - -// These really don't belong anywhere, but I guess they're kind of related -// to codecs etc. -pub use crate::vendor::str0m::packet::CodecExtra; -pub use crate::vendor::str0m::packet::H264CodecExtra; -pub use crate::vendor::str0m::packet::H265CodecExtra; -pub use crate::vendor::str0m::packet::Vp8CodecExtra; -pub use crate::vendor::str0m::packet::Vp9CodecExtra; -pub use crate::vendor::str0m::packet::Vp9PacketizerMode; -pub use crate::vendor::str0m::packet::detect_av1_keyframe; -pub use crate::vendor::str0m::packet::detect_h265_keyframe; -pub use crate::vendor::str0m::packet::detect_vp8_keyframe; -pub use crate::vendor::str0m::packet::detect_vp9_keyframe; -pub use crate::vendor::str0m::packet::{H265Level, H265Profile, H265ProfileTierLevel, H265Tier}; -pub use crate::vendor::str0m::packet::{detect_h264_keyframe, detect_h264_nalu}; - -mod codec; -mod codec_config; -mod format_params; -mod payload_params; - -pub use codec::{Codec, CodecSpec}; -pub use codec_config::CodecConfig; -pub use format_params::FormatParams; -pub use payload_params::PayloadParams; diff --git a/rs/moq-webrtc/src/vendor/str0m/format/payload_params.rs b/rs/moq-webrtc/src/vendor/str0m/format/payload_params.rs deleted file mode 100644 index a212d1f5ede..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/format/payload_params.rs +++ /dev/null @@ -1,1358 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::collections::HashSet; -use std::ops::RangeInclusive; -use tracing::{debug, warn}; - -use crate::vendor::str0m::packet::H264ProfileLevel; -use crate::vendor::str0m::packet::H265ProfileTierLevel; -use crate::vendor::str0m::rtp_::Pt; - -use super::codec::{Codec, CodecSpec}; -use super::format_params::FormatParams; - -/// Preferred ranges for dynamic payload type allocation. -pub(crate) const PREFERED_RANGES: &[RangeInclusive] = &[ - // Payload identifiers 96–127 are used for payloads defined dynamically during a session. - 96..=127, - // "unassigned" ranged. note that RTCP packet type 207 (XR, Extended Reports) would be - // indistinguishable from RTP payload types 79 with the marker bit set - 80..=95, - 77..=78, - // reserved because RTCP packet types 200–204 would otherwise be indistinguishable - // from RTP payload types 72–76 - // 72..77, - // lol range. - 35..=71, -]; - -pub(crate) trait Claimed { - fn assert_claim_once(&mut self, pt: Pt); - fn is_claimed(&self, pt: Pt) -> bool; - fn find_unclaimed(&self, ranges: &[RangeInclusive], unlocked: &HashSet) -> Option; -} - -impl Claimed for [bool; 128] { - fn assert_claim_once(&mut self, pt: Pt) { - let idx = *pt as usize; - assert!(!self[idx], "Pt locked multiple times: {}", pt); - self[idx] = true; - } - fn is_claimed(&self, pt: Pt) -> bool { - let idx = *pt as usize; - self[idx] - } - fn find_unclaimed(&self, ranges: &[RangeInclusive], unlocked: &HashSet) -> Option { - for range in ranges { - for i in range.clone() { - if !self[i] && !unlocked.contains(&(i as u8).into()) { - let pt: Pt = (i as u8).into(); - return Some(pt); - } - } - } - - // Failed to find unclaimed PT. - None - } -} - -/// Group of parameters for a payload type (PT). -/// -/// In the SDP a payload type has a number of associated parameters. See example below: -/// -/// ```text -/// a=rtpmap:96 H264/90000 -/// a=rtcp-fb:96 goog-remb -/// a=rtcp-fb:96 transport-cc -/// a=rtcp-fb:96 ccm fir -/// a=rtcp-fb:96 nack -/// a=rtcp-fb:96 nack pli -/// a=fmtp:96 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f -/// ``` -#[derive(Clone, Copy, Debug, Serialize, Deserialize)] -pub struct PayloadParams { - /// The payload type that groups these parameters. - pub(crate) pt: Pt, - - /// Whether these parameters are repairing some other set of parameters. - /// This is used to, via PT, separate RTX resend streams from the main stream. - pub(crate) resend: Option, - - /// The codec with settings for this group of parameters. - pub(crate) spec: CodecSpec, - - /// Whether the payload use the TWCC feedback mechanic. - pub(crate) fb_transport_cc: bool, - - /// Whether the payload uses NACK to request resends. - pub(crate) fb_nack: bool, - - /// Whether the payload uses the PLI (Picture Loss Indication) mechanic. - pub(crate) fb_pli: bool, - - /// Whether the payload uses the FIR (Full Intra Request) mechanic. - pub(crate) fb_fir: bool, - - /// Whether the payload uses the REMB (Receiver Estimated Maximum Bitrate) mechanic. - pub(crate) fb_remb: bool, - - /// Whether the payload is locked by negotiation or can still be debated. - /// - /// If we make an OFFER or ANSWER and the direction is sendrecv/recvonly, the parameters are locked - /// can't be further changed. If we make an OFFER for a sendonly, the parameters are only proposed - /// and don't lock. - pub(crate) locked: bool, -} - -// we don't want to compare "locked" -impl PartialEq for PayloadParams { - fn eq(&self, other: &Self) -> bool { - self.pt == other.pt - && self.resend == other.resend - && self.spec == other.spec - && self.fb_transport_cc == other.fb_transport_cc - && self.fb_nack == other.fb_nack - && self.fb_pli == other.fb_pli - && self.fb_fir == other.fb_fir - && self.fb_remb == other.fb_remb - } -} - -impl Eq for PayloadParams {} - -impl PayloadParams { - /// Maximum match score. - /// - /// This is returned for an exact `CodecSpec` match in `match_score()`. It is also used as the - /// starting point for codec-specific scoring in this file: - /// - Opus/H.264/H.265 decrement from a perfect match. - /// - VP9/AV1 return the max score when their relevant fmtp parameters match. - /// - VP8 currently only matches via the exact `CodecSpec` equality fast-path (no fuzzy scorer). - const EXACT_MATCH_SCORE: usize = 100; - - /// Score used for H.265 profile-only compatibility matches. - /// - /// Some endpoints (notably browsers) may signal H.265 using only `profile-id` without - /// tier/level information; when we can only validate profile equality we return this lower - /// score so full ProfileTierLevel matches win when available. - const PROFILE_ONLY_MATCH_SCORE: usize = 90; - - /// Creates new payload params. - /// - /// * `pt` is the payload type RTP mapping in the session. - /// * `resend` is the payload type used for (RTX) resend channel. - /// * `spec` configures details about the codec. - pub fn new(pt: Pt, resend: Option, spec: CodecSpec) -> Self { - let is_video = spec.codec.is_video(); - - PayloadParams { - pt, - resend, - - spec, - - // Both audio and video use TWCC - fb_transport_cc: true, - - // Only true for video. - fb_fir: is_video, - fb_nack: is_video, - fb_pli: is_video, - fb_remb: is_video, - - locked: false, - } - } - - /// Creates minimal payload params for SSRC 0 BWE probes. - /// - /// These probes don't carry real media, only padding for bandwidth estimation. - /// Uses 90kHz clock rate (video rate) and enables only transport_cc feedback. - pub(crate) fn new_probe(pt: Pt) -> Self { - use super::codec::Codec; - use super::format_params::FormatParams; - use crate::vendor::str0m::rtp_::Frequency; - - PayloadParams { - pt, - resend: None, - spec: CodecSpec { - codec: Codec::Null, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams::default(), - }, - fb_transport_cc: true, - fb_nack: false, - fb_pli: false, - fb_fir: false, - fb_remb: false, - locked: false, - } - } - - /// The payload type that groups these parameters. - pub fn pt(&self) -> Pt { - self.pt - } - - /// Whether these parameters are repairing some other set of parameters. - /// This is used to, via PT, separate RTX resend streams from the main stream. - pub fn resend(&self) -> Option { - self.resend - } - - /// The codec with settings for this group of parameters. - pub fn spec(&self) -> CodecSpec { - self.spec - } - - /// Sets whether the payload use the TWCC feedback mechanic. - pub fn set_fb_transport_cc(&mut self, fb_transport_cc: bool) { - self.fb_transport_cc = fb_transport_cc - } - - /// Whether the payload use the TWCC feedback mechanic. - pub fn fb_transport_cc(&self) -> bool { - self.fb_transport_cc - } - - /// Sets whether the payload uses NACK to request resends. - pub fn set_fb_nack(&mut self, fb_nack: bool) { - self.fb_nack = fb_nack - } - - /// Whether the payload uses NACK to request resends. - pub fn fb_nack(&self) -> bool { - self.fb_nack - } - - /// Set whether the payload uses the PLI (Picture Loss Indication) mechanic. - pub fn set_fb_pli(&mut self, fb_pli: bool) { - self.fb_pli = fb_pli - } - - /// Whether the payload uses the PLI (Picture Loss Indication) mechanic. - pub fn fb_pli(&self) -> bool { - self.fb_pli - } - - /// Set whether the payload uses the FIR (Full Intra Request) mechanic. - pub fn set_fb_fir(&mut self, fb_fir: bool) { - self.fb_fir = fb_fir - } - - /// Whether the payload uses the FIR (Full Intra Request) mechanic. - pub fn fb_fir(&self) -> bool { - self.fb_fir - } - - /// Set whether the payload uses the REMB (Receiver Estimated Maximum Bitrate) mechanic. - pub fn set_fb_remb(&mut self, fb_remb: bool) { - self.fb_remb = fb_remb - } - - /// Whether the payload uses the REMB (Receiver Estimated Maximum Bitrate) mechanic. - pub fn fb_remb(&self) -> bool { - self.fb_remb - } - - pub(crate) fn match_score(&self, o: &PayloadParams) -> Option { - // we don't want to compare PT - let c0 = self.spec; - let c1 = o.spec; - - if c0 == c1 && c0.codec != Codec::AmrWb { - // Exact match - return Some(Self::EXACT_MATCH_SCORE); - } - - // Attempt fuzzy matching, since we don't have an exact match - if c0.codec != c1.codec || (c0.codec == Codec::Unknown && c1.codec == Codec::Unknown) { - // Codecs must match - return None; - } - - if c0.clock_rate != c1.clock_rate { - // Clock rates must match - return None; - } - - // AMR-WB defaults an omitted channel count to mono, so it must match - // before the generic channel comparison below. - if c0.codec == Codec::AmrWb { - return Self::match_amr_wb_score(c0, c1); - } - - if c0.channels != c1.channels { - // Channels must match - return None; - } - - if c0.codec.is_audio() && c0.codec == Codec::Opus { - return Some(Self::match_opus_score(c0, c1)); - } - - if c0.codec == Codec::H264 { - return Self::match_h264_score(c0, c1); - } - - if c0.codec == Codec::H265 { - return Self::match_h265_score(c0, c1); - } - - if c0.codec == Codec::Vp9 { - return Self::match_vp9_score(c0, c1); - } - - if c0.codec == Codec::Av1 { - return Self::match_av1_score(c0, c1); - } - - // TODO: Fuzzy matching for any other audio codecs - // TODO: Fuzzy matching for video - - None - } - - fn match_opus_score(c0: CodecSpec, c1: CodecSpec) -> usize { - let mut score: usize = Self::EXACT_MATCH_SCORE; - - // If neither value is specified both sides should assume the default value, 3. - let either_p_time_specified = c0.format.min_p_time.is_some() || c1.format.min_p_time.is_some(); - if either_p_time_specified && c0.format.min_p_time != c1.format.min_p_time { - score = score.saturating_sub(1); - } - - // If neither value is specified both sides should assume FEC is not used as this is - // the default. - let either_fec_specified = c0.format.use_inband_fec.is_some() || c1.format.use_inband_fec.is_some(); - - if either_fec_specified && c0.format.use_inband_fec != c1.format.use_inband_fec { - score = score.saturating_sub(2); - } - - // If neither value is specified both sides should assume DTX is not used as this is - // the default. - let either_dtx_specified = c0.format.use_dtx.is_some() || c1.format.use_dtx.is_some(); - if either_dtx_specified && c0.format.use_dtx != c1.format.use_dtx { - score = score.saturating_sub(4); - } - - // If neither value is specified both sides should assume mono for stereo - // and the sprop-stereo hint defaults to false. - let c0_stereo = c0.format.stereo.unwrap_or(false); - let c1_stereo = c1.format.stereo.unwrap_or(false); - if c0_stereo != c1_stereo { - score = score.saturating_sub(8); - } - - let c0_sprop_stereo = c0.format.sprop_stereo.unwrap_or(false); - let c1_sprop_stereo = c1.format.sprop_stereo.unwrap_or(false); - if c0_sprop_stereo != c1_sprop_stereo { - score = score.saturating_sub(8); - } - - score - } - - fn match_vp9_score(c0: CodecSpec, c1: CodecSpec) -> Option { - // Default profile_id is 0. https://datatracker.ietf.org/doc/html/draft-ietf-payload-vp9-16#section-6 - let c0_profile_id = c0.format.profile_id.unwrap_or(0); - let c1_profile_id = c1.format.profile_id.unwrap_or(0); - - if c0_profile_id != c1_profile_id { - return None; - } - - Some(Self::EXACT_MATCH_SCORE) - } - - fn match_av1_score(c0: CodecSpec, c1: CodecSpec) -> Option { - // TODO: consider media direction for a proper less or equal matching - // The AV1 stream sent by either the offerer or the answerer MUST be - // encoded with a profile, level and tier, lesser or equal to the values - // of the level-idx, profile and tier declared in the SDP by the receiving - // agent. - // https://aomediacodec.github.io/av1-rtp-spec/#723-usage-with-the-sdp-offeranswer-model - - // Default values: profile = 0, level-idx = 5, tier = 0 - // https://aomediacodec.github.io/av1-rtp-spec/#72-sdp-parameters - let c0_profile = c0.format.profile.unwrap_or(0); - let c1_profile = c1.format.profile.unwrap_or(0); - if c0_profile != c1_profile { - return None; - } - - let c0_level_idx = c0.format.level_idx.unwrap_or(5); - let c1_level_idx = c1.format.level_idx.unwrap_or(5); - if c0_level_idx != c1_level_idx { - return None; - } - - let c0_tier = c0.format.tier.unwrap_or(0); - let c1_tier = c1.format.tier.unwrap_or(0); - if c0_tier != c1_tier { - return None; - } - - Some(Self::EXACT_MATCH_SCORE) - } - - fn match_amr_wb_score(c0: CodecSpec, c1: CodecSpec) -> Option { - // Only mono is implemented, and octet-aligned and bandwidth-efficient - // payloads are not interchangeable. - if c0.channels.unwrap_or(1) != 1 || c1.channels.unwrap_or(1) != 1 { - return None; - } - if c0.format.octet_align.unwrap_or(false) != c1.format.octet_align.unwrap_or(false) { - return None; - } - - // A mode-set binds both peers (RFC 4867 §8.3.1), so prefer unrestricted - // payload types when the remote offers both. - match (c0.format.mode_set, c1.format.mode_set) { - (None, None) => Some(Self::EXACT_MATCH_SCORE), - (Some(a), Some(b)) if a != b => None, - _ => Some(Self::EXACT_MATCH_SCORE - 1), - } - } - - pub(crate) fn match_h264_score(c0: CodecSpec, c1: CodecSpec) -> Option { - // Default packetization mode is 0. https://www.rfc-editor.org/rfc/rfc6184#section-6.2 - let c0_packetization_mode = c0.format.packetization_mode.unwrap_or(0); - let c1_packetization_mode = c1.format.packetization_mode.unwrap_or(0); - - if c0_packetization_mode != c1_packetization_mode { - return None; - } - - let c0_profile_level = c0 - .format - .profile_level_id - .map(|l| l.try_into().ok()) - .unwrap_or(Some(H264ProfileLevel::FALLBACK))?; - let c1_profile_level = c1 - .format - .profile_level_id - .map(|l| l.try_into().ok()) - .unwrap_or(Some(H264ProfileLevel::FALLBACK))?; - - // RFC 6184 Section 8.2.2: Profiles must match exactly. - if c0_profile_level.profile() != c1_profile_level.profile() { - return None; - } - - // RFC 6184 Section 8.2.2: the level is a negotiable (downgradable) - // parameter, so a level mismatch in either direction is allowed and - // only penalizes the match score rather than rejecting the payload. - // - // NOTE: this only affects *matching*. Unlike H.265/H.266, `update_param` - // does not narrow the answered H.264 level to `min(local, remote)`, so - // when `level-asymmetry-allowed` is absent we may answer with a level - // higher than the offer. See the note in `update_param`. - let level_difference: usize = c0_profile_level - .level() - .ordinal() - .abs_diff(c1_profile_level.level().ordinal()); - - Some(Self::EXACT_MATCH_SCORE.saturating_sub(level_difference)) - } - - /// Match H.265 codec specifications and return compatibility score. - /// - /// # Matching Rules - Full PTL (both sides have profile+tier+level) - /// - /// - **Profiles** must match exactly (no cross-profile compatibility) - /// - **Tiers** must match exactly (Main vs High tier are distinct) - /// - **Levels** penalize score by `|c0_level - c1_level|` but never reject. - /// Both H.264 and H.265 tolerate level mismatches in either direction at - /// match time. For H.265, `update_param` additionally narrows the - /// negotiated level to `min(local, remote)` afterward; H.264 does not. - /// - /// # Matching Rules - Profile-only (at least one side lacks tier+level) - /// - /// - **Profiles** must match; missing profile info falls back to - /// `FALLBACK.profile()` (not rejected). - /// - **Tiers and levels** are not checked (insufficient information). - /// - Returns a lower score (90) so full-PTL matches are preferred. - /// - /// # Returns - /// - /// - `Some(100)` for exact full-PTL match - /// - `Some(100 - level_gap)` for profile/tier match with level difference - /// - `Some(90)` for profile-only match (when tier/level unavailable) - /// - `None` for profile or tier mismatch - pub(crate) fn match_h265_score(c0: CodecSpec, c1: CodecSpec) -> Option { - match (c0.format.h265_profile_tier_level, c1.format.h265_profile_tier_level) { - (Some(c0_ptl), Some(c1_ptl)) => { - // Both have full PTL - strict matching - - // Profiles must match exactly. - // RFC 7798 §7.2.2: profile-id is a configuration parameter - // that MUST be used symmetrically in offer/answer. - // https://www.rfc-editor.org/rfc/rfc7798#section-7.2.2 - if c0_ptl.profile() != c1_ptl.profile() { - return None; - } - - // Tiers must match exactly. - // RFC 7798 §7.2.2: tier-flag is a configuration parameter - // that MUST be used symmetrically in offer/answer. - // https://www.rfc-editor.org/rfc/rfc7798#section-7.2.2 - if c0_ptl.tier() != c1_ptl.tier() { - return None; - } - - // Level difference penalizes score but never causes rejection. - // Actual level narrowing to min(local, remote) is done in update_param. - let level_difference: usize = c0_ptl.level().ordinal().abs_diff(c1_ptl.level().ordinal()); - - // Pure scoring without artificial floor - let caller decide policy - Some(Self::EXACT_MATCH_SCORE.saturating_sub(level_difference)) - } - _ => { - // At least one side has only profile-id (not full PTL). - // Match on profile only, using FALLBACK for missing values. - - // Get profile from PTL if present, otherwise from profile_id field - let c0_profile = c0 - .format - .h265_profile_tier_level - .map(|ptl| ptl.profile().to_id()) - .or_else(|| c0.format.profile_id.map(|p| p as u8)) - .unwrap_or(H265ProfileTierLevel::FALLBACK.profile().to_id()); - - let c1_profile = c1 - .format - .h265_profile_tier_level - .map(|ptl| ptl.profile().to_id()) - .or_else(|| c1.format.profile_id.map(|p| p as u8)) - .unwrap_or(H265ProfileTierLevel::FALLBACK.profile().to_id()); - - // Profiles must match - if c0_profile != c1_profile { - return None; - } - - // When only profile is specified, we can't verify tier/level compatibility. - // Return a lower score to prefer exact PTL matches when available. - Some(Self::PROFILE_ONLY_MATCH_SCORE) - } - } - } - - pub(crate) fn update_param( - &mut self, - remote_pts: &[PayloadParams], - claimed: &mut [bool; 128], - local_is_controlling: bool, - unlocked: &mut HashSet, - ) { - let Some((first, _)) = remote_pts - .iter() - // One unrestricted AMR-WB payload can match several local mode sets. - // Leave the other alternatives unlocked once its PT has been claimed. - .filter(|p| { - self.spec.codec != Codec::AmrWb || self.locked || local_is_controlling || !claimed.is_claimed(p.pt) - }) - .filter_map(|p| self.match_score(p).map(|s| (p, s))) - .max_by_key(|(_, s)| *s) - else { - return; - }; - - // The first negotiated m-line determines TWCC support for this PT. - if !self.locked { - self.fb_transport_cc &= first.fb_transport_cc(); - } - - // Mirror the remote's H.265 fmtp shape: echo back only the params they offered. - if self.spec.codec == Codec::H265 && first.spec.codec == Codec::H265 { - if let Some(remote_ptl) = first.spec.format.h265_profile_tier_level { - // Narrow level to min(local, remote) so the negotiated level - // never exceeds either side's capability. - let negotiated_ptl = if let Some(local_ptl) = self.spec.format.h265_profile_tier_level { - remote_ptl.with_level(std::cmp::min(local_ptl.level(), remote_ptl.level())) - } else { - remote_ptl - }; - self.spec.format.h265_profile_tier_level = Some(negotiated_ptl); - // Avoid also serializing `profile-id` via the VP9 `profile_id` field. - self.spec.format.profile_id = None; - } else if let Some(profile_id) = first.spec.format.profile_id { - // Remote only offered `profile-id`. - self.spec.format.h265_profile_tier_level = None; - self.spec.format.profile_id = Some(profile_id); - } else { - // No remote H.265 fmtp, omit ours as well. - self.spec.format.h265_profile_tier_level = None; - self.spec.format.profile_id = None; - } - - // Adopt remote's sprop-max-don-diff so the depacketizer knows whether - // incoming packets contain DONL fields (RFC 7798 §7.1). - // The packetizer also uses this to decide whether to emit DONL. - if first.spec.format.sprop_max_don_diff.is_some() { - self.spec.format.sprop_max_don_diff = first.spec.format.sprop_max_don_diff; - } - } - - // KNOWN LIMITATION: H.264 has no equivalent level-narrowing pass here. - // `match_h264_score` treats the level as negotiable, but we keep our - // locally configured `profile-level-id` in the answer instead of - // narrowing it to `min(local, remote)`. Per RFC 6184 §8.2.2, when - // `level-asymmetry-allowed` is not set the answer should use the lower - // level. - - // RFC 4867 §8.3.1: an answer repeats the offer's octet-align and channels, - // and a mode-set from either side applies to both directions. - if self.spec.codec == Codec::AmrWb { - let remote = first.spec; - self.spec.channels = remote.channels; - self.spec.format.octet_align = remote.format.octet_align; - self.spec.format.mode_set = self.spec.format.mode_set.or(remote.format.mode_set); - } - - let mut remote_pt = first.pt; - let mut remote_rtx = first.resend; - - if self.locked { - // This can happen if the incoming PTs are suggestions (send-direction) rather than demanded - // (receive-direction). We only want to warn if we get receive direction changes. - if local_is_controlling { - return; - } - // Just verify it's still the same. We should validate this in apply_offer/answer instead - // of ever seeing this error message. - if self.pt != remote_pt { - warn!("Ignore remote PT change {} => {}", self.pt, remote_pt); - } - - if self.resend != remote_rtx { - warn!("Ignore remote PT RTX change {:?} => {:?}", self.resend, remote_rtx); - } - } else { - // Before locking, check if the remote PT conflicts with an already locked PT. - // If we're receiving, we control what PTs to use, - // so we can remap the conflicting PT. - if local_is_controlling && claimed.is_claimed(remote_pt) { - // Prefer our configured PT, then fall back to any free PT. - let new_pt = (!claimed.is_claimed(self.pt)) - .then_some(self.pt) - .or_else(|| claimed.find_unclaimed(PREFERED_RANGES, unlocked)); - - if let Some(new_pt) = new_pt { - debug!( - "Remapped conflicting PT {} => {} for codec {:?}", - remote_pt, new_pt, self.spec.codec - ); - remote_pt = new_pt; - unlocked.remove(&new_pt); - } else { - panic!("Exhausted all PT ranges, inconsistent PayloadParam state"); - } - } - - // Lock down the PT - self.pt = remote_pt; - claimed.assert_claim_once(remote_pt); - - // Check if RTX PT also conflicts - if local_is_controlling { - if let Some(rtx) = remote_rtx { - if claimed.is_claimed(rtx) { - let new_rtx = self - .resend - .filter(|pt| !claimed.is_claimed(*pt)) - .or_else(|| claimed.find_unclaimed(PREFERED_RANGES, unlocked)); - - if let Some(new_rtx) = new_rtx { - debug!("Remapped conflicting RTX PT {:?} => {}", rtx, new_rtx); - remote_rtx = Some(new_rtx); - unlocked.remove(&new_rtx); - } else { - panic!("Exhausted all PT ranges, inconsistent PayloadParam state"); - } - } - } - } - - // Lock down the RTX PT - self.resend = remote_rtx; - if let Some(rtx) = remote_rtx { - claimed.assert_claim_once(rtx); - } - - // This is now locked. - self.locked = true; - } - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::rtp_::Frequency; - - use super::*; - use crate::vendor::str0m::format::{CodecSpec, FormatParams}; - - mod h264 { - use super::*; - - fn h264_codec_spec( - level_asymmetry_allowed: Option, - packetization_mode: Option, - profile_level_id: Option, - ) -> CodecSpec { - CodecSpec { - codec: Codec::H264, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - level_asymmetry_allowed, - packetization_mode, - profile_level_id, - ..Default::default() - }, - } - } - - #[test] - fn test_h264_profile_matching() { - struct Case { - c0: CodecSpec, - c1: CodecSpec, - must_match: bool, - msg: &'static str, - } - - let cases = [ - Case { - c0: h264_codec_spec(None, None, Some(0x42E01F)), - c1: h264_codec_spec(None, None, Some(0x4DA01F)), - must_match: true, - msg: "0x42A01F and 0x4DF01F should match, they are both constrained baseline subprofile", - }, - Case { - c0: h264_codec_spec(None, None, Some(0x42E01F)), - c1: h264_codec_spec(None, Some(1), Some(0x4DA01F)), - must_match: false, - msg: "0x42A01F and 0x4DF01F with differing packetization modes should not match", - }, - Case { - c0: h264_codec_spec(None, Some(0), Some(0x422000)), - c1: h264_codec_spec(None, None, Some(0x42B00A)), - must_match: true, - msg: "0x424000 and 0x42B00A should match because they are both the baseline subprofile \ - and the level idc of 0x42F01F will be adjusted to Level1B because the constraint \ - set 3 flag is set", - }, - ]; - - for Case { - c0, - c1, - must_match, - msg, - } in cases.into_iter() - { - let matched = PayloadParams::match_h264_score(c0, c1).is_some(); - assert_eq!(matched, must_match, "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"); - } - } - - #[test] - fn test_h264_level_matching_rfc_compliant() { - struct Case { - c0: CodecSpec, - c1: CodecSpec, - expected: Option, - msg: &'static str, - } - - let cases = [ - // Test 1: Same profile, same level -> should match - Case { - c0: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 - c1: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 - expected: Some(PayloadParams::EXACT_MATCH_SCORE), - msg: "Same profile (CB) and same level (4.0) should match", - }, - // Test 2: Same profile, offered level lower -> should match (RFC 6184) - Case { - c0: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 (configured) - c1: h264_codec_spec(None, None, Some(0x42e01f)), // CB L3.1 (offered) - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2), - msg: "Same profile (CB), offered level 3.1 < configured 4.0 should match per RFC 6184", - }, - // Test 3: Same profile, offered level higher -> should match (RFC 6184) - Case { - c0: h264_codec_spec(None, None, Some(0x42e01f)), // CB L3.1 (configured) - c1: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 (offered) - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2), - msg: "Same profile (CB), offered level 4.0 > configured 3.1 should match, \ - the level is negotiable per RFC 6184", - }, - // Test 4: Different profiles -> should NOT match - Case { - c0: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 - c1: h264_codec_spec(None, None, Some(0x4d0028)), // Main L4.0 - expected: None, - msg: "Different profiles (CB vs Main) should NOT match even with same level", - }, - // Test 5: Main profile, offered lower level -> should match - Case { - c0: h264_codec_spec(None, None, Some(0x4d002a)), // Main L4.2 (configured) - c1: h264_codec_spec(None, None, Some(0x4d0028)), // Main L4.0 (offered) - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2), - msg: "Same profile (Main), offered level 4.0 < configured 4.2 should match", - }, - // Test 6: High profile, multiple levels down -> should match - Case { - c0: h264_codec_spec(None, None, Some(0x640033)), // High L5.1 (configured) - c1: h264_codec_spec(None, None, Some(0x64001f)), // High L3.1 (offered) - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 6), - msg: "Same profile (High), offered level 3.1 < configured 5.1 should match", - }, - // Test 7: Baseline (not CB) with Level1B as offered - Case { - c0: h264_codec_spec(None, None, Some(0x42001f)), // Baseline L3.1 - c1: h264_codec_spec(None, None, Some(0x420000)), // Baseline Level1B - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 8), - msg: "Same profile (Baseline), offered level 1B < configured 3.1 should match", - }, - // Test 8: Baseline (not CB) offered lower level > should match with (special Level1B case) - Case { - c0: h264_codec_spec(None, None, Some(0x420000)), // Baseline Level1B - c1: h264_codec_spec(None, None, Some(0x42000a)), // Baseline L1 - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1), - msg: "Same profile (Baseline), offered level 1 < configured 1B should match", - }, - // Test 9: Baseline (not CB) offered higher level -> should match (special Level1B case) - Case { - c0: h264_codec_spec(None, None, Some(0x42000a)), // Baseline L1 - c1: h264_codec_spec(None, None, Some(0x420000)), // Baseline Level1B - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1), - msg: "Same profile (Baseline), offered level 1B > configured 1 should match", - }, - // Test 10: Offered Constrained Baseline level 5.2 is higher than - // the default configured 3.1. Must match. - Case { - c0: h264_codec_spec(Some(true), Some(1), Some(0x42e01f)), // CB L3.1 (configured) - c1: h264_codec_spec(Some(true), Some(1), Some(0x42e034)), // CB L5.2 (offered) - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 7), - msg: "Same profile (CB), offered level 5.2 > configured 3.1 should match", - }, - // Test 11: Constrained High (profile-iop 0x0C) must be recognized - // and match a configured Constrained High. - Case { - c0: h264_codec_spec(Some(true), Some(1), Some(0x640c1f)), // CH L3.1 (configured) - c1: h264_codec_spec(Some(true), Some(1), Some(0x640c34)), // CH L5.2 (offered) - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 7), - msg: "Same profile (Constrained High), offered level 5.2 should match", - }, - // Test 12: Constrained High is not the same profile as High. - Case { - c0: h264_codec_spec(None, None, Some(0x64001f)), // High L3.1 - c1: h264_codec_spec(None, None, Some(0x640c1f)), // Constrained High L3.1 - expected: None, - msg: "Different profiles (High vs Constrained High) should NOT match", - }, - ]; - - for Case { c0, c1, expected, msg } in cases.into_iter() { - assert_eq!( - PayloadParams::match_h264_score(c0, c1), - expected, - "{msg}\nc0: {c0:#?}\nc1: {c1:#?}" - ); - } - } - } - - mod h265 { - use super::*; - use crate::vendor::str0m::packet::Packetizer; - - fn h265_codec_spec(profile_id: u8, tier_flag: u8, level_id: u8) -> CodecSpec { - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - h265_profile_tier_level: Some(H265ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap()), - ..Default::default() - }, - } - } - - fn h265_codec_spec_profile_only(profile_id: u32) -> CodecSpec { - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - profile_id: Some(profile_id), - ..Default::default() - }, - } - } - - /// Test basic H.265 profile/tier/level matching scenarios. - /// Verifies that full ProfileTierLevel parameters are matched correctly. - #[test] - fn test_profile_tier_level_matching() { - struct Case { - c0: CodecSpec, - c1: CodecSpec, - must_match: bool, - msg: &'static str, - } - - let cases = [ - // Same profile, tier, level -> should match - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 0, 93), - must_match: true, - msg: "Same profile (Main), tier (Main), level (3.1) should match", - }, - // Same profile and tier, offered level lower -> should match - Case { - c0: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0 - c1: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - must_match: true, - msg: "Same profile/tier, offered level 3.1 < configured 4.0 should match", - }, - // Same profile and tier, offered level higher -> should still match (with penalty) - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0 - must_match: true, - msg: "Same profile/tier, offered level 4.0 > configured 3.1 should match (penalized)", - }, - // Different profiles -> should NOT match - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1 - must_match: false, - msg: "Different profiles (Main vs Main10) should NOT match", - }, - // Different tiers -> should NOT match - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1 - must_match: false, - msg: "Different tiers (Main vs High) should NOT match", - }, - // Main10 profile, same tier, lower level -> should match - Case { - c0: h265_codec_spec(2, 0, 153), // Main10, Main tier, Level 5.1 - c1: h265_codec_spec(2, 0, 120), // Main10, Main tier, Level 4.0 - must_match: true, - msg: "Main10 profile, offered level 4.0 < configured 5.1 should match", - }, - // High tier, multiple levels down -> should match - Case { - c0: h265_codec_spec(1, 1, 153), // Main, High tier, Level 5.1 - c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1 - must_match: true, - msg: "High tier, offered level 3.1 < configured 5.1 should match", - }, - ]; - - for Case { - c0, - c1, - must_match, - msg, - } in cases.into_iter() - { - let matched = PayloadParams::match_h265_score(c0, c1).is_some(); - assert_eq!(matched, must_match, "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"); - } - } - - /// Test H.265 level matching with exact scores. - /// Verifies that the score decrements based on level difference. - #[test] - fn test_level_matching_scores() { - struct Case { - c0: CodecSpec, - c1: CodecSpec, - expected: Option, - msg: &'static str, - } - - let cases = [ - // Exact match -> score 100 - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 0, 93), - expected: Some(PayloadParams::EXACT_MATCH_SCORE), - msg: "Exact match should return score 100", - }, - // One level down -> score 100 - 1 - Case { - c0: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0 - c1: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1), - msg: "One level difference should return score 99", - }, - // Two levels down -> score 100 - 2 - Case { - c0: h265_codec_spec(1, 0, 123), // Main, Main tier, Level 4.1 - c1: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2), - msg: "Two level difference should return score 98", - }, - // Multiple levels down - Case { - c0: h265_codec_spec(1, 0, 153), // Main, Main tier, Level 5.1 - c1: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 4), - msg: "Four level difference (5.1 to 3.1) should return score 96", - }, - // Offered level higher -> still matches, penalized by 1 ordinal - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0 - expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1), - msg: "Offered level one higher than configured should return score 99", - }, - // Different profiles -> None - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1 - expected: None, - msg: "Different profiles should return None", - }, - // Different tiers -> None - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1 - expected: None, - msg: "Different tiers should return None", - }, - ]; - - for Case { c0, c1, expected, msg } in cases.into_iter() { - assert_eq!( - PayloadParams::match_h265_score(c0, c1), - expected, - "{msg}\nc0: {c0:#?}\nc1: {c1:#?}" - ); - } - } - - /// Test H.265 profile-only matching (for Chrome compatibility). - /// When only profile-id is provided without tier/level, match on profile only. - #[test] - fn test_profile_only_matching() { - struct Case { - c0: CodecSpec, - c1: CodecSpec, - expected: Option, - msg: &'static str, - } - - let cases = [ - // Both have profile-only, same profile -> score 90 - Case { - c0: h265_codec_spec_profile_only(1), // Main - c1: h265_codec_spec_profile_only(1), // Main - expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE), - msg: "Profile-only match (Main) should return score 90", - }, - // Both have profile-only, different profiles -> None - Case { - c0: h265_codec_spec_profile_only(1), // Main - c1: h265_codec_spec_profile_only(2), // Main10 - expected: None, - msg: "Profile-only with different profiles should return None", - }, - // One has full PTL, other has profile-only, same profile -> score 90 - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec_profile_only(1), // Main - expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE), - msg: "Mixed PTL and profile-only with matching profile should return score 90", - }, - // One has full PTL, other has profile-only, different profiles -> None - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec_profile_only(2), // Main10 - expected: None, - msg: "Mixed PTL and profile-only with different profiles should return None", - }, - // Reverse: profile-only vs full PTL, same profile -> score 90 - Case { - c0: h265_codec_spec_profile_only(1), // Main - c1: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE), - msg: "Profile-only vs full PTL with matching profile should return score 90", - }, - ]; - - for Case { c0, c1, expected, msg } in cases.into_iter() { - assert_eq!( - PayloadParams::match_h265_score(c0, c1), - expected, - "{msg}\nc0: {c0:#?}\nc1: {c1:#?}" - ); - } - } - - /// Test negative cases for H.265 matching to ensure proper rejection. - #[test] - fn test_negative_cases() { - struct Case { - c0: CodecSpec, - c1: CodecSpec, - msg: &'static str, - } - - let cases = [ - // Profile mismatch with full PTL - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1 - msg: "Profile mismatch (Main vs Main10) must not match", - }, - // Tier mismatch - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1 - msg: "Tier mismatch (Main vs High) must not match", - }, - // All three different (profile+tier mismatch rejects) - Case { - c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1 - c1: h265_codec_spec(2, 1, 153), // Main10, High tier, Level 5.1 - msg: "Profile and tier different must not match", - }, - // Profile-only mismatch - Case { - c0: h265_codec_spec_profile_only(1), // Main - c1: h265_codec_spec_profile_only(2), // Main10 - msg: "Profile-only mismatch must not match", - }, - // Mixed full PTL vs profile-only with different profiles - Case { - c0: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1 - c1: h265_codec_spec_profile_only(1), // Main - msg: "Full PTL (Main10) vs profile-only (Main) must not match", - }, - ]; - - for Case { c0, c1, msg } in cases.into_iter() { - assert_eq!( - PayloadParams::match_h265_score(c0, c1), - None, - "{msg}\nc0: {c0:#?}\nc1: {c1:#?}" - ); - } - } - - /// Test that sprop-max-don-diff is adopted from remote SDP during negotiation, - /// and that packetizer/depacketizer are correctly initialized with DONL enabled. - #[test] - fn test_sprop_max_don_diff_negotiation_enables_donl() { - use crate::vendor::str0m::packet::{CodecDepacketizer, CodecPacketizer}; - - // Local config: no sprop-max-don-diff (default) - let local_spec = h265_codec_spec(1, 0, 93); - let mut local_params = - PayloadParams::new(Pt::new_with_value(102), Some(Pt::new_with_value(103)), local_spec); - assert_eq!( - local_params.spec.format.sprop_max_don_diff, None, - "Local should have no sprop-max-don-diff initially" - ); - - // Remote offers H.265 with sprop-max-don-diff=32 - let mut remote_spec = h265_codec_spec(1, 0, 93); - remote_spec.format.sprop_max_don_diff = Some(32); - let remote_params = PayloadParams::new(Pt::new_with_value(102), Some(Pt::new_with_value(103)), remote_spec); - - // Simulate SDP negotiation (update_param merges remote into local) - let mut claimed = [false; 128]; - let mut unlocked = std::collections::HashSet::new(); - local_params.update_param( - &[remote_params], - &mut claimed, - false, // remote is controlling (we're answering) - &mut unlocked, - ); - - // Verify sprop-max-don-diff was adopted from remote - assert_eq!( - local_params.spec.format.sprop_max_don_diff, - Some(32), - "sprop-max-don-diff should be adopted from remote after negotiation" - ); - - // Verify packetizer is initialized with DONL enabled - let donl_enabled = local_params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0; - assert!(donl_enabled, "DONL should be enabled when sprop-max-don-diff > 0"); - - let mut pack = CodecPacketizer::new( - local_params.spec.codec, - crate::vendor::str0m::format::Vp9PacketizerMode::default(), - ); - if let CodecPacketizer::H265(ref mut h265) = pack { - h265.with_donl(donl_enabled); - } - - // Packetize a NAL - should include DONL field (2 extra bytes) - let nalu = vec![0x02, 0x01, 0xAA, 0xBB]; - let packets = pack.packetize(1200, &nalu).unwrap(); - assert_eq!(packets.len(), 1); - assert_eq!( - packets[0].len(), - nalu.len() + 2, // +2 for DONL - "Packetized output should include 2-byte DONL field" - ); - - // Verify depacketizer is initialized with DONL enabled - let mut depack: CodecDepacketizer = local_params.spec.codec.into(); - if let CodecDepacketizer::H265(ref mut h265) = depack { - h265.with_donl(donl_enabled); - } - - // Depacketize the packet - should correctly strip DONL - use crate::vendor::str0m::packet::{CodecExtra, Depacketizer}; - let mut out = Vec::new(); - let mut extra = CodecExtra::None; - if let CodecDepacketizer::H265(ref mut h265) = depack { - h265.depacketize(&packets[0], &mut out, &mut extra).unwrap(); - } - - // Output should be Annex-B: start code + original NAL - assert_eq!(&out[0..4], &[0x00, 0x00, 0x00, 0x01]); - assert_eq!(&out[4..], &nalu[..], "Depacketized NAL should match original"); - } - - /// Test that sprop-max-don-diff=0 from remote does NOT enable DONL. - #[test] - fn test_sprop_max_don_diff_zero_disables_donl() { - let local_spec = h265_codec_spec(1, 0, 93); - let mut local_params = - PayloadParams::new(Pt::new_with_value(102), Some(Pt::new_with_value(103)), local_spec); - - // Remote offers with sprop-max-don-diff=0 (no reordering) - let mut remote_spec = h265_codec_spec(1, 0, 93); - remote_spec.format.sprop_max_don_diff = Some(0); - let remote_params = PayloadParams::new(Pt::new_with_value(102), Some(Pt::new_with_value(103)), remote_spec); - - let mut claimed = [false; 128]; - let mut unlocked = std::collections::HashSet::new(); - local_params.update_param(&[remote_params], &mut claimed, false, &mut unlocked); - - assert_eq!(local_params.spec.format.sprop_max_don_diff, Some(0)); - let donl_enabled = local_params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0; - assert!(!donl_enabled, "DONL should NOT be enabled when sprop-max-don-diff=0"); - - // Packetize without DONL - packet should be same size as NAL - let nalu = vec![0x02, 0x01, 0xAA, 0xBB]; - let mut pack = crate::vendor::str0m::packet::CodecPacketizer::new( - local_params.spec.codec, - crate::vendor::str0m::format::Vp9PacketizerMode::default(), - ); - // Don't call with_donl(true) since donl_enabled is false - let packets = pack.packetize(1200, &nalu).unwrap(); - assert_eq!(packets[0].len(), nalu.len(), "No DONL field when sprop-max-don-diff=0"); - } - - /// Test that missing sprop-max-don-diff from remote preserves local value. - #[test] - fn test_sprop_max_don_diff_absent_preserves_local() { - // Local has sprop-max-don-diff=16 - let mut local_spec = h265_codec_spec(1, 0, 93); - local_spec.format.sprop_max_don_diff = Some(16); - let mut local_params = - PayloadParams::new(Pt::new_with_value(102), Some(Pt::new_with_value(103)), local_spec); - - // Remote offers without sprop-max-don-diff - let remote_spec = h265_codec_spec(1, 0, 93); - assert!(remote_spec.format.sprop_max_don_diff.is_none()); - let remote_params = PayloadParams::new(Pt::new_with_value(102), Some(Pt::new_with_value(103)), remote_spec); - - let mut claimed = [false; 128]; - let mut unlocked = std::collections::HashSet::new(); - local_params.update_param(&[remote_params], &mut claimed, false, &mut unlocked); - - // Local value should be preserved (remote didn't override) - assert_eq!( - local_params.spec.format.sprop_max_don_diff, - Some(16), - "Local sprop-max-don-diff should be preserved when remote doesn't specify it" - ); - } - } - - mod amr_wb { - use super::*; - - fn amr_wb(channels: Option, format: FormatParams) -> PayloadParams { - let spec = CodecSpec { - codec: Codec::AmrWb, - clock_rate: Frequency::SIXTEEN_KHZ, - channels, - format, - }; - PayloadParams::new(122.into(), None, spec) - } - - fn octet_aligned() -> FormatParams { - FormatParams { - octet_align: Some(true), - ..Default::default() - } - } - - #[test] - fn matching() { - let local = amr_wb(Some(1), octet_aligned()); - let score = |remote: PayloadParams| local.match_score(&remote); - - assert!(score(local).is_some()); - assert!(score(amr_wb(None, octet_aligned())).is_some()); - assert!(score(amr_wb(Some(1), FormatParams::default())).is_none()); - - let bandwidth_efficient = FormatParams { - octet_align: Some(false), - ..Default::default() - }; - let default = amr_wb(None, FormatParams::default()); - assert!(default.match_score(&amr_wb(None, bandwidth_efficient)).is_some()); - - let modes = |mode_set| FormatParams { - mode_set: Some(mode_set), - ..octet_aligned() - }; - let restricted = amr_wb(Some(1), modes(0b111)); - assert!(score(restricted).is_some_and(|s| Some(s) < score(local))); - assert!(restricted.match_score(&amr_wb(None, modes(0b11))).is_none()); - - let stereo = amr_wb(Some(2), octet_aligned()); - assert!(stereo.match_score(&stereo).is_none()); - } - - #[test] - fn update_param_mirrors_layout_channels_and_mode_set() { - let mut local = amr_wb(Some(1), FormatParams::default()); - let remote_format = FormatParams { - octet_align: Some(false), - mode_set: Some(0b111), - ..Default::default() - }; - let remote = amr_wb(None, remote_format); - - local.update_param(&[remote], &mut [false; 128], false, &mut HashSet::new()); - - assert_eq!(local.spec.channels, None); - assert_eq!(local.spec.format, remote_format); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/io/error.rs b/rs/moq-webrtc/src/vendor/str0m/io/error.rs deleted file mode 100644 index da60e8d092e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/io/error.rs +++ /dev/null @@ -1,45 +0,0 @@ -use std::error::Error; -use std::fmt; -use std::io; - -pub use crate::vendor::is::StunError; - -/// Errors from parsing network data. -#[derive(Debug)] -pub enum NetError { - /// Some STUN protocol error. - Stun(StunError), - - /// A wrapped IO error. - Io(io::Error), -} - -impl fmt::Display for NetError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - NetError::Stun(err) => write!(f, "{}", err), - NetError::Io(err) => write!(f, "{}", err), - } - } -} - -impl Error for NetError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - NetError::Stun(err) => Some(err), - NetError::Io(err) => Some(err), - } - } -} - -impl From for NetError { - fn from(err: StunError) -> Self { - NetError::Stun(err) - } -} - -impl From for NetError { - fn from(err: io::Error) -> Self { - NetError::Io(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/io/mod.rs b/rs/moq-webrtc/src/vendor/str0m/io/mod.rs deleted file mode 100644 index da98952928e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/io/mod.rs +++ /dev/null @@ -1,171 +0,0 @@ -#![allow(clippy::manual_range_contains)] -#![allow(clippy::new_without_default)] - -use std::convert::TryFrom; -use std::fmt; -use std::io; -use std::net::SocketAddr; - -use serde::{Deserialize, Serialize}; - -pub use crate::vendor::is::stun::StunMessage; - -pub use crate::vendor::str0m_proto::DATAGRAM_MTU_TARGET; -pub use crate::vendor::str0m_proto::DATAGRAM_MTU_TARGET_MAX; -pub use crate::vendor::str0m_proto::DATAGRAM_MTU_TARGET_MIN; -pub use crate::vendor::str0m_proto::DATAGRAM_MTU_WARN; - -/// Max UDP packet size -pub(crate) const DATAGRAM_MAX_PACKET_SIZE: usize = 2000; - -/// Max expected DTLS record overhead (record header + explicit nonce + AEAD -/// auth tag), worst case across DTLS 1.2/1.3 and common AEAD ciphers -/// (AES-GCM, AES-CCM, CHACHA20-POLY1305). -pub const MAX_DTLS_OVERHEAD: usize = 48; - -mod error; -pub use self::error::NetError; -#[allow(unused_imports)] -pub use self::error::StunError; - -pub use crate::vendor::str0m_proto::{DatagramSend, Protocol, TcpType, Transmit}; - -#[derive(Debug, Serialize, Deserialize)] -/// Received incoming data. -pub struct Receive<'a> { - /// The protocol the socket this received data originated from is using. - pub proto: Protocol, - - /// The socket this received data originated from. - pub source: SocketAddr, - - /// The destination ip of the datagram. - pub destination: SocketAddr, - - /// Parsed contents of the datagram. - #[serde(borrow)] - pub contents: DatagramRecv<'a>, -} - -impl<'a> Receive<'a> { - /// Creates a new instance by trying to parse the contents of `buf`. - pub fn new(proto: Protocol, source: SocketAddr, destination: SocketAddr, buf: &'a [u8]) -> Result { - let contents = DatagramRecv::try_from(buf)?; - Ok(Receive { - proto, - source, - destination, - contents, - }) - } -} - -/// Wrapper for a parsed payload to be received. -#[derive(Serialize, Deserialize)] -pub struct DatagramRecv<'a> { - #[serde(borrow)] - pub(crate) inner: DatagramRecvInner<'a>, -} - -#[allow(clippy::large_enum_variant)] // We purposely don't want to allocate. -#[derive(Serialize, Deserialize)] -pub(crate) enum DatagramRecvInner<'a> { - Stun(StunMessage<'a>), - Dtls(&'a [u8]), - Rtp(&'a [u8]), - Rtcp(&'a [u8]), -} - -impl<'a> TryFrom<&'a [u8]> for DatagramRecv<'a> { - type Error = NetError; - - fn try_from(value: &'a [u8]) -> Result { - use DatagramRecvInner::*; - - let kind = MultiplexKind::try_from(value)?; - - let inner = match kind { - MultiplexKind::Stun => Stun(StunMessage::parse(value)?), - MultiplexKind::Dtls => Dtls(value), - MultiplexKind::Rtp => Rtp(value), - MultiplexKind::Rtcp => Rtcp(value), - }; - - Ok(DatagramRecv { inner }) - } -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub(crate) enum MultiplexKind { - Stun, - Dtls, - Rtp, - Rtcp, -} - -impl<'a> TryFrom<&'a [u8]> for MultiplexKind { - type Error = io::Error; - - fn try_from(value: &'a [u8]) -> Result { - if value.is_empty() { - return Err(io::Error::new(io::ErrorKind::InvalidData, "Empty datagram")); - } - - let byte0 = value[0]; - let len = value.len(); - - if byte0 < 2 && len >= 20 { - Ok(MultiplexKind::Stun) - } else if byte0 >= 20 && byte0 < 64 { - Ok(MultiplexKind::Dtls) - } else if byte0 >= 128 && byte0 < 192 && len > 2 { - let byte1 = value[1]; - let payload_type = byte1 & 0x7f; - - Ok(if payload_type < 64 { - // This is kinda novel, and probably breaks, but... - // we can use the < 64 pt as an escape hatch if we run out - // of dynamic numbers >= 96 - // https://bugs.chromium.org/p/webrtc/issues/detail?id=12194 - MultiplexKind::Rtp - } else if payload_type >= 64 && payload_type < 96 { - MultiplexKind::Rtcp - } else { - MultiplexKind::Rtp - }) - } else { - Err(io::Error::new(io::ErrorKind::InvalidData, "Unknown datagram")) - } - } -} - -impl<'a> TryFrom<&'a Transmit> for Receive<'a> { - type Error = NetError; - - fn try_from(t: &'a Transmit) -> Result { - Ok(Receive { - proto: t.proto, - source: t.source, - destination: t.destination, - contents: DatagramRecv::try_from(&t.contents[..])?, - }) - } -} - -impl fmt::Debug for DatagramRecv<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.inner.fmt(f) - } -} - -impl fmt::Debug for DatagramRecvInner<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stun(v) => f.debug_tuple("Stun").field(v).finish(), - Self::Dtls(v) => write!(f, "Dtls(len: {})", v.len()), - Self::Rtp(v) => write!(f, "Rtp(len: {})", v.len()), - Self::Rtcp(v) => write!(f, "Rtcp(len: {})", v.len()), - } - } - // -} diff --git a/rs/moq-webrtc/src/vendor/str0m/lib.rs b/rs/moq-webrtc/src/vendor/str0m/lib.rs deleted file mode 100644 index f9f531a6b94..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/lib.rs +++ /dev/null @@ -1,1996 +0,0 @@ -//! str0m logo -//! -//! -//! A Sans I/O WebRTC implementation in Rust. -//! -//! This is a [Sans I/O][sansio] implementation meaning the `Rtc` instance itself is not doing any network -//! talking. Furthermore it has no internal threads or async tasks. All operations are happening from the -//! calls of the public API. -//! -//! This is deliberately not a standard `RTCPeerConnection` API since that isn't a great fit for Rust. -//! See more details in below section. -//! -//! # Join us -//! -//! We are discussing str0m things on Discord. Join us using this [invitation link][discord]. -//! -//! silly clip showing video playing -//! -//! -//! # Usage -//! -//! The [`chat`][x-chat] example shows how to connect multiple browsers -//! together and act as an SFU (Selective Forwarding Unit). The example -//! multiplexes all traffic over one server UDP socket and uses two threads -//! (one for the web server, and one for the SFU loop). -//! -//! ## TLS -//! -//! For the browser to do WebRTC, all traffic must be under TLS. The -//! project ships with a self-signed certificate that is used for the -//! examples. The certificate is for hostname `str0m.test` since TLD .test -//! should never resolve to a real DNS name. -//! -//! ```text -//! cargo run --example chat -//! ``` -//! -//! The log should prompt you to connect a browser to https://10.0.0.103:3000 – this will -//! most likely cause a security warning that you must get the browser to accept. -//! -//! The [`http-post`][x-post] example roughly illustrates how to receive -//! media data from a browser client. The example is single threaded and -//! is a bit simpler than the chat. It is a good starting point to understand the API. -//! -//! ```text -//! cargo run --example http-post -//! ``` -//! -//! ### Real example -//! -//! To see how str0m is used in a real project, check out [BitWHIP][bitwhip] – -//! a CLI WebRTC Agent written in Rust. -//! -//! ## Passive -//! -//! For passive connections, i.e. where the media and initial OFFER is -//! made by a remote peer, we need these steps to open the connection. -//! -//! ```ignore -//! # use std::time::Instant; -//! # use crate::vendor::str0m::{Rtc, Candidate}; -//! // Instantiate a new Rtc instance. -//! let mut rtc = Rtc::new(Instant::now()); -//! -//! // Add some ICE candidate such as a locally bound UDP port. -//! let addr = "1.2.3.4:5000".parse().unwrap(); -//! let candidate = Candidate::host(addr, "udp").unwrap(); -//! rtc.add_local_candidate(candidate); -//! -//! // Accept an incoming offer from the remote peer -//! // and get the corresponding answer. -//! let offer = todo!(); -//! let answer = rtc.sdp_api().accept_offer(offer).unwrap(); -//! -//! // Forward the answer to the remote peer. -//! -//! // Go to _run loop_ -//! ``` -//! -//! ## Active -//! -//! Active connections means we are making the inital OFFER and waiting for a -//! remote ANSWER to start the connection. -//! -//! ```ignore -//! # use std::time::Instant; -//! # use crate::vendor::str0m::{Rtc, Candidate}; -//! # use crate::vendor::str0m::media::{MediaKind, Direction}; -//! // Instantiate a new Rtc instance. -//! let mut rtc = Rtc::new(Instant::now()); -//! -//! // Add some ICE candidate such as a locally bound UDP port. -//! let addr = "1.2.3.4:5000".parse().unwrap(); -//! let candidate = Candidate::host(addr, "udp").unwrap(); -//! rtc.add_local_candidate(candidate); -//! -//! // Create a `SdpApi`. The change lets us make multiple changes -//! // before sending the offer. -//! let mut change = rtc.sdp_api(); -//! -//! // Do some change. A valid OFFER needs at least one "m-line" (media). -//! let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); -//! -//! // Get the offer. -//! let (offer, pending) = change.apply().unwrap(); -//! -//! // Forward the offer to the remote peer and await the answer. -//! // How to transfer this is outside the scope for this library. -//! let answer = todo!(); -//! -//! // Apply answer. -//! rtc.sdp_api().accept_answer(pending, answer).unwrap(); -//! -//! // Go to _run loop_ -//! ``` -//! -//! ## Run loop -//! -//! ### The single-mutation invariant -//! -//! str0m's API has one strict contract that the run loop is built around: -//! -//! > **Every mutation of an `Rtc` instance must be followed by a complete -//! > drain of `poll_output` until it returns `Output::Timeout`, before the -//! > next mutation on the same `Rtc`.** -//! -//! A "mutation" is anything that takes `&mut Rtc` (directly or through a -//! handle obtained from it). The common ones are: -//! -//! - `Rtc::handle_input` - feeding a network packet or a timeout -//! - `Writer::write` / `Writer::request_keyframe` - sending media -//! - `SdpApi::apply` / `DirectApi::*` - negotiation -//! - `Rtc::add_local_candidate` / `Rtc::add_remote_candidate` -//! -//! Always: **mutate → drain to `Timeout` → mutate → drain to `Timeout` → …** -//! -//! Doing two mutations back-to-back without draining in between, or -//! waiting on I/O while the engine still has output queued, leaves the -//! engine in an inconsistent state and produces wrong behavior. Mutations -//! issued from inside the drain loop (e.g. calling `Writer::write` in -//! response to an `Output::Event`) are fine - the drain loop naturally -//! continues calling `poll_output` afterward and so the invariant holds. -//! -//! ### Canonical shape -//! -//! Driving an `Rtc` forward follows the same six-step shape, regardless -//! of sync or async: -//! -//! 1. **Wait** for one of: the next timeout firing, an incoming network -//! packet, or the application wanting to perform a mutation (e.g. -//! write media). -//! 2. **Perform that ONE mutation** - feed `Input` to `handle_input`, or -//! call into a writer / SDP API. -//! 3. **Poll** `Rtc::poll_output`. -//! 4. **Handle** the output: `Output::Transmit` is sent on the socket, -//! `Output::Event` is dispatched to the application, `Output::Timeout` -//! records the next deadline. -//! 5. **Goto 3** until `poll_output` returns `Output::Timeout`. Only then -//! is the engine fully drained. -//! 6. The returned timeout is what we wait on next - **goto 1**. -//! -//! ```ignore -//! # use crate::vendor::str0m::{Rtc, Output, IceConnectionState, Event, Input}; -//! # use crate::vendor::str0m::net::{Receive, Protocol}; -//! # use std::io::ErrorKind; -//! # use std::net::UdpSocket; -//! # use std::time::{Duration, Instant}; -//! # let mut rtc = Rtc::new(Instant::now()); -//! // A UdpSocket we obtained _somehow_. -//! let socket: UdpSocket = todo!(); -//! -//! // Buffer for reading incoming UDP packets. -//! let mut buf = vec![0; 2000]; -//! -//! loop { -//! // === Steps 3-5: drain poll_output until we get the next timeout. === -//! let timeout = loop { -//! match rtc.poll_output().unwrap() { -//! // Step 5: a Timeout exits the drain loop. -//! Output::Timeout(t) => break t, -//! -//! // Step 4: transmit on the socket and keep draining. -//! // The destination IP comes from the ICE agent and may -//! // change during the session. -//! Output::Transmit(t) => { -//! socket.send_to(&t.contents, t.destination).unwrap(); -//! } -//! -//! // Step 4: hand the event to the application and keep draining. -//! // Events are mainly incoming media data from the remote peer, -//! // but also statistics. -//! Output::Event(e) => { -//! if e == Event::IceConnectionStateChange(IceConnectionState::Disconnected) { -//! return; -//! } -//! // TODO: handle other events here, such as incoming media data. -//! } -//! } -//! }; -//! -//! // === Step 1: wait for ONE of: the timeout firing, an incoming -//! // packet, or application-side data. The example below uses a -//! // blocking UDP socket with a read timeout. With async you would -//! // `select!` over multiple futures; with application-side data you -//! // would also include a channel. -//! // -//! // set_read_timeout(Some(ZERO)) is not allowed, so clamp to >= 1ms. -//! let duration = (timeout - Instant::now()).max(Duration::from_millis(1)); -//! socket.set_read_timeout(Some(duration)).unwrap(); -//! buf.resize(2000, 0); -//! -//! // === Step 2: take ONE event and feed it as Input === -//! let input = match socket.recv_from(&mut buf) { -//! Ok((n, source)) => { -//! buf.truncate(n); -//! Input::Receive( -//! Instant::now(), -//! Receive { -//! proto: Protocol::Udp, -//! source, -//! destination: socket.local_addr().unwrap(), -//! contents: buf.as_slice().try_into().unwrap(), -//! }, -//! ) -//! } -//! -//! // The socket read timed out - feed Input::Timeout to advance -//! // the engine to the deadline. WouldBlock is the unix error, -//! // TimedOut is the windows error. -//! Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { -//! Input::Timeout(Instant::now()) -//! } -//! -//! Err(e) => { -//! eprintln!("Error: {:?}", e); -//! return; -//! } -//! }; -//! -//! rtc.handle_input(input).unwrap(); -//! -//! // === Step 6: back to the top of the outer loop (goto step 3). === -//! } -//! ``` -//! -//! ## Sending media data -//! -//! When creating the media, we can decide which codecs to support, and they -//! are negotiated with the remote side. Each codec corresponds to a -//! "payload type" (PT). To send media data we need to figure out which PT -//! to use when sending. -//! -//! ```ignore -//! # use crate::vendor::str0m::Rtc; -//! # use crate::vendor::str0m::media::Mid; -//! # let rtc: Rtc = todo!(); -//! // Obtain mid from Event::MediaAdded -//! let mid: Mid = todo!(); -//! -//! // Create a media writer for the mid. -//! let writer = rtc.writer(mid).unwrap(); -//! -//! // Get the payload type (pt) for the wanted codec. -//! let pt = writer.payload_params().nth(0).unwrap().pt(); -//! -//! // Write the data -//! let wallclock = todo!(); // Absolute time of the data -//! let media_time = todo!(); // Media time, in RTP time -//! let data: &[u8] = todo!(); // Actual data -//! writer.write(pt, wallclock, media_time, data).unwrap(); -//! ``` -//! -//! `Writer::write` is a mutation, so the -//! [single-mutation invariant](#the-single-mutation-invariant) applies: -//! after writing, drain `Rtc::poll_output` to `Output::Timeout` before -//! the next mutation on this `Rtc`. -//! -//! ## Media time, wallclock and local time -//! -//! str0m has three main concepts of time. "now", media time and wallclock. -//! -//! ### Now -//! -//! Some calls in str0m, such as `Rtc::handle_input` takes a `now` argument -//! that is a `std::time::Instant`. These calls "drive the time forward" in -//! the internal state. This is used for everything like deciding when -//! to produce various feedback reports (RTCP) to remote peers. -//! -//! Str0m has _no internal clock_ calls. I.e. str0m never calls -//! `Instant::now()` itself. All time is external input. That means it's -//! possible to construct test cases driving an `Rtc` instance faster -//! than realtime (see the [integration tests][intg]). -//! -//! ### Media time -//! -//! Each RTP header has a 32 bit number that str0m calls _media time_. -//! Media time is in some time base that is dependent on the codec, -//! however all codecs in str0m use 90_000Hz for video and 48_000Hz -//! for audio. -//! -//! For video the `MediaTime` type is `/90_000` str0m extends -//! the 32 bit number in the RTP header to 64 bit taking into account -//! "rollover". 64 bit is such a large number the user doesn't need to -//! think about rollovers. -//! -//! ### Wallclock -//! -//! With _wallclock_ str0m means the time a sample of media was produced -//! at an originating source. I.e. if we are talking into a microphone the -//! wallclock is the NTP time the sound is sampled. -//! -//! We can't know the exact wallclock for media from a remote peer since -//! not every device is synchronized with NTP. Every sender does -//! periodically produce a Sender Report (SR) that contains the peer's -//! idea of its wallclock, however this number can be very wrong compared to -//! "real" NTP time. -//! -//! Furthermore, not all remote devices will have a linear idea of -//! time passing that exactly matches the local time. A minute on the -//! remote peer might not be exactly one minute locally. -//! -//! These timestamps become important when handling simultaneous audio from -//! multiple peers. -//! -//! When writing media we need to provide str0m with an estimated wallclock. -//! The simplest strategy is to only trust local time and use arrival time -//! of the incoming UDP packet. Another simple strategy is to lock some -//! time T at the first UDP packet, and then offset each wallclock using -//! `MediaTime`, i.e. for video we could have `T + /90_000` -//! -//! A production worthy SFU probably needs an even more sophisticated -//! strategy weighing in all possible time sources to get a good estimate -//! of the remote wallclock for a packet. -//! -//! # Crypto backends -//! -//! The vendored copy keeps only the rind backend (`str0m_rind`, DTLS from -//! dimpl), which is the default. The `CryptoProvider` trait stays so another -//! backend can be installed process-wide or per instance: -//! -//! ```ignore -//! use std::sync::Arc; -//! use std::time::Instant; -//! use crate::vendor::str0m::Rtc; -//! -//! let rtc = Rtc::builder() -//! .set_crypto_provider(Arc::new(my_provider())) -//! .build(Instant::now()); -//! ``` -//! -//! # Project status -//! -//! Str0m was originally developed by Martin Algesten of -//! [Lookback][lookback]. We use str0m for a specific use case: str0m as a -//! server SFU (as opposed to peer-2-peer). That means we are heavily -//! testing and developing the parts needed for our use case. Str0m is -//! intended to be an all-purpose WebRTC library, which means it also -//! works for peer-2-peer, though that aspect has received less testing. -//! -//! Performance is very good, there have been some work the discover and -//! optimize bottlenecks. Such efforts are of course never ending with -//! diminishing returns. While there are no glaringly obvious performance -//! bottlenecks, more work is always welcome – both algorithmically and -//! allocation/cloning in hot paths etc. -//! -//! # Design -//! -//! Output from the `Rtc` instance can be grouped into three kinds. -//! -//! 1. Events (such as receiving media). -//! 2. Network output. Data to be sent, typically from a UDP socket. -//! 3. Timeouts. Indicates when the instance next expects a time input. -//! -//! Input to the `Rtc` instance is: -//! -//! 1. User operations (such as sending media). -//! 2. Network input. Typically read from a UDP socket. -//! 3. Timeouts. As obtained from the output above. -//! -//! The correct use can be seen in the above [Run loop](#run-loop) or in the -//! examples. -//! -//! Sans I/O is a pattern where we turn both network input/output as well -//! as time passing into external input to the API. This means str0m has -//! no internal threads, just an enormous state machine that is driven -//! forward by different kinds of input. -//! -//! ## Frame or RTP level? -//! -//! Str0m defaults to the "frame level" which treats the RTP as an internal detail. The user -//! will thus mainly interact with: -//! -//! 1. [`Event::MediaData`][evmed] to receive full frames (audio frames or video frames). -//! 2. [`Writer::write`][writer] to write full frames. -//! 3. [`Writer::request_keyframe`][reqkey] to request keyframes. -//! -//! ### Frame level -//! -//! All codecs such as h264, vp8, vp9 and opus outputs what we call -//! "Frames". A frame has a very specific meaning for video, but this -//! project uses it in a broader sense, where a frame is either a video -//! or audio time stamped chunk of encoded data that typically represents -//! a chunk of audio, or _one single frame for video_. -//! -//! Frames are not suitable to use directly in UDP (RTP) packets - for -//! one they are too big. Frames are therefore further chunked up by -//! codec specific payloaders into RTP packets. -//! -//! ### RTP mode -//! -//! Str0m also provides an RTP level API. This would be similar to many other -//! RTP libraries where the RTP packets themselves are the API surface -//! towards the user (when building an SFU one would often talk about "forwarding -//! RTP packets", while with str0m we can also "forward frames"). Using -//! this API requires a deeper knowledge of RTP and WebRTC. -//! -//! To enable RTP mode -//! -//! ```ignore -//! # use std::time::Instant; -//! # use crate::vendor::str0m::Rtc; -//! let rtc = Rtc::builder() -//! // Enable RTP mode for this Rtc instance. -//! // This disables `MediaEvent` and the `Writer::write` API. -//! .set_rtp_mode(true) -//! .build(Instant::now()); -//! ``` -//! -//! RTP mode gives us some new API points. -//! -//! 1. [`Event::RtpPacket`][rtppak] emitted for every incoming RTP packet. Empty packets for bandwidth -//! estimation are silently discarded. -//! 2. [`StreamTx::write_rtp`][wrtrtp] to write outgoing RTP packets. -//! 3. [`StreamRx::request_keyframe`][reqkey2] to request keyframes from remote. -//! -//! ## NIC enumeration and TURN (and STUN) -//! -//! The [ICE RFC][ice] talks about "gathering ice candidates". This means -//! inspecting the local network interfaces and potentially binding UDP -//! sockets on each usable interface. Since str0m is Sans I/O, this part -//! is outside the scope of what str0m does. How the user figures out -//! local IP addresses, via config or via looking up local NICs is not -//! something str0m cares about. -//! -//! TURN is a way of obtaining IP addresses that can be used as fallback -//! in case direct connections fail. We consider TURN similar to -//! enumerating local network interfaces – it's a way of obtaining -//! sockets. -//! -//! All discovered candidates, be they local (NIC) or remote sockets -//! (TURN), are added to str0m and str0m will perform the task of ICE -//! agent, forming "candidate pairs" and figuring out the best connection -//! while the actual task of sending the network traffic is left to the -//! user. -//! -//! ## The importance of `&mut self` -//! -//! Rust shines when we can eschew locks and heavily rely `&mut` for data -//! write access. Since str0m has no internal threads, we never have to -//! deal with shared data. Furthermore the the internals of the library is -//! organized such that we don't need multiple references to the same -//! entities. In str0m there are no `Rc`, `Mutex`, `mpsc`, `Arc`(*), or -//! other locks. -//! -//! This means all input to the lib can be modelled as -//! `handle_something(&mut self, something)`. -//! -//! (*) Ok. There is one `Arc` if you use Windows where we also require openssl. -//! -//! ## Not a standard WebRTC "Peer Connection" API -//! -//! The library deliberately steps away from the "standard" WebRTC API as -//! seen in JavaScript and/or [webrtc-rs][webrtc-rs] (or [Pion][pion] in Go). -//! There are few reasons for this. -//! -//! First, in the standard API, events are callbacks, which are not a -//! great fit for Rust. Callbacks require some kind of reference -//! (ownership?) over the entity the callback is being dispatched -//! upon. I.e. if in Rust we want `pc.addEventListener(x)`, `x` needs -//! to be wholly owned by `pc`, or have some shared reference (like -//! `Arc`). Shared references means shared data, and to get mutable shared -//! data, we will need some kind of lock. i.e. `Arc>` -//! or similar. -//! -//! As an alternative we could turn all events into `mpsc` channels, but -//! listening to multiple channels is awkward without async. -//! -//! Second, in the standard API, entities like `RTCPeerConnection` and -//! `RTCRtpTransceiver`, are easily clonable and/or long lived -//! references. I.e. `pc.getTranscievers()` returns objects that can be -//! retained and owned by the caller. This pattern is fine for garbage -//! collected or reference counted languages, but not great with Rust. -//! -//! ## Panics, Errors and unwraps -//! -//! Str0m adheres to [fail-fast][ff]. That means rather than brushing state -//! bugs under the carpet, it panics. We make a distinction between errors and -//! bugs. -//! -//! * Errors are as a result of incorrect or impossible to understand user input. -//! * Bugs are broken internal invariants (assumptions). -//! -//! If you scan the str0m code you find a few `unwrap()` (or `expect()`). These -//! will (should) always be accompanied by a code comment that explains why the -//! unwrap is okay. This is an internal invariant, a state assumption that -//! str0m is responsible for maintaining. -//! -//! We do not believe it's correct to change every `unwrap()`/`expect()` into -//! `unwrap_or_else()`, `if let Some(x) = x { ... }` etc, because doing so -//! brushes an actual problem (an incorrect assumption) under the carpet. Trying -//! to hobble along with an incorrect state would at best result in broken -//! behavior, at worst a security risk! -//! -//! Panics are our friends: *panic means bug* -//! -//! And also: str0m should *never* panic on any user input. If you encounter a panic, -//! please report it! -//! -//! ### Catching panics -//! -//! Panics should be incredibly rare, or we have a serious problem as a project. For an SFU, -//! it might not be ideal if str0m encounters a bug and brings the entire server down with it. -//! -//! For those who want an extra level of safety, we recommend looking at [`catch_unwind`][catch] -//! to safely discard a faulty `Rtc` instance. Since `Rtc` has no internal threads, locks or async -//! tasks, discarding the instance never risk poisoning locks or other issues that can happen -//! when catching a panic. -//! -//! ## FAQ -//! -//! ### Features -//! -//! Below is a brief comparison of features between libWebRTC and str0m to help you determine -//! if str0m is suitable for your project. -//! -//! | Feature | str0m | libWebRTC | -//! | ------------------------ | ------------------ | ------------------ | -//! | Peer Connection API | :x: | :white_check_mark: | -//! | SDP | :white_check_mark: | :white_check_mark: | -//! | ICE | :white_check_mark: | :white_check_mark: | -//! | Data Channels | :x: | :white_check_mark: | -//! | Send/Recv Reports | :white_check_mark: | :white_check_mark: | -//! | Transport Wide CC | :white_check_mark: | :white_check_mark: | -//! | Bandwidth Estimation | :x: | :white_check_mark: | -//! | Simulcast | :white_check_mark: | :white_check_mark: | -//! | NACK | :white_check_mark: | :white_check_mark: | -//! | Packetize | :white_check_mark: | :white_check_mark: | -//! | Fixed Depacketize Buffer | :white_check_mark: | :white_check_mark: | -//! | Adaptive Jitter Buffer | :x: | :white_check_mark: | -//! | Video/audio capture | :x: | :white_check_mark: | -//! | Video/audio encode | :x: | :white_check_mark: | -//! | Video/audio decode | :x: | :white_check_mark: | -//! | Audio render | :x: | :white_check_mark: | -//! | Turn | :x: | :white_check_mark: | -//! | Network interface enum | :x: | :white_check_mark: | -//! -//! ### Platform Support -//! -//! Platforms str0m is compiled and tested on: -//! -//! | Platform | Compiled | Tested | -//! | ------------------------------ | ----------------- | ----------------- | -//! | `x86_64-pc-windows-msvc` | :white_check_mark:| :white_check_mark:| -//! | `x86_64-unknown-linux-gnu` | :white_check_mark:| :white_check_mark:| -//! | `x86_64-apple-darwin` | :white_check_mark:| :white_check_mark:| -//! | `aarch64-apple-darwin` | :white_check_mark:| :white_check_mark:| -//! | `aarch64-unknown-linux-gnu` | :white_check_mark:| :white_check_mark:| -//! | `aarch64-pc-windows-msvc` | :white_check_mark:| :white_check_mark:| -//! | `aarch64-apple-ios` | :white_check_mark:| :x: | -//! | `aarch64-linux-android` | :white_check_mark:| :x: | -//! -//! If your platform isn't listed but is supported by Rust, we'd love for you to give str0m a try and -//! share your experience. We greatly appreciate your feedback! -//! -//! ### Does str0m support IPv4, IPv6, UDP and TCP? -//! -//! Certainly! str0m fully support IPv4, IPv6, UDP and TCP protocols. -//! -//! ### Can I utilize str0m with any Rust async runtime? -//! -//! Absolutely! str0m is fully sync, ensuring that it integrates seamlessly with any Rust async -//! runtime you opt for. -//! -//! ### Can I create a client with str0m? -//! -//! Of course! You have the freedom to create a client with str0m. However, please note that some -//! common client features like media encoding, decoding, and capture are not included in str0m. But -//! don't let that stop you from building amazing applications! -//! -//! ### Can I use str0m in a media server? -//! -//! Yes! str0m excels as a server component with support for both RTP API and Frame API. You can -//! easily build that recording server or SFU you dreamt of in Rust! -//! -//! ### Can I deploy the chat example into production? -//! -//! While the chat example showcases how to use str0m's API, it's not intended for production use or -//! heavy load. Writing a full-featured SFU or MCU (Multipoint Control Unit) is a significant -//! undertaking, involving various design decisions based on production requirements. -//! -//! ### Discovered a bug? Here's how to share it with us -//! -//! We'd love to hear about it! Please submit an issue and consider joining our Discord community -//! to discuss further. For a seamless reporting experience, refer to this exemplary -//! bug report: . We appreciate your contribution -//! to making str0m better! -//! -//! ### I am allergic to SDP can you help me? -//! -//! Yes use the direct API! -//! -//! [sansio]: https://sans-io.readthedocs.io -//! [quinn]: https://github.com/quinn-rs/quinn -//! [pion]: https://github.com/pion/webrtc -//! [webrtc-rs]: https://github.com/webrtc-rs/webrtc -//! [discord]: https://discord.gg/e2CC8UYebP -//! [zulip]: https://str0m.zulipchat.com -//! [ice]: https://www.rfc-editor.org/rfc/rfc8445 -//! [lookback]: https://www.lookback.com -//! [x-post]: https://github.com/algesten/str0m/blob/main/examples/http-post.rs -//! [x-chat]: https://github.com/algesten/str0m/blob/main/examples/chat.rs -//! [intg]: https://github.com/algesten/str0m/blob/main/tests/unidirectional.rs#L12 -//! [ff]: https://en.wikipedia.org/wiki/Fail-fast -//! [catch]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html -//! [evmed]: https://docs.rs/str0m/*/str0m/enum.Event.html#variant.MediaData -//! [writer]: https://docs.rs/str0m/*/str0m/media/struct.Writer.html#method.write -//! [reqkey]: https://docs.rs/str0m/*/str0m/media/struct.Writer.html#method.request_keyframe -//! [rtppak]: https://docs.rs/str0m/*/str0m/enum.Event.html#variant.RtpPacket -//! [wrtrtp]: https://docs.rs/str0m/*/str0m/rtp/struct.StreamTx.html#method.write_rtp -//! [reqkey2]: https://docs.rs/str0m/*/str0m/rtp/struct.StreamRx.html#method.request_keyframe -//! [bitwhip]: https://github.com/bitwhip/bitwhip - -// Avoid rewriting existing code: nested conditions are often more readable than long if-chains. -#![allow(clippy::collapsible_if)] -#![forbid(unsafe_code)] -#![allow(clippy::new_without_default)] -#![allow(clippy::bool_to_int_with_if)] -#![allow(clippy::assertions_on_constants)] -#![allow(clippy::manual_range_contains)] -#![allow(clippy::get_first)] -#![allow(clippy::needless_lifetimes)] -#![allow(clippy::precedence)] -#![allow(clippy::doc_overindented_list_items)] -#![allow(clippy::uninlined_format_args)] -#![allow(mismatched_lifetime_syntaxes)] -#![deny(clippy::needless_pass_by_ref_mut)] -#![deny(missing_docs)] - -use crate::vendor::str0m_proto::Pii; -use bwe::BweKind; -use change::{DirectApi, SdpApi}; -use rtp::RawPacket; -use std::fmt; -use std::net::SocketAddr; -use std::sync::Arc; -use std::time::Instant; -use streams::RtpPacket; -use streams::StreamPaused; -use tracing::{debug, trace, warn}; -use util::InstantExt; - -/// Cryptographic provider traits and implementations. -/// -/// This module provides the traits for pluggable cryptographic operations -/// used in DTLS, SRTP, and STUN. -pub mod crypto; -use crypto::Fingerprint; - -mod dtls; -use crate::vendor::str0m::crypto::dtls::DtlsOutput; -use crate::vendor::str0m::crypto::{CryptoProvider, DtlsError, from_feature_flags}; -use crate::vendor::str0m::dtls::is_would_block; -use dtls::Dtls; - -use crate::vendor::is::IceAgent; -use crate::vendor::is::IceAgentEvent; -pub use crate::vendor::is::{Candidate, CandidateBuilder, CandidateKind, IceConnectionState, IceCreds}; - -#[path = "config.rs"] -mod config_mod; -pub use config_mod::RtcConfig; - -/// Default target MTU used when none is configured. -pub use io::DATAGRAM_MTU_TARGET; -/// Upper bound that the target endpoint of [`RtcConfig::set_mtu`] must satisfy. -pub use io::DATAGRAM_MTU_TARGET_MAX; -/// Lower bound that the target endpoint of [`RtcConfig::set_mtu`] must satisfy. -pub use io::DATAGRAM_MTU_TARGET_MIN; -/// Default warning threshold for over-sized packets. -pub use io::DATAGRAM_MTU_WARN; - -/// Additional configuration. -pub mod config { - pub use super::crypto::dtls::{DtlsCert, KeyingMaterial}; - pub use super::crypto::{CryptoProvider, Fingerprint}; -} - -/// Low level ICE access. -// The ICE API is not necessary to interact with directly for "regular" -// use of str0m. This is exported for other libraries that want to -// reuse str0m's ICE implementation. This is now in the `is` crate. -pub mod ice { - pub use crate::vendor::is::IceCreds; - pub use crate::vendor::is::stun::{StunMessage, StunMessageBuilder, StunPacket, TransId}; - pub use crate::vendor::is::{IceAgent, IceAgentEvent}; - pub use crate::vendor::is::{LocalPreference, default_local_preference}; -} - -mod io; -use io::DatagramRecvInner; - -mod packet; - -#[path = "rtp/mod.rs"] -mod rtp_; -use rtp_::{Bitrate, DataSize}; - -/// Low level RTP access. -pub mod rtp { - /// Feedback for RTP. - pub mod rtcp { - pub use crate::vendor::str0m::rtp_::{Descriptions, ExtendedReport, Fir, Goodbye, Nack, Pli}; - pub use crate::vendor::str0m::rtp_::{Dlrr, NackEntry, ReceptionReport, ReportBlock}; - pub use crate::vendor::str0m::rtp_::{FirEntry, ReceiverReport, SenderInfo, SenderReport, Twcc}; - pub use crate::vendor::str0m::rtp_::{ReportList, Rrtr, Rtcp, Sdes, SdesType}; - } - use self::rtcp::Rtcp; - - pub use crate::vendor::str0m::rtp_::{AbsCaptureTime, ExtensionValues, UserExtensionValues}; - pub use crate::vendor::str0m::rtp_::{Extension, ExtensionMap, ExtensionSerializer}; - - pub use crate::vendor::str0m::packet::{ - Vp8Descriptor, Vp8DescriptorError, Vp8Patch, Vp8PatchBuilder, Vp8PatchError, - }; - pub use crate::vendor::str0m::rtp_::{RtpHeader, SeqNo, Ssrc, VideoOrientation}; - pub use crate::vendor::str0m::streams::{RtpPacket, RtpWrite, StreamPaused, StreamRx, StreamTx, StreamTxQueueInfo}; - - /// Debug output of the unencrypted RTP and RTCP packets. - /// - /// Enable using [`RtcConfig::enable_raw_packets()`][crate::vendor::str0m::RtcConfig::enable_raw_packets]. - /// This clones data, and is therefore expensive. - /// Should not be enabled outside of tests and troubleshooting. - #[derive(Debug)] - pub enum RawPacket { - /// Sent RTCP. - RtcpTx(Rtcp), - /// Incoming RTCP. - RtcpRx(Rtcp), - /// Sent RTP. - RtpTx(RtpHeader, Vec), - /// Incoming RTP. - RtpRx(RtpHeader, Vec), - } -} - -pub(crate) mod pacer; - -/// Bitrates the remote peer asks for. -pub mod bwe { - pub use crate::vendor::str0m::rtp_::Bitrate; - use crate::vendor::str0m::rtp_::Mid; - - /// Bandwidth estimation kind. - #[derive(Debug, PartialEq)] - #[non_exhaustive] - pub enum BweKind { - /// REMB (Receiver Estimated Maximum Bitrate) - Remb { - /// Bitrate reported by the remote receiver. - estimate: Bitrate, - /// Media section associated with the report. - mid: Mid, - }, - } -} - -mod sdp; - -pub mod format; -use format::CodecConfig; - -pub mod media; -use media::SenderFeedback; -use media::{Direction, Media, Mid, Pt, Rid, Writer}; -use media::{KeyframeRequest, KeyframeRequestKind}; -use media::{MediaAdded, MediaChanged, MediaData}; - -pub mod change; - -mod util; -use util::{Soonest, not_happening}; - -mod poll; -use crate::vendor::str0m::poll::Readiness; - -mod session; -use session::Session; - -mod streams; - -pub mod error; - -/// Network related types to get socket data in/out of [`Rtc`]. -pub mod net { - pub use crate::vendor::str0m::io::{DatagramRecv, DatagramSend, Protocol, Receive, TcpType, Transmit}; -} - -const VERSION: &str = "0.24.1"; - -pub use error::RtcError; - -/// Instance that does WebRTC. Main struct of the entire library. -/// -/// ## Usage -/// -/// The canonical run loop is: perform exactly one mutation (typically -/// `handle_input` with a network packet or timeout), then drain -/// `poll_output` until it returns `Output::Timeout`, then wait for the -/// next event. **Every mutation must be followed by a full drain before -/// the next mutation.** See the [crate docs](crate#run-loop) for the full -/// explanation of the single-mutation invariant. -/// -/// ```ignore -/// # use std::time::Instant; -/// # use crate::vendor::str0m::{Rtc, Output, Input}; -/// let mut rtc = Rtc::new(Instant::now()); -/// -/// loop { -/// // Drain poll_output until it returns the next timeout. -/// let timeout = loop { -/// match rtc.poll_output().unwrap() { -/// Output::Timeout(t) => break t, -/// Output::Transmit(t) => { -/// // TODO: Send t.contents to t.destination on a UDP socket. -/// } -/// Output::Event(e) => { -/// // TODO: Handle event. -/// } -/// } -/// }; -/// -/// // TODO: Wait for ONE of: `timeout` firing, an incoming network -/// // packet, or application-side data to send. Build an -/// // `Input` from whichever fires first. -/// let input: Input = todo!(); -/// -/// rtc.handle_input(input).unwrap(); -/// } -/// ``` -pub struct Rtc { - state: RtcState, - ice: IceAgent, - dtls: Dtls, - dtls_connected: bool, - dtls_buf: Vec, - next_dtls_timeout: Option, - session: Session, - remote_fingerprint: Option, - remote_addrs: Vec, - send_addr: Option, - need_init_time: bool, - last_now: Instant, - change_counter: usize, - last_timeout_reason: Reason, - crypto_provider: Arc, - fingerprint_verification: bool, - close_dtls_started: bool, - // Signals which halves of the tree may need re-polling. Written locally by - // the components that mutate, via the `Wake` guard handed down the tree; - // read (and cleared) by `poll_output`. See the `poll` module. - readiness: Readiness, - // Last timeout returned by `poll_output`, reused while the readiness says - // the timeout is still valid. - cached_timeout: Instant, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum RtcState { - Alive, - Closing, - Closed, -} - -struct SendAddr { - proto: net::Protocol, - source: SocketAddr, - destination: SocketAddr, -} - -/// Events produced by [`Rtc::poll_output()`]. -#[derive(Debug)] -#[non_exhaustive] -#[rustfmt::skip] -pub enum Event { - // =================== ICE related events =================== - - /// Emitted when we got ICE connection and established DTLS. - Connected, - - /// ICE connection state changes tells us whether the [`Rtc`] instance is - /// connected to the peer or not. - IceConnectionStateChange(IceConnectionState), - - // =================== Media related events ================== - - /// Upon detecting the remote side adding new media to the session. - /// - /// For locally added media, this event never fires. Thus it can be thought of as an - /// "SDP only" event. If the direct API is used on both sides, the declaration is local \ - /// to both sides and the event never fires. - /// - /// The [`Media`] instance is available via [`Rtc::media()`]. - MediaAdded(MediaAdded), - - /// Incoming media data sent by the remote peer. - MediaData(MediaData), - - /// Changes to the media may be emitted. - /// - ///. Currently only covers a change of direction. - MediaChanged(MediaChanged), - - // =================== BWE related events =================== - - /// A bitrate the remote peer asked for. - EgressBitrateEstimate(BweKind), - - // =================== RTP related events =================== - - /// Incoming keyframe request for media that we are sending to the remote peer. - /// - /// The request is either PLI (Picture Loss Indication) or FIR (Full Intra Request). - KeyframeRequest(KeyframeRequest), - - /// Whether an incoming encoded stream is paused. - /// - /// This means the stream has not received any data for some time (default 1.5 seconds). - StreamPaused(StreamPaused), - - /// Sender feedback for an incoming stream, derived from RTCP SR. - SenderFeedback(SenderFeedback), - - /// Incoming RTP data. - RtpPacket(RtpPacket), - - /// The remote DTLS connection has closed. - /// - /// When this event is emitted, `Rtc` starts local shutdown signals and - /// remains alive only while [`Rtc::poll_output()`] drains pending local - /// close output such as RTCP BYE and the DTLS close_notify response. - Closed, - - /// Debug output of incoming and outgoing RTCP/RTP packets. - /// - /// Enable using [`RtcConfig::enable_raw_packets()`]. - /// This clones data, and is therefore expensive. - /// Should not be enabled outside of tests and troubleshooting. - RawPacket(Box), -} - -impl Event { - /// Reference to the [`RawPacket`] if this is indeed an `Event::RawPacket`. - pub fn as_raw_packet(&self) -> Option<&RawPacket> { - if let Self::RawPacket(boxed) = &self { - Some(&**boxed) - } else { - None - } - } -} - -/// Input as expected by [`Rtc::handle_input()`]. Either network data or a timeout. -#[derive(Debug)] -#[allow(clippy::large_enum_variant)] // We purposely don't want to allocate. -pub enum Input<'a> { - /// A timeout without any network input. - Timeout(Instant), - /// Network input. The [`Instant`] is the time the packet was received from the socket - - /// not necessarily "now" (e.g. when UDP demultiplexing runs on a separate thread). It - /// drives time forward when more recent than the last "now" the instance has seen. - Receive(Instant, net::Receive<'a>), -} - -/// Output produced by [`Rtc::poll_output()`] -#[allow(clippy::large_enum_variant)] -#[derive(Debug)] -pub enum Output { - /// When the [`Rtc`] instance expects an [`Input::Timeout`]. - Timeout(Instant), - - /// Network data that is to be sent. - Transmit(net::Transmit), - - /// Some event such as media data arriving from the remote peer or connection events. - Event(Event), -} - -pub use crate::vendor::str0m::pacer::PacerReason; - -/// The reason for the next [`Output::Timeout`]. -/// -/// This enum is not considered stable API and may change in minor revisions. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] -#[non_exhaustive] -pub enum Reason { - /// No timeout scheduled. - /// - /// The timeout value is in the distant future. - #[default] - NotHappening, - - /// The DTLS subsystem. - /// - /// Only relevant during handshaking. - DTLS, - - /// The ICE agent. - /// - /// Includes checking candidate pairs and various cleanups. - Ice, - - /// Regular RTP feedback. - /// - /// Receiver reports (RR) and sender reports (SR). - Feedback, - - /// Sending of RTP NACK. - /// - /// When missing packets are discovered, a NACK is scheduled. - /// Retries for each packet wait for the receive-stream RTT plus 5 ms, - /// using a 100 ms RTT until a measurement is available. - Nack, - - /// Reporting of TWCC (if enabled). - /// - /// All incoming RTP packets are reported using TWCC. Enabled via SDP if both - /// sides support it. - Twcc, - - /// RTP streams not receiving data goes into a paused state. - /// - /// Whenever an RTP receive stream receives data, a new timeout is scheduled. - PauseCheck, - - /// Preprocessing of RTP packets to be sent. - /// - /// Housekeeping task in RTP send streams. - SendStream, - - /// Packetizing of media into RTP data (if used). - /// - /// Written media data needs packetizing. This is not used in RTP mode. - Packetize, - - /// A complete video frame is waiting for missing earlier packets or its timeout. - ReceiveReorder, - - /// Pacer doing things. - Pacer(PacerReason), -} - -impl Rtc { - /// Creates a new instance with default settings. - /// - /// To configure the instance, use [`RtcConfig`]. - /// - /// ```ignore - /// use std::time::Instant; - /// use crate::vendor::str0m::Rtc; - /// - /// let rtc = Rtc::new(Instant::now()); - /// ``` - pub fn new(start: Instant) -> Self { - let config = RtcConfig::default(); - Self::new_from_config(config, start).expect("Failed to create Rtc from default config") - } - - /// Creates a config builder that configures an [`Rtc`] instance. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// let rtc = Rtc::builder() - /// .set_ice_lite(true) - /// .build(Instant::now()); - /// ``` - pub fn builder() -> RtcConfig { - RtcConfig::new() - } - - pub(crate) fn new_from_config(config: RtcConfig, start: Instant) -> Result { - let crypto_provider = config - .crypto_provider - .clone() - // If crypto_provider is not set in config, check process default - .or_else(|| CryptoProvider::get_default().cloned().map(Arc::new)) - // Or fall back on the vendored rind backend - .unwrap_or_else(|| Arc::new(from_feature_flags())); - - let session = Session::new(&config); - - // Capture before any partial moves of `config` below. - let mtu = config.mtu.clone(); - - let local_creds = config.local_ice_credentials.unwrap_or_else(IceCreds::new); - let mut ice = IceAgent::with_hmac(local_creds, crypto_provider.sha1_hmac_provider); - if config.ice_lite { - ice.set_ice_lite(config.ice_lite); - } - - if let Some(initial_stun_rto) = config.initial_stun_rto { - ice.set_initial_stun_rto(initial_stun_rto); - } - - if let Some(max_stun_rto) = config.max_stun_rto { - ice.set_max_stun_rto(max_stun_rto); - } - - if let Some(max_stun_retransmits) = config.max_stun_retransmits { - ice.set_max_stun_retransmits(max_stun_retransmits); - } - - ice.set_mtu(mtu.clone()); - - let dtls_cert = config - .dtls_cert - .or_else(|| crypto_provider.dtls_provider.generate_certificate()) - .expect( - "No DTLS certificate provided and the crypto provider cannot generate one. \ - Either provide a certificate via RtcConfig::set_dtls_cert or use a \ - crypto provider that supports certificate generation.", - ); - - Ok(Rtc { - state: RtcState::Alive, - ice, - dtls: Dtls::new( - &dtls_cert, - crypto_provider.dtls_provider, - crypto_provider.sha256_provider, - start, - mtu, - ) - .expect("DTLS to init without problem"), - dtls_connected: false, - dtls_buf: vec![0; 2000], - next_dtls_timeout: None, - session, - remote_fingerprint: None, - remote_addrs: vec![], - send_addr: None, - need_init_time: true, - last_now: start, - change_counter: 0, - last_timeout_reason: Reason::NotHappening, - crypto_provider, - fingerprint_verification: config.fingerprint_verification, - close_dtls_started: false, - readiness: Readiness::armed(), - cached_timeout: start, - }) - } - - /// Tests if this instance is still working. - /// - /// Certain events will straight away disconnect the `Rtc` instance, such as - /// the DTLS fingerprint from the setup not matching that of the TLS negotiation - /// (since that would potentially indicate a MITM attack!). - /// - /// The instance can be manually disconnected using [`Rtc::disconnect()`]. - /// - /// During shutdown, this remains `true` until [`Rtc::poll_output()`] - /// has drained pending local close output. App-facing operations such as - /// [`Rtc::writer()`] is unavailable during that closing drain. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// assert!(rtc.is_alive()); - /// - /// rtc.disconnect(); - /// assert!(!rtc.is_alive()); - /// ``` - pub fn is_alive(&self) -> bool { - self.state != RtcState::Closed - } - - /// Force disconnects the instance making [`Rtc::is_alive()`] return `false`. - /// - /// This makes [`Rtc::poll_output`] and [`Rtc::handle_input`] go inert and not - /// produce anymore network output or events. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// rtc.disconnect(); - /// assert!(!rtc.is_alive()); - /// ``` - pub fn disconnect(&mut self) { - self.state = RtcState::Closed; - } - - /// Add a local ICE candidate. Local candidates are socket addresses the `Rtc` instance - /// use for communicating with the peer. - /// - /// If the candidate is accepted by the `Rtc` instance, it will return `Some` with a reference - /// to it. You should then signal this candidate to the remote peer. - /// - /// This library has no built-in discovery of local network addresses on the host - /// or NATed addresses via a STUN server or TURN server. The user of the library - /// is expected to add new local candidates as they are discovered. - /// - /// In WebRTC lingo, the `Rtc` instance is permanently in a mode of [Trickle Ice][1]. It's - /// however advisable to add at least one local candidate before starting the instance. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{Rtc, Candidate}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let a = "127.0.0.1:5000".parse().unwrap(); - /// let c = Candidate::host(a, "udp").unwrap(); - /// - /// rtc.add_local_candidate(c); - /// ``` - /// - /// [1]: https://www.rfc-editor.org/rfc/rfc8838.txt - pub fn add_local_candidate(&mut self, c: Candidate) -> Option<&Candidate> { - // ICE is an external crate and can't take a `Wake`; adding a candidate - // can start connectivity checks (transmits) and arm timers. - self.wake_all(); - self.ice.add_local_candidate(c) - } - - /// Add a remote ICE candidate. Remote candidates are addresses of the peer. - /// - /// For [`SdpApi`]: Remote candidates are typically added via - /// receiving a remote [`SdpOffer`][change::SdpOffer] or [`SdpAnswer`][change::SdpAnswer]. - /// - /// However for the case of [Trickle Ice][1], this is the way to add remote candidates - /// that are "trickled" from the other side. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{Rtc, Candidate}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let a = "1.2.3.4:5000".parse().unwrap(); - /// let c = Candidate::host(a, "udp").unwrap(); - /// - /// rtc.add_remote_candidate(c); - /// ``` - /// - /// [1]: https://www.rfc-editor.org/rfc/rfc8838.txt - pub fn add_remote_candidate(&mut self, c: Candidate) { - // ICE is an external crate and can't take a `Wake`; see above. - self.wake_all(); - self.ice.add_remote_candidate(c); - } - - /// Checks if we are connected. - /// - /// This tests if we have ICE connection, DTLS and the SRTP crypto derived contexts are up. - pub fn is_connected(&self) -> bool { - self.ice.state().is_connected() && self.dtls_connected && self.session.is_connected() - } - - /// Make changes to the Rtc session via SDP. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::media::{MediaKind, Direction}; - /// # use crate::vendor::str0m::change::SdpAnswer; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let mut changes = rtc.sdp_api(); - /// let mid_audio = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - /// let mid_video = changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - /// - /// let (offer, pending) = changes.apply().unwrap(); - /// let json = serde_json::to_vec(&offer).unwrap(); - /// - /// // Send json OFFER to remote peer. Receive an answer back. - /// let answer: SdpAnswer = todo!(); - /// - /// rtc.sdp_api().accept_answer(pending, answer).unwrap(); - /// ``` - pub fn sdp_api(&mut self) -> SdpApi { - SdpApi::new(self) - } - - /// Makes direct changes to the Rtc session. - /// - /// This is a low level API. For "normal" use via SDP, see [`Rtc::sdp_api()`]. - pub fn direct_api(&mut self) -> DirectApi { - DirectApi::new(self) - } - - /// Send outgoing media data (frames) or request keyframes. - /// - /// Returns `None` if the direction isn't sending (`sendrecv` or `sendonly`). - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::media::{MediaData, Mid}; - /// # use crate::vendor::str0m::format::PayloadParams; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// // add candidates, do SDP negotiation - /// let mid: Mid = todo!(); // obtain mid from Event::MediaAdded. - /// - /// // Writer for this mid. - /// let writer = rtc.writer(mid).unwrap(); - /// - /// // Get incoming media data from another peer - /// let data: MediaData = todo!(); - /// - /// // Match incoming PT to an outgoing PT. - /// let pt = writer.match_params(data.params).unwrap(); - /// - /// writer.write(pt, data.network_time, data.time, data.data).unwrap(); - /// ``` - /// - /// This is a frame level API: For RTP level see [`DirectApi::stream_tx()`] - /// and [`DirectApi::stream_rx()`]. - /// - pub fn writer(&mut self, mid: Mid) -> Option { - if self.session.rtp_mode { - panic!("In rtp_mode use direct_api().stream_tx().write_rtp()"); - } - - if self.state != RtcState::Alive { - return None; - } - - // Disjoint borrows let the writer arm readiness within each mutation. - let Rtc { session, readiness, .. } = self; - - // This does not catch potential RIDs required to send simulcast, but - // it's a good start. An error might arise later on RID mismatch. - session.media_by_mid(mid)?; - - Some(Writer::new(session, readiness, mid)) - } - - /// Currently configured media. - /// - /// Read only access. Changes are made via [`Rtc::sdp_api()`] or [`Rtc::direct_api()`]. - pub fn media(&self, mid: Mid) -> Option<&Media> { - self.session.media_by_mid(mid) - } - - fn init_dtls(&mut self, active: bool) -> Result<(), RtcError> { - if self.dtls.is_inited() { - return Ok(()); - } - - debug!("DTLS setup is: {:?}", active); - self.dtls.set_active(active); - - // Initialize the DTLS state (client or server) before any operations - // This ensures internal state like random (client) or last_now (server) is initialized - self.dtls.handle_timeout(self.last_now)?; - - if active { - // Drive handshake by sending an empty packet to trigger ClientHello - let _ = self.dtls.handle_receive(&[]); - } - - Ok(()) - } - - /// Creates a new Mid that is not in the session already. - pub(crate) fn new_mid(&self) -> Mid { - loop { - let mid = Mid::new(); - if !self.session.has_mid(mid) { - break mid; - } - } - } - - /// Poll the `Rtc` instance for output. Output can be three things, something to _Transmit_ - /// via a UDP socket (maybe via a TURN server). An _Event_, such as receiving media data, - /// or a _Timeout_. - /// - /// The user of the library is expected to continuously call this function and deal with - /// the output until it encounters an [`Output::Timeout`] at which point no further output - /// is produced (if polled again, it will result in just another timeout). - /// - /// After exhausting the `poll_output`, the function will only produce more output again - /// when one of two things happen: - /// - /// 1. The polled timeout is reached. - /// 2. New network input. - /// - /// See [`Rtc`] instance documentation for how this is expected to be used in a loop. - pub fn poll_output(&mut self) -> Result { - let o = self.do_poll_output()?; - - match &o { - Output::Event(e) => match e { - Event::MediaData(_) - | Event::RtpPacket(_) - | Event::SenderFeedback(_) - | Event::EgressBitrateEstimate(_) - | Event::KeyframeRequest(_) => { - trace!("{:?}", e) - } - _ => debug!("{:?}", e), - }, - Output::Transmit(t) => trace!("OUT {:?}", t), - Output::Timeout(_t) => {} - } - - Ok(o) - } - - /// Conservatively re-poll the whole tree. - fn wake_all(&mut self) { - drop(self.readiness.wake()); - } - - fn do_poll_output(&mut self) -> Result { - if self.state == RtcState::Closed { - self.last_timeout_reason = Reason::NotHappening; - return Ok(Output::Timeout(not_happening())); - } - - if !self.readiness.wants_events() { - return Ok(Output::Timeout(self.poll_timeout())); - } - - while let Some(e) = self.ice.poll_event() { - match e { - IceAgentEvent::IceRestart(_) => { - // - } - IceAgentEvent::IceConnectionStateChange(v) => { - return Ok(Output::Event(Event::IceConnectionStateChange(v))); - } - IceAgentEvent::DiscoveredRecv { proto, source } => { - debug!("ICE remote address: {:?}/{:?}", Pii(source), proto); - self.remote_addrs.push(source); - while self.remote_addrs.len() > 20 { - self.remote_addrs.remove(0); - } - } - IceAgentEvent::NominatedSend { - proto, - source, - destination, - } => { - debug!( - "ICE nominated send from: {:?} to: {:?} with protocol {:?}", - Pii(source), - Pii(destination), - proto, - ); - self.send_addr = Some(SendAddr { - proto, - source, - destination, - }); - } - } - } - - // Handle DTLS timeout before polling output so any retransmit packets - // queued by dimpl and the re-armed flight timer are picked up by the - // poll loop below in the same iteration. - if let Some(timeout) = self.next_dtls_timeout { - if timeout <= self.last_now { - self.next_dtls_timeout = None; - - if let Err(error) = self.dtls.handle_timeout(self.last_now) { - // A failed timer transition leaves DTLS unrecoverable. Close the - // RTC so continued polling cannot expose the same due timeout again. - self.disconnect(); - return Err(error.into()); - } - } - } - - // Poll DTLS output - collect packets, handle events - let mut just_connected = false; - loop { - match self.dtls.poll_output(&mut self.dtls_buf) { - DtlsOutput::Packet(_) => { - unreachable!("We don't expect DTLS packets here since we use poll_packet"); - } - DtlsOutput::Connected => { - if !self.dtls_connected { - debug!("DTLS connected"); - self.dtls_connected = true; - just_connected = true; - } - } - DtlsOutput::KeyingMaterial(km, profile) => { - use config::KeyingMaterial; - let km_bytes = km.to_vec(); - debug!("DTLS set SRTP keying material and profile: {}", profile); - let active = self.dtls.is_active().expect("DTLS must be inited by now"); - self.session.set_keying_material( - KeyingMaterial::new(&km_bytes), - &self.crypto_provider, - profile, - active, - ); - } - DtlsOutput::PeerCert(der) => { - debug!("DTLS verify remote fingerprint"); - // Compute the fingerprint of the peer's DER certificate with the hash - // function of the expected one (RFC 8122 §5): sha-256, or sha-1 as some - // endpoints still announce. sha-256 when there is none to compare with. - let provider = &self.crypto_provider; - let matching = self.remote_fingerprint.as_ref().and_then(|expected| { - crate::vendor::str0m::crypto::Fingerprint::of_certificate(der, &expected.hash_func, provider) - }); - let fingerprint = matching.clone().unwrap_or_else(|| { - crate::vendor::str0m::crypto::Fingerprint::of_certificate(der, "sha-256", provider) - .expect("sha-256 is supported") - }); - self.dtls.set_remote_fingerprint(fingerprint.clone()); - if let Some(expected) = &self.remote_fingerprint { - if !self.fingerprint_verification { - debug!("DTLS fingerprint verification disabled"); - } else if matching.is_none() { - let message = format!("unsupported fingerprint hash function: {}", expected.hash_func); - self.disconnect(); - return Err(RtcError::RemoteSdp(message)); - } else if fingerprint != *expected { - self.disconnect(); - return Err(RtcError::RemoteSdp("remote fingerprint no match".into())); - } - } else { - self.disconnect(); - return Err(RtcError::RemoteSdp("no a=fingerprint before dtls".into())); - } - } - // SCTP, which this build does not run: application m-lines are rejected. - DtlsOutput::ApplicationData(data) => { - trace!("Dropping {} bytes of DTLS application data", data.len()); - } - DtlsOutput::Timeout(t) => { - self.next_dtls_timeout = Some(t); - break; - } - DtlsOutput::CloseNotify => { - self.start_close()?; - return Ok(Output::Event(Event::Closed)); - } - other => { - return Err(RtcError::Dtls(DtlsError::Io(std::io::Error::other(format!( - "Unexpected DTLS output: {other:?}" - ))))); - } - } - } - - if just_connected { - return Ok(Output::Event(Event::Connected)); - } - - if let Some(ev) = self.session.poll_event() { - return Ok(Output::Event(ev)); - } - - // Some polling needs to bubble up errors. - if let Some(ev) = self.session.poll_event_fallible(self.last_now)? { - return Ok(Output::Event(ev)); - } - - if let Some(v) = self.ice.poll_transmit() { - return Ok(Output::Transmit(v)); - } - - if let Some(send) = &self.send_addr { - // These can only be sent after we got an ICE connection. - let datagram = None - .or_else(|| self.dtls.poll_packet()) - .or_else(|| self.session.poll_datagram(self.last_now)); - - if let Some(contents) = datagram { - let t = net::Transmit { - proto: send.proto, - source: send.source, - destination: send.destination, - contents, - }; - return Ok(Output::Transmit(t)); - } - } else { - // Don't allow accumulated feedback to build up indefinitely - self.session.clear_feedback(); - } - - self.readiness.clear_events(); - - Ok(Output::Timeout(self.poll_timeout())) - } - - // Called only after the output pipeline has drained. - fn poll_timeout(&mut self) -> Instant { - if self.readiness.wants_timeout() { - // ICE has no clock until its first timeout and asks for none, yet a remote - // candidate gives it checks to run: drive it at once, since a passive peer - // may have no other timer that would. - let ice_timeout = self - .ice - .poll_timeout() - .or_else(|| self.ice.remote_candidates().next().map(|_| self.last_now)); - let time_and_reason = (None, Reason::NotHappening) - .soonest((self.next_dtls_timeout, Reason::DTLS)) - .soonest((ice_timeout, Reason::Ice)) - .soonest(self.session.poll_timeout()); - - let time = time_and_reason.0.unwrap_or_else(not_happening); - self.cached_timeout = time.max(self.last_now); - self.last_timeout_reason = time_and_reason.1; - self.readiness.clear_timeout(); - } - - if self.state == RtcState::Closing && self.close_drain_complete() { - self.state = RtcState::Closed; - self.last_timeout_reason = Reason::NotHappening; - return not_happening(); - } - - self.cached_timeout - } - - /// The reason for the last [`Output::Timeout`] - /// - /// This is updated when calling [`Rtc::poll_output()`] and the next output - /// is a timeout. - /// - /// ```ignore - /// # use crate::vendor::str0m::{Rtc, Reason}; - /// # use std::time::Instant; - /// let rtc = Rtc::new(Instant::now()); - /// - /// // Before any call to poll_output(), the reason is the default. - /// assert_eq!(rtc.last_timeout_reason(), Reason::NotHappening); - /// ``` - pub fn last_timeout_reason(&self) -> Reason { - self.last_timeout_reason - } - - /// Check if this `Rtc` instance accepts the given input. This is used for demultiplexing - /// several `Rtc` instances over the same UDP server socket. - /// - /// [`Input::Timeout`] is always accepted. [`Input::Receive`] is tested against the nominated - /// ICE candidate. If that doesn't match and the incoming data is a STUN packet, the accept call - /// is delegated to the ICE agent which recognizes the remote peer from `a=ufrag`/`a=password` - /// credentials negotiated in the SDP. If that also doesn't match, all remote ICE candidates are - /// checked for a match. - /// - /// In a server setup, the server would try to find an `Rtc` instances using [`Rtc::accepts()`]. - /// The first found instance would be given the input via [`Rtc::handle_input()`]. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{Rtc, Input}; - /// // A vec holding the managed rtc instances. One instance per remote peer. - /// let now = Instant::now(); - /// let mut rtcs = vec![Rtc::new(now), Rtc::new(now), Rtc::new(now)]; - /// - /// // Configure instances with local ice candidates etc. - /// - /// loop { - /// // TODO poll_timeout() and handle the output. - /// - /// let input: Input = todo!(); // read network data from socket. - /// for rtc in &mut rtcs { - /// if rtc.accepts(&input) { - /// rtc.handle_input(input).unwrap(); - /// } - /// } - /// } - /// ``` - pub fn accepts(&self, input: &Input) -> bool { - let Input::Receive(_, r) = input else { - // always accept the Input::Timeout. - return true; - }; - - // Fast path: DTLS, RTP, and RTCP traffic coming in from the same socket address - // we've nominated for sending via the ICE agent. This is the typical case - if let Some(send_addr) = &self.send_addr { - if r.source == send_addr.destination { - return true; - } - } - - // STUN can use the ufrag/password to identify that a message belongs - // to this Rtc instance. - if let DatagramRecvInner::Stun(v) = &r.contents.inner { - return self.ice.accepts_message(v); - } - - // Slow path: Occasionally, traffic comes in on a socket address corresponding - // to a successful candidate pair other than the one we've currently nominated. - // This typically happens at the beginning of the connection - if self.ice.has_viable_remote_candidate(r.source) { - return true; - } - - false - } - - /// Provide input to this `Rtc` instance. Input is either a [`Input::Timeout`] for some - /// time that was previously obtained from [`Rtc::poll_output()`], or [`Input::Receive`] - /// for network data. - /// - /// Both the timeout and the network data contains a [`std::time::Instant`] which drives - /// time forward in the instance. For network data, the intention is to record the time - /// of receiving the network data as precise as possible. This time is used to calculate - /// things like jitter and bandwidth. - /// - /// It's always okay to call [`Rtc::handle_input()`] with a timeout, also before the - /// time obtained via [`Rtc::poll_output()`]. - /// - /// ```ignore - /// # use crate::vendor::str0m::{Rtc, Input}; - /// # use std::time::Instant; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// loop { - /// let timeout: Instant = todo!(); // rtc.poll_output() until we get a timeout. - /// - /// let input: Input = todo!(); // wait for network data or timeout. - /// rtc.handle_input(input); - /// } - /// ``` - pub fn handle_input(&mut self, input: Input) -> Result<(), RtcError> { - if self.state == RtcState::Closed { - return Ok(()); - } - - // The handlers below each arm their own `Wake`; nothing to do here. - match input { - Input::Timeout(now) => self.do_handle_timeout(now)?, - Input::Receive(recv_time, r) => { - self.do_handle_receive(recv_time, r)?; - self.do_handle_timeout(recv_time)?; - } - } - Ok(()) - } - - /// Starts local shutdown. - /// - /// The `Rtc` instance schedules RTCP BYE and sends - /// DTLS close_notify without waiting for remote replies. It enters a closing - /// drain state where app-facing operations stop, but [`Rtc::poll_output()`] - /// continues polling until pending local close output has drained. Once the - /// drain is complete, [`Rtc::is_alive()`] returns `false`. - pub fn close(&mut self) -> Result<(), RtcError> { - self.start_close() - } - - fn start_close(&mut self) -> Result<(), RtcError> { - if self.state == RtcState::Closed { - return Ok(()); - } - - // Closing queues RTCP BYE and a DTLS close_notify that must be drained - // from the pipeline, so re-poll the whole tree. - self.wake_all(); - - if self.state != RtcState::Closing { - self.session.close_rtp(); - self.state = RtcState::Closing; - } - - self.start_dtls_close() - } - - fn start_dtls_close(&mut self) -> Result<(), RtcError> { - if !self.close_dtls_started { - self.dtls.close()?; - self.close_dtls_started = true; - } - - Ok(()) - } - - fn close_drain_complete(&self) -> bool { - self.close_dtls_started && self.dtls.is_closed() && self.session.is_rtp_closed() - } - - fn init_time(&mut self, now: Instant) { - // The operation is somewhat expensive, hence we only do it once. - if !self.need_init_time { - return; - } - - // We assume this first "now" is a time 0 start point for calculating ntp/unix time offsets. - // This initializes the conversion of Instant -> NTP/Unix time. - let _ = now.to_unix_duration(); - - self.need_init_time = false; - } - - fn do_handle_timeout(&mut self, now: Instant) -> Result<(), RtcError> { - self.init_time(now); - - // Prevent time from going backwards. - if now < self.last_now { - return Ok(()); - } - - self.last_now = now; - - // Disjoint borrows so each subsystem gets its own armed `Wake` and - // makes its own re-poll decision; the guards fold into `readiness` - // independently as each statement ends. - let Rtc { - ice, - session, - readiness, - .. - } = self; - - // ICE is an external crate and can't be handed a `Wake`. Driving it can - // transmit and re-arm timers, so arm both on its behalf at the boundary. - ice.handle_timeout(now); - drop(readiness.wake()); - - session.handle_timeout(now, &mut readiness.wake())?; - - Ok(()) - } - - fn do_handle_receive(&mut self, recv_time: Instant, r: net::Receive) -> Result<(), RtcError> { - trace!("IN {:?}", r); - use DatagramRecvInner::*; - - // Disjoint borrows so each subsystem gets its own armed `Wake`. - let Rtc { - ice, - dtls, - session, - readiness, - .. - } = self; - - match r.contents.inner { - Stun(stun) => { - let packet = crate::vendor::is::stun::StunPacket { - proto: r.proto, - source: r.source, - destination: r.destination, - message: stun, - }; - // ICE is an external crate; arm both on its behalf. - ice.handle_packet(recv_time, packet); - drop(readiness.wake()); - } - Dtls(dtls_packet) => { - // A failed receive can still change DTLS state and timers. - let _wake = readiness.wake(); - dtls.handle_receive(dtls_packet)?; - } - Rtp(rtp) => session.handle_rtp_receive(recv_time, rtp, &mut readiness.wake()), - Rtcp(rtcp) => session.handle_rtcp_receive(recv_time, rtcp, &mut readiness.wake()), - } - - Ok(()) - } - - fn is_correct_change_id(&self, change_id: usize) -> bool { - self.change_counter == change_id + 1 - } - - fn next_change_id(&mut self) -> usize { - let n = self.change_counter; - self.change_counter += 1; - n - } - - /// The codec configs for sending/receiving data. - /// - /// The configurations can be set with [`RtcConfig`] before setting up the session, and they - /// might be further updated by SDP negotiation. - pub fn codec_config(&self) -> &CodecConfig { - &self.session.codec_config - } -} - -impl PartialEq for Event { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Self::IceConnectionStateChange(l0), Self::IceConnectionStateChange(r0)) => l0 == r0, - (Self::MediaAdded(m0), Self::MediaAdded(m1)) => m0 == m1, - (Self::MediaData(m1), Self::MediaData(m2)) => m1 == m2, - _ => false, - } - } -} - -impl Eq for Event {} - -impl fmt::Debug for Rtc { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Rtc").finish() - } -} - -#[cfg(test)] -pub fn init_crypto_default() { - crate::vendor::str0m::crypto::from_feature_flags().install_process_default(); -} - -#[cfg(test)] -mod test { - use std::panic::UnwindSafe; - use std::time::Duration; - - use super::*; - - #[test] - fn rtc_is_send() { - fn is_send(_t: T) {} - fn is_sync(_t: T) {} - is_send(Rtc::new(Instant::now())); - is_sync(Rtc::new(Instant::now())); - } - - #[test] - fn rtc_is_unwind_safe() { - fn is_unwind_safe(_t: T) {} - is_unwind_safe(Rtc::new(Instant::now())); - } - - #[test] - fn event_is_reasonably_sized() { - let n = std::mem::size_of::(); - assert!(n < 530); - } - - /// A passive answerer has no DTLS timer before the peer speaks, so a - /// trickled candidate must still start its checks when driven only on the - /// timeouts it asks for. - #[test] - fn idle_answerer_checks_a_trickled_candidate() { - crate::vendor::str0m::init_crypto_default(); - let start = Instant::now(); - - let mut offerer = Rtc::new(start); - let mut change = offerer.sdp_api(); - change.add_media(media::MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, _pending) = change.apply().unwrap(); - - let mut answerer = Rtc::new(start); - let local = Candidate::host("127.0.0.1:2000".parse().unwrap(), "udp").unwrap(); - answerer.add_local_candidate(local); - answerer.sdp_api().accept_offer(offer).unwrap(); - let remote = Candidate::host("127.0.0.1:1000".parse().unwrap(), "udp").unwrap(); - answerer.add_remote_candidate(remote); - - let mut now = start; - loop { - match answerer.poll_output().unwrap() { - Output::Transmit(transmit) => { - assert_eq!(transmit.destination, "127.0.0.1:1000".parse().unwrap()); - return; - } - Output::Timeout(at) => { - assert!( - at < start + Duration::from_secs(1), - "the answerer waits until {:?} to check its candidate", - at - start - ); - now = now.max(at); - answerer.handle_input(Input::Timeout(now)).unwrap(); - } - Output::Event(_) => {} - } - } - } -} - -#[cfg(test)] -mod tests; diff --git a/rs/moq-webrtc/src/vendor/str0m/media/event.rs b/rs/moq-webrtc/src/vendor/str0m/media/event.rs deleted file mode 100644 index 729e806c49b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/media/event.rs +++ /dev/null @@ -1,355 +0,0 @@ -use std::fmt; -use std::ops::RangeInclusive; -use std::sync::Arc; -use std::time::Instant; - -use crate::vendor::str0m::packet::MediaKind; -use crate::vendor::str0m::rtp_::{Direction, ExtensionValues, MediaTime, Mid, Pt, Rid, SenderInfo, SeqNo, Ssrc}; -use crate::vendor::str0m::sdp::SimulcastLayer as SdpSimulcastLayer; -use crate::vendor::str0m::sdp::{RestrictionId, Simulcast as SdpSimulcast, SimulcastGroups as SdpSimulcastGroups}; - -use super::PayloadParams; -use crate::vendor::str0m::format::CodecExtra; - -impl From<&SdpSimulcastLayer> for SimulcastLayer { - fn from(layer: &SdpSimulcastLayer) -> Self { - SimulcastLayer { - rid: Rid::from(layer.restriction_id.0.as_ref()), - attributes: layer.attributes.clone(), - } - } -} - -impl From<&SimulcastLayer> for SdpSimulcastLayer { - fn from(layer: &SimulcastLayer) -> Self { - SdpSimulcastLayer { - restriction_id: RestrictionId::new_active(layer.rid.to_string()), - attributes: layer.attributes.clone(), - } - } -} - -impl From for Simulcast { - fn from(s: SdpSimulcast) -> Self { - let send = s.send.iter().map(Into::into).collect(); - let recv = s.recv.iter().map(Into::into).collect(); - - Simulcast { send, recv } - } -} - -/// A new media appeared in an Rtc session. -/// -/// This event fires both for negotiations triggered by a remote or local offer. -/// -/// Does not fire for application media (data channel). -#[derive(Debug, PartialEq, Eq)] -pub struct MediaAdded { - /// Identifier of the new media. - pub mid: Mid, - - /// The kind of media carried. - pub kind: MediaKind, - - /// Current direction. - pub direction: Direction, - - /// If simulcast is configured, this holds the Rids. - /// - /// `a=simulcast:send h;l` - pub simulcast: Option, -} - -/// A change happening during an SDP re-negotiation. -/// -/// This event fires both for re-negotiations triggered by a remote or local offer. -/// -/// Does not fire for application media (data channel). -#[derive(Debug, PartialEq, Eq)] -pub struct MediaChanged { - /// Identifier of the media. - pub mid: Mid, - - /// Current direction. - pub direction: Direction, -} - -/// Simplified information about the simulcast config from SDP. -/// -/// The [full spec][1] covers many cases that are not used by simple simulcast. -/// -/// [1]: https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-sdp-simulcast-14 -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct Simulcast { - /// The layers used for sending simulcast. - pub send: Vec, - /// The layers used for receiving simulcast. - pub recv: Vec, -} - -impl Simulcast { - /// Create a new struct with no layers - pub fn new() -> Simulcast { - Simulcast { - send: vec![], - recv: vec![], - } - } -} - -impl Simulcast { - /// Add a send layer - pub fn add_send_layer(&mut self, layer: SimulcastLayer) { - self.send.push(layer); - } - - /// Add a receive layer - pub fn add_recv_layer(&mut self, layer: SimulcastLayer) { - self.recv.push(layer); - } -} - -/// A simulcast layer which has a RID and optional attributes -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct SimulcastLayer { - /// The layer's rid - pub rid: Rid, - /// The layer's attributes per RFC 8851 - pub attributes: Option>, -} - -impl SimulcastLayer { - /// Creates a new layer with the rid - pub fn new(rid: &str) -> SimulcastLayer { - SimulcastLayer { - rid: Rid::from(rid), - attributes: None, - } - } - - /// Create a new layer builder for setting attributes - pub fn new_with_attributes(rid: &str) -> SimulcastLayerBuilder { - SimulcastLayerBuilder { - rid: Rid::from(rid), - attributes: vec![], - } - } -} - -/// A builder which is used to populate layer attributes -pub struct SimulcastLayerBuilder { - rid: Rid, - // We could use a HashMap but that doesn't preserve order - which we need for tests (to validate the - // resulting SDP). BTreeMap seems like overkill for 4-6 keys, so does HashMap, actually. A simple - // vector of pairs is perfect: preserves order and is efficient enough. - attributes: Vec<(String, String)>, -} - -impl SimulcastLayerBuilder { - /// Maximum video width - pub fn max_width(mut self, max_width: u32) -> Self { - self.update_or_insert("max-width", max_width.to_string()); - self - } - - /// Maximum video height - pub fn max_height(mut self, max_height: u32) -> Self { - self.update_or_insert("max-height", max_height.to_string()); - self - } - - /// Maximum bitrate, in bits per second (not kilobits) - pub fn max_br(mut self, max_br: u32) -> Self { - self.update_or_insert("max-br", max_br.to_string()); - self - } - - /// Maximum frame rate, in frames per second, or 0 if none - pub fn max_fps(mut self, max_fps: u32) -> Self { - self.update_or_insert("max-fps", max_fps.to_string()); - self - } - - /// A custom attribute - pub fn custom(mut self, key: &str, value: &str) -> Self { - self.update_or_insert(key, value.to_string()); - self - } - - /// Build the layer - pub fn build(self) -> SimulcastLayer { - SimulcastLayer { - rid: self.rid, - attributes: if self.attributes.is_empty() { - None - } else { - Some(self.attributes) - }, - } - } - - fn update_or_insert(&mut self, key: &str, value: String) { - for (k, v) in &mut self.attributes { - if k == key { - *v = value; - return; - } - } - - self.attributes.push((key.to_string(), value)); - } -} - -impl Simulcast { - pub(crate) fn into_sdp(self) -> SdpSimulcast { - SdpSimulcast { - send: SdpSimulcastGroups(self.send.iter().map(Into::into).collect()), - recv: SdpSimulcastGroups(self.recv.iter().map(Into::into).collect()), - is_munged: false, - } - } -} - -/// Video or audio data from the remote peer. -/// -/// This is obtained via [`Event::MediaData`][crate::vendor::str0m::Event::MediaData]. -#[derive(PartialEq, Eq)] -pub struct MediaData { - /// Identifier of the media in the session this media belongs to. - pub mid: Mid, - - /// Payload type (PT) tells which negotiated codec is being used. Each media - /// can carry different codecs, the payload type can theoretically change - /// from one packet to the next. - pub pt: Pt, - - /// Rtp Stream Id (RID) identifies an RTP stream without referring to its - /// Synchronization Source (SSRC). - /// - /// This is a newer standard that is sometimes used in WebRTC to identify - /// a stream. Specifically when using Simulcast in Chrome. - pub rid: Option, - - /// Parameters for the codec. This is used to match incoming PT to outgoing PT. - pub params: PayloadParams, - - /// The RTP media time of this packet. Media time is described as a numerator/denominator - /// quantity. The numerator is the timestamp field from the RTP header, the denominator - /// depends on whether this is an audio or video packet. - /// - /// For audio the timebase is often 48kHz for video it is 90kHz. - pub time: MediaTime, - - /// The time of the [`Input::Receive`][crate::vendor::str0m::Input::Receive] of the first packet - /// that caused this MediaData. - /// - /// In simple SFU setups this can be used as wallclock for [`Writer::write`][crate::vendor::str0m::media::Writer]. - pub network_time: Instant, - - /// The (RTP) sequence numbers that made up this data. - pub seq_range: RangeInclusive, - - /// Whether the data is contiguous from the one just previously emitted. If this is false, - /// we got an interruption in RTP packets, and the data may or may not be usable in a decoder - /// without requesting a new keyframe. - /// - /// For audio this flag most likely doesn't matter. - pub contiguous: bool, - - /// The actual packet data a.k.a Frame. - /// - /// Bigger frames don't fit in one UDP packet, thus WebRTC RTP is chopping up codec - /// transmission units into smaller parts. - /// - /// This data is a full depayloaded Frame. - pub data: Arc<[u8]>, - - /// RTP header extensions for this media data. This is taken from the - /// first RTP header. - pub ext_vals: ExtensionValues, - - /// Additional codec specific information - pub codec_extra: CodecExtra, - - /// Sender information from the most recent Sender Report(SR). - /// - /// If no Sender Report(SR) has been received this is [`None`]. - pub last_sender_info: Option, - - /// First packet of a talkspurt, that is the first packet after a silence period during - /// which packets have not been transmitted contiguously. - /// - /// For audio only when dtx or silence suppression is enabled. - pub audio_start_of_talk_spurt: bool, -} - -impl MediaData { - /// Return true if MediaData is keyframe independently of Codec - pub fn is_keyframe(&self) -> bool { - match self.codec_extra { - CodecExtra::None => false, - CodecExtra::H264(h264_extra) => h264_extra.is_keyframe, - CodecExtra::H265(h265_extra) => h265_extra.is_keyframe, - CodecExtra::Vp8(vp8_extra) => vp8_extra.is_keyframe, - CodecExtra::Vp9(vp9_extra) => vp9_extra.is_keyframe, - CodecExtra::Av1(av1_extra) => av1_extra.is_keyframe, - } - } -} - -/// Details for an incoming a keyframe request (PLI or FIR). -/// -/// This is obtained via the [`Event::KeyframeRequest`][crate::vendor::str0m::Event::KeyframeRequest]. -/// -/// Sending a keyframe request is done via [`Media::request_keyframe()`][crate::vendor::str0m::media::Media]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct KeyframeRequest { - /// The media identifier this keyframe request is for. - pub mid: Mid, - - /// Rid the keyframe request is for. Relevant when doing simulcast. - pub rid: Option, - - /// The kind of keyframe request (PLI or FIR). - pub kind: KeyframeRequestKind, -} - -/// Type of keyframe request. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum KeyframeRequestKind { - /// Picture Loss Indication (PLI) is a less severe keyframe request that can be - /// automatically generated by an SFU or by the end peer. - Pli, - - /// Full Intra Request (FIR) is a more severe keyframe request that should only - /// be used when it's impossible for an end peer to show a video stream. - Fir, -} - -/// Incoming feedback from a sender. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct SenderFeedback { - /// The media identifier this feedback is for. - pub mid: Mid, - - /// Rid the feedback is for. Relevant when doing simulcast. - pub rid: Option, - - /// When the RTCP packet containing the included [`SenderInfo`] was received. - pub received_at: Instant, - - /// Information about the sender of this report. - pub sender_info: SenderInfo, -} - -impl fmt::Debug for MediaData { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("MediaData") - .field("mid", &self.mid) - .field("pt", &self.pt) - .field("rid", &self.rid) - .field("time", &self.time) - .field("len", &self.data.len()) - .finish() - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/media/mod.rs b/rs/moq-webrtc/src/vendor/str0m/media/mod.rs deleted file mode 100644 index c5d2a8b606b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/media/mod.rs +++ /dev/null @@ -1,731 +0,0 @@ -//! Media (audio/video) related content. - -use std::collections::{HashMap, VecDeque}; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tracing::debug; - -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::change::AddMedia; -use crate::vendor::str0m::format::CodecConfig; - -use crate::vendor::str0m::packet::RtpMeta; -use crate::vendor::str0m::packet::{CodecDepacketizer, DepacketizingBuffer, Payloader}; -use crate::vendor::str0m::rtp_::ExtensionMap; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::SRTP_BLOCK_SIZE; -use crate::vendor::str0m::rtp_::SRTP_OVERHEAD; -use crate::vendor::str0m_proto::Id; - -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::format::Vp9PacketizerMode; -use crate::vendor::str0m::sdp::Simulcast as SdpSimulcast; -use crate::vendor::str0m::sdp::{MediaLine, Msid, is_no_stream}; -use crate::vendor::str0m::streams::{RtpPacket, Streams}; -use crate::vendor::str0m::util::already_happened; - -mod event; -pub use event::*; - -mod writer; -pub use writer::Writer; - -pub use crate::vendor::str0m::packet::MediaKind; -pub use crate::vendor::str0m::rtp_::{Direction, ExtensionValues, Frequency, MediaTime, Mid, Pt, Rid}; - -/// Mid used for SSRC 0 non-media BWE probes. -/// -/// Outgoing probes use a negotiated media Mid on the wire and do not require -/// an initialized video/RTX stream. -/// -/// These probes carry `transport_cc` for TWCC feedback but no real media. -pub(crate) const MID_PROBE: Mid = Mid::from_array(*b"~]probe\0\0\0\0\0\0\0\0\0"); -/// Bound on the writes queued between polls. -const MAX_PENDING_PAYLOADS: usize = 512; - -#[derive(Debug)] -/// Information about some configured media. -pub struct Media { - // ========================================= RTP level ========================================= - // - /// Identifier of this media. - /// - /// RTP level. - mid: Mid, - - /// Canonical name. - /// - /// RTP level. - cname: String, - - /// Rid that we are expecting to see on incoming RTP packets that map to this mid. - /// Once discovered, we make an entry in `stream_rx`. - /// - /// RTP level. - rids_rx: Rids, - - /// Rid that we can send using the [`Writer`]. - /// - /// RTP level. - rids_tx: Rids, - - // ========================================= SDP level ========================================= - // - /// The index of this media line in the Session::media Vec. - /// - /// SDP property. - index: usize, - - /// "Stream and track" identifiers. - /// - /// This is for _outgoing_ SDP. - /// - /// SDP property. - msid: Msid, - - /// Audio or video. - kind: MediaKind, - - /// Current media direction. - /// - /// Can be altered via negotiation. - /// - /// SDP property. - dir: Direction, - - /// Remote PTs negotiated for this media. - /// - /// This tells us both the desired priority order of payload types - /// as well as which PT the remote side wants (in case they are narrowed). - /// - /// These must have corresponding entries in Session::codec_config. - /// - /// SDP property. - /// - /// If this is empty, the m-line is disabled/rejected (port=0 in SDP). - remote_pts: Vec, - - /// Set when this m-line has been stopped via - /// [`SdpApi::stop_media`](crate::vendor::str0m::change::SdpApi::stop_media) or - /// rejected by the remote peer. Independent of `remote_pts` so that - /// an explicit stop preserves the negotiated PT list in SDP output - /// (the SDP grammar requires at least one fmt on a port=0 m-line). - stopped: bool, - - /// Remote extmaps negotiated for this media. - /// - /// The corresponding entries must exist in Session::codec_config. - /// - /// These are 1-indexed to be exactly like in the SDP. - remote_exts: ExtensionMap, - - /// [`true`] if this media was created by the remote peer, [`false`] if it was created by us. - remote_created: bool, - - /// Simulcast configuration, if set. - /// - /// SDP property. - simulcast: Option, - - // ========================================= Payloaders, etc ========================================= - // - /// Buffers of incoming RTP packets. These do reordering/jitter buffer and also - /// depayload from RTP to frames. - depayloaders: HashMap<(Pt, Option), DepacketizingBuffer>, - - /// Payloaders for outoing RTP packets. - payloaders: HashMap<(Pt, Option), Payloader>, - - /// Outgoing payloads ordered by their send deadlines or media wallclock times. - to_payload: VecDeque, - - pub(crate) need_open_event: bool, - pub(crate) need_changed_event: bool, -} - -#[derive(Debug)] -/// Config value for [`Media::rids_rx()`] and [`Media::rids_tx()`] -pub enum Rids { - /// No rid is allowed. - None, - /// Any Rid is allowed. - /// - /// This is the default value for direct API. - Any, - /// These specific [`Rid`] are allowed. - /// - /// This is the default value for Simulcast configured via SDP. - Specific(Vec), -} - -impl Rids { - pub(crate) fn contains(&self, rid: Rid) -> bool { - match self { - Rids::None => false, - Rids::Any => true, - Rids::Specific(v) => v.contains(&rid), - } - } - - pub(crate) fn is_specific(&self) -> bool { - matches!(self, Rids::Specific(_)) - } - - fn add(&mut self, rid: Rid) { - match self { - Rids::None | Rids::Any => { - *self = Rids::Specific(vec![rid]); - } - Rids::Specific(vec) if !vec.contains(&rid) => vec.push(rid), - Rids::Specific(_) => {} - } - } -} - -#[derive(Debug)] -pub(crate) struct ToPayload { - pub pt: Pt, - pub rid: Option, - pub wallclock: Instant, - pub rtp_time: MediaTime, - pub start_of_talk_spurt: bool, - pub data: Arc<[u8]>, - pub ext_vals: ExtensionValues, -} - -impl Media { - /// Identifier of the media. - /// - /// RTP level. - pub fn mid(&self) -> Mid { - self.mid - } - - /// Canonical name. - /// - /// Persistent transport-level identifier for an RTP source. - /// - /// RTP level property. The value is sent in RTCP reports for `StreamTx`. Incoming - /// cnames can be found in [`StreamRx::cname`][crate::vendor::str0m::rtp::StreamRx::cname]. - pub fn cname(&self) -> &str { - &self.cname - } - - /// Add rid as one we are expecting to receive for this mid. - /// - /// This is used for situations where we don't know the SSRC upfront, such as not having - /// a=ssrc lines in an SDP. Adding a rid means we are dynamically discovering the SSRC from - /// a mid/rid combination in the RTP header extensions. - /// - /// RTP level. - pub fn expect_rid_rx(&mut self, rid: Rid) { - self.rids_rx.add(rid); - } - - /// Rids we are expecting to see on incoming RTP packets that map to this mid. - /// - /// By default this is set to [`Rids::Any`], which changes to [`Rids::Specific`] via SDP negotiation - /// that configures Simulcast where specific rids are expected. - /// - /// RTP level. - pub fn rids_rx(&self) -> &Rids { - &self.rids_rx - } - - /// Rids we are can send via the [`Writer`]. - /// - /// By default this is set to [`Rids::None`], which changes to [`Rids::Specific`] via SDP negotiation - /// that configures Simulcast where specific rids are expected. - /// - /// RTP level. - pub fn rids_tx(&self) -> &Rids { - &self.rids_tx - } - - pub(crate) fn index(&self) -> usize { - self.index - } - - pub(crate) fn msid(&self) -> &Msid { - &self.msid - } - - /// Identifier for the group this Media belongs to. - pub fn stream_id(&self) -> &str { - &self.msid().stream_id - } - - /// Identifier for this Media. Should be unique for the given stream id. - pub fn track_id(&self) -> &str { - &self.msid().track_id - } - - /// Whether this media is audio or video. - /// - /// SDP level property. - pub fn kind(&self) -> MediaKind { - self.kind - } - - /// Current direction. This can be changed using - /// [`SdpApi::set_direction()`][crate::vendor::str0m::SdpApi::set_direction()] followed by an SDP negotiation. - /// - /// To test whether it's possible to send media with the current direction, use - /// - /// ```ignore - /// # use crate::vendor::str0m::media::Media; - /// let media: Media = todo!(); // Get hold of media row. - /// if media.direction().is_sending() { - /// // media.write(...); - /// } - /// ``` - /// - /// SDP level property. - pub fn direction(&self) -> Direction { - self.dir - } - - /// Whether this m-line is disabled/rejected (port=0 in SDP). - /// - /// An m-line is disabled if it has been stopped (via - /// [`SdpApi::stop_media`](crate::vendor::str0m::change::SdpApi::stop_media) or by the - /// remote peer), or if no codecs matched during negotiation. - /// - /// SDP level property. - pub fn disabled(&self) -> bool { - self.stopped || self.remote_pts.is_empty() - } - - /// Whether this m-line has been stopped. - /// - /// Unlike [`disabled`](Self::disabled) this does not include the "no - /// codecs matched" case - only explicit stop via - /// [`SdpApi::stop_media`](crate::vendor::str0m::change::SdpApi::stop_media) or a - /// port=0 m-line received from the remote peer. A stopped m-line - /// cannot be reactivated; its slot can however be recycled by a - /// subsequent new m-line (RFC 8829 §5.2.2). - pub fn stopped(&self) -> bool { - self.stopped - } - - pub(crate) fn mark_stopped(&mut self) { - self.stopped = true; - } - - pub(crate) fn simulcast(&self) -> Option<&SdpSimulcast> { - self.simulcast.as_ref() - } - - pub(crate) fn poll_sample( - &mut self, - params: &[PayloadParams], - now: Instant, - audio_timeout: Option, - ) -> Result, RtcError> { - for ((pt, rid), buf) in &mut self.depayloaders { - if let Some(r) = buf.pop(now, audio_timeout) { - let dep = r.map_err(|e| RtcError::Packet(self.mid, *pt, e))?; - let Some(codec) = params.iter().find(|c| c.pt() == *pt) else { - return Ok(None); - }; - // Telephone payloads are audio media even though Codec::is_audio() - // excludes their payload format. - let audio_start_of_talk_spurt = codec.spec().codec.kind().is_audio() && dep.start_of_talkspurt(); - return Ok(Some(MediaData { - mid: self.mid, - pt: *pt, - rid: *rid, - params: *codec, - // The depacketized time is in the RTP wire clock rate. For the - // media (samples/frame) API we present it in the codec's nominal - // clock rate. These differ only for G722, which has a 16 kHz - // nominal rate but an 8 kHz RTP clock rate (RFC 3551 §4.5.2). For - // all other codecs this rebase is a no-op. See - // https://en.wikipedia.org/wiki/RTP_payload_formats#cite_note-55 - time: dep.time.rebase(codec.spec().clock_rate), - network_time: dep.first_network_time(), - seq_range: dep.seq_range(), - contiguous: dep.contiguous, - ext_vals: dep.ext_vals(), - codec_extra: dep.codec_extra, - last_sender_info: dep.first_sender_info(), - audio_start_of_talk_spurt, - data: dep.data.into(), - })); - } - } - Ok(None) - } - - pub(crate) fn depayload( - &mut self, - rid: Option, - packet: RtpPacket, - reordering_size_audio: usize, - reordering_size_video: usize, - params: &[PayloadParams], - ) { - if !self.dir.is_receiving() { - return; - } - - let pt = packet.header.payload_type; - - let key = (pt, rid); - - let exists = self.depayloaders.contains_key(&key); - - if !exists { - // This unwrap is ok, because the handle_input doesn't accept the RtpPacket for - // depayloading unless we have matched the PT to one in the session. - let params = params.iter().find(|p| p.pt == pt).unwrap(); - - let codec = params.spec.codec; - - // How many packets to hold back in the jitter buffer. - let hold_back = if codec.is_audio() { - reordering_size_audio - } else { - reordering_size_video - }; - - let mut depack: CodecDepacketizer = codec.into(); - - // Enable DONL for H.265 when sprop-max-don-diff > 0 (RFC 7798 §7.1) - if let CodecDepacketizer::H265(ref mut h265) = depack { - if params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0 { - h265.with_donl(true); - } - } - - // RFC 4867: without octet-align=1 the payload is bandwidth-efficient. - if let CodecDepacketizer::AmrWb(ref mut amr) = depack { - amr.octet_align = params.spec.format.octet_align.unwrap_or(false); - } - - let buffer = DepacketizingBuffer::new(depack, hold_back); - - self.depayloaders.insert((pt, rid), buffer); - } - - let meta = RtpMeta { - received: packet.timestamp, - time: packet.time, - seq_no: packet.seq_no, - header: packet.header.clone(), - last_sender_info: packet.last_sender_info, - }; - - for ((other_pt, other_rid), buffer) in &mut self.depayloaders { - if *other_pt != pt && *other_rid == rid { - buffer.push_padding(meta.clone()); - } - } - - // The entry will be there by now. - let buffer = self.depayloaders.get_mut(&key).unwrap(); - - buffer.push(meta, packet.payload); - } - - pub(crate) fn set_cname(&mut self, cname: String) { - self.cname = cname; - } - - pub(crate) fn set_msid(&mut self, msid: Msid) { - self.msid = msid; - } - - pub(crate) fn set_direction(&mut self, new_dir: Direction) { - self.need_changed_event = self.dir != new_dir; - self.dir = new_dir; - - if !new_dir.is_sending() { - self.to_payload.clear(); - } - } - - pub(crate) fn set_simulcast(&mut self, s: SdpSimulcast) { - debug!("Set simulcast: {:?}", s); - self.simulcast = Some(s); - } - - fn payloader_for( - &mut self, - pt: Pt, - rid: Option, - params: &[PayloadParams], - vp9_mode: Vp9PacketizerMode, - ) -> &mut Payloader { - self.payloaders.entry((pt, rid)).or_insert_with(|| { - // Unwrap is OK, the pt should be checked already when calling this function. - let params = params.iter().find(|p| p.pt == pt).unwrap(); - Payloader::new(params.spec, vp9_mode) - }) - } - - fn queue_position(&self, to_payload: &ToPayload) -> usize { - self.to_payload - .iter() - .position(|p| p.wallclock > to_payload.wallclock) - .unwrap_or(self.to_payload.len()) - } - - fn set_to_payload(&mut self, to_payload: ToPayload) -> Result<(), RtcError> { - let position = self.queue_position(&to_payload); - self.to_payload.insert(position, to_payload); - if self.to_payload.len() > MAX_PENDING_PAYLOADS { - self.to_payload.remove(position); - return Err(RtcError::WriteWithoutPoll); - } - Ok(()) - } - - pub(crate) fn poll_timeout(&self) -> Option { - self.to_payload.front().map(|_| already_happened()) - } - - pub(crate) fn receive_buffers(&mut self) -> impl Iterator, &mut DepacketizingBuffer)> { - self.depayloaders.iter_mut().map(|((_, rid), buf)| (*rid, buf)) - } - - pub(crate) fn poll_receive_timeout(&mut self, audio_timeout: Option) -> Option { - self.depayloaders - .values_mut() - .filter_map(|buf| buf.poll_timeout(audio_timeout)) - .min() - } - - pub(crate) fn do_payload( - &mut self, - now: Instant, - streams: &mut Streams, - params: &[PayloadParams], - vp9_mode: Vp9PacketizerMode, - mtu: usize, - ) -> Result<(), RtcError> { - let Some(to_payload) = self.to_payload.pop_front() else { - return Ok(()); - }; - let ToPayload { pt, rid, .. } = &to_payload; - - let midrid = MidRid(self.mid, *rid); - - let stream = streams.stream_tx_by_midrid(midrid); - - let Some(stream) = stream else { - return Err(RtcError::NoSenderSource); - }; - - let pt = *pt; - - let rtp_size: usize = mtu - SRTP_OVERHEAD; - // align to SRTP block size to minimize padding needs - let aligned_mtu: usize = rtp_size - rtp_size % SRTP_BLOCK_SIZE; - - let payloader = self.payloader_for(pt, *rid, params, vp9_mode); - let result = payloader.push_sample(to_payload, aligned_mtu, stream); - - result.map_err(|e| RtcError::Packet(self.mid, pt, e)) - } - - pub(crate) fn set_remote_pts(&mut self, pts: Vec) { - // Have we already set PTs? - if !self.remote_pts.is_empty() { - return; - } - - // TODO: We should verify the remote peer doesn't suddenly change the PT - // order or removes/adds PTs that weren't there from the start. - debug!("Mid ({}) remote PT order is: {:?}", self.mid, pts); - self.remote_pts = pts; - } - - pub(crate) fn set_remote_extmap(&mut self, exts: ExtensionMap) { - self.remote_exts = exts; - } - - /// The remote PT (payload types) configured for this Media. - /// - /// These are negotiated with the remote peer and is the order the remote prefer them. - /// - /// I.e. these can be fewer than the `PayloadParams` configured for the `Rtc` instance, - /// and in a different order. - pub fn remote_pts(&self) -> &[Pt] { - &self.remote_pts - } - - /// The remote, agreed on, extension map, configured for this Media. - /// - /// For the SDP API, these are negotiated with the remote peer. - /// - /// For the Direct API, these are a clone of the session configured values narrowed by media - /// kind (audio/video). - pub fn remote_extmap(&self) -> &ExtensionMap { - &self.remote_exts - } - - pub(crate) fn remote_created(&self) -> bool { - self.remote_created - } - - pub(crate) fn reset_depayloaders_for_rid(&mut self, rid: Option) { - // A replacement SSRC can use any negotiated payload type for this RID. - self.depayloaders.retain(|(_, existing_rid), _| *existing_rid != rid); - } - - pub(crate) fn set_rid_rx(&mut self, rids: Rids) { - self.rids_rx = rids; - } - - pub(crate) fn set_rid_tx(&mut self, rids: Rids) { - self.rids_tx = rids; - } - - pub(crate) fn add_to_rid_tx(&mut self, rid: Rid) { - self.rids_tx.add(rid) - } -} - -impl Default for Media { - fn default() -> Self { - Self { - mid: Mid::new(), - index: 0, - cname: Id::<20>::random().to_string(), - msid: Msid::random(), - kind: MediaKind::Video, - remote_pts: vec![], - stopped: false, - remote_exts: ExtensionMap::empty(), - remote_created: false, - dir: Direction::SendRecv, - simulcast: None, - rids_rx: Rids::Any, - rids_tx: Rids::None, - payloaders: HashMap::new(), - depayloaders: HashMap::new(), - to_payload: VecDeque::default(), - need_open_event: true, - need_changed_event: false, - } - } -} - -impl Media { - pub(crate) fn from_remote_media_line(l: &MediaLine, index: usize, remote_created: bool) -> Self { - Media { - mid: l.mid(), - index, - // This is not reflected back, and thus added by add_pending_changes(). - // cname, - msid: l - .msid() - .filter(|m| !is_no_stream(&m.stream_id)) - .unwrap_or(Msid::random()), - kind: l.typ.clone().into(), - dir: if l.disabled { - Direction::Inactive - } else { - l.direction().invert() // remote direction is reverse. - }, - remote_created, - ..Default::default() - } - } - - // Going from AddMedia to Media for pending in a Change and are sent - // in the offer to the other side. - // - // from_add_media is only used when creating temporary Media to be - // included in the SDP. We don't want to make an _actual_ changes with this. - pub(crate) fn from_add_media(a: AddMedia) -> Self { - Media { - mid: a.mid, - index: a.index, - cname: a.cname, - msid: a.msid, - kind: a.kind, - dir: a.dir, - remote_pts: a.pts, - remote_exts: a.exts, - remote_created: false, - simulcast: a.simulcast.map(|s| s.into_sdp()), - ..Default::default() - } - } - - pub(crate) fn from_direct_api(mid: Mid, index: usize, kind: MediaKind, exts: ExtensionMap) -> Media { - Media { - mid, - index, - kind, - dir: Direction::SendRecv, - remote_exts: exts, - ..Default::default() - } - } -} - -#[cfg(test)] -mod receive_timeout_test { - use super::*; - use crate::vendor::str0m::format::Codec; - use crate::vendor::str0m::rtp_::RtpHeader; - - fn blocked_buffer(base: Instant) -> DepacketizingBuffer { - let mut buffer = DepacketizingBuffer::new(Codec::Vp8.into(), 30); - for seq in [1u64, 3] { - buffer.push( - RtpMeta { - received: base, - time: MediaTime::from_90khz(seq * 3000), - seq_no: seq.into(), - header: RtpHeader { - marker: true, - ..Default::default() - }, - last_sender_info: None, - }, - [0x10, 0, 0], - ); - if seq == 1 { - buffer.pop(base, None).unwrap().unwrap(); - } - } - buffer - } - - /// Test the earliest deadline covers all payload types and RIDs and changes after buffer resets. - #[test] - fn deadlines_cover_payload_types_rids_and_resets() { - let base = Instant::now(); - let mut media = Media::default(); - let pt1 = Pt::new_with_value(96); - let pt2 = Pt::new_with_value(98); - let rid1 = Some("a".into()); - let rid2 = Some("b".into()); - media - .depayloaders - .insert((pt1, rid1), blocked_buffer(base + Duration::from_millis(100))); - media.depayloaders.insert((pt2, rid1), blocked_buffer(base)); - media - .depayloaders - .insert((pt1, rid2), blocked_buffer(base + Duration::from_millis(50))); - let timeout = Some(Duration::from_millis(250)); - assert_eq!( - media.poll_receive_timeout(timeout), - Some(base + Duration::from_millis(250)) - ); - media.reset_depayloaders_for_rid(rid1); - assert_eq!( - media.poll_receive_timeout(timeout), - Some(base + Duration::from_millis(300)) - ); - media.reset_depayloaders_for_rid(rid2); - assert_eq!(media.poll_receive_timeout(timeout), None); - assert_eq!(media.poll_receive_timeout(None), None); - media.depayloaders.insert((pt1, rid1), blocked_buffer(base)); - assert_eq!(media.poll_receive_timeout(Some(Duration::ZERO)), Some(base)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/media/writer.rs b/rs/moq-webrtc/src/vendor/str0m/media/writer.rs deleted file mode 100644 index 8310df45426..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/media/writer.rs +++ /dev/null @@ -1,261 +0,0 @@ -use std::sync::Arc; -use std::time::Instant; -use tracing::trace; - -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::format::{CodecConfig, PayloadParams}; -use crate::vendor::str0m::packet::PacketError; -use crate::vendor::str0m::poll::Readiness; -use crate::vendor::str0m::rtp_::AbsCaptureTime; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::VideoOrientation; -use crate::vendor::str0m::session::Session; -use crate::vendor::str0m::streams::Streams; - -use super::{ExtensionValues, KeyframeRequestKind, Media, MediaTime, Mid, Pt, Rid, ToPayload}; - -/// Writer of frame level data. -/// -/// Obtained via [`Rtc::writer`][crate::vendor::str0m::Rtc::writer]. -/// -/// This is the Frame Level API. For RTP level see -/// [`DirectApi::stream_tx`][crate::vendor::str0m::change::DirectApi::stream_tx]. -pub struct Writer<'a> { - session: &'a mut Session, - readiness: &'a mut Readiness, - mid: Mid, - rid: Option, - start_of_talkspurt: Option, - ext_vals: ExtensionValues, -} - -impl<'a> Writer<'a> { - /// Create a new writer object. - /// - /// The `mid` parameter is required to have a corresponding media in `self.session`. - /// - /// Mutations arm readiness within the method so read-only access leaves it - /// intact and no persistent drop guard extends the caller's borrow. - pub(crate) fn new(session: &'a mut Session, readiness: &'a mut Readiness, mid: Mid) -> Self { - Writer { - session, - readiness, - mid, - rid: None, - start_of_talkspurt: None, - ext_vals: ExtensionValues::default(), - } - } - - /// Get the configured payload parameters for the `mid` this writer is for. - /// - /// For the [`Writer::write()`] call, the `pt` must be set correctly. - pub fn payload_params(&self) -> impl Iterator { - // This unwrap is OK due to the invariant of self.mid being resolvable - let media = self.session.media_by_mid(self.mid).unwrap(); - self.session - .codec_config - .params() - .iter() - .filter(|p| media.remote_pts().contains(&p.pt)) - } - - /// Match the given parameters to the configured parameters for this [`Media`]. - /// - /// In a server scenario, a certain codec configuration might not have the same - /// payload type (PT) for two different peers. We will have incoming data with one - /// PT and need to match that against the PT of the outgoing [`Media`]. - /// - /// This call performs matching and if a match is found, returns the _local_ PT - /// that can be used for sending media. - pub fn match_params(&self, params: PayloadParams) -> Option { - self.session.codec_config.match_params(params).map(|p| p.pt()) - } - - /// Add on an Rtp Stream Id. This is typically used to separate simulcast layers. - pub fn rid(mut self, rid: Rid) -> Self { - self.rid = Some(rid); - self - } - - /// Add on audio level and voice activity. These values are communicated in the same - /// RTP header extension, hence it makes sense setting both at the same time. - /// - /// Audio level is measured in negative decibel. 0 is max and a "normal" value might be -30. - pub fn audio_level(mut self, audio_level: i8, voice_activity: bool) -> Self { - self.ext_vals.audio_level = Some(audio_level); - self.ext_vals.voice_activity = Some(voice_activity); - self - } - - /// First packet of a talkspurt, that is the first packet after a silence period during - /// which packets have not been transmitted contiguously. - /// - /// For audio only when dtx or silence suppression is enabled. - /// This will set the marker bit in the RTP header. - pub fn start_of_talkspurt(mut self, start_of_talkspurt: bool) -> Self { - self.start_of_talkspurt = Some(start_of_talkspurt); - self - } - - /// Add video orientation. This can be used by a player on the receiver end to decide - /// whether the video requires to be rotated to show correctly. - pub fn video_orientation(mut self, o: VideoOrientation) -> Self { - self.ext_vals.video_orientation = Some(o); - self - } - - /// Set absolute capture time for this frame. - pub fn abs_capture_time(mut self, capture_time: AbsCaptureTime) -> Self { - self.ext_vals.abs_capture_time = Some(capture_time); - self - } - - /// Set the minimum and maximum playout delay values. This can be used by a player - /// on the receiver end to determine the size of the jitter buffer. - pub fn playout_delay(mut self, min: MediaTime, max: MediaTime) -> Self { - self.ext_vals.play_delay_min = Some(min); - self.ext_vals.play_delay_max = Some(max); - self - } - - /// Set a user extension value. - pub fn user_extension_value(mut self, val: T) -> Self { - self.ext_vals.user_values.set(val); - self - } - - /// Write media. - /// - /// This operation fails if the PT doesn't match a negotiated codec, or the RID (`None` or a value) - /// does not match anything negotiated. - /// - /// Regarding `wallclock` and `rtp_time`, the wallclock is the real world time that corresponds to - /// the `MediaTime`. For an SFU, this can be hard to know, since RTP packets typically only - /// contain the media time (RTP time). In the simplest SFU setup, the wallclock could simply - /// be the arrival time of the incoming RTP data (see - /// [`MediaData::network_time`][crate::vendor::str0m::media::MediaData]). For better synchronization the SFU - /// probably needs to weigh in clock drifts and data provided via the statistics. - /// - /// If you write media before `IceConnectionState` is `Connected` it will be dropped. - /// - /// Panics if [`RtcConfig::set_rtp_mode()`][crate::vendor::str0m::RtcConfig::set_rtp_mode] is `true`. - pub fn write( - self, - pt: Pt, - wallclock: Instant, - rtp_time: MediaTime, - data: impl Into>, - ) -> Result<(), RtcError> { - let _wake = self.readiness.wake(); - - if !self.session.codec_config.has_pt(pt) { - return Err(RtcError::UnknownPt(pt)); - } - let params = self - .session - .codec_config - .params() - .iter() - .find(|p| p.pt() == pt) - .expect("configured payload type exists"); - let clock_rate = params.spec().clock_rate; - - // This (indirect) unwrap is OK due to the invariant of self.mid being resolvable - let media = media_by_mid_mut(&mut self.session.medias, self.mid); - - if let Some(rid) = self.rid { - if !media.rids_tx().contains(rid) { - return Err(RtcError::UnknownRid(rid)); - } - } - - let data: Arc<[u8]> = data.into(); - - trace!( - "write {:?} {:?} {:?} time: {:?} len: {}", - self.mid, - self.rid, - pt, - rtp_time, - data.len() - ); - - media.set_to_payload(ToPayload { - pt, - rid: self.rid, - wallclock, - rtp_time, - data, - start_of_talk_spurt: self.start_of_talkspurt.unwrap_or(false), - ext_vals: self.ext_vals.clone(), - })?; - - Ok(()) - } - - /// Test if the kind of keyframe request is possible. - /// - /// Sending a keyframe request requires the mechanic to be negotiated as a feedback mechanic - /// in the SDP offer/answer dance first. - /// - /// Specifically these SDP lines would enable FIR and PLI respectively (for payload type 96). - /// - /// ```text - /// a=rtcp-fb:96 ccm fir - /// a=rtcp-fb:96 nack pli - /// ``` - pub fn is_request_keyframe_possible(&self, kind: KeyframeRequestKind) -> bool { - self.session.is_request_keyframe_possible(kind) - } - - /// Request a keyframe from a remote peer sending media data. - /// - /// For SDP: This can fail if the kind of request (PLI or FIR), as specified by the - /// [`KeyframeRequestKind`], is not negotiated in the SDP answer/offer for this m-line. - /// - /// To ensure the call will not fail, use [`Writer::is_request_keyframe_possible()`] to - /// check whether the feedback mechanism is enabled. - /// - /// # Example - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::media::{Mid, KeyframeRequestKind}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// // add candidates, do SDP negotiation - /// let mid: Mid = todo!(); // obtain mid from Event::MediaAdded. - /// - /// let writer = rtc.writer(mid).unwrap(); - /// - /// writer.request_keyframe(None, KeyframeRequestKind::Pli).unwrap(); - /// ``` - pub fn request_keyframe(&mut self, rid: Option, kind: KeyframeRequestKind) -> Result<(), RtcError> { - if !self.is_request_keyframe_possible(kind) { - return Err(RtcError::NotReceivingDirection); - } - - // Requests become RTCP feedback on the next timeout, so arm both signals. - let _wake = self.readiness.wake(); - let midrid = MidRid(self.mid, rid); - - let stream = self - .session - .streams - .stream_rx_by_midrid(midrid) - .ok_or(RtcError::NoReceiverSource(rid))?; - - stream.request_keyframe(kind); - - Ok(()) - } -} - -/// Get a &mut Media in a slice for a `mid`. -/// -/// `mid` must be resolvable or panic will ensue. -fn media_by_mid_mut(medias: &mut [Media], mid: Mid) -> &mut Media { - medias.iter_mut().find(|m| m.mid() == mid).unwrap() -} diff --git a/rs/moq-webrtc/src/vendor/str0m/pacer/mod.rs b/rs/moq-webrtc/src/vendor/str0m/pacer/mod.rs deleted file mode 100644 index c326738de5a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/pacer/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -mod null; -pub(crate) use null::NullPacer; - -mod queue; -pub(crate) use queue::{QueuePriority, QueueSnapshot, QueueState}; - -/// The sub-reason for the [`Reason::Pacer`][crate::vendor::str0m::Reason::Pacer]. -/// -/// This enum is not considered stable API and may change in minor revisions. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub enum PacerReason { - /// Handle to update the pacer's queue snapshots. - Handle, -} diff --git a/rs/moq-webrtc/src/vendor/str0m/pacer/null.rs b/rs/moq-webrtc/src/vendor/str0m/pacer/null.rs deleted file mode 100644 index 5382ec65f5c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/pacer/null.rs +++ /dev/null @@ -1,127 +0,0 @@ -use std::collections::HashMap; -use std::time::Instant; - -use super::QueueState; -use crate::vendor::str0m::Reason; -use crate::vendor::str0m::pacer::PacerReason; -use crate::vendor::str0m::rtp_::{DataSize, MidRid}; - -/// A pacer that doesn't pace: it drains every queue, least recently sent first. -#[derive(Debug, Default)] -pub struct NullPacer { - last_sends: HashMap, - /// Snapshots from the last `handle_timeout`. `poll_queue` counts off - /// each packet it hands out. - queue_states: Vec, - /// Set when `poll_queue` hands out a queue that `register_send` never confirms: - /// the stream had nothing to send after all, so the snapshot is stale. - unsent_since: Option, -} - -impl NullPacer { - /// Poll for a timeout. - pub fn poll_timeout(&self) -> (Option, Reason) { - // Only a poll that sent nothing needs a fresh snapshot: other queued packets go - // out on the next poll. New media requests a timeout, and receiving a NACK - // refreshes the snapshot through Rtc::handle_input before polling resumes. - (self.unsent_since, Reason::Pacer(PacerReason::Handle)) - } - - /// Take fresh snapshots of the send queues, as asked for by [`Self::poll_timeout`]. - pub fn handle_timeout(&mut self, _now: Instant, iter: impl Iterator) { - self.unsent_since = None; - self.queue_states.clear(); - self.queue_states.extend(iter); - } - - /// Determines which queue to poll, if any. - pub fn poll_queue(&mut self) -> Option { - // Pick a queue using round robin, prioritize the least recently sent on queue. - let queue = self - .queue_states - .iter_mut() - .filter(|q| q.snapshot.packet_count > 0) - .min_by_key(|q| self.last_sends.get(&q.midrid))?; - - queue.snapshot.packet_count -= 1; - self.unsent_since = Some(queue.snapshot.created_at); - - Some(queue.midrid) - } - - /// Register a packet having been sent. - /// - /// **MUST** be called each time [`Self::poll_queue`] produces a mid. - pub fn register_send(&mut self, now: Instant, _packet_size: DataSize, from: MidRid) { - self.unsent_since = None; - let e = self.last_sends.entry(from).or_insert(now); - *e = now; - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::str0m::pacer::QueueSnapshot; - - fn queue(mid: &str, packet_count: u32, now: Instant) -> QueueState { - QueueState { - midrid: MidRid(mid.into(), None), - snapshot: QueueSnapshot { - created_at: now, - packet_count, - ..Default::default() - }, - } - } - - #[test] - fn drains_every_queue_without_another_timeout() { - let now = Instant::now(); - let mut pacer = NullPacer::default(); - let queues = [queue("a", 2, now), queue("b", 1, now), queue("c", 0, now)]; - pacer.handle_timeout(now, queues.into_iter()); - - let mut sent = vec![]; - for _ in 0..3 { - let midrid = pacer.poll_queue().expect("queued packet"); - pacer.register_send(now, DataSize::bytes(100), midrid); - assert_eq!(pacer.poll_timeout().0, None, "no timeout between sends"); - sent.push(midrid.mid().to_string()); - } - sent.sort(); - assert_eq!(sent, ["a", "a", "b"]); - assert_eq!(pacer.poll_queue(), None); - assert_eq!(pacer.poll_timeout().0, None, "no timeout after draining"); - } - - #[test] - fn unsent_poll_asks_for_a_fresh_snapshot() { - let now = Instant::now(); - let mut pacer = NullPacer::default(); - pacer.handle_timeout(now, [queue("a", 1, now), queue("b", 1, now)].into_iter()); - - assert!(pacer.poll_queue().is_some()); - assert_eq!(pacer.poll_timeout().0, Some(now), "stream sent nothing"); - - pacer.handle_timeout(now, [queue("b", 1, now)].into_iter()); - assert_eq!(pacer.poll_timeout().0, None); - let midrid = pacer.poll_queue().expect("remaining packet"); - assert_eq!(midrid, MidRid("b".into(), None)); - pacer.register_send(now, DataSize::bytes(100), midrid); - assert_eq!(pacer.poll_queue(), None); - assert_eq!(pacer.poll_timeout().0, None); - } - - #[test] - fn round_robin_by_least_recently_sent() { - let now = Instant::now(); - let mut pacer = NullPacer::default(); - pacer.register_send(now, DataSize::bytes(100), MidRid("a".into(), None)); - let later = now + std::time::Duration::from_millis(1); - pacer.register_send(later, DataSize::bytes(100), MidRid("b".into(), None)); - pacer.handle_timeout(later, [queue("a", 1, later), queue("b", 1, later)].into_iter()); - - assert_eq!(pacer.poll_queue(), Some(MidRid("a".into(), None))); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/pacer/queue.rs b/rs/moq-webrtc/src/vendor/str0m/pacer/queue.rs deleted file mode 100644 index dc0bf4daf42..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/pacer/queue.rs +++ /dev/null @@ -1,95 +0,0 @@ -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::util::not_happening; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct QueueSnapshot { - /// Time this snapshot was made - pub created_at: Instant, - /// The total byte size of the snapshot. - pub byte_size: usize, - /// The total number of packets in the queue. - /// NB: This is not a [`usize`] because it will later be used to divide a [`Duration`], for which - /// [`usize`] isn't implement. If the queues end up with 2^32 packets something has gone very wrong - /// in any case. - pub packet_count: u32, - /// Accumulation of all queue time at the time point `created_at`. To use this - /// Look at `total_queue_time(now)` which allows getting the queue time at a later Instant. - pub total_queue_time_origin: Duration, - /// Last time something was emitted from this queue. - pub last_emitted: Option, - /// Time the first unsent packet has spent in the queue. - pub first_unsent: Option, - /// The priority of the most important packet in the queue. - pub priority: QueuePriority, -} - -/// Priority for a given queue. -/// -/// When sorted, higher priority sorts first. -#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] -pub enum QueuePriority { - // Highest, priority for a queue that contains media. - Media = 0, - // Priority for an empty queue. - #[default] - Empty = 2, -} - -impl QueueSnapshot { - /// Update the priority if the snapshot is non-empty. - /// - /// Sets the priority to the provided priority if the queue is non-empty, otherwise empty. - pub fn update_priority(&mut self, priority: QueuePriority) { - if self.packet_count > 0 { - self.priority = priority; - } else { - self.priority = QueuePriority::Empty; - } - } -} - -impl Default for QueueSnapshot { - fn default() -> Self { - Self { - created_at: not_happening(), - byte_size: Default::default(), - packet_count: Default::default(), - total_queue_time_origin: Default::default(), - last_emitted: Default::default(), - first_unsent: Default::default(), - priority: QueuePriority::default(), - } - } -} - -/// The state of a single upstream queue. -/// The pacer manages packets across several upstream queues. -#[derive(Debug, Clone, Copy)] -pub struct QueueState { - pub midrid: MidRid, - pub snapshot: QueueSnapshot, -} - -impl QueueSnapshot { - /// Merge other into self. - pub fn merge(&mut self, other: &Self) { - self.created_at = self.created_at.min(other.created_at); - self.byte_size += other.byte_size; - self.packet_count += other.packet_count; - self.total_queue_time_origin += other.total_queue_time_origin; - self.last_emitted = self.last_emitted.max(other.last_emitted); - self.first_unsent = match (self.first_unsent, other.first_unsent) { - (None, None) => None, - (None, Some(v2)) => Some(v2), - (Some(v1), None) => Some(v1), - (Some(v1), Some(v2)) => Some(v1.min(v2)), - }; - self.priority = self.priority.min(other.priority); - } - - pub fn total_queue_time(&self, now: Instant) -> Duration { - self.total_queue_time_origin + self.packet_count * (now - self.created_at) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/LICENSE-APACHE.txt b/rs/moq-webrtc/src/vendor/str0m/packet/LICENSE-APACHE.txt deleted file mode 100644 index 16fe87b06e8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/LICENSE-APACHE.txt +++ /dev/null @@ -1,201 +0,0 @@ - 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. diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/amr_wb.rs b/rs/moq-webrtc/src/vendor/str0m/packet/amr_wb.rs deleted file mode 100644 index d46786feee4..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/amr_wb.rs +++ /dev/null @@ -1,339 +0,0 @@ -//! AMR-WB RTP payload format, [RFC 4867](https://datatracker.ietf.org/doc/html/rfc4867). -//! -//! str0m doesn't encode or decode AMR-WB. The application exchanges frames in the -//! 3GPP IF / storage format (RFC 4867 §5.3): a header octet `(FT << 3) | (Q << 2)` -//! followed by the frame's speech bits, zero-padded to a whole octet. -//! -//! Sending: write exactly one 20 ms frame per call. It goes out as one RTP payload -//! with codec mode request 15 (no request). NO_DATA frames aren't sent. -//! -//! Receiving: `MediaData` holds every frame of an RTP payload back to back, 20 ms -//! apart starting at `MediaData::time`. Peers may resend earlier frames for -//! redundancy (RFC 4867 §4.1), so the same frame time can arrive more than once. -//! The codec mode request is ignored and padding bits are ignored. Payloads with -//! reserved frame types, missing speech bits, or more bytes than their table of -//! contents describes are dropped. -//! -//! Supported in SDP negotiation: -//! - Mono payloads in the octet-aligned (`octet-align=1`, used by `enable_amr_wb`) -//! or bandwidth-efficient layout. Both sides must use the same layout. -//! - `mode-set`, from either side. It applies to both directions, so the -//! application must only write frames in those modes. -//! -//! Declined: CRCs (`crc=1`), robust sorting (`robust-sorting=1`), interleaving, -//! more than one channel, and `mode-change-period=2`, which str0m can't enforce on -//! application frames. Other AMR-WB parameters, such as `max-red` and -//! `mode-change-capability`, are ignored and left out of answers. - -use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer}; - -/// Speech bits per frame type (RFC 4867 Table 1a). `None` marks the reserved types. -const FRAME_BITS: [Option; 16] = [ - Some(132), // 6.60 kbit/s - Some(177), // 8.85 kbit/s - Some(253), // 12.65 kbit/s - Some(285), // 14.25 kbit/s - Some(317), // 15.85 kbit/s - Some(365), // 18.25 kbit/s - Some(397), // 19.85 kbit/s - Some(461), // 23.05 kbit/s - Some(477), // 23.85 kbit/s - Some(40), // SID - None, - None, - None, - None, - Some(0), // SPEECH_LOST - Some(0), // NO_DATA -]; - -const NO_DATA: u8 = 15; - -/// First payload octet with Codec Mode Request 15 ("no mode requested"). -const CMR_NO_REQUEST: u8 = 0xf0; - -/// Packetizes one AMR-WB IF frame per RTP payload. -#[derive(Debug, Default)] -pub struct AmrWbPacketizer { - pub(crate) octet_align: bool, -} - -impl Packetizer for AmrWbPacketizer { - fn packetize(&mut self, mtu: usize, frame: &[u8]) -> Result>, PacketError> { - let Some((&header, speech)) = frame.split_first() else { - return Ok(vec![]); - }; - - let frame_type = (header >> 3) & 0x0f; - let bits = FRAME_BITS[frame_type as usize].ok_or(PacketError::ErrAmrWbCorruptedPacket)?; - if speech.len() != bits.div_ceil(8) { - return Err(PacketError::ErrAmrWbCorruptedPacket); - } - - // RFC 4867 §4.3.2: payloads with only NO_DATA frames should not be sent. - if frame_type == NO_DATA { - return Ok(vec![]); - } - - // A ToC entry F|FT|Q with F=0 (last frame) is the IF header without its P bits. - let toc = header & 0x7c; - let (mut payload, header_bits) = if self.octet_align { - // CMR and 4 reserved bits, the ToC entry and 2 padding bits, then the - // speech bits, which are already octet-aligned in the IF frame. - ([&[CMR_NO_REQUEST, toc][..], speech].concat(), 16) - } else { - // The 4-bit CMR and 6-bit ToC entry put the speech bits 2 bits to the - // right of where they are in the IF frame. - let mut payload = vec![CMR_NO_REQUEST | (toc >> 4)]; - let mut carry = toc << 4; - for &byte in speech { - payload.push(carry | (byte >> 2)); - carry = byte << 6; - } - payload.push(carry); - (payload, 10) - }; - payload.truncate((header_bits + bits).div_ceil(8)); - - // Clear the trailing padding bits, which the IF frame may leave set. - let padding = (8 - (header_bits + bits) % 8) % 8; - let last = payload.len() - 1; - payload[last] &= 0xff << padding; - - if payload.len() > mtu { - return Err(PacketError::ErrPayloadTooLarge); - } - - Ok(vec![payload]) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, _last: bool) -> bool { - false - } - - fn marks_talkspurt(&self) -> bool { - true - } - - fn nackable(&self) -> bool { - false - } -} - -/// Depacketizes AMR-WB RTP payloads into concatenated IF frames. -#[derive(Debug, Default)] -pub struct AmrWbDepacketizer { - pub(crate) octet_align: bool, -} - -impl Depacketizer for AmrWbDepacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, _: &mut CodecExtra) -> Result<(), PacketError> { - if packet.is_empty() { - return Ok(()); - } - - // Skip the codec mode request, and its 4 reserved bits when octet-aligned. - let mut reader: (&[u8], usize) = (packet, if self.octet_align { 8 } else { 4 }); - - // Table of contents: an F|FT|Q entry per frame, where F=1 means another follows. - let mut headers = Vec::new(); - loop { - let entry = reader.get_bits(6).ok_or(PacketError::ErrShortPacket)?; - if self.octet_align { - reader.get_bits(2).ok_or(PacketError::ErrShortPacket)?; - } - // The IF frame header holds the entry's FT and Q. - headers.push((entry << 2) & 0x7c); - if entry & 0x20 == 0 { - break; - } - } - - for header in headers { - let bits = FRAME_BITS[(header >> 3) as usize].ok_or(PacketError::ErrAmrWbCorruptedPacket)?; - out.push(header); - for _ in 0..bits / 8 { - out.push(reader.get_u8().ok_or(PacketError::ErrShortPacket)?); - } - let rest = bits % 8; - if rest > 0 { - let tail = reader.get_bits(rest).ok_or(PacketError::ErrShortPacket)?; - out.push(tail << (8 - rest)); - } - if self.octet_align { - reader.1 = reader.1.next_multiple_of(8); - } - } - - // RFC 4867 §4.5.1: discard payloads longer than the ToC describes. At most - // seven padding bits may remain, and their values are ignored. - if reader.remaining_bits() >= 8 { - return Err(PacketError::ErrAmrWbCorruptedPacket); - } - - Ok(()) - } - - fn is_partition_head(&self, _packet: &[u8]) -> bool { - true - } - - fn is_partition_tail(&self, _marker: bool, _packet: &[u8]) -> bool { - true - } -} - -#[cfg(test)] -mod test { - use super::*; - - /// An IF frame of `frame_type` (Q=1) whose speech bytes are `fill`, padding cleared. - fn if_frame(frame_type: u8, fill: u8) -> Vec { - let bits = FRAME_BITS[frame_type as usize].unwrap(); - let mut frame = vec![(frame_type << 3) | 0x04]; - frame.extend(std::iter::repeat_n(fill, bits.div_ceil(8))); - if bits % 8 != 0 { - *frame.last_mut().unwrap() &= 0xff << (8 - bits % 8); - } - frame - } - - fn packetize(octet_align: bool, frame: &[u8]) -> Vec { - let mut packets = AmrWbPacketizer { octet_align }.packetize(1200, frame).unwrap(); - assert_eq!(packets.len(), 1); - packets.remove(0) - } - - fn depacketize(octet_align: bool, payload: &[u8]) -> Result, PacketError> { - let mut out = Vec::new(); - AmrWbDepacketizer { octet_align }.depacketize(payload, &mut out, &mut CodecExtra::None)?; - Ok(out) - } - - #[test] - fn packetizer_uses_audio_packet_policy() { - let pack = crate::vendor::str0m::packet::CodecPacketizer::from(crate::vendor::str0m::format::Codec::AmrWb); - assert!(pack.marks_talkspurt()); - assert!(!pack.nackable()); - } - - #[test] - fn round_trips_every_frame_type_in_both_layouts() { - for octet_align in [false, true] { - for frame_type in (0..=9).chain([14]) { - let frame = if_frame(frame_type, 0xa5); - let payload = packetize(octet_align, &frame); - assert_eq!(depacketize(octet_align, &payload).unwrap(), frame); - } - } - } - - #[test] - fn payload_layout_matches_rfc_4867() { - let frame = if_frame(8, 0xa5); - - // CMR=15 and reserved bits, ToC F=0 FT=8 Q=1, then the octet-aligned frame. - let payload = packetize(true, &frame); - assert_eq!(payload[..2], [0xf0, 0x44]); - assert_eq!(payload[2..], frame[1..]); - - // 4-bit CMR and 6-bit ToC, then the 477 speech bits shifted 2 bits right, so - // each 0xa5 becomes 0x69, and one padding bit. - let payload = packetize(false, &frame); - assert_eq!(payload.len(), 61); - assert_eq!(payload[0], 0xf4); - assert!(payload[1..60].iter().all(|&b| b == 0x69)); - assert_eq!(payload[60], 0x68); - } - - #[test] - fn depacketizes_compound_payloads() { - let lost = if_frame(14, 0); - let speech = if_frame(0, 0xa5); - let sid = if_frame(9, 0x5a); - - // One ToC octet per frame, then each frame padded to an octet. The padding - // after the 132 speech bits is non-zero and must be ignored. - let mut payload = vec![0xf0, 0x80 | lost[0], 0x80 | speech[0], sid[0]]; - payload.extend(&speech[1..]); - *payload.last_mut().unwrap() |= 0x0f; - payload.extend(&sid[1..]); - assert_eq!( - depacketize(true, &payload).unwrap(), - [lost.clone(), speech, sid.clone()].concat() - ); - - // CMR=15, ToC [F=1 FT=14 Q=1] [F=0 FT=9 Q=1], then the 40 SID bits. - let payload = [0xff, 0x53, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a]; - assert_eq!(depacketize(false, &payload).unwrap(), [lost, sid].concat()); - } - - #[test] - fn padding_and_reserved_bits_are_ignored() { - let frame = if_frame(0, 0xa5); - - let mut dirty = frame.clone(); - dirty[0] |= 0x83; - *dirty.last_mut().unwrap() |= 0x0f; - assert_eq!(packetize(true, &dirty), packetize(true, &frame)); - - let mut payload = packetize(true, &frame); - payload[0] |= 0x0f; - payload[1] |= 0x03; - *payload.last_mut().unwrap() |= 0x0f; - assert_eq!(depacketize(true, &payload).unwrap(), frame); - - let mut payload = packetize(false, &frame); - *payload.last_mut().unwrap() |= 0x03; - assert_eq!(depacketize(false, &payload).unwrap(), frame); - } - - #[test] - fn packetizer_skips_empty_and_no_data_frames() { - let mut pack = AmrWbPacketizer::default(); - assert!(pack.packetize(1200, &[]).unwrap().is_empty()); - assert!(pack.packetize(1200, &[0x7c]).unwrap().is_empty()); - } - - #[test] - fn packetizer_rejects_invalid_frames() { - let mut pack = AmrWbPacketizer { octet_align: true }; - let frame = if_frame(8, 0x11); - - let reserved = vec![10 << 3]; - let truncated = frame[..30].to_vec(); - let concatenated = [frame.clone(), if_frame(9, 0x22)].concat(); - for invalid in [reserved, truncated, concatenated] { - assert_eq!( - pack.packetize(1200, &invalid), - Err(PacketError::ErrAmrWbCorruptedPacket) - ); - } - - assert_eq!(pack.packetize(61, &frame), Err(PacketError::ErrPayloadTooLarge)); - } - - #[test] - fn depacketizer_rejects_malformed_payloads() { - let mut payload = packetize(true, &if_frame(8, 0x11)); - - assert_eq!(depacketize(true, &payload[..30]), Err(PacketError::ErrShortPacket)); - assert_eq!(depacketize(false, &[0xf0]), Err(PacketError::ErrShortPacket)); - assert_eq!( - depacketize(true, &[0xf0, 10 << 3]), - Err(PacketError::ErrAmrWbCorruptedPacket) - ); - - payload.push(0); - assert_eq!(depacketize(true, &payload), Err(PacketError::ErrAmrWbCorruptedPacket)); - } - - #[test] - fn depacketizes_empty_payload_to_nothing() { - assert!(depacketize(true, &[]).unwrap().is_empty()); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/av1.rs b/rs/moq-webrtc/src/vendor/str0m/packet/av1.rs deleted file mode 100644 index 8d110f3b89b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/av1.rs +++ /dev/null @@ -1,1254 +0,0 @@ -use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer}; - -const OBU_EXTENSION_PRESENT_MASK: u8 = 0b0000_0100; -const OBU_SIZE_PRESENT_MASK: u8 = 0b0000_0010; -const OBU_TYPE_MASK: u8 = 0b0111_1000; -const AGGREGATION_HEADER_SIZE: usize = 1; -const MAX_NUM_OBUS_TO_OMTI_SIZE: usize = 3; - -/// Detect whether an AV1 RTP payload contains a keyframe. -/// -/// Checks the N bit (new coded video sequence) in the AV1 aggregation header. -/// N=1 indicates the first packet of a keyframe (random access point). -/// -/// AV1 aggregation header layout: `Z|Y|W W|N|reserved` -/// - N (bit 3): 1 = new coded video sequence starts -pub fn detect_av1_keyframe(payload: &[u8]) -> bool { - if payload.is_empty() { - return false; - } - // N bit is bit 3 of the aggregation header - payload[0] & 0x08 != 0 -} - -/// AV1 information describing the depacketized / packetized data -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct Av1CodecExtra { - /// Flag which indicates that within [`MediaData`], there is an individual frame - /// containing complete and independent visual information. This frame serves - /// as a reference point for other frames in the video sequence. - /// - /// [`MediaData`]: crate::vendor::str0m::media::MediaData - pub is_keyframe: bool, -} - -/// AV1 packetizer -#[derive(Default, Debug)] -pub struct Av1Packetizer { - packets: Vec, - obus: Vec, -} - -impl Av1Packetizer { - fn emit(&mut self, mtu: usize, payloads: &mut Vec>) { - if self.obus.is_empty() { - return; - } - - // Clear previous frame data - self.packets.clear(); - - // Reserve 1 byte for aggregation header - let max_payload_size = mtu - AGGREGATION_HEADER_SIZE; - let mut remaining_packet_size = max_payload_size; - - // Push as many obus as possible into each packet - let mut current_packet = Packet::new(0); - for (obu_idx, obu) in self.obus.iter().enumerate() { - let mut previous_obu_extra_size = self.extra_size_for_previous_obu(¤t_packet); - let min_required_size = if current_packet.num_obu_elements >= MAX_NUM_OBUS_TO_OMTI_SIZE { - 2 - } else { - 1 - }; - - // Check if new packet is needed - if remaining_packet_size < previous_obu_extra_size + min_required_size { - self.packets.push(current_packet); - current_packet = Packet::new(obu_idx); - remaining_packet_size = max_payload_size; - previous_obu_extra_size = 0; - } - - current_packet.packet_size += previous_obu_extra_size; - current_packet.num_obu_elements += 1; - remaining_packet_size -= previous_obu_extra_size; - - let must_write_obu_element_size = current_packet.num_obu_elements > MAX_NUM_OBUS_TO_OMTI_SIZE; - let mut required_bytes = obu.size; - if must_write_obu_element_size { - required_bytes += leb_128_size(obu.size); - } - - if required_bytes <= remaining_packet_size { - current_packet.last_obu_size = obu.size; - current_packet.packet_size += required_bytes; - remaining_packet_size -= required_bytes; - continue; - } - - // Fragment the obu - let max_first_fragment_size = match must_write_obu_element_size { - true => self.max_fragment_size(remaining_packet_size), - false => remaining_packet_size, - }; - - if max_first_fragment_size == 0 { - current_packet.num_obu_elements -= 1; - current_packet.packet_size -= previous_obu_extra_size; - } else { - current_packet.packet_size += max_first_fragment_size; - if must_write_obu_element_size { - current_packet.packet_size += leb_128_size(max_first_fragment_size); - } - current_packet.last_obu_size = max_first_fragment_size; - } - - // Middle fragments - let mut obu_offset = max_first_fragment_size; - while obu_offset + max_payload_size < obu.size { - self.packets.push(current_packet); - current_packet = Packet::new(obu_idx); - current_packet.num_obu_elements = 1; - current_packet.first_obu_offset = obu_offset; - current_packet.last_obu_size = max_payload_size; - current_packet.packet_size = max_payload_size; - - obu_offset += max_payload_size - } - - // Last fragment - let last_fragment_size = obu.size - obu_offset; - self.packets.push(current_packet); - current_packet = Packet::new(obu_idx); - current_packet.num_obu_elements = 1; - current_packet.first_obu_offset = obu_offset; - current_packet.last_obu_size = last_fragment_size; - current_packet.packet_size = last_fragment_size; - - remaining_packet_size = max_payload_size - last_fragment_size; - } - - self.packets.push(current_packet); - self.write_rtp_payloads(payloads) - } - - fn write_rtp_payloads(&self, payloads: &mut Vec>) { - for (i, packet) in self.packets.iter().enumerate() { - let is_first_packet = i == 0; - let mut rtp_payload: Vec = vec![0u8; AGGREGATION_HEADER_SIZE + packet.packet_size]; - let mut pos = 0; - - let header = self.aggregation_header(packet, &self.obus, is_first_packet); - rtp_payload[pos] = header; - pos += 1; - - let mut obu_offset = packet.first_obu_offset; - // Write all obu elements except the last one - for obu_idx in 0..(packet.num_obu_elements - 1) { - let obu = &self.obus[packet.first_obu + obu_idx]; - let obu_fragment_size = obu.size - obu_offset; - pos += encode_leb_u63(obu_fragment_size as u64, &mut rtp_payload[pos..]); - - if obu_offset == 0 { - rtp_payload[pos] = obu.header & !OBU_SIZE_PRESENT_MASK; - pos += 1; - } - - if obu_offset <= 1 && obu.has_extension() { - rtp_payload[pos] = obu.ext_header; - pos += 1; - } - - let payload_offset = obu_offset.saturating_sub(if obu.has_extension() { 2 } else { 1 }); - let payload_size = obu.payload.len() - payload_offset; - - if !obu.payload.is_empty() && payload_size > 0 { - rtp_payload[pos..pos + payload_size] - .copy_from_slice(&obu.payload[payload_offset..payload_offset + payload_size]); - } - - pos += payload_size; - obu_offset = 0; - } - - let last_obu = &self.obus[packet.first_obu + packet.num_obu_elements - 1]; - let mut obu_fragment_size = packet.last_obu_size; - if packet.num_obu_elements > MAX_NUM_OBUS_TO_OMTI_SIZE { - pos += encode_leb_u63(obu_fragment_size as u64, &mut rtp_payload[pos..]); - } - - if obu_offset == 0 && obu_fragment_size > 0 { - rtp_payload[pos] = last_obu.header & !OBU_SIZE_PRESENT_MASK; - pos += 1; - obu_fragment_size -= 1; - } - - if obu_offset <= 1 && last_obu.has_extension() && obu_fragment_size > 0 { - rtp_payload[pos] = last_obu.ext_header; - pos += 1; - obu_fragment_size -= 1; - } - - let payload_offset = obu_offset.saturating_sub(if last_obu.has_extension() { 2 } else { 1 }); - rtp_payload[pos..pos + obu_fragment_size] - .copy_from_slice(&last_obu.payload[payload_offset..payload_offset + obu_fragment_size]); - - payloads.push(rtp_payload); - } - } - - fn aggregation_header(&self, packet: &Packet, obus: &[Obu], is_first_packet: bool) -> u8 { - let mut agg_header = 0; - - // set Z flag: the first obu element is the continuation of the previous one - if packet.first_obu_offset > 0 { - agg_header |= 1 << 7; - } - - // set Y flag: the last obu element is continued in the next packet - let last_obu_offset = if packet.num_obu_elements == 1 { - packet.first_obu_offset - } else { - 0 - }; - let last_obu_is_fragment = - (last_obu_offset + packet.last_obu_size) < obus[packet.first_obu + packet.num_obu_elements - 1].size; - if last_obu_is_fragment { - agg_header |= 1 << 6; - } - - // set W field: small number of obu elements in the packet - if packet.num_obu_elements <= MAX_NUM_OBUS_TO_OMTI_SIZE { - agg_header |= packet.num_obu_elements << 4; - } - - // set N flag: - if let Some(ObuType::SequenceHeader) = obus[0].obu_type() { - if is_first_packet { - agg_header |= 1 << 3; - } - } - - agg_header as u8 - } - - /// Adding new OBU to the last packet would mean that the previous one is - /// no longer the final OBU element in that packet. Any OBU that is not the - /// last element must be prefixed with its length. `extra_size_for_previous_obu` - /// computes the number of bytes required to encode that length. - fn extra_size_for_previous_obu(&self, packet: &Packet) -> usize { - if packet.packet_size == 0 { - return 0; - } - - if packet.num_obu_elements > MAX_NUM_OBUS_TO_OMTI_SIZE { - return 0; - } - - leb_128_size(packet.last_obu_size) - } - - // Given the number of free bytes remaining in a packet, the function returns the largest - // OBU fragment size that will fit into the packet - // That is, FragmentSize + Leb128Size(FragmentSize) must not exceed remaining_bytes - fn max_fragment_size(&self, size: usize) -> usize { - if size <= 1 { - return 0; - } - - let mut idx = 1; - loop { - if size < (1 << 7 * idx) + 1 { - return size - idx; - } - idx += 1; - } - } -} - -impl Packetizer for Av1Packetizer { - fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - if payload.is_empty() || mtu <= AGGREGATION_HEADER_SIZE { - return Ok(vec![]); - } - - let mut payloads = vec![]; - parse_obus(payload, &mut self.obus)?; - self.emit(mtu, &mut payloads); - - Ok(payloads) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool { - last - } -} - -/// AV1 Depacketizer -#[derive(Default, Debug)] -pub struct Av1Depacketizer { - /// current obu payload - obu_buffer: Vec, - - /// reusable buffer for parsed OBUs - parsed_obus: Vec, - - /// length of current obu - obu_length: usize, - - /// aggregation header Z bit - z: bool, - - /// aggregation header Y bit - y: bool, - - /// aggregation header N bit - n: bool, - - /// Number of obus in packet - obu_count: u8, -} - -impl Av1Depacketizer { - fn parse_aggregation_header(&mut self, agg_header: u8) { - // TODO: store these values as mask - self.z = agg_header & (1 << 7) != 0; - self.y = agg_header & (1 << 6) != 0; - self.obu_count = (agg_header & 0b0011_0000) >> 4; - self.n = agg_header & (1 << 3) != 0; - } -} - -impl Depacketizer for Av1Depacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - fn depacketize( - &mut self, - packet: &[u8], - out: &mut Vec, - codec_extra: &mut super::CodecExtra, - ) -> Result<(), PacketError> { - if packet.is_empty() { - return Err(PacketError::ErrShortPacket); - } - - let mut reader = (packet, 0); - - self.parse_aggregation_header(packet[0]); - reader.skip_bytes(1); - - // if packet does not start with a continuation of an obu fragment - // from the previous packet new obu starts - if !self.z { - self.obu_length = 0; - self.obu_buffer.clear(); - } - - // set the key frame flag if N bit is set and clear the obu buffer - // as it cannot start with a fragment of the previous packet - let mut is_keyframe = matches!(*codec_extra, CodecExtra::Av1(Av1CodecExtra { is_keyframe: true })); - if self.n { - is_keyframe = true; - self.obu_length = 0; - self.obu_buffer.clear(); - } - *codec_extra = CodecExtra::Av1(Av1CodecExtra { is_keyframe }); - - let mut obu_idx: usize = 0; - while reader.remaining_bits() > 0 { - let is_first_obu = obu_idx == 0; - let mut is_last_obu = self.obu_count != 0 && obu_idx == (self.obu_count as usize - 1); - - // Read the length of obu - let fragment_obu_length = if self.obu_count == 0 || !is_last_obu { - let len = reader.get_leb128().ok_or(PacketError::ErrAv1CorruptedPacket)?; - - if self.obu_count == 0 && len == reader.remaining_bytes() { - is_last_obu = true; - } - - len - } else { - reader.remaining_bytes() - }; - - // Safety checks - if fragment_obu_length == 0 { - return Err(PacketError::ErrAv1CorruptedPacket); - } - if reader.byte_offset() > packet.len() || fragment_obu_length > packet.len() - reader.byte_offset() { - return Err(PacketError::ErrAv1CorruptedPacket); - } - - if is_first_obu && self.z { - // the previous fragment is lost, drop the buffer - if self.obu_buffer.is_empty() { - reader.skip_bytes(fragment_obu_length); - obu_idx = 1; - continue; - } - } - - let offset = reader.byte_offset(); - self.obu_buffer - .extend_from_slice(&packet[offset..offset + fragment_obu_length]); - reader.skip_bytes(fragment_obu_length); - - if is_last_obu && self.y { - self.obu_length += fragment_obu_length; - break; - } - - self.obu_length += fragment_obu_length; - - parse_obus(&self.obu_buffer, &mut self.parsed_obus)?; - let Some(obu) = self.parsed_obus.first_mut() else { - self.obu_length = 0; - self.obu_buffer.clear(); - obu_idx += 1; - continue; - }; - - // Write the obu payload to output - // set size flag - let size_flag_set = obu.header & OBU_SIZE_PRESENT_MASK != 0; - obu.header |= OBU_SIZE_PRESENT_MASK; - out.push(obu.header); - self.obu_length = self.obu_length.saturating_sub(1); - - // add extension if any - if obu.has_extension() { - out.push(obu.ext_header); - self.obu_length = self.obu_length.saturating_sub(1); - } - - // add size if not present - if !size_flag_set { - let mut temp_space = [0u8; 9]; - let bytes_written = encode_leb_u63(self.obu_length as u64, &mut temp_space[..]); - out.extend_from_slice(&temp_space[..bytes_written]); - } - - // finally payload - if self.obu_length > self.obu_buffer.len() { - return Err(PacketError::ErrAv1CorruptedPacket); - } - let start_idx = self.obu_buffer.len() - self.obu_length; - out.extend_from_slice(&self.obu_buffer[start_idx..start_idx + self.obu_length]); - - self.obu_length = 0; - self.obu_buffer.clear(); - - if is_last_obu { - self.obu_length = 0; - self.obu_buffer.clear(); - break; - } - - obu_idx += 1; - } - - Ok(()) - } - - fn is_partition_head(&self, packet: &[u8]) -> bool { - if packet.is_empty() { - return false; - } - - // Z bit in the aggregation header is set to 0 - packet[0] & (1 << 7) == 0 - } - - fn is_partition_tail(&self, marker: bool, _payload: &[u8]) -> bool { - marker - } -} - -#[repr(u8)] -enum ObuType { - SequenceHeader = 1, - TemporalDelimiter = 2, - FrameHeader = 3, - TileGroup = 4, - MetaData = 5, - Frame = 6, - RedundantFrameHeader = 7, - TileList = 8, - Padding = 15, -} - -impl ObuType { - fn include_in_packetization(self) -> bool { - !matches!(self, Self::TemporalDelimiter | Self::TileList | Self::Padding) - } -} - -/// Represents an OBU (Open Bitstream Unit) with its header, extension, payload, and size. -#[derive(Default, Debug)] -struct Obu { - header: u8, - ext_header: u8, - payload: Vec, - size: usize, -} - -impl Obu { - fn has_extension(&self) -> bool { - (self.header & OBU_EXTENSION_PRESENT_MASK) != 0 - } - - fn has_size(&self) -> bool { - (self.header & OBU_SIZE_PRESENT_MASK) != 0 - } - - fn obu_type(&self) -> Option { - match (self.header & OBU_TYPE_MASK) >> 3 { - 1 => Some(ObuType::SequenceHeader), - 2 => Some(ObuType::TemporalDelimiter), - 3 => Some(ObuType::FrameHeader), - 4 => Some(ObuType::TileGroup), - 5 => Some(ObuType::MetaData), - 6 => Some(ObuType::Frame), - 7 => Some(ObuType::RedundantFrameHeader), - 8 => Some(ObuType::TileList), - 15 => Some(ObuType::Padding), - _ => None, - } - } -} - -/// The `Packet` struct holds information about the OBU (Open Bitstream Unit) and -/// related metadata necessary for constructing an RTP packet payload during packetization -#[derive(Debug)] -struct Packet { - first_obu: usize, - num_obu_elements: usize, - first_obu_offset: usize, - last_obu_size: usize, - packet_size: usize, -} - -impl Packet { - pub fn new(first_obu: usize) -> Self { - Packet { - first_obu, - num_obu_elements: 0, - first_obu_offset: 0, - last_obu_size: 0, - packet_size: 0, - } - } -} - -/// Returns the number of bytes required to encode a value using unsigned LEB128 encoding. -/// LEB128 uses variable-length encoding with 7 bits per byte, and this function computes -/// how many bytes are needed to represent the given `value`. -pub fn leb_128_size(mut value: usize) -> usize { - let mut size = 0; - - while value >= 0x80 { - size += 1; - value >>= 7; - } - - size + 1 -} - -/// OBU Header Structure (8 bits total): -/// -/// 0 1 2 3 4 5 6 7 -/// +-+-+-+-+-+-+-+-+ -/// |F| T |S|E|R| -/// +-+-+-+-+-+-+-+-+ -/// -/// Explanation of each bit: -/// - F (1 bit) - OBU Forbidden Bit: must be set to 0. -/// - T (4 bits) - OBU Type: This field specifies the type of data structure contained in the OBU payload. -/// - S (1 bit) - OBU Has Size Field: A flag indicating whether the obu_size syntax element will be present. -/// - E (1 bit) - OBU Extension Flag: A flag indicatin if the optional obu_extension_header is present. -/// - R (1 bit) - OBU Reserved Bits: must be set to 0. The value is ignored by a decoder. -fn parse_obus(payload: &[u8], parsed_obus: &mut Vec) -> Result<(), PacketError> { - let mut reader = (payload, 0); - let mut obu_idx = 0; - - while reader.remaining_bits() > 0 { - // Reuse existing Obu entry if available, otherwise grow the Vec - if obu_idx >= parsed_obus.len() { - parsed_obus.push(Obu::default()); - } - let obu = &mut parsed_obus[obu_idx]; - - obu.header = reader.get_u8().ok_or(PacketError::ErrAv1CorruptedPacket)?; - obu.ext_header = 0; - obu.size = 1; - - if obu.has_extension() { - obu.ext_header = reader.get_u8().ok_or(PacketError::ErrAv1CorruptedPacket)?; - obu.size += 1; - } - - // Reuse the existing payload Vec - clear preserves capacity - obu.payload.clear(); - - if obu.has_size() { - let obu_size = reader.get_leb128().ok_or(PacketError::ErrAv1CorruptedPacket)?; - if obu_size > reader.remaining_bytes() { - return Err(PacketError::ErrAv1CorruptedPacket); - } - let bytes = reader.get_bytes(obu_size).ok_or(PacketError::ErrAv1CorruptedPacket)?; - obu.payload.extend_from_slice(bytes); - } else { - obu.payload.extend_from_slice(reader.get_remaining()); - } - obu.size += obu.payload.len(); - - if let Some(obu_type) = obu.obu_type() { - if obu_type.include_in_packetization() { - obu_idx += 1; - } - } - } - - // Trim any leftover entries from previous calls - parsed_obus.truncate(obu_idx); - Ok(()) -} - -fn encode_leb_u63(mut value: u64, buf: &mut [u8]) -> usize { - let mut index = 0; - loop { - if value < 0x80 { - buf[index] = value as u8; - index += 1; - break; - } else { - buf[index] = ((value & 0x7f) | 0x80) as u8; - value >>= 7; - index += 1; - } - } - - index -} - -#[cfg(test)] -mod test { - use super::*; - - /// AV1 Packetizer tets - #[test] - fn packetize_one_frame_type_obu_without_size() { - let payload = &[0x30, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[0x10, 0x30, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]] - ); - } - - #[test] - fn packetize_one_frame_type_obu_without_size_with_extension() { - let payload = &[0x34, 0x28, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[0x10, 0x34, 0x28, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]] - ); - } - - #[test] - fn packetize_one_frame_type_obu_remove_size_field_without_extension() { - let payload = &[0x32, 0x07, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[0x10, 0x30, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11]] - ); - } - - #[test] - fn packetize_one_frame_type_obu_remove_size_field_with_extension() { - let payload = &[0x36, 0x28, 0x07, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[0x10, 0x34, 0x28, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]] - ); - } - - #[test] - fn omit_size_for_last_obu_when_three_obus_fits_into_the_packet() { - let payload = &[ - 0x0a, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // sequence header - 0x2a, 0x04, 0x0b, 0x0c, 0x0d, 0x0e, // metadata - 0x32, 0x06, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, // frame - ]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[ - 0x38, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x05, 0x28, 0x0b, 0x0c, 0x0d, 0x0e, 0x30, 0x15, - 0x16, 0x17, 0x18, 0x19, 0x1a - ]] - ); - } - - #[test] - fn use_size_for_all_obus_when_four_obus_fit_into_the_packet() { - let payload = &[ - 0x0a, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // sequence header - 0x2a, 0x04, 0x0b, 0x0c, 0x0d, 0x0e, // metadata - 0x1a, 0x03, 0x15, 0x16, 0x17, // frame - 0x22, 0x06, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, // tile group - ]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[ - 0x08, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x05, 0x28, 0x0b, 0x0c, 0x0d, 0x0e, 0x04, 0x18, - 0x15, 0x16, 0x17, 0x07, 0x20, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24 - ]] - ); - } - - #[test] - fn discards_temporal_delimiter_and_tile_list_obu() { - let payload = &[ - 0x12, 0x00, // temporal delimeter - 0x2a, 0x00, // metadata - 0x42, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // tile list - 0x1a, 0x03, 0x15, 0x16, 0x17, // frame - 0x22, 0x06, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, // tile group - ]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(1200, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - [[ - 0x30, 0x01, 0x28, 0x04, 0x18, 0x15, 0x16, 0x17, 0x20, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24 - ]] - ); - } - - #[test] - fn split_two_obus_into_two_packets_force_split_obu_header() { - let payload = &[ - 0x1e, 0x28, 0x01, 0x15, // frame - 0x26, 0x28, 0x04, 0x0b, 0x0c, 0x0d, 0x0e, // tile group - ]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(6, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - vec![ - vec![0x60, 0x03, 0x1c, 0x28, 0x15, 0x24], - vec![0x90, 0x28, 0x0b, 0x0c, 0x0d, 0x0e] - ] - ); - } - - #[test] - fn set_nbit_at_the_first_packet_of_coded_video_sequence() {} - - #[test] - fn split_single_obu_into_two_packets() { - let payload = &[0x32, 0x09, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(8, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - vec![ - vec![0x50, 0x30, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10], - vec![0x90, 0x11, 0x12, 0x13] - ] - ); - } - - #[test] - fn split_single_obu_into_many_packets() { - let mut payload: Vec = vec![0x32, 0xB0, 0x09]; // obu header and leb128 encoded size - payload.extend(vec![27u8; 1200]); // obu payload - - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(100, &payload); - - assert!(result.is_ok()); - assert_eq!(result.unwrap().len(), 13); - } - - #[test] - fn split_two_obus_into_two_packets() { - let payload = &[ - 0x0a, 0x02, 0x0b, 0x0c, // sequence header - 0x32, 0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, // frame - ]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(8, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - vec![ - vec![0x68, 0x03, 0x08, 0x0b, 0x0c, 0x30, 0x01, 0x02], - vec![0x90, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09] - ] - ); - } - - #[test] - fn split_single_obu_into_two_packets_because_of_mtu_limit() { - let payload = &[0x32, 0x09, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13]; - let mut packetizer = Av1Packetizer::default(); - - let result = packetizer.packetize(10, payload); - - assert!(result.is_ok()); - assert_eq!( - result.unwrap(), - vec![ - vec![0x50, 0x30, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12], - vec![0x90, 0x13] - ] - ); - } - - /// AV1 Depacketizer tests - #[test] - fn obu_payload_size_set_when_absent() { - let paylod = &[0x10, 0x30, 0x14, 0x1e, 0x28]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra); - - assert!(result.is_ok()); - assert_eq!(out, vec![0x32, 0x03, 0x14, 0x1e, 0x28]); - } - - #[test] - fn obu_payload_size_set_when_present() { - let paylod = &[0x10, 0x32, 0x03, 0x14, 0x1e, 0x28]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra); - - assert!(result.is_ok()); - assert_eq!(out, vec![0x32, 0x03, 0x14, 0x1e, 0x28]); - } - - #[test] - fn obu_payload_size_set_after_extension_when_absent() { - let paylod = &[0x10, 0x34, 0x48, 0x14, 0x1e, 0x28]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra); - - assert!(result.is_ok()); - assert_eq!(out, vec![0x36, 0x48, 0x03, 0x14, 0x1e, 0x28]); - } - - #[test] - fn obu_payload_size_set_after_extension_when_present() { - let paylod = &[0x10, 0x36, 0x48, 0x03, 0x14, 0x1e, 0x28]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra); - - assert!(result.is_ok()); - assert_eq!(out, vec![0x36, 0x48, 0x03, 0x14, 0x1e, 0x28]); - } - - #[test] - fn one_packet_with_two_obus() { - let paylod = &[0x20, 0x02, 0x08, 0x0a, 0x30, 0x14]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(paylod, &mut out, &mut codec_extra); - - assert!(result.is_ok()); - assert_eq!(out, vec![0x0a, 0x01, 0x0a, 0x32, 0x01, 0x14]); - } - - #[test] - fn one_obu_from_two_packets() { - let payload1 = &[0x50, 0x30, 0x14, 0x1e]; - let payload2 = &[0x90, 0x28]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra); - assert!(result.is_ok()); - - let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!(out, vec![0x32, 0x03, 0x14, 0x1e, 0x28]); - } - - #[test] - fn two_packets_with_three_obus() { - let payload1 = &[0x60, 0x02, 0x08, 0x0a, 0x30, 0x14, 0x1e]; - let payload2 = &[0x90, 0x28]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra); - assert!(result.is_ok()); - - let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!(out, vec![0x0a, 0x01, 0x0a, 0x32, 0x03, 0x14, 0x1e, 0x28]); - } - - #[test] - fn two_packets_with_many_obus_some_with_extensions() { - let payload1 = &[ - 0x40, 0x02, 0x08, 0x0a, 0x02, 0x28, 0x14, 0x04, 0x2c, 0x30, 0x14, 0x1e, 0x05, 0x34, 0x30, 0x28, 0x32, 0x3c, - ]; - let payload2 = &[0x90, 0x46, 0x50, 0x5a]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra); - assert!(result.is_ok()); - - let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!( - out, - vec![ - 0x0a, 0x01, 0x0a, 0x2a, 0x01, 0x14, 0x2e, 0x30, 0x02, 0x14, 0x1e, 0x36, 0x30, 0x06, 0x28, 0x32, 0x3c, - 0x46, 0x50, 0x5a - ] - ); - } - - #[test] - fn one_obu_from_many_packets() { - let payload1 = &[0x50, 0x30, 0x0b, 0x0c]; - let payload2 = &[0xd0, 0x0d, 0x0e]; - let payload3 = &[0xd0, 0x0f, 0x10, 0x11]; - let payload4 = &[0x90, 0x12]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(payload3, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(payload4, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!(out, vec![0x32, 0x08, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12]); - } - - #[test] - fn many_packets_with_border_aligned_obus() { - let payload1 = &[0x60, 0x03, 0x18, 0x0b, 0x0c, 0x20, 0x15, 0x16, 0x17]; - let payload2 = &[0x90, 0x18, 0x19, 0x1a, 0x1b]; - let payload3 = &[0x60, 0x03, 0x38, 0x0b, 0x0c, 0x20, 0x1f, 0x20]; - let payload4 = &[0x90, 0x21, 0x22, 0x23, 0x24]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - let result = depacketizer.depacketize(payload1, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(payload2, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(payload3, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(payload4, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!( - out, - vec![ - 0x1a, 0x02, 0x0b, 0x0c, 0x22, 0x07, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x3a, 0x02, 0x0b, 0x0c, - 0x22, 0x06, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24 - ] - ); - } - - #[test] - fn one_packet_one_obu_with_payload_size_127_bytes() { - let mut payload = [0; 131]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - payload[0] = 0b0000_0000; // aggregation header - payload[1] = 0x80; // leb128 encoded size of 128 bytes - payload[2] = 0x01; // in two bytes - payload[3] = 0b0011_0000; // obu_header with size and extension bits unset. - payload[4 + 42] = 0x42; // random - - let result = depacketizer.depacketize(&payload, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!(out[0], 0b0011_0010); // size bit set - assert_eq!(out[1], 127); // obu payloa size, 1 byte is enough - assert_eq!(out[44], 0x42); // check random byte - } - - #[test] - fn two_packets_one_obu_with_payload_size_128_bytes() { - let mut payload1 = [0; 35]; - let mut payload2 = [0; 98]; - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - - payload1[0] = 0b0100_0000; // aggregation header - payload1[1] = 33; // payload size - payload1[2] = 0b0011_0000; // obu_header with size and extension bits unset. - payload1[3 + 10] = 0x10; // random - - payload2[0] = 0b1000_0000; - payload2[1] = 96; - payload2[2 + 20] = 0x20; - - let result = depacketizer.depacketize(&payload1, &mut out, &mut codec_extra); - assert!(result.is_ok()); - let result = depacketizer.depacketize(&payload2, &mut out, &mut codec_extra); - assert!(result.is_ok()); - assert_eq!(out[0], 0b0011_0010); - assert_eq!(out[1], 0x80); - assert_eq!(out[2], 0x01); - assert_eq!(out[3 + 10], 0x10); - assert_eq!(out[3 + 32 + 20], 0x20); - } - - // Regression tests for leb_128_size boundary values. - // The bug was `value > 0x80` instead of `value >= 0x80`. - // LEB128 encodes 7 bits per byte, so values >= 128 need 2 bytes, - // values >= 16384 need 3 bytes, etc. - - #[test] - fn leb128_size_boundary_at_128() { - // 127 fits in 1 byte (7 bits), 128 needs 2 bytes - assert_eq!(leb_128_size(0), 1); - assert_eq!(leb_128_size(1), 1); - assert_eq!(leb_128_size(127), 1); - assert_eq!(leb_128_size(128), 2); // was incorrectly 1 before fix - assert_eq!(leb_128_size(129), 2); - assert_eq!(leb_128_size(255), 2); - } - - #[test] - fn leb128_size_boundary_at_16384() { - // 16383 fits in 2 bytes (14 bits), 16384 needs 3 bytes - assert_eq!(leb_128_size(16383), 2); - assert_eq!(leb_128_size(16384), 3); // was incorrectly 2 before fix - assert_eq!(leb_128_size(16385), 3); - } - - #[test] - fn leb128_size_boundary_at_2097152() { - // 2097151 fits in 3 bytes (21 bits), 2097152 needs 4 bytes - assert_eq!(leb_128_size(2097151), 3); - assert_eq!(leb_128_size(2097152), 4); // was incorrectly 3 before fix - } - - // Regression test: packetize an OBU with exactly 128 bytes of payload. - // This triggers the leb_128_size boundary (128 needs 2-byte LEB128). - // Before the fix, leb_128_size(128) returned 1 instead of 2, causing - // the output buffer to be 1 byte too small → panic on slice indexing. - #[test] - fn packetize_obu_with_128_byte_payload_no_panic() { - // Build a raw OBU: header (0x32 = frame, size present) - // + LEB128 size (0x80, 0x01 = 128) + 128 bytes payload - let mut payload = Vec::with_capacity(3 + 128); - payload.push(0x32); // OBU header: frame type, size present - payload.push(0x80); // LEB128 size byte 1: 128 - payload.push(0x01); // LEB128 size byte 2 - payload.extend(vec![0xAB; 128]); // 128 bytes of payload - - let mut packetizer = Av1Packetizer::default(); - let result = packetizer.packetize(1200, &payload); - assert!(result.is_ok()); - let packets = result.unwrap(); - assert!(!packets.is_empty()); - } - - // Regression test: packetize an OBU that requires fragmentation across - // multiple RTP packets, with exactly 128 bytes of payload. - // This exercises both the leb_128_size fix (buffer allocation) and - // the payload_offset fix (correct data in continuation fragments). - #[test] - fn packetize_128_byte_obu_fragmented_correctly() { - // OBU: header + LEB128(128) + 128 bytes payload - let mut payload = Vec::with_capacity(3 + 128); - payload.push(0x32); // frame type, size present - payload.push(0x80); // LEB128: 128 - payload.push(0x01); - for i in 0u8..128 { - payload.push(i); // distinguishable payload bytes - } - - let mut packetizer = Av1Packetizer::default(); - // MTU of 50 forces fragmentation into multiple packets - let result = packetizer.packetize(50, &payload); - assert!(result.is_ok()); - let packets = result.unwrap(); - assert!( - packets.len() >= 3, - "128-byte OBU with MTU 50 should produce at least 3 packets" - ); - - // Verify round-trip: depacketize all packets and check payload integrity - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - for pkt in &packets { - let r = depacketizer.depacketize(pkt, &mut out, &mut codec_extra); - assert!(r.is_ok(), "depacketize failed: {:?}", r); - } - // Output should be: OBU header (with size bit) + LEB128 size + payload - // Find the payload portion and verify it matches - assert!(out.len() >= 128, "round-tripped output too short: {} bytes", out.len()); - // The payload bytes should appear in order at the end - let payload_start = out.len() - 128; - for i in 0u8..128 { - assert_eq!( - out[payload_start + i as usize], - i, - "payload byte {} mismatch after round-trip", - i - ); - } - } - - // Regression test for the payload_offset bug in continuation fragments. - // When an OBU with extension header spans multiple packets, the second - // fragment used `obu_offset` instead of `payload_offset` to compute the - // remaining payload size, causing incorrect data or panics. - #[test] - fn packetize_obu_with_extension_fragmented_round_trip() { - // OBU with extension: header=0x36 (frame type + extension + size present), - // ext_header=0x10, LEB128 size, then payload - let mut raw = Vec::with_capacity(4 + 200); - raw.push(0x36); // OBU header: frame, extension present, size present - raw.push(0x10); // extension header - raw.push(0xC8); // LEB128 size: 200 - raw.push(0x01); - for i in 0u8..200 { - raw.push(i); - } - - let mut packetizer = Av1Packetizer::default(); - let result = packetizer.packetize(40, &raw); - assert!(result.is_ok()); - let packets = result.unwrap(); - assert!( - packets.len() >= 5, - "200-byte OBU with MTU 40 should produce multiple packets" - ); - - // Round-trip through depacketizer - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - let mut depacketizer = Av1Depacketizer::default(); - for pkt in &packets { - depacketizer.depacketize(pkt, &mut out, &mut codec_extra).unwrap(); - } - - // Verify the 200-byte payload is intact - let payload_start = out.len() - 200; - for i in 0u8..200 { - assert_eq!( - out[payload_start + i as usize], - i, - "extension OBU payload byte {} corrupted after round-trip", - i - ); - } - } - - #[test] - fn test_detect_av1_keyframe() { - // Empty - assert!(!detect_av1_keyframe(&[])); - - // AV1 aggregation header: Z|Y|W W|N|reserved - // N bit is bit 3 (0x08) - - // N=1 → keyframe - assert!(detect_av1_keyframe(&[0x08])); - assert!(detect_av1_keyframe(&[0x18])); // Z=0,Y=0,W=01,N=1 - assert!(detect_av1_keyframe(&[0x78])); // Z=0,Y=1,W=11,N=1 - assert!(detect_av1_keyframe(&[0x88])); // Z=1,Y=0,W=00,N=1 - assert!(detect_av1_keyframe(&[0x0F])); // N=1, reserved bits set - - // N=0 → not a keyframe - assert!(!detect_av1_keyframe(&[0x00])); - assert!(!detect_av1_keyframe(&[0x10])); // W=01, N=0 - assert!(!detect_av1_keyframe(&[0x70])); // Y=1, W=11, N=0 - assert!(!detect_av1_keyframe(&[0xF0])); // Z=1, Y=1, W=11, N=0 - } - - #[test] - fn packetize_respects_mtu() { - // OBU header (frame-type, no size field) + payload bytes. - let mut payload = vec![0x30u8]; - payload.extend(std::iter::repeat_n(0xABu8, 2000)); - for &mtu in &[100usize, 300, 600, 1200] { - let mut packetizer = Av1Packetizer::default(); - let pkts = packetizer.packetize(mtu, &payload).expect("AV1 packetize ok"); - assert!(!pkts.is_empty(), "AV1 produced no packets at mtu {mtu}"); - for (i, pkt) in pkts.iter().enumerate() { - assert!(pkt.len() <= mtu, "AV1 packet {i} size {} > mtu {mtu}", pkt.len()); - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/buffer_rx.rs b/rs/moq-webrtc/src/vendor/str0m/packet/buffer_rx.rs deleted file mode 100644 index f640ac7550c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/buffer_rx.rs +++ /dev/null @@ -1,2170 +0,0 @@ -use std::collections::VecDeque; -use std::fmt; -use std::ops::{Range, RangeInclusive}; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tracing::trace; - -use crate::vendor::str0m::rtp_::{ExtensionValues, MediaTime, RtpHeader, SenderInfo, SeqNo}; - -use super::contiguity::Contiguity; -use super::contiguity_vp8::Vp8Contiguity; -use super::contiguity_vp9::Vp9Contiguity; -use super::{CodecDepacketizer, CodecExtra, Depacketizer, PacketError}; - -// Bound incomplete frames as well as complete frames waiting for reordering. -// 4,096 packets allow roughly 5 MB of payload at a typical 1,200-byte packet size. -const MAX_BUFFERED_PACKETS: usize = 4096; - -#[derive(Clone, PartialEq, Eq)] -/// Holds metadata incoming RTP data. -pub struct RtpMeta { - /// When this RTP packet was received. - pub received: Instant, - /// Media time translated from the RtpHeader time. - pub time: MediaTime, - /// Sequence number, extended from the RTPHeader. - pub seq_no: SeqNo, - /// The actual header. - pub header: RtpHeader, - /// Sender information from the most recent Sender Report(SR). - /// - /// If no Sender Report(SR) has been received this is [`None`]. - pub last_sender_info: Option, -} - -#[derive(Clone)] -pub struct Depacketized { - pub time: MediaTime, - pub contiguous: bool, - pub meta: Vec, - pub data: Vec, - pub codec_extra: CodecExtra, -} - -impl Depacketized { - pub fn first_network_time(&self) -> Instant { - self.meta - .iter() - .map(|m| m.received) - .min() - .expect("a depacketized to consist of at least one packet") - } - - pub fn first_sender_info(&self) -> Option { - self.meta - .iter() - .min_by_key(|m| m.received) - .map(|m| m.last_sender_info) - .expect("a depacketized to consist of at least one packet") - } - - pub fn seq_range(&self) -> RangeInclusive { - let first = self - .meta - .first() - .expect("a depacketized to consist of at least one packet") - .seq_no; - let last = self - .meta - .last() - .expect("a depacketized to consist of at least one packet") - .seq_no; - first..=last - } - - pub fn start_of_talkspurt(&self) -> bool { - self.meta - .first() - .expect("a depacketized to consist of at least one packet") - .header - .marker - } - - pub fn ext_vals(&self) -> ExtensionValues { - let last = &self - .meta - .last() - .expect("depacketized video frame must contain a trailing packet") - .header - .ext_vals; - - let first = &self - .meta - .first() - .expect("depacketized video frame must contain a leading packet") - .header - .ext_vals; - - // We use the extensions from the last packet because certain extensions, such as video - // orientation, are only added on the last packet to save bytes. - let mut merged = last.clone(); - - // str0m strictly attaches some fields to the first packet of a frame. - if let Some(first_val) = &first.abs_capture_time { - merged.abs_capture_time = Some(*first_val); - } - - merged - } -} - -#[derive(Debug)] -struct Entry { - meta: RtpMeta, - data: Arc<[u8]>, - head: bool, - tail: bool, -} - -#[derive(Debug, Clone, Copy)] -enum LastProcessed { - /// The cutoff advanced without a frame timeout, including depacketization errors. - Advanced(SeqNo), - /// An incomplete frame expired; the next emitted frame has a discontinuity. - Expired(SeqNo), -} - -impl LastProcessed { - fn seq_no(self) -> SeqNo { - match self { - Self::Advanced(seq_no) | Self::Expired(seq_no) => seq_no, - } - } - - fn with_seq_no(self, seq_no: SeqNo) -> Self { - match self { - Self::Advanced(_) => Self::Advanced(seq_no), - Self::Expired(_) => Self::Expired(seq_no), - } - } -} - -#[derive(Debug)] -pub struct DepacketizingBuffer { - hold_back: usize, - - // Session supplies the recovery deadline for video. None means keep waiting. - wait_for_recovery: bool, - recovery_deadline: Option, - depack: CodecDepacketizer, - queue: VecDeque, - // Segment indices are relative to the queue at the last rebuild. - segments: VecDeque<(usize, usize, Instant)>, - segments_dirty: bool, - segments_offset: usize, - #[cfg(test)] - segment_rebuilds: usize, - last_processed: Option, - max_time: Option, - depack_cache: Option<(Range, Depacketized)>, - contiguity: Contiguity, -} - -impl DepacketizingBuffer { - pub(crate) fn new(depack: CodecDepacketizer, hold_back: usize) -> Self { - let contiguity = match depack { - CodecDepacketizer::Vp8(_) => Contiguity::Vp8(Vp8Contiguity::new()), - CodecDepacketizer::Vp9(_) => Contiguity::Vp9(Vp9Contiguity::new()), - CodecDepacketizer::H264(_) - | CodecDepacketizer::H265(_) - | CodecDepacketizer::Av1(_) - | CodecDepacketizer::Boxed(_) - | CodecDepacketizer::Opus(_) - | CodecDepacketizer::AmrWb(_) - | CodecDepacketizer::Null(_) => Contiguity::None, - }; - - DepacketizingBuffer { - hold_back, - wait_for_recovery: false, - recovery_deadline: None, - depack, - queue: VecDeque::new(), - segments: VecDeque::new(), - segments_dirty: false, - segments_offset: 0, - #[cfg(test)] - segment_rebuilds: 0, - last_processed: None, - max_time: None, - depack_cache: None, - contiguity, - } - } - - pub fn push(&mut self, meta: RtpMeta, data: impl Into>) { - self.push_entry(meta, data.into(), None); - } - - pub(crate) fn push_padding(&mut self, meta: RtpMeta) { - self.push_entry(meta, Arc::from([]), Some((false, false))); - } - - fn push_entry(&mut self, meta: RtpMeta, data: Arc<[u8]>, partition: Option<(bool, bool)>) { - // We're not emitting frames in the wrong order. If we receive - // packets that are before the last emitted, we drop. - // - // As a special case, per popular demand, if hold_back is 0, we do emit - // out of order packets. - if let Some(last) = self.last_processed.map(LastProcessed::seq_no) { - if meta.seq_no <= last && self.hold_back > 0 { - trace!("Drop before emitted: {} <= {}", meta.seq_no, last); - return; - } - } - - // Record that latest seen max time (used for extending time to u64). - self.max_time = Some(if let Some(m) = self.max_time { - m.max(meta.time) - } else { - meta.time - }); - - match self.queue.binary_search_by_key(&meta.seq_no, |r| r.meta.seq_no) { - Ok(_) => { - // exact same seq_no found. ignore - trace!("Drop exactly same packet: {}", meta.seq_no); - } - Err(mut i) => { - if self.queue.len() == MAX_BUFFERED_PACKETS { - if i == 0 { - // This packet is older than everything we can retain. - return; - } - self.queue.pop_front(); - self.depack_cache = None; - i -= 1; - } - - let (head, tail) = partition.unwrap_or_else(|| { - ( - self.depack.is_partition_head(data.as_ref()), - self.depack.is_partition_tail(meta.header.marker, data.as_ref()), - ) - }); - - // i is insertion point to maintain order - let entry = Entry { meta, data, head, tail }; - self.queue.insert(i, entry); - self.segments_dirty = true; - - // The depack cache is keyed by queue index. Inserting at or before the cached - // segment shifts it, so the cache would answer for the wrong packets. - if let Some((range, _)) = &self.depack_cache { - if i <= range.end { - self.depack_cache = None; - } - } - } - } - } - - /// The next complete candidate and the sequence range it would skip. - pub(crate) fn recovery_candidate(&mut self) -> Option<(Range, Instant)> { - self.update_segments(); - let (start, received) = self.segments.iter().find_map(|&(start, stop, received)| { - self.queue[stop - self.segments_offset] - .tail - .then_some((start - self.segments_offset, received)) - })?; - if start == 0 - && !matches!(self.last_processed, Some(LastProcessed::Expired(_))) - && self.is_following_last(start) - { - return None; - } - let first = self.last_processed.map_or(self.queue.front()?.meta.seq_no, |last| { - (*last.seq_no()).saturating_add(1).into() - }); - Some((first..self.queue[start].meta.seq_no, received)) - } - - pub(crate) fn set_recovery_deadline(&mut self, deadline: Option) { - self.wait_for_recovery = true; - self.recovery_deadline = deadline; - } - - pub fn pop( - &mut self, - now: Instant, - reordering_timeout: Option, - ) -> Option> { - loop { - let queued = self.queue.len(); - let result = self.pop_frame(now, reordering_timeout); - let count_only = !self.wait_for_recovery && reordering_timeout.is_none(); - let queue_unchanged = self.queue.len() == queued; - if result.is_some() || count_only || queue_unchanged { - return result; - } - // A discarded frame must not leave later frames waiting for new input. - } - } - - fn pop_frame( - &mut self, - now: Instant, - reordering_timeout: Option, - ) -> Option> { - self.update_segments(); - - if self.wait_for_recovery || reordering_timeout.is_some() { - if let Some((end, first_received)) = self.first_incomplete_frame() { - if self.timeout_allows_progress(now, first_received, reordering_timeout) { - let last = self.queue[end - 1].meta.seq_no; - self.queue.drain(0..end); - self.segments_dirty = true; - self.depack_cache = None; - self.last_processed = Some(LastProcessed::Expired(last)); - } - return None; - } - } - - if self.segments.is_empty() { - self.discard_old_padding(); - return None; - } - - // println!( - // "{:?} {:?}", - // self.queue.iter().map(|e| e.meta.seq_no).collect::>(), - // self.segments - // ); - - let (start, stop, first_received) = self.first_segment().expect("segment exists"); - - // A timestamp change can delimit a frame without a tail marker. Keep - // that fallback for count-only mode, but with a timeout the oldest - // frame must expire before any later frame is considered. - if (self.wait_for_recovery || reordering_timeout.is_some()) && !self.queue[stop].tail { - if self.timeout_allows_progress(now, first_received, reordering_timeout) { - let last = self.queue[stop].meta.seq_no; - self.consume_segment(stop); - self.last_processed = Some(LastProcessed::Expired(last)); - } - return None; - } - - let seq = { - let last = self.queue.get(stop).expect("entry for stop index"); - last.meta.seq_no - }; - - // If we have contiguity of seq numbers we emit right away, - // Otherwise, we wait for retransmissions up to `hold_back` frames - // and re-evaluate contiguity based on codec specific information - - let more_than_hold_back = self.segments.len() >= self.hold_back; - let expired = matches!(self.last_processed, Some(LastProcessed::Expired(_))); - let contiguous_seq = !expired && self.is_following_last(start); - let wait_for_contiguity = !contiguous_seq - && !more_than_hold_back - && !self.timeout_allows_progress(now, first_received, reordering_timeout); - - // VP8 and VP9 picture-ID width changes must be extended in RTP order. - // Wait before parsing so a later frame cannot advance the counters first. - let ordered_counters = matches!(self.depack, CodecDepacketizer::Vp8(_) | CodecDepacketizer::Vp9(_)); - if wait_for_contiguity && ordered_counters { - self.discard_old_padding(); - return None; - } - - // depack ahead, even if we may not emit right away - let mut dep = match self.depacketize(start, stop, seq) { - Ok(d) => d, - Err(e) => { - // this segment cannot be decoded correctly - // remove from the queue and return the error - self.last_processed = Some(LastProcessed::Advanced(seq)); - self.consume_segment(stop); - return Some(Err(e)); - } - }; - - if wait_for_contiguity { - // if we are not sending, cache the depacked - self.depack_cache = Some((start..stop, dep)); - self.discard_old_padding(); - return None; - } - - let (can_emit, contiguous_codec) = self.contiguity.check(&dep.codec_extra, contiguous_seq); - dep.contiguous = contiguous_codec && !expired; - - let last = self.queue.get(stop).expect("entry for stop index").meta.seq_no; - - // We're not going to emit frames in the incorrect order, there's no point in keeping - // stuff before the emitted range. - self.consume_segment(stop); - - if !can_emit { - if ordered_counters { - // Keep the counters in RTP order after committing a rejected range. - self.last_processed = Some( - self.last_processed - .map_or(LastProcessed::Advanced(last), |p| p.with_seq_no(last)), - ); - } - return None; - } - - self.last_processed = Some(LastProcessed::Advanced(last)); - - Some(Ok(dep)) - } - - pub(crate) fn poll_timeout(&mut self, reordering_timeout: Option) -> Option { - self.update_segments(); - if self.wait_for_recovery { - return self.recovery_deadline; - } - let timeout = reordering_timeout?; - - if let Some((_, first_received)) = self.first_incomplete_frame() { - return first_received.checked_add(timeout); - } - - let (start, stop, first_received) = self.first_segment()?; - - if !self.queue[stop].tail { - return first_received.checked_add(timeout); - } - - let contiguous_seq = - !matches!(self.last_processed, Some(LastProcessed::Expired(_))) && self.is_following_last(start); - let more_than_hold_back = self.segments.len() >= self.hold_back; - if contiguous_seq || more_than_hold_back { - return None; - } - - // No representable input time can reach a deadline beyond Instant's range. - first_received.checked_add(timeout) - } - - fn discard_old_padding(&mut self) { - let original_len = self.queue.len(); - let is_padding = |entry: &Entry| entry.data.is_empty() && !entry.head && !entry.tail; - - if let Some(processed) = self.last_processed { - let mut last = processed.seq_no(); - while self.queue.len() > self.hold_back { - let entry = self.queue.front().expect("queue exceeds hold back"); - if !is_padding(entry) { - break; - } - - if last.is_next(entry.meta.seq_no) { - last = entry.meta.seq_no; - } - self.queue.pop_front(); - } - - self.last_processed = Some(processed.with_seq_no(last)); - } - - // An incomplete frame can remain at the front while another payload type - // contributes synthetic padding indefinitely. Keep the frame, but retain - // only the newest padding needed for the reordering window. Padding removed - // from behind media cannot advance last_processed across that media. - let mut excess_padding = self - .queue - .iter() - .filter(|entry| is_padding(entry)) - .count() - .saturating_sub(self.hold_back); - self.queue.retain(|entry| { - if excess_padding > 0 && is_padding(entry) { - excess_padding -= 1; - false - } else { - true - } - }); - - if self.queue.len() != original_len { - self.segments_dirty = true; - self.depack_cache = None; - } - } - - fn timeout_allows_progress( - &self, - now: Instant, - first_received: Instant, - reordering_timeout: Option, - ) -> bool { - if self.wait_for_recovery { - return self.recovery_deadline.is_some_and(|deadline| now >= deadline); - } - let Some(timeout) = reordering_timeout else { - return false; - }; - - now.checked_duration_since(first_received) - .is_some_and(|age| age >= timeout) - } - - fn depacketize(&mut self, start: usize, stop: usize, _seq: SeqNo) -> Result { - if let Some(cached) = self.depack_cache.take() { - if cached.0 == (start..stop) { - trace!("depack cache hit for segment start {}", start); - return Ok(cached.1); - } - } - - let packets_size = self.queue.range(start..=stop).map(|p| p.data.len()).sum(); - let mut data = self - .depack - .out_size_hint(packets_size) - .map(Vec::with_capacity) - .unwrap_or_else(Vec::new); - let mut codec_extra = CodecExtra::None; - - let time = self.queue.get(start).expect("first index exist").meta.time; - let mut meta = Vec::with_capacity(stop - start + 1); - - for entry in self.queue.range_mut(start..=stop) { - self.depack.depacketize(&entry.data, &mut data, &mut codec_extra)?; - meta.push(entry.meta.clone()); - } - - Ok(Depacketized { - time, - contiguous: true, // the caller taking ownership will modify this accordingly - meta, - data, - codec_extra, - }) - } - - fn first_segment(&self) -> Option<(usize, usize, Instant)> { - self.segments - .front() - .map(|&(start, stop, received)| (start - self.segments_offset, stop - self.segments_offset, received)) - } - - /// The oldest received frame that has no complete segment yet. Its end is - /// exclusive, so later frames remain queued when it expires. - fn first_incomplete_frame(&self) -> Option<(usize, Instant)> { - let first_media = self - .queue - .iter() - .position(|entry| !entry.data.is_empty() || entry.head || entry.tail)?; - let next_complete = self - .first_segment() - .map(|(start, _, _)| start) - .unwrap_or(self.queue.len()); - if first_media >= next_complete { - return None; - } - - let time = self.queue[first_media].meta.time; - let end = (first_media + 1..next_complete) - .find(|&index| self.queue[index].meta.time != time) - .unwrap_or(next_complete); - let first_received = self - .queue - .range(first_media..end) - .map(|entry| entry.meta.received) - .min()?; - Some((end, first_received)) - } - - fn consume_segment(&mut self, stop: usize) { - if self.queue[stop].tail { - // A following candidate needs its own deadline from Session. - self.recovery_deadline = None; - } - // Removing the first segment leaves later boundaries intact. Advance the - // index origin instead of rescanning packets or shifting every segment. - self.queue.drain(0..=stop); - self.segments.pop_front(); - self.segments_offset += stop + 1; - } - - fn update_segments(&mut self) { - if !self.segments_dirty { - return; - } - self.segments_dirty = false; - self.segments_offset = 0; - #[cfg(test)] - { - self.segment_rebuilds += 1; - } - self.segments.clear(); - - #[derive(Clone, Copy)] - struct Start { - index: i64, - time: MediaTime, - offset: i64, - first_received: Instant, - } - - let mut start: Option = None; - - for (index, entry) in self.queue.iter().enumerate() { - let index = index as i64; - let iseq = *entry.meta.seq_no as i64; - let expected_seq = start.map(|s| s.offset.saturating_add(index)); - - let is_expected_seq = expected_seq == Some(iseq); - let is_same_timestamp = start.map(|s| s.time) == Some(entry.meta.time); - let is_defacto_tail = is_expected_seq && !is_same_timestamp; - - if start.is_some() && is_defacto_tail { - // We found a segment that ended because the timestamp changed without - // a gap in the sequence number. The marker bit in the RTP packet is - // just indicative, this is the robust fallback. - let s = start.unwrap(); - let segment = (s.index as usize, index as usize - 1, s.first_received); - self.segments.push_back(segment); - start = None; - } - - if start.is_some() && (!is_expected_seq || !is_same_timestamp) { - // Not contiguous. Start looking again. - start = None; - } - - // Each segment can have multiple is_partition_head() == true, record the first. - if start.is_none() && entry.head { - start = Some(Start { - index, - time: entry.meta.time, - offset: iseq.saturating_sub(index), - first_received: entry.meta.received, - }); - } - - if let Some(s) = start.as_mut() { - s.first_received = s.first_received.min(entry.meta.received); - } - - if start.is_some() && entry.tail { - // We found a contiguous sequence of packets ending with something from - // the packet (like the RTP marker bit) indicating it's the tail. - let s = start.unwrap(); - let segment = (s.index as usize, index as usize, s.first_received); - self.segments.push_back(segment); - start = None; - } - } - } - - fn is_following_last(&self, start: usize) -> bool { - let Some(last) = self.last_processed.map(LastProcessed::seq_no) else { - // First time we emit something. - return true; - }; - - // track sequence numbers are sequential - let mut seq = last; - - // Expect all entries before start to be padding. - for entry in self.queue.range(0..start) { - if !seq.is_next(entry.meta.seq_no) { - // Not a sequence - return false; - } - // for next loop round. - seq = entry.meta.seq_no; - - let is_padding = entry.data.is_empty() && !entry.head && !entry.tail; - if !is_padding { - return false; - } - } - - let start_entry = self.queue.get(start).expect("entry for start index"); - - seq.is_next(start_entry.meta.seq_no) - } -} - -impl fmt::Debug for RtpMeta { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RtpMeta") - .field("received", &self.received) - .field("time", &self.time) - .field("seq_no", &self.seq_no) - .field("header", &self.header) - .finish() - } -} - -impl fmt::Debug for Depacketized { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Depacketized") - .field("time", &self.time) - .field("meta", &self.meta) - .field("data", &self.data.len()) - .finish() - } -} - -#[cfg(test)] -mod test { - use std::time::{Duration, Instant, SystemTime}; - - use super::*; - use crate::vendor::str0m::packet::Vp8Depacketizer; - use crate::vendor::str0m::packet::vp9::Vp9Depacketizer; - use crate::vendor::str0m::rtp_::{AbsCaptureTime, Frequency, MediaTime, Pt, Ssrc, VideoOrientation}; - - fn bounded_queue_meta(seq: u64) -> RtpMeta { - RtpMeta { - received: Instant::now(), - seq_no: seq.into(), - time: MediaTime::from_90khz(seq), - last_sender_info: None, - header: RtpHeader::default(), - } - } - - #[test] - fn incomplete_frames_cannot_grow_queue_forever() { - for hold_back in [0, 3] { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp8(Default::default()), hold_back); - for i in 0..MAX_BUFFERED_PACKETS * 2 { - // Frame heads with gaps and no tails never form a complete segment. - buf.push(bounded_queue_meta((i * 2) as u64), [0x10, 0]); - assert!(buf.pop(Instant::now(), None).is_none()); - } - assert!(buf.queue.len() <= MAX_BUFFERED_PACKETS); - - // A new complete keyframe must still get through after the overflow. - let seq = (MAX_BUFFERED_PACKETS * 4) as u64; - let mut meta = bounded_queue_meta(seq); - meta.header.marker = true; - buf.push(meta, [0x10, 0]); - let frame = buf.pop(Instant::now(), None).unwrap().unwrap(); - assert_eq!(*frame.seq_range().start(), seq.into()); - } - } - - #[test] - fn queue_overflow_discards_cached_frame_and_preserves_gap() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), MAX_BUFFERED_PACKETS); - buf.push(bounded_queue_meta(1), [1, 1, 9]); - assert!(buf.pop(Instant::now(), None).unwrap().unwrap().contiguous); - buf.push(bounded_queue_meta(3), [1, 3, 9]); - assert!(buf.pop(Instant::now(), None).is_none()); - assert!(buf.depack_cache.is_some()); - - // Fill without polling. Evict the cached frame when the queue overflows. - for seq in 4..=MAX_BUFFERED_PACKETS as u64 + 3 { - buf.push(bounded_queue_meta(seq), [1, 4, 9]); - } - assert_eq!(buf.queue.len(), MAX_BUFFERED_PACKETS); - let frame = buf.pop(Instant::now(), None).unwrap().unwrap(); - assert_eq!(*frame.seq_range().start(), 4.into()); - assert_eq!(frame.data, [1, 4, 9]); - assert!(!frame.contiguous); - } - - #[test] - fn full_queue_ignores_older_packets_and_duplicates() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - for seq in 2..=MAX_BUFFERED_PACKETS as u64 + 1 { - buf.push(bounded_queue_meta(seq), [0]); - } - buf.push(bounded_queue_meta(1), [0]); - buf.push(bounded_queue_meta(2), [0]); - assert_eq!(buf.queue.len(), MAX_BUFFERED_PACKETS); - assert_eq!(buf.queue.front().unwrap().meta.seq_no, 2.into()); - assert_eq!( - buf.queue.back().unwrap().meta.seq_no, - (MAX_BUFFERED_PACKETS as u64 + 1).into() - ); - } - - #[test] - fn end_on_marker() { - test(&[ - // - (1, 1, &[1], &[]), - (2, 1, &[9], &[(1, &[1, 9])]), - ]) - } - - #[test] - fn late_packet_in_front_of_waiting_frame() { - // Seq 3 is late. Seq 4 arrives first and waits for contiguity (it is depacketized ahead - // and cached). When 3 then arrives it is inserted in front of 4, and both must come out - // as themselves: 3 must not be emitted with 4's data. - test_n( - 15, - &[ - (1, 1, &[1, 1, 9], &[(1, &[1, 1, 9])]), - (2, 2, &[1, 2, 9], &[(2, &[1, 2, 9])]), - (4, 4, &[1, 4, 9], &[]), - (3, 3, &[1, 3, 9], &[(3, &[1, 3, 9]), (4, &[1, 4, 9])]), - ], - ) - } - - #[test] - fn ext_vals_extracts_from_first_and_last_packet() { - let first_time = Instant::now(); - let abs_capture_time = AbsCaptureTime { - capture_time: SystemTime::UNIX_EPOCH + Duration::from_secs(1), - clock_offset: None, - }; - - let first_header = RtpHeader { - version: 2, - has_padding: false, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: Pt::new_with_value(98), - sequence_number: 1, - timestamp: 100, - ssrc: Ssrc::from(42), - csrc: [0; 15], - ext_vals: ExtensionValues { - abs_capture_time: Some(abs_capture_time), - ..Default::default() - }, - header_len: 0, - }; - - let last_header = RtpHeader { - ext_vals: ExtensionValues { - video_orientation: Some(VideoOrientation::Deg90), - ..Default::default() - }, - ..first_header.clone() - }; - - let time_value = 100_u64; - let dep = Depacketized { - time: MediaTime::new(time_value, Frequency::new(90000).unwrap()), - contiguous: true, - meta: vec![ - RtpMeta { - received: first_time, - time: MediaTime::new(time_value, Frequency::new(90000).unwrap()), - seq_no: SeqNo::from(1u64), - header: first_header, - last_sender_info: None, - }, - RtpMeta { - received: first_time + Duration::from_millis(1), - time: MediaTime::new(time_value, Frequency::new(90000).unwrap()), - seq_no: SeqNo::from(2u64), - header: last_header, - last_sender_info: None, - }, - ], - data: Vec::new(), - codec_extra: CodecExtra::None, - }; - - let merged = dep.ext_vals(); - assert_eq!( - merged.abs_capture_time.unwrap().capture_time, - abs_capture_time.capture_time - ); - assert_eq!(merged.video_orientation, Some(VideoOrientation::Deg90)); - } - - #[test] - fn end_on_defacto() { - test(&[(1, 1, &[1], &[]), (2, 1, &[2], &[]), (3, 2, &[3], &[(1, &[1, 2])])]) - } - - #[test] - fn skip_padding() { - test(&[ - (1, 1, &[1], &[]), - (2, 1, &[9], &[(1, &[1, 9])]), - (3, 1, &[], &[]), // padding! - (4, 2, &[1], &[]), - (5, 2, &[9], &[(2, &[1, 9])]), - ]) - } - - #[test] - fn gap_after_emit() { - test(&[ - (1, 1, &[1], &[]), - (2, 1, &[9], &[(1, &[1, 9])]), - // gap - (4, 2, &[1], &[]), - (5, 2, &[9], &[]), - ]) - } - - #[test] - fn gap_after_padding() { - test(&[ - (1, 1, &[1], &[]), - (2, 1, &[9], &[(1, &[1, 9])]), - (3, 1, &[], &[]), // padding! - // gap - (5, 2, &[1], &[]), - (6, 2, &[9], &[]), - ]) - } - - #[test] - fn single_packets() { - test(&[ - (1, 1, &[1, 9], &[(1, &[1, 9])]), - (2, 2, &[1, 9], &[(2, &[1, 9])]), - (3, 3, &[1, 9], &[(3, &[1, 9])]), - (4, 4, &[1, 9], &[(4, &[1, 9])]), - ]) - } - - #[test] - fn packets_out_of_order() { - test(&[ - (1, 1, &[1], &[]), - (2, 1, &[9], &[(1, &[1, 9])]), - (4, 2, &[9], &[]), - (3, 2, &[1], &[(2, &[1, 9])]), - ]) - } - - #[test] - fn packets_after_hold_out() { - test(&[ - (1, 1, &[1, 9], &[(1, &[1, 9])]), - (3, 3, &[1, 9], &[]), - (4, 4, &[1, 9], &[]), - (5, 5, &[1, 9], &[(3, &[1, 9]), (4, &[1, 9]), (5, &[1, 9])]), - ]) - } - - #[test] - fn packets_with_hold_0() { - test0(&[ - (1, 1, &[1, 9], &[(1, &[1, 9])]), - (3, 3, &[1, 9], &[(3, &[1, 9])]), - (4, 4, &[1, 9], &[(4, &[1, 9])]), - (5, 5, &[1, 9], &[(5, &[1, 9])]), - ]) - } - - #[test] - fn out_of_order_packets_with_hold_0() { - test0(&[ - (3, 1, &[1, 9], &[(1, &[1, 9])]), - (1, 3, &[1, 9], &[(3, &[1, 9])]), - (5, 4, &[1, 9], &[(4, &[1, 9])]), - (2, 5, &[1, 9], &[(5, &[1, 9])]), - ]) - } - - #[test] - fn padding_only_run_does_not_grow_the_queue_without_bound() { - let depack = CodecDepacketizer::Boxed(Box::new(TestDepack)); - let mut buf = DepacketizingBuffer::new(depack, 3); - let meta = |seq: u64| RtpMeta { - received: Instant::now(), - seq_no: seq.into(), - time: MediaTime::from_90khz(seq), - last_sender_info: None, - header: RtpHeader { - sequence_number: seq as u16, - timestamp: seq as u32, - ..Default::default() - }, - }; - - // Emit one packet for this PT, then model a long run on another PT. - buf.push(meta(1), vec![1, 9]); - assert!(buf.pop(Instant::now(), None).is_some()); - - for seq in 2..=1_001 { - buf.push_padding(meta(seq)); - assert!(buf.pop(Instant::now(), None).is_none()); - } - - assert!( - buf.queue.len() <= buf.hold_back, - "padding-only queue retained {} entries after a 1,000-packet run", - buf.queue.len() - ); - - // Returning to this PT after compaction must still be contiguous with the last packet. - buf.push(meta(1_002), vec![1, 9]); - let dep = buf - .pop(Instant::now(), None) - .expect("packet emitted") - .expect("valid packet"); - assert!(dep.contiguous); - } - - #[test] - fn padding_only_run_with_loss_stays_bounded_and_reports_discontinuity() { - let depack = CodecDepacketizer::Boxed(Box::new(TestDepack)); - let mut buf = DepacketizingBuffer::new(depack, 3); - let meta = |seq: u64| RtpMeta { - received: Instant::now(), - seq_no: seq.into(), - time: MediaTime::from_90khz(seq), - last_sender_info: None, - header: RtpHeader { - sequence_number: seq as u16, - timestamp: seq as u32, - ..Default::default() - }, - }; - - buf.push(meta(1), vec![1, 9]); - assert!(buf.pop(Instant::now(), None).is_some()); - - // Sequence 2 is lost while another PT remains active. - for seq in 3..=1_002 { - buf.push_padding(meta(seq)); - assert!(buf.pop(Instant::now(), None).is_none()); - } - - assert!(buf.queue.len() <= buf.hold_back); - - // A discontinuity waits for the normal hold-back before it is emitted. - buf.push(meta(1_003), vec![1, 9]); - assert!(buf.pop(Instant::now(), None).is_none()); - buf.push(meta(1_004), vec![1, 9]); - assert!(buf.pop(Instant::now(), None).is_none()); - buf.push(meta(1_005), vec![1, 9]); - let dep = buf - .pop(Instant::now(), None) - .expect("packet emitted") - .expect("valid packet"); - assert!(!dep.contiguous); - } - - #[test] - fn padding_after_incomplete_vp8_frame_does_not_grow_without_bound() { - let depack = CodecDepacketizer::Vp8(Default::default()); - let mut buf = DepacketizingBuffer::new(depack, 3); - let meta = |seq: u64, marker: bool| RtpMeta { - received: Instant::now(), - seq_no: seq.into(), - time: MediaTime::from_90khz(seq), - last_sender_info: None, - header: RtpHeader { - marker, - sequence_number: seq as u16, - timestamp: seq as u32, - ..Default::default() - }, - }; - - // Emit one complete VP8 frame for this PT. - buf.push(meta(1, true), [0x10, 0x00]); - assert!(buf.pop(Instant::now(), None).is_some()); - - // The next frame's head is lost, leaving an S=0 fragment at the front. - buf.push(meta(2, false), [0x00]); - assert!(buf.pop(Instant::now(), None).is_none()); - - // The sender switches PT. Every packet becomes synthetic padding here. - for seq in 3..=1_002 { - buf.push_padding(meta(seq, false)); - assert!(buf.pop(Instant::now(), None).is_none()); - } - - assert!( - buf.queue.len() <= buf.hold_back + 1, - "incomplete VP8 frame retained {} entries after a 1,000-packet PT switch", - buf.queue.len() - ); - } - - #[test] - fn padding_after_waiting_vp8_frame_does_not_grow_without_bound() { - let depack = CodecDepacketizer::Vp8(Default::default()); - let mut buf = DepacketizingBuffer::new(depack, 3); - let meta = |seq: u64, marker: bool| RtpMeta { - received: Instant::now(), - seq_no: seq.into(), - time: MediaTime::from_90khz(seq), - last_sender_info: None, - header: RtpHeader { - marker, - sequence_number: seq as u16, - timestamp: seq as u32, - ..Default::default() - }, - }; - - buf.push(meta(1, true), [0x10, 0x00]); - assert!(buf.pop(Instant::now(), None).is_some()); - - // Lose a frame head, then switch away long enough to compact its padding. - buf.push(meta(2, false), [0x00]); - assert!(buf.pop(Instant::now(), None).is_none()); - for seq in 3..=1_002 { - buf.push_padding(meta(seq, false)); - assert!(buf.pop(Instant::now(), None).is_none()); - } - - // One complete frame returns, but waits behind the orphan for hold-back. - buf.push(meta(1_003, true), [0x10, 0x00]); - assert!(buf.pop(Instant::now(), None).is_none()); - - // Switching away again must remain bounded while that frame waits. - for seq in 1_004..=2_003 { - buf.push_padding(meta(seq, false)); - assert!(buf.pop(Instant::now(), None).is_none()); - } - - assert!( - buf.queue.len() <= buf.hold_back + 2, - "waiting VP8 frame retained {} entries after a second 1,000-packet PT switch", - buf.queue.len() - ); - } - - #[test] - fn padding_after_initial_incomplete_vp8_frame_does_not_grow_without_bound() { - let depack = CodecDepacketizer::Vp8(Default::default()); - let mut buf = DepacketizingBuffer::new(depack, 3); - let meta = |seq: u64| RtpMeta { - received: Instant::now(), - seq_no: seq.into(), - time: MediaTime::from_90khz(seq), - last_sender_info: None, - header: RtpHeader { - sequence_number: seq as u16, - timestamp: seq as u32, - ..Default::default() - }, - }; - - // Start observing this PT after the head of a VP8 frame was lost. - buf.push(meta(1), [0x00]); - assert!(buf.pop(Instant::now(), None).is_none()); - - // The sender switches PT before this depayloader has emitted anything. - for seq in 2..=1_001 { - buf.push_padding(meta(seq)); - assert!(buf.pop(Instant::now(), None).is_none()); - } - - assert!( - buf.queue.len() <= buf.hold_back + 1, - "initial incomplete VP8 frame retained {} entries after a 1,000-packet PT switch", - buf.queue.len() - ); - } - - fn test_meta(base: Instant, seq: u64, time: u64, received_ms: u64) -> RtpMeta { - RtpMeta { - received: base + Duration::from_millis(received_ms), - time: MediaTime::from_90khz(time), - seq_no: seq.into(), - last_sender_info: None, - header: RtpHeader { - sequence_number: seq as u16, - timestamp: time as u32, - ..Default::default() - }, - } - } - - /// Repeated output/deadline polls share a scan; consuming frames retains the suffix. - #[test] - fn segment_cache_reuses_scans_until_packet_insertion() { - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 300); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - for seq in 3..103 { - buf.push(test_meta(base, seq, seq, 100), [1, 9]); - } - let deadline = base + Duration::from_millis(350); - assert!(buf.pop(base + Duration::from_millis(100), timeout).is_none()); - let scans = buf.segment_rebuilds; - for _ in 0..10 { - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - assert!(buf.pop(base + Duration::from_millis(100), timeout).is_none()); - } - assert_eq!(buf.segment_rebuilds, scans); - for seq in 3..103 { - let dep = buf.pop(deadline, timeout).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), seq); - assert_eq!(dep.contiguous, seq != 3); - assert_eq!(buf.poll_timeout(timeout), None); - } - assert_eq!(buf.segment_rebuilds, scans); - assert!(buf.pop(deadline, timeout).is_none()); - - // An out-of-order insertion must replace a cached blocked candidate. - buf.push(test_meta(base, 104, 104, 400), [1, 9]); - assert!(buf.pop(deadline, timeout).is_none()); - buf.push(test_meta(base, 103, 103, 400), [1, 9]); - for seq in [103, 104] { - let dep = buf.pop(base + Duration::from_millis(400), timeout).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), seq); - assert!(dep.contiguous); - } - assert_eq!(buf.segment_rebuilds, scans + 2); - } - - #[test] - fn segment_cache_ignores_duplicate_and_old_packets() { - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - buf.push(test_meta(base, 3, 3, 100), [1, 9]); - let deadline = base + Duration::from_millis(350); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - let scans = buf.segment_rebuilds; - - for seq in [3, 1, 0] { - buf.push(test_meta(base, seq, seq, 200), [1, 9]); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - assert!(buf.pop(base + Duration::from_millis(200), timeout).is_none()); - assert_eq!(buf.segment_rebuilds, scans); - } - let dep = buf.pop(deadline, timeout).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), 3); - assert!(!dep.contiguous); - assert_eq!(buf.segment_rebuilds, scans); - } - - #[test] - fn segment_cache_preserves_frames_after_depacketization_error() { - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - let mut buf = DepacketizingBuffer::new(crate::vendor::str0m::format::Codec::H264.into(), 3); - for (seq, payload) in [(1, [0x7e, 0xaa]), (2, [0x61, 0xaa])] { - let mut meta = test_meta(base, seq, seq, 0); - meta.header.marker = true; - buf.push(meta, payload); - } - assert_eq!(buf.poll_timeout(timeout), None); - let scans = buf.segment_rebuilds; - assert!(buf.pop(base, timeout).unwrap().is_err()); - assert_eq!(buf.poll_timeout(timeout), None); - let dep = buf.pop(base, timeout).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), 2); - assert!(dep.contiguous); - assert!(buf.pop(base, timeout).is_none()); - assert_eq!(buf.segment_rebuilds, scans); - } - - /// Test disabled-timeout polling preserves padding cleanup after frame emission or an error. - #[test] - fn timeout_none_preserves_padding_cleanup_after_emit_and_error() { - let base = Instant::now(); - for (payload, valid) in [([0x61, 0xaa], true), ([0x7e, 0xaa], false)] { - let mut buf = DepacketizingBuffer::new(crate::vendor::str0m::format::Codec::H264.into(), 3); - let mut meta = test_meta(base, 1, 1, 0); - meta.header.marker = true; - buf.push(meta, payload); - for seq in 2..=6 { - buf.push_padding(test_meta(base, seq, 1, 0)); - } - - assert_eq!(buf.pop(base, None).unwrap().is_ok(), valid); - assert_eq!(buf.queue.len(), 5); - assert_eq!(*buf.last_processed.unwrap().seq_no(), 1); - assert_eq!(buf.poll_timeout(None), None); - assert_eq!(buf.queue.len(), 5); - - // Cleanup runs on the next poll, which has no frame to process. - let scans = buf.segment_rebuilds; - assert!(buf.pop(base, None).is_none()); - assert_eq!(buf.queue.len(), 3); - assert_eq!(*buf.last_processed.unwrap().seq_no(), 3); - assert_eq!(buf.segment_rebuilds, scans); - - // Compaction invalidates indices; the next poll rebuilds exactly once. - for _ in 0..3 { - assert!(buf.pop(base, None).is_none()); - assert_eq!(buf.segment_rebuilds, scans + 1); - } - } - } - - /// Test an unrepresentable deadline neither panics nor releases a frame early. - #[test] - fn timeout_deadline_beyond_instant_range_does_not_panic() { - let base = Instant::now(); - let (mut low, mut high) = (0, u64::MAX); - while low < high { - let mid = low + (high - low) / 2 + 1; - if base.checked_add(Duration::from_secs(mid)).is_some() { - low = mid; - } else { - high = mid - 1; - } - } - let anchor = base.checked_add(Duration::from_secs(low)).unwrap(); - let timeout = Some(Duration::from_secs(600)); - assert!(anchor.checked_add(timeout.unwrap()).is_none()); - - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - buf.push(test_meta(anchor, 3, 3, 0), [1, 9]); - assert!(buf.pop(anchor, timeout).is_none()); - assert_eq!(buf.poll_timeout(timeout), None); - assert!(buf.pop(anchor, Some(Duration::ZERO)).unwrap().is_ok()); - } - - /// Test a zero timeout does not release a candidate before its packet receipt time. - #[test] - fn timeout_zero_does_not_expire_before_packet_receipt() { - let base = Instant::now(); - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, None).unwrap().unwrap(); - buf.push(test_meta(base, 3, 3, 100), [1, 9]); - assert!(buf.pop(base, Some(Duration::ZERO)).is_none()); - assert_eq!( - buf.poll_timeout(Some(Duration::ZERO)), - Some(base + Duration::from_millis(100)) - ); - } - - /// A zero timeout drops an incomplete frame immediately; a later complete frame survives. - #[test] - fn timeout_zero_drops_incomplete_then_emits_later_complete_frame() { - let depack = CodecDepacketizer::Boxed(Box::new(TestDepack)); - let mut buf = DepacketizingBuffer::new(depack, 3); - let base = Instant::now(); - - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - let dep = buf.pop(base, Some(Duration::ZERO)).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), 1); - assert!(dep.contiguous); - - buf.push(test_meta(base, 2, 2, 100), [1]); - assert!( - buf.pop(base + Duration::from_millis(100), Some(Duration::ZERO)) - .is_none() - ); - assert!(buf.queue.is_empty()); - - buf.push(test_meta(base, 4, 4, 200), [1]); - buf.push(test_meta(base, 5, 4, 200), [9]); - let dep = buf - .pop(base + Duration::from_millis(200), Some(Duration::ZERO)) - .expect("frame emitted") - .expect("valid frame"); - assert_eq!(**dep.seq_range().start(), 4); - assert_eq!(**dep.seq_range().end(), 5); - assert!(!dep.contiguous); - assert!(buf.queue.is_empty()); - assert_eq!(buf.hold_back, 3); - buf.push(test_meta(base, 3, 2, 300), [9]); - assert!( - buf.queue.is_empty(), - "zero timeout must not allow late packets to backtrack" - ); - assert_eq!(buf.poll_timeout(Some(Duration::ZERO)), None); - } - - /// Test multi-packet deadlines start at the earliest receipt, not frame completion. - #[test] - fn timeout_uses_earliest_packet_receipt_for_multi_packet_frame() { - for complete_ms in [200, 400] { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - assert!(buf.pop(base, None).unwrap().unwrap().contiguous); - - buf.push(test_meta(base, 3, 3, 100), [1]); - let deadline = base + Duration::from_millis(350); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - assert!(buf.pop(deadline - Duration::from_nanos(1), timeout).is_none()); - - if complete_ms < 350 { - buf.push(test_meta(base, 4, 3, complete_ms), [9]); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - assert!(buf.pop(deadline - Duration::from_nanos(1), timeout).is_none()); - // Neither duplicates nor subsequent padding restart the anchor. - buf.push(test_meta(base, 3, 3, 300), [1]); - buf.push_padding(test_meta(base, 5, 5, 300)); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - let dep = buf.pop(deadline, timeout).unwrap().unwrap(); - assert_eq!((**dep.seq_range().start(), **dep.seq_range().end()), (3, 4)); - assert!(!dep.contiguous); - } else { - assert!(buf.pop(deadline, timeout).is_none()); - assert!(buf.queue.is_empty()); - buf.push(test_meta(base, 4, 3, complete_ms), [9]); - assert_eq!( - buf.poll_timeout(timeout), - Some(base + Duration::from_millis(complete_ms + 250)) - ); - assert!( - buf.pop(base + Duration::from_millis(complete_ms + 250), timeout) - .is_none() - ); - assert_eq!(buf.poll_timeout(timeout), None); - } - assert_eq!(buf.poll_timeout(timeout), None); - } - } - - /// An earlier incomplete frame expires before a later complete frame with reordered receipts. - #[test] - fn timeout_uses_earliest_receipt_with_reordered_packets() { - for received_ms in [[100, 200, 150], [200, 100, 150], [200, 150, 100]] { - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - buf.push(test_meta(base, 2, 2, 25), [1]); - - let mut packets = [ - (test_meta(base, 4, 3, received_ms[0]), [1]), - (test_meta(base, 5, 3, received_ms[1]), [2]), - (test_meta(base, 6, 3, received_ms[2]), [9]), - ]; - packets.sort_by_key(|(meta, _)| meta.received); - for (meta, data) in packets { - buf.push(meta, data); - } - - let deadline = base + Duration::from_millis(275); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - assert!(buf.pop(deadline - Duration::from_nanos(1), timeout).is_none()); - assert!(buf.pop(deadline, timeout).is_none()); - assert_eq!(buf.poll_timeout(timeout), Some(base + Duration::from_millis(350))); - let dep = buf.pop(base + Duration::from_millis(350), timeout).unwrap().unwrap(); - assert_eq!((**dep.seq_range().start(), **dep.seq_range().end()), (4, 6)); - assert_eq!(dep.data, [1, 2, 9]); - assert_eq!(dep.first_network_time(), base + Duration::from_millis(100)); - assert!(!dep.contiguous); - assert_eq!(buf.poll_timeout(timeout), None); - } - } - - /// The next frame's timeout wins even when a later complete frame arrived earlier. - #[test] - fn timeout_drops_only_oldest_incomplete_frame() { - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - - buf.push(test_meta(base, 5, 4, 50), [1, 9]); - assert_eq!(buf.poll_timeout(timeout), Some(base + Duration::from_millis(300))); - buf.push(test_meta(base, 3, 3, 100), [1]); - buf.push(test_meta(base, 4, 3, 150), [2]); - - let deadline = base + Duration::from_millis(350); - assert_eq!(buf.poll_timeout(timeout), Some(deadline)); - assert!(buf.pop(deadline - Duration::from_nanos(1), timeout).is_none()); - let dep = buf.pop(deadline, timeout).unwrap().unwrap(); - assert_eq!((**dep.seq_range().start(), **dep.seq_range().end()), (5, 5)); - assert_eq!(dep.data, [1, 9]); - assert_eq!(dep.first_network_time(), base + Duration::from_millis(50)); - assert!(!dep.contiguous); - assert!(buf.pop(deadline, timeout).is_none()); - assert_eq!(buf.poll_timeout(timeout), None); - } - - #[test] - fn timeout_preserves_each_later_frame_until_its_own_deadline() { - let base = Instant::now(); - let timeout = Some(Duration::from_millis(250)); - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(TestDepack)), 3); - buf.push(test_meta(base, 1, 1, 0), [1]); - buf.push(test_meta(base, 2, 2, 100), [1]); - buf.push(test_meta(base, 3, 3, 200), [1, 9]); - - assert_eq!(buf.poll_timeout(timeout), Some(base + Duration::from_millis(250))); - assert!(buf.pop(base + Duration::from_millis(250), timeout).is_none()); - assert_eq!( - buf.queue.iter().map(|entry| *entry.meta.seq_no).collect::>(), - [2, 3] - ); - assert_eq!(buf.poll_timeout(timeout), Some(base + Duration::from_millis(350))); - assert!(buf.pop(base + Duration::from_millis(350), timeout).is_none()); - assert_eq!( - buf.queue.iter().map(|entry| *entry.meta.seq_no).collect::>(), - [3] - ); - assert_eq!(buf.poll_timeout(timeout), Some(base + Duration::from_millis(450))); - let frame = buf.pop(base + Duration::from_millis(450), timeout).unwrap().unwrap(); - assert_eq!((**frame.seq_range().start(), **frame.seq_range().end()), (3, 3)); - assert!(!frame.contiguous); - } - - /// Test a disabled timeout keeps count-based release. - #[test] - fn timeout_disabled_preserves_count_release() { - let depack = CodecDepacketizer::Boxed(Box::new(TestDepack)); - let mut buf = DepacketizingBuffer::new(depack, 3); - let base = Instant::now(); - - let timeout = None; - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - buf.push(test_meta(base, 3, 3, 100), [1, 9]); - assert!(buf.pop(base + Duration::from_millis(100), timeout).is_none()); - assert_eq!(buf.poll_timeout(None), None); - assert!(buf.pop(base + Duration::from_secs(1), None).is_none()); - for seq in 4..=5 { - buf.push(test_meta(base, seq, seq, 1000), [1, 9]); - } - let dep = buf.pop(base + Duration::from_secs(1), None).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), 3); - assert!(!dep.contiguous); - } - - /// Test the count threshold can release a blocked frame before its deadline. - #[test] - fn timeout_count_limit_can_win_before_deadline() { - let depack = CodecDepacketizer::Boxed(Box::new(TestDepack)); - let mut buf = DepacketizingBuffer::new(depack, 3); - let base = Instant::now(); - - let timeout = Some(Duration::from_secs(1)); - buf.push(test_meta(base, 1, 1, 0), [1, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - for seq in 3..=5 { - buf.push(test_meta(base, seq, seq, 100), [1, 9]); - } - let dep = buf.pop(base + Duration::from_millis(100), timeout).unwrap().unwrap(); - assert_eq!(**dep.seq_range().start(), 3); - assert!(!dep.contiguous); - } - - /// Test codec rejection retries the next candidate only when the timeout is enabled. - #[test] - fn timeout_codec_rejection_makes_progress() { - #[derive(Debug)] - struct LayerDepack; - impl Depacketizer for LayerDepack { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - fn depacketize( - &mut self, - packet: &[u8], - out: &mut Vec, - extra: &mut CodecExtra, - ) -> Result<(), PacketError> { - out.extend_from_slice(packet); - *extra = CodecExtra::Vp8(super::super::Vp8CodecExtra { - picture_id: Some(packet[1].into()), - tl0_picture_id: Some(packet[2].into()), - layer_index: packet[3], - discardable: false, - sync: false, - is_keyframe: false, - }); - Ok(()) - } - fn is_partition_head(&self, packet: &[u8]) -> bool { - TestDepack.is_partition_head(packet) - } - fn is_partition_tail(&self, marker: bool, packet: &[u8]) -> bool { - TestDepack.is_partition_tail(marker, packet) - } - } - - for timeout in [None, Some(Duration::ZERO), Some(Duration::from_millis(250))] { - let base = Instant::now(); - let hold_back = if timeout.is_none() { 2 } else { 30 }; - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Boxed(Box::new(LayerDepack)), hold_back); - buf.contiguity = Contiguity::Vp8(Vp8Contiguity::new()); - buf.push(test_meta(base, 1, 1, 0), [1, 1, 1, 0, 9]); - buf.pop(base, timeout).unwrap().unwrap(); - buf.push(test_meta(base, 3, 3, 100), [1, 3, 1, 1, 9]); - buf.push(test_meta(base, 4, 4, 100), [1, 4, 2, 0, 9]); - let due = base + Duration::from_millis(100) + timeout.unwrap_or_default(); - if timeout.is_none() { - for seq in 5..=9 { - buf.push_padding(test_meta(base, seq, seq, 100)); - } - assert!(buf.pop(due, None).is_none()); - assert_eq!(*buf.queue.front().unwrap().meta.seq_no, 4); - assert_eq!(buf.queue.len(), 6); - assert_eq!(*buf.last_processed.unwrap().seq_no(), 1); - continue; - } - buf.update_segments(); - let scans = buf.segment_rebuilds; - let dep = buf.pop(due, timeout).expect("drain past codec-rejected frame").unwrap(); - assert_eq!(**dep.seq_range().start(), 4); - assert_eq!(buf.segment_rebuilds, scans, "codec rejection must reuse segments"); - assert!(buf.queue.is_empty()); - assert_eq!(buf.poll_timeout(timeout), None); - } - } - - fn test( - v: &[( - u64, // seq - u64, // time - &[u8], // data - &[( - u64, // time - &[u8], // depacketized data - )], - )], - ) { - test_n(3, v) - } - - fn test0( - v: &[( - u64, // seq - u64, // time - &[u8], // data - &[( - u64, // time - &[u8], // depacketized data - )], - )], - ) { - test_n(0, v) - } - - fn test_n( - hold_back: usize, - v: &[( - u64, // seq - u64, // time - &[u8], // data - &[( - u64, // time - &[u8], // depacketized data - )], - )], - ) { - let depack = CodecDepacketizer::Boxed(Box::new(TestDepack)); - let mut buf = DepacketizingBuffer::new(depack, hold_back); - - for (step, (seq, time, data, checks)) in (1..).zip(v.iter()) { - let meta = RtpMeta { - received: Instant::now(), - seq_no: (*seq).into(), - time: MediaTime::from_90khz(*time), - last_sender_info: None, - header: RtpHeader { - sequence_number: *seq as u16, - timestamp: *time as u32, - ..Default::default() - }, - }; - - buf.push(meta, data.to_vec()); - - let mut depacks = vec![]; - while let Some(res) = buf.pop(Instant::now(), None) { - let d = res.unwrap(); - depacks.push(d); - } - - assert_eq!( - depacks.len(), - checks.len(), - "Step {}: check count not matching {} != {}", - step, - depacks.len(), - checks.len() - ); - - let iter = depacks.into_iter().zip(checks.iter()); - - for (depack, (dtime, ddata)) in iter { - assert_eq!( - depack.time.numer(), - *dtime, - "Step {}: Time not matching {} != {}", - step, - depack.time.numer(), - *dtime - ); - - assert_eq!( - depack.data, *ddata, - "Step {}: Data not correct {:?} != {:?}", - step, depack.data, *ddata - ); - } - } - } - - #[derive(Debug)] - struct TestDepack; - - impl Depacketizer for TestDepack { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, _: &mut CodecExtra) -> Result<(), PacketError> { - out.extend_from_slice(packet); - Ok(()) - } - - fn is_partition_head(&self, packet: &[u8]) -> bool { - !packet.is_empty() && packet[0] == 1 - } - - fn is_partition_tail(&self, _marker: bool, packet: &[u8]) -> bool { - !packet.is_empty() && packet.contains(&9) - } - } - - #[test] - fn rtp_out_of_order() { - let construct_input = |(time, seq, marker, cc, data): (u32, u16, bool, u16, Vec)| -> (RtpMeta, Vec) { - ( - RtpMeta { - received: Instant::now(), - time: MediaTime::new(time.into(), Frequency::new(90000).unwrap()), - seq_no: SeqNo::from(seq as u64), - header: RtpHeader { - version: 2, - has_padding: false, - has_extension: true, - csrc_count: 0, - marker, - payload_type: Pt::new_with_value(98), - sequence_number: seq, - timestamp: time, - ssrc: Ssrc::from(2930203832), - csrc: [0; 15], - ext_vals: ExtensionValues { - transport_cc: Some(cc), - ..Default::default() - }, - header_len: 28, - }, - last_sender_info: None, - }, - data, - ) - }; - - let inputs = [ - // PID: 23860 - ( - 821395241, // Timestamp - 8685, // SeqN - false, // Marker - 56, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([236, 221, 52, 80, 26, 10, 1, 1, 1, 1, 1, 1, 1, 1]), // Data - ), - // PID: 23860 - ( - 821395241, // Timestamp - 8686, // SeqN - true, // Marker - 57, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([237, 221, 52, 83, 26, 10, 2, 2, 2, 2, 2, 2, 2, 2]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8687, // SeqN - false, // Marker - 60, // Transport CC - // VP9 header--------+ - // | - // +------------------------+ - Vec::from([170, 221, 53, 16, 27, 56, 20, 0, 0, 0, 0, 0, 0, 0, 0]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8688, // SeqN - false, // Marker - 61, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([160, 221, 53, 16, 27, 20, 1, 1, 1, 1, 1, 1, 1, 1]), // Data - ), - // PID: 23861 - ( - 821398481, - 8689, - false, - 62, - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([164, 221, 53, 16, 27, 20, 2, 2, 2, 2, 2, 2, 2, 2]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8690, // SeqN - false, // Marker - 63, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([169, 221, 53, 19, 27, 20, 3, 3, 3, 3, 3, 3, 3, 3]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8691, // SeqN - false, // Marker - 64, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([161, 221, 53, 19, 27, 20, 4, 4, 4, 4, 4, 4, 4, 4]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8692, // SeqN - false, // Marker - 65, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([161, 221, 53, 19, 27, 20, 5, 5, 5, 5, 5, 5, 5, 5]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8693, // SeqN - false, // Marker - 66, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([161, 221, 53, 19, 27, 20, 6, 6, 6, 6, 6, 6, 6, 6]), // Data - ), - // PID: 23861 - ( - 821398481, // Timestamp - 8694, // SeqN - true, // Marker - 67, // Transport CC - // VP9 header--------+ - // | - // +--------------------+ - Vec::from([165, 221, 53, 19, 27, 20, 7, 7, 7, 7, 7, 7, 7, 7]), // Data - ), - ]; - - let mut buffer = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 30); - - for input in &inputs { - let (meta, data) = construct_input(input.clone()); - buffer.push(meta, data); - } - - let now = Instant::now(); - let res0before = buffer.pop(now, None).unwrap().unwrap(); // Pop PID: 23860, `contiguous_seq == true`. - let res1before = buffer.pop(now, None).unwrap().unwrap(); // Pop PID: 23861, `contiguous_seq == true`. - - let mut buffer = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 30); - - for input in &inputs { - let (meta, data) = construct_input(input.clone()); - if meta.seq_no == SeqNo::from(8689) { - continue; // Skip RTP packet with seq_num=8689 vp9_payload=[20, 2, 2, 2, 2, 2, 2, 2, 2]. - } - buffer.push(meta.clone(), data.clone()); - } - - // Pop PID: 23860, `contiguous_seq == true`. - let res0after = buffer.pop(now, None).unwrap().unwrap(); - // Try to pop PID: 23861. `None` because `contiguous_seq == false` -- no seq_num=8689. - assert!(buffer.pop(now, None).is_none()); - assert!(buffer.pop(now, None).is_none()); // Ensure once again. - - for input in &inputs { - let (meta, data) = construct_input(input.clone()); - if meta.seq_no == SeqNo::from(8689) { - // Send RTP packet with seq_num=8689 vp9_payload=[20, 2, 2, 2, 2, 2, 2, 2, 2]. - buffer.push(meta.clone(), data.clone()); - break; - } - } - - let res1after = buffer.pop(now, None).unwrap().unwrap(); - - assert_eq!(res0before.data, res0after.data); - assert_eq!(res1before.data, res1after.data); - } - - #[test] - fn vp9_late_enhancement_before_picture_id_width_change() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 3); - let now = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, packet: &[u8]| { - let mut meta = test_meta(now, seq, seq * 3000, 0); - meta.header.marker = true; - buf.push(meta, packet); - }; - let pop = |buf: &mut DepacketizingBuffer, expected: u64| { - let dep = buf.pop(now, None).expect("frame must be emitted").unwrap(); - let CodecExtra::Vp9(extra) = dep.codec_extra else { - panic!("expected VP9 codec extra"); - }; - assert_eq!(extra.picture_id, Some(expected)); - assert!(dep.contiguous); - }; - - // Base picture 0x1bbe, followed by two enhancement pictures on the same TL0. - push(&mut buf, 0, &[0xAC, 0x9B, 0xBE, 0x00, 10, 0x80]); - pop(&mut buf, 0x1BBE); - - // The sender truncates the 15-bit counter to 7 bits on picture 0x1bc0. - push(&mut buf, 2, &[0xEC, 0x40, 0x20, 10, 0x84]); - assert!(buf.pop(now, None).is_none()); - assert!(buf.pop(now, None).is_none()); - - // The missing enhancement still has a 15-bit ID and must remain decodable. - push(&mut buf, 1, &[0xEC, 0x9B, 0xBF, 0x20, 10, 0x84]); - pop(&mut buf, 0x1BBF); - pop(&mut buf, 0x1BC0); - - // Growing the wire ID again must retain the truncated high bits. - push(&mut buf, 3, &[0xEC, 0x80, 0x41, 0x20, 10, 0x84]); - pop(&mut buf, 0x1BC1); - } - - #[test] - fn vp9_discards_late_enhancement_after_rejected_width_change() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 3); - let now = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, packet: &[u8]| { - let mut meta = test_meta(now, seq, seq * 3000, 0); - meta.header.marker = true; - buf.push(meta, packet); - }; - - push(&mut buf, 0, &[0xAC, 0x9B, 0xBE, 0x00, 10, 0x80]); - assert!(buf.pop(now, None).unwrap().unwrap().contiguous); - - // The missing enhancement still has a 15-bit ID. Later enhancements - // use 7 bits and fill the hold-back window, so picture 0x1bc0 is parsed - // and rejected because its predecessor has not arrived. - for seq in 2..=4 { - push(&mut buf, seq, &[0xEC, 0x3E + seq as u8, 0x20, 10, 0x84]); - } - assert!(buf.pop(now, None).is_none()); - assert_eq!(*buf.last_processed.unwrap().seq_no(), 2); - - // Rejecting the later picture closes its RTP range, so this older - // enhancement is discarded without rewinding the counters. - push(&mut buf, 1, &[0xEC, 0x9B, 0xBF, 0x20, 10, 0x84]); - assert_eq!(*buf.queue.front().unwrap().meta.seq_no, 3); - assert!(buf.pop(now, Some(Duration::ZERO)).is_none()); - assert!(buf.queue.is_empty()); - - // A following base frame and its enhancement retain the correct IDs. - for (seq, pid, tid, expected) in [(5, 0x43, 0, 0x1BC3), (6, 0x44, 1, 0x1BC4)] { - push(&mut buf, seq, &[0xEC, 0x80, pid, tid << 5, 11, 0x84]); - let dep = buf.pop(now, None).unwrap().unwrap(); - let CodecExtra::Vp9(extra) = dep.codec_extra else { - panic!("expected VP9 codec extra"); - }; - assert_eq!(extra.picture_id, Some(expected)); - assert!(dep.contiguous); - } - } - - #[test] - fn vp9_rejection_preserves_pending_timeout_discontinuity() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 3); - let now = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, packet: &[u8], marker: bool| { - let mut meta = test_meta(now, seq, seq * 3000, 0); - meta.header.marker = marker; - buf.push(meta, packet); - }; - - push(&mut buf, 0, &[0xAC, 1, 0x00, 1, 0x80], true); - assert!(buf.pop(now, None).unwrap().unwrap().contiguous); - push(&mut buf, 1, &[0xE8, 2, 0x00, 2, 0x84], false); - push(&mut buf, 3, &[0xEC, 4, 0x20, 1, 0x84], true); - push(&mut buf, 4, &[0xEC, 5, 0x00, 2, 0x84], true); - - // Expire the incomplete frame and reject the dependent enhancement. - // Advancing the cutoff must retain the timeout's discontinuity. - let dep = buf.pop(now, Some(Duration::ZERO)).unwrap().unwrap(); - assert_eq!(*dep.meta[0].seq_no, 4); - assert!(!dep.contiguous); - - push(&mut buf, 5, &[0xEC, 6, 0x20, 2, 0x84], true); - assert!(buf.pop(now, None).unwrap().unwrap().contiguous); - } - - /// X=1 S=1, I=1 L=1 T=1, picture id, tl0picidx, TID - fn vp8_packet(keyframe: bool, picture_id: &[u8], tid: u8, tl0_pic_idx: u8) -> Vec { - let mut packet = vec![0x90, 0xE0]; - packet.extend_from_slice(picture_id); - packet.extend_from_slice(&[tl0_pic_idx, tid << 6, u8::from(!keyframe)]); - packet - } - - #[test] - fn vp8_late_enhancement_before_picture_id_width_change() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp8(Vp8Depacketizer::default()), 3); - let now = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, packet: Vec| { - let mut meta = test_meta(now, seq, seq * 3000, 0); - meta.header.marker = true; - buf.push(meta, packet); - }; - let pop = |buf: &mut DepacketizingBuffer, expected: u64| { - let dep = buf.pop(now, None).expect("frame must be emitted").unwrap(); - let CodecExtra::Vp8(extra) = dep.codec_extra else { - panic!("expected VP8 codec extra"); - }; - assert_eq!(extra.picture_id, Some(expected)); - assert!(dep.contiguous); - }; - - // Base picture 0x1bbe, followed by two enhancement pictures on the same TL0. - push(&mut buf, 0, vp8_packet(true, &[0x9B, 0xBE], 0, 10)); - pop(&mut buf, 0x1BBE); - - // The sender truncates the 15-bit counter to 7 bits on picture 0x1bc0. - push(&mut buf, 2, vp8_packet(false, &[0x40], 1, 10)); - assert!(buf.pop(now, None).is_none()); - assert!(buf.pop(now, None).is_none()); - - // The missing enhancement still has a 15-bit ID and must remain decodable. - push(&mut buf, 1, vp8_packet(false, &[0x9B, 0xBF], 1, 10)); - pop(&mut buf, 0x1BBF); - pop(&mut buf, 0x1BC0); - - // Growing the wire ID again must retain the truncated high bits. - push(&mut buf, 3, vp8_packet(false, &[0x80, 0x41], 1, 10)); - pop(&mut buf, 0x1BC1); - } - - #[test] - fn vp8_discards_late_enhancement_after_rejected_width_change() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp8(Vp8Depacketizer::default()), 3); - let now = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, packet: Vec| { - let mut meta = test_meta(now, seq, seq * 3000, 0); - meta.header.marker = true; - buf.push(meta, packet); - }; - - push(&mut buf, 0, vp8_packet(true, &[0x9B, 0xBE], 0, 10)); - assert!(buf.pop(now, None).unwrap().unwrap().contiguous); - - // The missing enhancement still has a 15-bit ID. Later enhancements - // use 7 bits and fill the hold-back window, so picture 0x1bc0 is parsed - // and rejected because its predecessor has not arrived. - for seq in 2..=4 { - push(&mut buf, seq, vp8_packet(false, &[0x3E + seq as u8], 1, 10)); - } - assert!(buf.pop(now, None).is_none()); - assert_eq!(*buf.last_processed.unwrap().seq_no(), 2); - - // Rejecting the later picture closes its RTP range, so this older - // enhancement is discarded without rewinding the counters. - push(&mut buf, 1, vp8_packet(false, &[0x9B, 0xBF], 1, 10)); - assert_eq!(*buf.queue.front().unwrap().meta.seq_no, 3); - assert!(buf.pop(now, Some(Duration::ZERO)).is_none()); - assert!(buf.queue.is_empty()); - - // A following base frame and its enhancement retain the correct IDs. - for (seq, pid, tid, expected) in [(5, 0x43, 0, 0x1BC3), (6, 0x44, 1, 0x1BC4)] { - push(&mut buf, seq, vp8_packet(false, &[0x80, pid], tid, 11)); - let dep = buf.pop(now, None).unwrap().unwrap(); - let CodecExtra::Vp8(extra) = dep.codec_extra else { - panic!("expected VP8 codec extra"); - }; - assert_eq!(extra.picture_id, Some(expected)); - assert!(dep.contiguous); - } - } - - #[test] - fn vp8_rejection_preserves_pending_timeout_discontinuity() { - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp8(Vp8Depacketizer::default()), 3); - let now = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, packet: Vec, marker: bool| { - let mut meta = test_meta(now, seq, seq * 3000, 0); - meta.header.marker = marker; - buf.push(meta, packet); - }; - - push(&mut buf, 0, vp8_packet(true, &[1], 0, 1), true); - assert!(buf.pop(now, None).unwrap().unwrap().contiguous); - push(&mut buf, 1, vp8_packet(false, &[2], 0, 2), false); - push(&mut buf, 3, vp8_packet(false, &[4], 1, 1), true); - push(&mut buf, 4, vp8_packet(false, &[5], 0, 2), true); - - // Expire the incomplete frame and reject the dependent enhancement. - // Advancing the cutoff must retain the timeout's discontinuity. - let dep = buf.pop(now, Some(Duration::ZERO)).unwrap().unwrap(); - assert_eq!(*dep.meta[0].seq_no, 4); - assert!(!dep.contiguous); - - push(&mut buf, 5, vp8_packet(false, &[6], 1, 2), true); - assert!(buf.pop(now, None).unwrap().unwrap().contiguous); - } - - #[test] - fn vp9_late_frame_before_picture_id_wrap() { - fn frame(pid: u16, tl0: u8) -> [u8; 6] { - // I=1 P=1 L=1 B=1 E=1, 15-bit picture id, TID=0, tl0picidx - [0xEC, 0x80 | (pid >> 8) as u8, pid as u8, 0x00, tl0, 0x84] - } - fn picture_id(dep: &Depacketized) -> Option { - let CodecExtra::Vp9(extra) = dep.codec_extra else { - panic!("expected VP9 codec extra"); - }; - extra.picture_id - } - - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 3); - let base = Instant::now(); - let push = |buf: &mut DepacketizingBuffer, seq: u64, data: [u8; 6]| { - let mut meta = test_meta(base, seq, seq * 3000, 0); - meta.header.marker = true; - buf.push(meta, data); - }; - - push(&mut buf, 0, frame(0x7FFE, 254)); - let dep = buf.pop(base, None).unwrap().unwrap(); - assert_eq!(picture_id(&dep), Some(0x7FFE)); - - // The frame after the wrap waits while the late frame is missing. - push(&mut buf, 2, frame(0, 0)); - assert!(buf.pop(base, None).is_none()); - - push(&mut buf, 1, frame(0x7FFF, 255)); - let dep = buf.pop(base, None).unwrap().unwrap(); - assert_eq!(picture_id(&dep), Some(0x7FFF)); - assert!(dep.contiguous); - - let dep = buf.pop(base, None).unwrap().unwrap(); - assert_eq!(picture_id(&dep), Some(0x8000)); - assert!(dep.contiguous); - - push(&mut buf, 3, frame(1, 1)); - let dep = buf.pop(base, None).unwrap().unwrap(); - assert_eq!(picture_id(&dep), Some(0x8001)); - assert!(dep.contiguous); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/contiguity.rs b/rs/moq-webrtc/src/vendor/str0m/packet/contiguity.rs deleted file mode 100644 index dbe51e18524..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/contiguity.rs +++ /dev/null @@ -1,106 +0,0 @@ -use super::CodecExtra; -use super::contiguity_vp8::Vp8Contiguity; -use super::contiguity_vp9::Vp9Contiguity; -use tracing::{debug, warn}; - -#[derive(Debug)] -pub enum Contiguity { - Vp8(Vp8Contiguity), - Vp9(Vp9Contiguity), - None, -} - -impl Contiguity { - pub fn check(&mut self, next: &CodecExtra, contiguous_seq: bool) -> (bool, bool) { - match (self, next) { - (Self::Vp8(contiguity), CodecExtra::Vp8(next)) => contiguity.check(next, contiguous_seq), - (Self::Vp9(contiguity), CodecExtra::Vp9(next)) => contiguity.check(next, contiguous_seq), - (Self::Vp8(_) | Self::Vp9(_) | Self::None, _) => (true, contiguous_seq), - } - } -} - -#[derive(Debug)] -pub(crate) struct FrameContiguityState { - /// last picture id of layer 0 that we allowed emitting - pub(crate) last_picture_id: Option, - - /// last picture id of any layer that we allowed emitting - pub(crate) last_tl0_picture_id: Option, -} - -impl FrameContiguityState { - /// Returns whether we can emit such frame and whether it's decodable with contiguity - pub(crate) fn next_frame( - &mut self, - picture_id: Option, - tl0_picture_id: Option, - layer_index: Option, - is_keyframe: bool, - contiguous_seq: bool, - ) -> (bool, bool) { - let Some(picture_id) = picture_id else { - // picture id is not enabled or not progressing anyway - return (true, contiguous_seq); - }; - - let Some(tl0_picture_id) = tl0_picture_id else { - return (true, contiguous_seq); - }; - - let (Some(last_tl0_picture_id), Some(last_picture_id)) = (self.last_tl0_picture_id, self.last_picture_id) - else { - self.last_tl0_picture_id = Some(tl0_picture_id); - self.last_picture_id = Some(picture_id); - return (true, true); - }; - - // A new encoder can keep the SSRC while restarting picture IDs. A keyframe - // is independently decodable, so it can establish a fresh baseline. - if is_keyframe && picture_id <= last_picture_id { - self.last_tl0_picture_id = Some(tl0_picture_id); - self.last_picture_id = Some(picture_id); - return (true, false); - } - - // discard older pictures if any - if picture_id <= last_picture_id { - return (false, true); - } - - if layer_index == Some(0) { - if tl0_picture_id == last_tl0_picture_id { - warn!( - "VP8 or VP9: 2 subsequent frames on layer zero must \ - have different tl0 picture id: encoding problem?" - ); - } - - // Frame on layer 0: always emit and report discontinuity if not subsequent - let emit = true; - // note: we use wrapping add because the encoder can restart if the - // camera is closed / reopened and here we only care about - // contiguity - let contiguous = tl0_picture_id == last_tl0_picture_id.wrapping_add(1); - - self.last_tl0_picture_id = Some(tl0_picture_id); - self.last_picture_id = Some(picture_id); - - return (emit, contiguous); - } - - // Frame on layer 1 or 2: only emit if they refer to the current layer 0 - // and they are subsequent - let emit = tl0_picture_id == last_tl0_picture_id && picture_id == last_picture_id.wrapping_add(1); - - if emit { - self.last_picture_id = Some(picture_id); - if !contiguous_seq { - // this as happened in Safari + very lossy network (very rare) - debug!("VP8 or VP9: contiguous pictures implies contiguous seq numbers: encoding issue ?") - } - } - - (emit, true) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/contiguity_vp8.rs b/rs/moq-webrtc/src/vendor/str0m/packet/contiguity_vp8.rs deleted file mode 100644 index bcbd6b235fd..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/contiguity_vp8.rs +++ /dev/null @@ -1,186 +0,0 @@ -use super::Vp8CodecExtra; -use super::contiguity::FrameContiguityState; - -#[derive(Debug, Default)] -pub struct Vp8Contiguity { - /// last picture id of layer 0 that we allowed emitting - last_tl0_picture_id: Option, - /// last picture id of any layer that we allowed emitting - last_picture_id: Option, -} - -impl Vp8Contiguity { - pub fn new() -> Self { - Self::default() - } - - /// Called when depacketizing a new frame is ready to be emitted - /// - /// Returns whether we can emit such frame and whether it's decodable with contiguity - pub fn check(&mut self, next: &Vp8CodecExtra, contiguous_seq: bool) -> (bool, bool) { - let mut frame_state: FrameContiguityState = self.into(); - let res = frame_state.next_frame( - next.picture_id, - next.tl0_picture_id, - Some(next.layer_index.into()), - next.is_keyframe, - contiguous_seq, - ); - - *self = frame_state.into(); - res - } -} - -impl From<&mut Vp8Contiguity> for FrameContiguityState { - fn from(value: &mut Vp8Contiguity) -> Self { - Self { - last_picture_id: value.last_picture_id, - last_tl0_picture_id: value.last_tl0_picture_id, - } - } -} - -impl From for Vp8Contiguity { - fn from(value: FrameContiguityState) -> Self { - Self { - last_picture_id: value.last_picture_id, - last_tl0_picture_id: value.last_tl0_picture_id, - } - } -} - -#[cfg(test)] -mod test { - - use super::Vp8Contiguity; - const L1T3_LAYERS: &[u64] = &[0, 2, 1, 2]; - const L1T2_LAYERS: &[u64] = &[0, 1, 0, 1]; - - #[test] - fn contiguous_l1t3() { - let mut contiguity = Vp8Contiguity::new(); - - for i in 0..100 { - let next = &crate::vendor::str0m::packet::Vp8CodecExtra { - discardable: false, - sync: true, - layer_index: L1T3_LAYERS[i as usize % 4] as u8, - picture_id: Some(i), - tl0_picture_id: Some(i / 4), - is_keyframe: false, - }; - - let res = contiguity.check(next, true); - assert_eq!(res, (true, true), "Failure at picture {} {:?}", i, next); - } - } - - #[test] - fn contiguous_l1t3_no_l2_contig_l0() { - const L1T3_LAYERS: &[u64] = &[0, 2, 1, 2]; - - let mut contiguity = Vp8Contiguity::new(); - - for i in 0..100 { - let layer_index = L1T3_LAYERS[i as usize % 4] as u8; - if layer_index == 2 { - continue; - } - - let next = &crate::vendor::str0m::packet::Vp8CodecExtra { - discardable: false, - sync: i % 8 == 0, - layer_index, - picture_id: Some(i), - tl0_picture_id: Some(i / 4), - is_keyframe: false, - }; - - let (emit, contiguous) = contiguity.check(next, true); - - // all layer 0 are contiguous therefore no discontinuity - assert_eq!(emit, next.layer_index == 0); - assert!(contiguous); - - if layer_index == 1 { - // frames on layer 1 are not emitted (could be improved tracking more deps) - // and we don't raise a discontinuity (stream still decodable) - assert!(!emit); - assert!(contiguous); - } - } - } - - #[test] - fn contiguous_l1t3_no_l2_discontig_l0() { - const L1T3_LAYERS: &[u64] = &[0, 2, 1, 2]; - - let mut contiguity = Vp8Contiguity::new(); - - for i in 0..100 { - let layer_index = L1T3_LAYERS[i as usize % 4] as u8; - if layer_index == 2 { - continue; - } - - let next = &crate::vendor::str0m::packet::Vp8CodecExtra { - discardable: false, - sync: i % 8 == 0, - layer_index, - picture_id: Some(i), - tl0_picture_id: Some(i), - is_keyframe: false, - }; - - let (emit, _) = contiguity.check(next, true); - - assert!(emit == (next.layer_index == 0)); - } - } - - #[test] - fn contiguous_l1t2() { - let mut contiguity = Vp8Contiguity::new(); - - for i in 0..100 { - let next = &crate::vendor::str0m::packet::Vp8CodecExtra { - discardable: false, - sync: true, - layer_index: L1T2_LAYERS[i as usize % 4] as u8, - picture_id: Some(i), - tl0_picture_id: Some(i / 2), - is_keyframe: false, - }; - - let res = contiguity.check(next, true); - assert_eq!(res, (true, true), "Failure at picture {} {:?}", i, next); - } - } - - #[test] - fn contiguous_l1t1_no_l1_contig_l0() { - let mut contiguity = Vp8Contiguity::new(); - - for i in 0..100 { - let layer_index = L1T2_LAYERS[i as usize % 4] as u8; - if layer_index == 1 { - continue; - } - - let next = &crate::vendor::str0m::packet::Vp8CodecExtra { - discardable: false, - sync: i % 8 == 0, - layer_index, - picture_id: Some(i), - tl0_picture_id: Some(i / 2), - is_keyframe: false, - }; - - let (emit, _) = contiguity.check(next, true); - - // all layer 0 are contiguous therefore can be emitted - assert_eq!(emit, next.layer_index == 0); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/contiguity_vp9.rs b/rs/moq-webrtc/src/vendor/str0m/packet/contiguity_vp9.rs deleted file mode 100644 index bd4850cf69f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/contiguity_vp9.rs +++ /dev/null @@ -1,174 +0,0 @@ -use super::Vp9CodecExtra; -use super::contiguity::FrameContiguityState; - -#[derive(Debug, Default)] -pub struct Vp9Contiguity { - /// last picture id of layer 0 that we allowed emitting - last_tl0_picture_id: Option, - - /// last picture id of any layer that we allowed emitting - last_picture_id: Option, -} - -impl Vp9Contiguity { - pub fn new() -> Self { - Self::default() - } - - /// Called when depacketizing a new frame is ready to be emitted - /// - /// Returns whether we can emit such frame and whether it's decodable with contiguity - pub fn check(&mut self, next: &Vp9CodecExtra, contiguous_seq: bool) -> (bool, bool) { - let mut frame_state: FrameContiguityState = self.into(); - let res = frame_state.next_frame( - next.picture_id, - next.tl0_picture_id, - next.tid.map(Into::into), - next.is_keyframe, - contiguous_seq, - ); - - *self = frame_state.into(); - res - } -} - -impl From<&mut Vp9Contiguity> for FrameContiguityState { - fn from(value: &mut Vp9Contiguity) -> Self { - Self { - last_picture_id: value.last_picture_id, - last_tl0_picture_id: value.last_tl0_picture_id, - } - } -} - -impl From for Vp9Contiguity { - fn from(value: FrameContiguityState) -> Self { - Self { - last_picture_id: value.last_picture_id, - last_tl0_picture_id: value.last_tl0_picture_id, - } - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::packet::Vp9CodecExtra; - - use super::Vp9Contiguity; - - const L1T3_LAYERS: &[u64] = &[0, 2, 1, 2]; - const L1T2_LAYERS: &[u64] = &[0, 1, 0, 1]; - - fn get_codec_extra(pid: u16, tid: u8, tl0_picture_id: u8) -> Vp9CodecExtra { - Vp9CodecExtra { - picture_id: Some(pid.into()), - tid: Some(tid), - tl0_picture_id: Some(tl0_picture_id.into()), - ..Default::default() - } - } - - #[test] - fn contiguous_l1t3() { - let mut contiguity = Vp9Contiguity::new(); - - for i in 0..100 { - let next = get_codec_extra(i, L1T3_LAYERS[i as usize % 4] as u8, (i / 4) as u8); - - let res = contiguity.check(&next, true); - assert_eq!(res, (true, true), "Failure at picture {} {:?}", i, next); - } - } - - #[test] - fn contiguous_l1t3_no_l2_contig_l0() { - const L1T3_LAYERS: &[u64] = &[0, 2, 1, 2]; - - let mut contiguity = Vp9Contiguity::new(); - - for i in 0..100 { - let layer_index = L1T3_LAYERS[i as usize % 4] as u8; - if layer_index == 2 { - continue; - } - - let next = get_codec_extra(i, layer_index, (i / 4) as u8); - let (emit, contiguous) = contiguity.check(&next, true); - - // all layer 0 are contiguous therefore no discontinuity - assert_eq!(emit, next.tid == Some(0)); - assert!(contiguous); - - if layer_index == 1 { - // frames on layer 1 are not emitted (could be improved tracking more deps) - // and we don't raise a discontinuity (stream still decodable) - assert!(!emit); - assert!(contiguous); - } - } - } - - #[test] - fn contiguous_l1t3_no_l2_discontig_l0() { - const L1T3_LAYERS: &[u64] = &[0, 2, 1, 2]; - - let mut contiguity = Vp9Contiguity::new(); - - for i in 0..100 { - let layer_index = L1T3_LAYERS[i as usize % 4] as u8; - if layer_index == 2 { - continue; - } - - let next = get_codec_extra(i, layer_index, i as u8); - let (emit, _) = contiguity.check(&next, true); - - assert!(emit == (next.tid == Some(0))); - } - } - - #[test] - fn contiguous_l1t2() { - let mut contiguity = Vp9Contiguity::new(); - - for i in 0..100 { - let next = get_codec_extra(i, L1T2_LAYERS[i as usize % 4] as u8, (i / 2) as u8); - - let res = contiguity.check(&next, true); - assert_eq!(res, (true, true), "Failure at picture {} {:?}", i, next); - } - } - - #[test] - fn contiguous_l1t1_no_l1_contig_l0() { - let mut contiguity = Vp9Contiguity::new(); - - for i in 0..100 { - let layer_index = L1T2_LAYERS[i as usize % 4] as u8; - if layer_index == 1 { - continue; - } - - let next = get_codec_extra(i, layer_index, (i / 2) as u8); - let (emit, _) = contiguity.check(&next, true); - - // all layer 0 are contiguous therefore can be emitted - assert_eq!(emit, next.tid == Some(0)); - } - } - - #[test] - fn keyframe_accepts_restarted_picture_ids() { - let mut contiguity = Vp9Contiguity::new(); - let mut first = get_codec_extra(40, 0, 40); - first.is_keyframe = true; - assert_eq!(contiguity.check(&first, true), (true, true)); - - let mut restarted = get_codec_extra(1, 0, 1); - restarted.is_keyframe = true; - assert_eq!(contiguity.check(&restarted, true), (true, false)); - assert_eq!(contiguity.check(&restarted, true), (true, false)); - assert_eq!(contiguity.check(&get_codec_extra(2, 0, 2), true), (true, true)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/error.rs b/rs/moq-webrtc/src/vendor/str0m/packet/error.rs deleted file mode 100644 index b44286dde8f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/error.rs +++ /dev/null @@ -1,50 +0,0 @@ -use std::error::Error; -use std::fmt; - -/// Errors arising in packet- and depacketization. -#[derive(Debug, PartialEq, Eq)] -#[non_exhaustive] -#[allow(missing_docs)] -pub enum PacketError { - ErrShortPacket, - ErrPayloadTooLarge, - ErrTooManySpatialLayers, - ErrTooManyPDiff, - ErrH265CorruptedPacket, - ErrInvalidH265PacketType, - ErrH265PACIPHESTooLong, - StapASizeLargerThanBuffer(usize, usize), - NaluTypeIsNotHandled(u8), - ErrVP8CorruptedPacket, - ErrVP9CorruptedPacket, - ErrAv1CorruptedPacket, - ErrAmrWbCorruptedPacket, -} - -impl fmt::Display for PacketError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - PacketError::ErrShortPacket => write!(f, "Packet is too short"), - PacketError::ErrPayloadTooLarge => write!(f, "Payload exceeds the MTU"), - PacketError::ErrTooManySpatialLayers => write!(f, "Too many spatial layers"), - PacketError::ErrTooManyPDiff => write!(f, "Too many P-Diff"), - PacketError::ErrH265CorruptedPacket => write!(f, "H265 corrupted packet"), - PacketError::ErrInvalidH265PacketType => write!(f, "H265 invalid packet type"), - PacketError::ErrH265PACIPHESTooLong => { - write!(f, "H265 PACI PHES field exceeds maximum size of 31 bytes") - } - PacketError::StapASizeLargerThanBuffer(size, buffer) => { - write!(f, "H264 StapA size larger than buffer: {} > {}", size, buffer) - } - PacketError::NaluTypeIsNotHandled(nalu_type) => { - write!(f, "H264 NALU type is not handled: {}", nalu_type) - } - PacketError::ErrVP8CorruptedPacket => write!(f, "VP8 corrupted packet"), - PacketError::ErrVP9CorruptedPacket => write!(f, "VP9 corrupted packet"), - PacketError::ErrAv1CorruptedPacket => write!(f, "AV1 corrupted packet"), - PacketError::ErrAmrWbCorruptedPacket => write!(f, "AMR-WB corrupted packet"), - } - } -} - -impl Error for PacketError {} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/h264.rs b/rs/moq-webrtc/src/vendor/str0m/packet/h264.rs deleted file mode 100644 index 84073084bb0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/h264.rs +++ /dev/null @@ -1,932 +0,0 @@ -#![allow(clippy::all)] - -use super::{CodecExtra, Depacketizer, PacketError, Packetizer}; - -/// H264 information describing the depacketized / packetized data -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct H264CodecExtra { - /// Flag which indicates that within [`MediaData`], there is an individual frame - /// containing complete and independent visual information. This frame serves - /// as a reference point for other frames in the video sequence. - /// - /// [`MediaData`]: crate::vendor::str0m::media::MediaData - pub is_keyframe: bool, -} - -/// Packetizes H264 RTP packets. -/// -/// ## Unversioned API surface -/// -/// This struct is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -#[derive(Default, Debug, Clone)] -pub struct H264Packetizer { - sps_nalu: Option>, - pps_nalu: Option>, -} - -pub const STAPA_NALU_TYPE: u8 = 24; -pub const FUA_NALU_TYPE: u8 = 28; -pub const FUB_NALU_TYPE: u8 = 29; -pub const IDR_NALU_TYPE: u8 = 5; -pub const SPS_NALU_TYPE: u8 = 7; -pub const PPS_NALU_TYPE: u8 = 8; -pub const AUD_NALU_TYPE: u8 = 9; -#[allow(dead_code)] // Referenced by tests. -pub const FILLER_NALU_TYPE: u8 = 12; - -pub const FUA_HEADER_SIZE: usize = 2; -pub const STAPA_HEADER_SIZE: usize = 1; -pub const STAPA_NALU_LENGTH_SIZE: usize = 2; - -pub const NALU_TYPE_BITMASK: u8 = 0x1F; -pub const NALU_REF_IDC_BITMASK: u8 = 0x60; -pub const FU_START_BITMASK: u8 = 0x80; -pub const FU_END_BITMASK: u8 = 0x40; - -pub const OUTPUT_STAP_AHEADER: u8 = 0x78; - -pub static ANNEXB_NALUSTART_CODE: &[u8] = &[0x00, 0x00, 0x00, 0x01]; - -/// Detect whether an H264 RTP payload contains a keyframe. -/// -/// Checks for IDR (Instantaneous Decoding Refresh) NAL units (type 5) -/// in the RTP payload. -pub fn detect_h264_keyframe(payload: &[u8]) -> bool { - detect_h264_nalu(payload, IDR_NALU_TYPE) -} - -/// Checks for target NAL units in the RTP payload. -/// Handles single NAL units, STAP-A aggregation -/// packets, and FU-A fragmentation units. -/// -/// For FU-A packets, only the start fragment (S=1) is checked -/// since the NAL type is only reliably available there. -pub fn detect_h264_nalu(payload: &[u8], target_nalu: u8) -> bool { - if payload.is_empty() { - return false; - } - - let nalu_type = payload[0] & NALU_TYPE_BITMASK; - - match nalu_type { - // Single NAL unit (types 1-23) - 1..=23 => nalu_type == target_nalu, - - // STAP-A: check all aggregated NALUs - STAPA_NALU_TYPE => { - let mut offset = STAPA_HEADER_SIZE; - while offset + STAPA_NALU_LENGTH_SIZE <= payload.len() { - let nalu_size = ((payload[offset] as usize) << 8) | payload[offset + 1] as usize; - offset += STAPA_NALU_LENGTH_SIZE; - if offset + nalu_size > payload.len() { - break; - } - if let Some(&b0) = payload.get(offset) { - if b0 & NALU_TYPE_BITMASK == target_nalu { - return true; - } - } - offset += nalu_size; - } - false - } - - // FU-A: check start fragment for IDR type - FUA_NALU_TYPE => { - if payload.len() < FUA_HEADER_SIZE { - return false; - } - let b1 = payload[1]; - // Only the start fragment (S=1) reliably carries the original NAL type - if b1 & FU_START_BITMASK == 0 { - return false; - } - b1 & NALU_TYPE_BITMASK == target_nalu - } - - _ => false, - } -} - -impl H264Packetizer { - fn next_ind(nalu: &[u8], start: usize) -> (isize, isize) { - let mut zero_count = 0; - - for (i, &b) in nalu[start..].iter().enumerate() { - if b == 0 { - zero_count += 1; - continue; - } else if b == 1 && zero_count >= 2 { - return ((start + i - zero_count) as isize, zero_count as isize + 1); - } - zero_count = 0 - } - (-1, -1) - } - - fn emit(&mut self, nalu: &[u8], mtu: usize, payloads: &mut Vec>) { - if nalu.is_empty() { - return; - } - - let nalu_type = nalu[0] & NALU_TYPE_BITMASK; - let nalu_ref_idc = nalu[0] & NALU_REF_IDC_BITMASK; - - if nalu_type == AUD_NALU_TYPE { - return; - } else if nalu_type == SPS_NALU_TYPE { - self.sps_nalu = Some(nalu.to_vec()); - return; - } else if nalu_type == PPS_NALU_TYPE { - self.pps_nalu = Some(nalu.to_vec()); - return; - } else if let (Some(sps_nalu), Some(pps_nalu)) = (&self.sps_nalu, &self.pps_nalu) { - // Pack current NALU with SPS and PPS as STAP-A - let sps_len = (sps_nalu.len() as u16).to_be_bytes(); - let pps_len = (pps_nalu.len() as u16).to_be_bytes(); - - let mut stap_a_nalu = Vec::with_capacity(1 + 2 + sps_nalu.len() + 2 + pps_nalu.len()); - stap_a_nalu.push(OUTPUT_STAP_AHEADER); - stap_a_nalu.extend(sps_len); - stap_a_nalu.extend_from_slice(sps_nalu); - stap_a_nalu.extend(pps_len); - stap_a_nalu.extend_from_slice(pps_nalu); - if stap_a_nalu.len() <= mtu { - payloads.push(stap_a_nalu); - } - } - - if self.sps_nalu.is_some() && self.pps_nalu.is_some() { - self.sps_nalu = None; - self.pps_nalu = None; - } - - // Single NALU - if nalu.len() <= mtu { - payloads.push(nalu.to_vec()); - return; - } - - // FU-A - let max_fragment_size = mtu as isize - FUA_HEADER_SIZE as isize; - - // The FU payload consists of fragments of the payload of the fragmented - // NAL unit so that if the fragmentation unit payloads of consecutive - // FUs are sequentially concatenated, the payload of the fragmented NAL - // unit can be reconstructed. The NAL unit type octet of the fragmented - // NAL unit is not included as such in the fragmentation unit payload, - // but rather the information of the NAL unit type octet of the - // fragmented NAL unit is conveyed in the F and NRI fields of the FU - // indicator octet of the fragmentation unit and in the type field of - // the FU header. An FU payload MAY have any number of octets and MAY - // be empty. - - let nalu_data = nalu; - // According to the RFC, the first octet is skipped due to redundant information - let mut nalu_data_index = 1; - let nalu_data_length = nalu.len() as isize - nalu_data_index; - let mut nalu_data_remaining = nalu_data_length; - - if std::cmp::min(max_fragment_size, nalu_data_remaining) <= 0 { - return; - } - - while nalu_data_remaining > 0 { - let current_fragment_size = std::cmp::min(max_fragment_size, nalu_data_remaining); - //out: = make([]byte, fuaHeaderSize + currentFragmentSize) - let mut out = Vec::with_capacity(FUA_HEADER_SIZE + current_fragment_size as usize); - // +---------------+ - // |0|1|2|3|4|5|6|7| - // +-+-+-+-+-+-+-+-+ - // |F|NRI| Type | - // +---------------+ - let b0 = FUA_NALU_TYPE | nalu_ref_idc; - out.push(b0); - - // +---------------+ - //|0|1|2|3|4|5|6|7| - //+-+-+-+-+-+-+-+-+ - //|S|E|R| Type | - //+---------------+ - - let mut b1 = nalu_type; - if nalu_data_remaining == nalu_data_length { - // Set start bit - b1 |= 1 << 7; - } else if nalu_data_remaining - current_fragment_size == 0 { - // Set end bit - b1 |= 1 << 6; - } - out.push(b1); - - out.extend_from_slice( - &nalu_data[nalu_data_index as usize..(nalu_data_index + current_fragment_size) as usize], - ); - payloads.push(out); - - nalu_data_remaining -= current_fragment_size; - nalu_data_index += current_fragment_size; - } - } -} - -impl Packetizer for H264Packetizer { - /// Payload fragments a H264 packet across one or more byte arrays - fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - if payload.is_empty() || mtu == 0 { - return Ok(vec![]); - } - - let mut payloads = vec![]; - - let (mut next_ind_start, mut next_ind_len) = H264Packetizer::next_ind(payload, 0); - if next_ind_start == -1 { - self.emit(payload, mtu, &mut payloads); - } else { - while next_ind_start != -1 { - let prev_start = (next_ind_start + next_ind_len) as usize; - let (next_ind_start2, next_ind_len2) = H264Packetizer::next_ind(payload, prev_start); - next_ind_start = next_ind_start2; - next_ind_len = next_ind_len2; - if next_ind_start != -1 { - self.emit(&payload[prev_start..next_ind_start as usize], mtu, &mut payloads); - } else { - // Emit until end of stream, no end indicator found - self.emit(&payload[prev_start..], mtu, &mut payloads); - } - } - } - - Ok(payloads) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool { - last - } -} - -/// Depacketizes H264 RTP packets. -/// -/// ## Unversioned API surface -/// -/// This struct is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -#[derive(PartialEq, Eq, Debug, Default, Clone)] -pub struct H264Depacketizer { - /// Whether to output in AVC format (length-prefixed NALUs) instead of Annex B format - pub is_avc: bool, - fua_buffer: Option>, -} - -impl Depacketizer for H264Depacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - // Roughly account for Annex B start codes or AVC length prefixes. - let estimated_packets = (packets_size / 1200).saturating_add(1); - Some(packets_size.saturating_add(4usize.saturating_mul(estimated_packets))) - } - - /// depacketize parses the passed byte slice and stores the result in the - /// H264Packet this method is called upon - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, extra: &mut CodecExtra) -> Result<(), PacketError> { - if packet.len() == 0 { - return Err(PacketError::ErrShortPacket); - } - - // NALU Types - // https://tools.ietf.org/html/rfc6184#section-5.4 - let b0 = packet[0]; - let nalu_type = b0 & NALU_TYPE_BITMASK; - - match nalu_type { - t @ 1..=23 => { - let is_keyframe = if let CodecExtra::H264(e) = extra { - (t == IDR_NALU_TYPE) | e.is_keyframe - } else { - t == IDR_NALU_TYPE - }; - *extra = CodecExtra::H264(H264CodecExtra { is_keyframe }); - - if self.is_avc { - out.extend_from_slice(&(packet.len() as u32).to_be_bytes()); - } else { - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - } - out.extend_from_slice(packet); - Ok(()) - } - STAPA_NALU_TYPE => { - let mut curr_offset = STAPA_HEADER_SIZE; - while curr_offset + 1 < packet.len() { - let nalu_size = ((packet[curr_offset] as usize) << 8) | packet[curr_offset + 1] as usize; - curr_offset += STAPA_NALU_LENGTH_SIZE; - - if curr_offset + nalu_size > packet.len() { - return Err(PacketError::StapASizeLargerThanBuffer( - nalu_size, - packet.len() - curr_offset, - )); - } - - let Some(b0) = packet.get(curr_offset) else { - continue; - }; - let t = b0 & NALU_TYPE_BITMASK; - let is_keyframe = if let CodecExtra::H264(e) = extra { - (t == IDR_NALU_TYPE) | e.is_keyframe - } else { - t == IDR_NALU_TYPE - }; - *extra = CodecExtra::H264(H264CodecExtra { is_keyframe }); - - if self.is_avc { - out.extend_from_slice(&(nalu_size as u32).to_be_bytes()); - } else { - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - } - out.extend_from_slice(&packet[curr_offset..curr_offset + nalu_size]); - curr_offset += nalu_size; - } - - Ok(()) - } - FUA_NALU_TYPE => { - if packet.len() < FUA_HEADER_SIZE as usize { - return Err(PacketError::ErrShortPacket); - } - - if self.fua_buffer.is_none() { - self.fua_buffer = Some(Vec::new()); - } - - if let Some(fua_buffer) = &mut self.fua_buffer { - fua_buffer.extend_from_slice(&packet[FUA_HEADER_SIZE as usize..]); - } - - let b1 = packet[1]; - if b1 & FU_END_BITMASK != 0 { - let nalu_ref_idc = b0 & NALU_REF_IDC_BITMASK; - let fragmented_nalu_type = b1 & NALU_TYPE_BITMASK; - - let is_keyframe = if let CodecExtra::H264(e) = extra { - (fragmented_nalu_type == IDR_NALU_TYPE) | e.is_keyframe - } else { - fragmented_nalu_type == IDR_NALU_TYPE - }; - *extra = CodecExtra::H264(H264CodecExtra { is_keyframe }); - - if let Some(fua_buffer) = self.fua_buffer.take() { - if self.is_avc { - out.extend_from_slice(&((fua_buffer.len() + 1) as u32).to_be_bytes()); - } else { - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - } - out.push(nalu_ref_idc | fragmented_nalu_type); - out.extend_from_slice(&fua_buffer); - } - - Ok(()) - } else { - Ok(()) - } - } - _ => Err(PacketError::NaluTypeIsNotHandled(nalu_type)), - } - } - - /// is_partition_head checks if this is the head of a packetized nalu stream. - fn is_partition_head(&self, packet: &[u8]) -> bool { - if packet.len() < 2 { - return false; - } - - if packet[0] & NALU_TYPE_BITMASK == FUA_NALU_TYPE || packet[0] & NALU_TYPE_BITMASK == FUB_NALU_TYPE { - (packet[1] & FU_START_BITMASK) != 0 - } else { - true - } - } - - fn is_partition_tail(&self, marker: bool, _packet: &[u8]) -> bool { - marker - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_h264_payload() -> Result<(), PacketError> { - let empty = &[]; - let small_payload = &[0x90, 0x90, 0x90]; - let multiple_payload = &[0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x01, 0x90]; - let large_payload = &[ - 0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, - 0x15, - ]; - let large_payload_packetized = vec![ - &[0x1c, 0x80, 0x01, 0x02, 0x03], - &[0x1c, 0x00, 0x04, 0x05, 0x06], - &[0x1c, 0x00, 0x07, 0x08, 0x09], - &[0x1c, 0x00, 0x10, 0x11, 0x12], - &[0x1c, 0x40, 0x13, 0x14, 0x15], - ]; - - let mut pck = H264Packetizer::default(); - - // Positive MTU, empty payload - let result = pck.packetize(1, empty)?; - assert!(result.is_empty(), "Generated payload should be empty"); - - // 0 MTU, small payload - let result = pck.packetize(0, small_payload)?; - assert_eq!(result.len(), 0, "Generated payload should be empty"); - - // Positive MTU, small payload - let result = pck.packetize(1, small_payload)?; - assert_eq!(result.len(), 0, "Generated payload should be empty"); - - // Positive MTU, small payload - let result = pck.packetize(5, small_payload)?; - assert_eq!(result.len(), 1, "Generated payload should be the 1"); - assert_eq!( - result[0].len(), - small_payload.len(), - "Generated payload should be the same size as original payload size" - ); - - // Multiple NALU in a single payload - let result = pck.packetize(5, multiple_payload)?; - assert_eq!(result.len(), 2, "2 nal units should be broken out"); - for i in 0..2 { - assert_eq!(result[i].len(), 1, "Payload {} of 2 is packed incorrectly", i + 1,); - } - - // Large Payload split across multiple RTP Packets - let result = pck.packetize(5, large_payload)?; - assert_eq!(result, large_payload_packetized, "FU-A packetization failed"); - - // Nalu type 9 - let small_payload2 = &[0x09, 0x00, 0x00]; - let result = pck.packetize(5, small_payload2)?; - assert_eq!(result.len(), 0, "Generated payload should be empty"); - - // Nalu type 12 - let filler_payload = &[FILLER_NALU_TYPE, 0xff, 0x80]; - let result = pck.packetize(5, filler_payload)?; - assert_eq!(result, vec![filler_payload], "Filler NALU should be kept"); - - Ok(()) - } - - macro_rules! test_h264 { - ($name:tt, $is_avc:expr, $is_ok: expr, $payload:expr, $err:tt) => { - #[test] - fn $name() -> Result<(), PacketError> { - let mut pkt = H264Depacketizer::default(); - pkt.is_avc = $is_avc; - let mut extra = CodecExtra::None; - let mut out: Vec = Vec::new(); - let result = pkt.depacketize($payload, &mut out, &mut extra); - if $is_ok { - assert!(result.is_ok(), $err); - } else { - assert!(result.is_err(), $err); - } - Ok(()) - } - }; - } - - test_h264!(nil_payload, false, false, &[], "Unmarshal did not fail on nil payload"); - test_h264!( - unit_delimiter, - false, - true, - &[0x09, 0x30], - "Unmarshal should accept minimal h.264 access unit delimiter" - ); - test_h264!( - end_of_sequence_nalu, - false, - true, - &[0x0A], - "Unmarshal should accept end of sequence NALU" - ); - test_h264!( - not_handled, - false, - false, - &[0xFF, 0x00, 0x00], - "Unmarshal accepted a packet with a NALU Type we don't handle" - ); - test_h264!( - incomplete_single_payload_multi_nalu, - false, - false, - &[ - 0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c, 0x22, 0x11, - ], - "Unmarshal accepted a STAP-A packet with insufficient data" - ); - - #[test] - fn single_payload() -> Result<(), PacketError> { - let mut pkt = H264Depacketizer::default(); - let mut extra = CodecExtra::None; - let mut out: Vec = Vec::new(); - let single_payload = &[0x90, 0x90, 0x90]; - let _ = pkt.depacketize(single_payload, &mut out, &mut extra); - let single_payload_unmarshaled = &[0x00, 0x00, 0x00, 0x01, 0x90, 0x90, 0x90]; - assert_eq!( - out, single_payload_unmarshaled, - "Unmarshaling a single payload shouldn't modify the payload" - ); - Ok(()) - } - - #[test] - fn single_payload_avc() -> Result<(), PacketError> { - let mut pkt = H264Depacketizer::default(); - pkt.is_avc = true; - let mut extra = CodecExtra::None; - let mut out: Vec = Vec::new(); - let single_payload = &[0x90, 0x90, 0x90]; - let _ = pkt.depacketize(single_payload, &mut out, &mut extra); - let single_payload_unmarshaled_avc = &[0x00, 0x00, 0x00, 0x03, 0x90, 0x90, 0x90]; - assert_eq!( - out, single_payload_unmarshaled_avc, - "Unmarshaling a single payload into avc stream shouldn't modify the payload" - ); - Ok(()) - } - - #[test] - fn h264_large_out() -> Result<(), PacketError> { - let large_payload_packetized = vec![ - &[0x1c, 0x80, 0x01, 0x02, 0x03], - &[0x1c, 0x00, 0x04, 0x05, 0x06], - &[0x1c, 0x00, 0x07, 0x08, 0x09], - &[0x1c, 0x00, 0x10, 0x11, 0x12], - &[0x1c, 0x40, 0x13, 0x14, 0x15], - ]; - - let large_payload = &[ - 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, - ]; - - let mut pkt = H264Depacketizer::default(); - let mut extra = CodecExtra::None; - - let mut large_out = Vec::new(); - for p in &large_payload_packetized { - pkt.depacketize(*p, &mut large_out, &mut extra)?; - } - assert_eq!(large_out, large_payload, "Failed to unmarshal a large payload"); - - Ok(()) - } - - #[test] - fn h264_large_out_avc() -> Result<(), PacketError> { - let large_payload_packetized = vec![ - &[0x1c, 0x80, 0x01, 0x02, 0x03], - &[0x1c, 0x00, 0x04, 0x05, 0x06], - &[0x1c, 0x00, 0x07, 0x08, 0x09], - &[0x1c, 0x00, 0x10, 0x11, 0x12], - &[0x1c, 0x40, 0x13, 0x14, 0x15], - ]; - - let large_payload_avc = &[ - 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, - ]; - - let mut avc_pkt = H264Depacketizer { - is_avc: true, - ..Default::default() - }; - - let mut extra = CodecExtra::None; - - let mut large_out_avc = Vec::new(); - for p in &large_payload_packetized { - avc_pkt.depacketize(*p, &mut large_out_avc, &mut extra)?; - } - assert_eq!( - large_out_avc, large_payload_avc, - "Failed to unmarshal a large payload into avc stream" - ); - - Ok(()) - } - - #[test] - fn single_payload_multi_nalu() -> Result<(), PacketError> { - let single_payload_multi_nalu = &[ - 0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c, 0x22, 0x11, 0xa8, - 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8, 0x00, - ]; - let single_payload_multi_nalu_unmarshaled = &[ - 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c, 0x22, 0x11, - 0xa8, 0x00, 0x00, 0x00, 0x01, 0x68, 0x1a, 0x34, 0xe3, 0xc8, - ]; - - let mut pkt = H264Depacketizer::default(); - - let mut extra = CodecExtra::None; - - let mut out = Vec::new(); - pkt.depacketize(single_payload_multi_nalu, &mut out, &mut extra)?; - assert_eq!( - out, single_payload_multi_nalu_unmarshaled, - "Failed to unmarshal a single packet with multiple NALUs" - ); - - Ok(()) - } - - #[test] - fn single_payload_multi_nalu_avc() -> Result<(), PacketError> { - let single_payload_multi_nalu = &[ - 0x78, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c, 0x22, 0x11, 0xa8, - 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8, 0x00, - ]; - let single_payload_multi_nalu_unmarshaled_avc = &[ - 0x00, 0x00, 0x00, 0x0f, 0x67, 0x42, 0xc0, 0x1f, 0x1a, 0x32, 0x35, 0x01, 0x40, 0x7a, 0x40, 0x3c, 0x22, 0x11, - 0xa8, 0x00, 0x00, 0x00, 0x05, 0x68, 0x1a, 0x34, 0xe3, 0xc8, - ]; - - let mut avc_pkt = H264Depacketizer::default(); - avc_pkt.is_avc = true; - - let mut extra = CodecExtra::None; - - let mut out = Vec::new(); - avc_pkt.depacketize(single_payload_multi_nalu, &mut out, &mut extra)?; - assert_eq!( - out, single_payload_multi_nalu_unmarshaled_avc, - "Failed to unmarshal a single packet with multiple NALUs into avc stream" - ); - - Ok(()) - } - - #[test] - fn test_h264_partition_head_checker_is_partition_head() -> Result<(), PacketError> { - let h264 = H264Depacketizer::default(); - let empty_nalu = &[]; - assert!( - !h264.is_partition_head(empty_nalu), - "empty nalu must not be a partition head" - ); - - let single_nalu = &[1, 0]; - assert!( - h264.is_partition_head(single_nalu), - "single nalu must be a partition head" - ); - - let stapa_nalu = &[STAPA_NALU_TYPE, 0]; - assert!( - h264.is_partition_head(stapa_nalu), - "stapa nalu must be a partition head" - ); - - let fua_start_nalu = &[FUA_NALU_TYPE, FU_START_BITMASK]; - assert!( - h264.is_partition_head(fua_start_nalu), - "fua start nalu must be a partition head" - ); - - let fua_end_nalu = &[FUA_NALU_TYPE, FU_END_BITMASK]; - assert!( - !h264.is_partition_head(fua_end_nalu), - "fua end nalu must not be a partition head" - ); - - let fub_start_nalu = &[FUB_NALU_TYPE, FU_START_BITMASK]; - assert!( - h264.is_partition_head(fub_start_nalu), - "fub start nalu must be a partition head" - ); - - let fub_end_nalu = &[FUB_NALU_TYPE, FU_END_BITMASK]; - assert!( - !h264.is_partition_head(fub_end_nalu), - "fub end nalu must not be a partition head" - ); - - Ok(()) - } - - #[test] - fn test_h264_packetizer_payload_sps_and_pps_handling() -> Result<(), PacketError> { - let mut pck = H264Packetizer::default(); - let expected: Vec<&[u8]> = vec![ - &[0x78, 0x00, 0x03, 0x07, 0x00, 0x01, 0x00, 0x03, 0x08, 0x02, 0x03], - &[0x05, 0x04, 0x05], - ]; - - // When packetizing SPS and PPS are emitted with following NALU - let res = pck.packetize(1500, &[0x07, 0x00, 0x01])?; - assert!(res.is_empty(), "Generated payload should be empty"); - - let res = pck.packetize(1500, &[0x08, 0x02, 0x03])?; - assert!(res.is_empty(), "Generated payload should be empty"); - - let actual = pck.packetize(1500, &[0x05, 0x04, 0x05])?; - assert_eq!(actual, expected, "SPS and PPS aren't packed together"); - - Ok(()) - } - - #[test] - fn test_h264_depacketizer_idr_handling() -> Result<(), PacketError> { - let mut pck = H264Depacketizer::default(); - let mut extra = CodecExtra::None; - let mut out = vec![]; - - // First byte is NALU type - let packet = [0x85]; - pck.depacketize(&packet, &mut out, &mut extra)?; - let CodecExtra::H264(e) = extra else { - panic!("Expected CodecExtra::H264"); - }; - assert!(e.is_keyframe); - - // First byte is STAPA NALU type - let packet = vec![ - vec![ - 120, 0, 15, 103, 66, 192, 21, 140, 141, 64, 160, 203, 207, 0, 240, 136, 70, 160, 0, 4, 104, 206, 60, - 128, 1, 20, 101, - ], - vec![0; 276], - ] - .into_iter() - .flatten() - .collect::>(); - pck.depacketize(packet.as_slice(), &mut out, &mut extra)?; - let CodecExtra::H264(e) = extra else { - panic!("Expected CodecExtra::H264"); - }; - assert!(e.is_keyframe); - - // First byte is FUA NALU type - let packet = [124, 69]; - pck.depacketize(&packet, &mut out, &mut extra)?; - let CodecExtra::H264(e) = extra else { - panic!("Expected CodecExtra::H264"); - }; - assert!(e.is_keyframe); - Ok(()) - } - - #[test] - fn parse_first_packet() { - const PACKET: &[u8] = &[ - 120, 000, 015, 103, 066, 192, 021, 140, 141, 064, 160, 203, 207, 000, 240, 136, 070, 160, 000, 004, 104, - 206, 060, 128, 000, 204, 101, 184, 000, 004, 000, 000, 005, 057, 049, 064, 000, 064, 222, 078, 078, 078, - 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 078, 186, 235, 174, 186, 235, - 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, - 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 173, 223, 039, 125, 247, 223, 125, 245, 215, - 093, 117, 215, 093, 117, 214, 239, 174, 187, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, - 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 183, 093, 117, 215, 093, 117, 215, - 093, 117, 215, 093, 117, 215, 093, 117, 215, 093, 117, 215, 092, 189, 117, 215, 093, 117, 215, 093, 117, - 215, 093, 117, 215, 093, 117, 215, 093, 117, 215, 093, 117, 214, 239, 190, 251, 239, 190, 186, 235, 174, - 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 174, 186, 235, 175, - 227, 255, 240, 247, 021, 223, 125, 247, 223, 125, 247, 223, 125, 247, 223, 125, 247, 223, 125, 248, - ]; - - let mut pck = H264Depacketizer::default(); - let mut extra = CodecExtra::None; - let mut out = vec![]; - pck.depacketize(PACKET, &mut out, &mut extra).unwrap(); - } - - #[test] - fn test_out_of_bounds_access() { - const PACKET: &[u8] = &[STAPA_NALU_TYPE, 0x00, 0x00]; - - let mut pck = H264Depacketizer::default(); - let mut extra = CodecExtra::None; - let mut out = vec![]; - pck.depacketize(PACKET, &mut out, &mut extra).unwrap(); - } - - #[test] - fn test_detect_h264_keyframe() { - // Empty payload - assert!(!detect_h264_keyframe(&[])); - - // Single IDR NAL unit (type 5) - assert!(detect_h264_keyframe(&[0x65, 0x00, 0x00])); // 0x65 & 0x1F = 5 - - // Single non-IDR NAL unit (type 1 = coded slice) - assert!(!detect_h264_keyframe(&[0x41, 0x00, 0x00])); // 0x41 & 0x1F = 1 - - // SPS (type 7) - not a keyframe - assert!(!detect_h264_keyframe(&[0x67, 0x00, 0x00])); - - // PPS (type 8) - not a keyframe - assert!(!detect_h264_keyframe(&[0x68, 0x00, 0x00])); - - // STAP-A containing IDR - // Header: type 24 (STAP-A) - // NALU 1: 2 bytes, type 7 (SPS) - // NALU 2: 2 bytes, type 5 (IDR) - let stapa_with_idr = [ - 0x18, // STAP-A (24) - 0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7 - 0x00, 0x02, 0x65, 0xBB, // IDR: size=2, type=5 - ]; - assert!(detect_h264_keyframe(&stapa_with_idr)); - - // STAP-A without IDR - let stapa_no_idr = [ - 0x18, // STAP-A (24) - 0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7 - 0x00, 0x02, 0x68, 0xBB, // PPS: size=2, type=8 - ]; - assert!(!detect_h264_keyframe(&stapa_no_idr)); - - // FU-A start fragment with IDR type - let fua_start_idr = [ - 0x7C, // FU indicator: type=28 (FU-A) - 0x85, // FU header: S=1, type=5 (IDR) - 0x00, 0x00, - ]; - assert!(detect_h264_keyframe(&fua_start_idr)); - - // FU-A start fragment with non-IDR type - let fua_start_non_idr = [ - 0x7C, // FU indicator: type=28 (FU-A) - 0x81, // FU header: S=1, type=1 (non-IDR) - 0x00, 0x00, - ]; - assert!(!detect_h264_keyframe(&fua_start_non_idr)); - - // FU-A continuation fragment (S=0) - cannot detect - let fua_continuation = [ - 0x7C, // FU indicator: type=28 (FU-A) - 0x05, // FU header: S=0, type=5 (IDR) but S=0 - 0x00, 0x00, - ]; - assert!(!detect_h264_keyframe(&fua_continuation)); - - // FU-A too short - assert!(!detect_h264_keyframe(&[0x7C])); - } - - #[test] - fn test_detect_h264_nalu() { - // Empty payload - assert!(!detect_h264_nalu(&[], SPS_NALU_TYPE)); - - // SPS (type 7) - assert!(detect_h264_nalu(&[0x67, 0x00, 0x00], SPS_NALU_TYPE)); - - // PPS (type 8) - assert!(!detect_h264_nalu(&[0x68, 0x00, 0x00], SPS_NALU_TYPE)); - - // STAP-A containing IDR - // Header: type 24 (STAP-A) - // NALU 1: 2 bytes, type 7 (SPS) - // NALU 2: 2 bytes, type 5 (IDR) - let stapa_with_idr = [ - 0x18, // STAP-A (24) - 0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7 - 0x00, 0x02, 0x65, 0xBB, // IDR: size=2, type=5 - ]; - assert!(detect_h264_nalu(&stapa_with_idr, SPS_NALU_TYPE)); - - // STAP-A without IDR - let stapa_no_idr = [ - 0x18, // STAP-A (24) - 0x00, 0x02, 0x67, 0xAA, // SPS: size=2, type=7 - 0x00, 0x02, 0x68, 0xBB, // PPS: size=2, type=8 - ]; - assert!(detect_h264_nalu(&stapa_no_idr, SPS_NALU_TYPE)); - - // FU-A too short - assert!(!detect_h264_nalu(&[0x7C], SPS_NALU_TYPE)); - } - - #[test] - fn packetize_respects_mtu() -> Result<(), PacketError> { - // NAL header byte (type=5, IDR slice) + payload. - let mut payload = vec![0x05u8]; - payload.extend(std::iter::repeat(0xABu8).take(2000)); - for &mtu in &[100usize, 300, 600, 1200] { - let mut pck = H264Packetizer::default(); - let pkts = pck.packetize(mtu, &payload)?; - assert!(!pkts.is_empty(), "H264 produced no packets at mtu {mtu}"); - for (i, pkt) in pkts.iter().enumerate() { - assert!(pkt.len() <= mtu, "H264 packet {i} size {} > mtu {mtu}", pkt.len()); - } - } - Ok(()) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/h264_profile.rs b/rs/moq-webrtc/src/vendor/str0m/packet/h264_profile.rs deleted file mode 100644 index 9180fe3269b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/h264_profile.rs +++ /dev/null @@ -1,353 +0,0 @@ -use crate::vendor::str0m::util::BitPattern; - -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub(crate) struct H264ProfileLevel { - profile: H264Profile, - level_idc: H264LevelIdc, -} - -impl H264ProfileLevel { - // TODO: The default should really be Baseline and Level1 - // according to the spec: https://tools.ietf.org/html/rfc6184#section-8.1. However, libWebRTC - // specifies Level3_1 to not break backwards compatibility and we copy them. - // When libWebRTC updates we are probably safe to do the same. - // - // See: https://webrtc.googlesource.com/src/+/main/api/video_codecs/h264_profile_level_id.cc#182 - pub(crate) const FALLBACK: Self = Self { - profile: H264Profile::Baseline, - level_idc: H264LevelIdc::Level3_1, - }; - - /// Different combinations of profile-iop and profile-idc match to the same profile. - /// See table 5 in https://www.rfc-editor.org/rfc/rfc6184#section-8.1 - /// - /// The first value in each tuple is the profile that is matched if the profile-idc and the - /// BitPattern matches a given fmtp line. - const PROFILES: &'static [(H264Profile, H264ProfileIdc, BitPattern)] = &[ - // Constrained Baseline - ( - H264Profile::ConstrainedBaseline, - H264ProfileIdc::X42, - BitPattern::new(*b"x1xx0000"), - ), - ( - H264Profile::ConstrainedBaseline, - H264ProfileIdc::X4D, - BitPattern::new(*b"1xxx0000"), - ), - ( - H264Profile::ConstrainedBaseline, - H264ProfileIdc::X58, - BitPattern::new(*b"11xx0000"), - ), - // Baseline - ( - H264Profile::Baseline, - H264ProfileIdc::X42, - BitPattern::new(*b"x0xx0000"), - ), - ( - H264Profile::Baseline, - H264ProfileIdc::X58, - BitPattern::new(*b"10xx0000"), - ), - // Main - (H264Profile::Main, H264ProfileIdc::X4D, BitPattern::new(*b"0x0x0000")), - // Extended - ( - H264Profile::Extended, - H264ProfileIdc::X58, - BitPattern::new(*b"00xx0000"), - ), - // High(No constraints) - (H264Profile::High, H264ProfileIdc::X64, BitPattern::new(*b"00000000")), - // Constrained High - ( - H264Profile::ConstrainedHigh, - H264ProfileIdc::X64, - BitPattern::new(*b"00001100"), - ), - (H264Profile::High10, H264ProfileIdc::X6E, BitPattern::new(*b"00000000")), - (H264Profile::High422, H264ProfileIdc::X7A, BitPattern::new(*b"00000000")), - ( - H264Profile::High444Predictive, - H264ProfileIdc::XF4, - BitPattern::new(*b"00000000"), - ), - // Intra profiles - ( - H264Profile::High10Intra, - H264ProfileIdc::X6E, - BitPattern::new(*b"00010000"), - ), - ( - H264Profile::High422Intra, - H264ProfileIdc::X7A, - BitPattern::new(*b"00010000"), - ), - ( - H264Profile::High444Intra, - H264ProfileIdc::XF4, - BitPattern::new(*b"00010000"), - ), - ( - H264Profile::CAVLC444Intra, - H264ProfileIdc::X2C, - BitPattern::new(*b"00010000"), - ), - ]; - - /// Construct a new H264ProfileLevel. - /// - /// Returns `Some(Self)` only if the provided parameters identify a valid profile. - fn new(profile_idc: H264ProfileIdc, profile_iop: u8, level_idc: H264LevelIdc) -> Option { - Self::PROFILES - .iter() - .find_map(|&(profile, expected_pidc, iop_pattern)| { - // Profile IDC must match - if expected_pidc != profile_idc { - return None; - } - // The profile-iop must match the pattern for the profile - if !iop_pattern.matches(profile_iop) { - return None; - } - - Some(Self { profile, level_idc }) - }) - } - - /// Returns the H.264 profile (Baseline, Main, High, etc.). - pub(crate) fn profile(&self) -> H264Profile { - self.profile - } - - /// Returns the H.264 level (Level 3.1, Level 4.0, etc.). - pub(crate) fn level(&self) -> H264LevelIdc { - self.level_idc - } -} - -impl TryFrom for H264ProfileLevel { - type Error = (); - - fn try_from(value: u32) -> Result { - const CONSTRAINT_SET3_FLAG: u8 = 0x10; - - let bytes = value.to_be_bytes(); - - let profile_idc = bytes[1].try_into()?; - let profile_iop = bytes[2]; - let mut profile_level = bytes[3].try_into()?; - - // When profile_idc is equal to 66, 77, or 88 (the Baseline, Main, or - // Extended profile), level_idc is equal to 11, and bit 4 - // (constraint_set3_flag) of the profile-iop byte is equal to 1, - // the default level is Level 1b. - if [H264ProfileIdc::X42, H264ProfileIdc::X4D, H264ProfileIdc::X58].contains(&profile_idc) - && profile_level == H264LevelIdc::Level1 - { - profile_level = if (profile_iop & CONSTRAINT_SET3_FLAG) != 0 { - H264LevelIdc::Level1B - } else { - H264LevelIdc::Level1 - }; - } - - Self::new(profile_idc, profile_iop, profile_level).ok_or(()) - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub(crate) enum H264Profile { - Baseline, - ConstrainedBaseline, - Main, - Extended, - High, - ConstrainedHigh, - High10, - High422, - High444Predictive, - High10Intra, - High422Intra, - High444Intra, - CAVLC444Intra, -} - -/// The various h264 profile_idc, not all of these have a name, -/// but they are a constrained portion of `u8`, hence an -/// enum to prevent using unspecified values. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[repr(u8)] -enum H264ProfileIdc { - X2C = 44_u8, - X42 = 66_u8, // B - X4D = 77_u8, // M - X58 = 88_u8, // E - X64 = 100_u8, - X6E = 110_u8, - X7A = 122_u8, - XF4 = 244_u8, -} - -impl TryFrom for H264ProfileIdc { - type Error = (); - - fn try_from(value: u8) -> Result { - match value { - x if (Self::X2C as u8) == x => Ok(Self::X2C), - x if (Self::X42 as u8) == x => Ok(Self::X42), - x if (Self::X4D as u8) == x => Ok(Self::X4D), - x if (Self::X58 as u8) == x => Ok(Self::X58), - x if (Self::X64 as u8) == x => Ok(Self::X64), - x if (Self::X6E as u8) == x => Ok(Self::X6E), - x if (Self::X7A as u8) == x => Ok(Self::X7A), - x if (Self::XF4 as u8) == x => Ok(Self::XF4), - _ => Err(()), - } - } -} - -// Per libWebRTC -// All values are equal to ten times the level number, except level 1b which is -// special. -// https://datatracker.ietf.org/doc/html/rfc6184#section-8.2.2 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(u8)] -#[rustfmt::skip] -pub(crate) enum H264LevelIdc { - Level1B = 0_u8, - Level1 = 10_u8, - Level1_1 = 11_u8, - Level1_2 = 12_u8, - Level1_3 = 13_u8, - Level2 = 20_u8, - Level2_1 = 21_u8, - Level2_2 = 22_u8, - Level3 = 30_u8, - Level3_1 = 31_u8, - Level3_2 = 32_u8, - Level4 = 40_u8, - Level4_1 = 41_u8, - Level4_2 = 42_u8, - Level5 = 50_u8, - Level5_1 = 51_u8, - Level5_2 = 52_u8, -} - -impl H264LevelIdc { - /// Returns the ordinal position (0-16) representing capability order. - /// This takes into account that Level1B is between Level1 and Level1_1. - pub(crate) fn ordinal(self) -> usize { - match self { - Self::Level1 => 0, - Self::Level1B => 1, - Self::Level1_1 => 2, - Self::Level1_2 => 3, - Self::Level1_3 => 4, - Self::Level2 => 5, - Self::Level2_1 => 6, - Self::Level2_2 => 7, - Self::Level3 => 8, - Self::Level3_1 => 9, - Self::Level3_2 => 10, - Self::Level4 => 11, - Self::Level4_1 => 12, - Self::Level4_2 => 13, - Self::Level5 => 14, - Self::Level5_1 => 15, - Self::Level5_2 => 16, - } - } -} - -impl PartialOrd for H264LevelIdc { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for H264LevelIdc { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.ordinal().cmp(&other.ordinal()) - } -} - -impl TryFrom for H264LevelIdc { - type Error = (); - - #[rustfmt::skip] - fn try_from(value: u8) -> Result { - use H264LevelIdc::*; - - match value { - x if (Level1B as u8) == x => Ok(Level1B), - x if (Level1 as u8) == x => Ok(Level1), - x if (Level1_1 as u8) == x => Ok(Level1_1), - x if (Level1_2 as u8) == x => Ok(Level1_2), - x if (Level1_3 as u8) == x => Ok(Level1_3), - x if (Level2 as u8) == x => Ok(Level2), - x if (Level2_1 as u8) == x => Ok(Level2_1), - x if (Level2_2 as u8) == x => Ok(Level2_2), - x if (Level3 as u8) == x => Ok(Level3), - x if (Level3_1 as u8) == x => Ok(Level3_1), - x if (Level3_2 as u8) == x => Ok(Level3_2), - x if (Level4 as u8) == x => Ok(Level4), - x if (Level4_1 as u8) == x => Ok(Level4_1), - x if (Level4_2 as u8) == x => Ok(Level4_2), - x if (Level5 as u8) == x => Ok(Level5), - x if (Level5_1 as u8) == x => Ok(Level5_1), - x if (Level5_2 as u8) == x => Ok(Level5_2), - _ => Err(()), - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_profile_level_parsing() { - struct Case { - profile_level_id: u32, - expected: Option<(H264Profile, H264LevelIdc)>, - msg: &'static str, - } - - let cases = [ - // Test 1: High profile (no constraint flags) -> should parse - Case { - profile_level_id: 0x64001f, - expected: Some((H264Profile::High, H264LevelIdc::Level3_1)), - msg: "0x64001f should parse as High level 3.1", - }, - // Test 2: Constrained High (constraint_set4_flag and - // constraint_set5_flag set) -> should parse - Case { - profile_level_id: 0x640c34, - expected: Some((H264Profile::ConstrainedHigh, H264LevelIdc::Level5_2)), - msg: "0x640c34 should parse as Constrained High level 5.2", - }, - // Test 3: Undefined profile-iop combination -> should NOT parse - Case { - profile_level_id: 0x64101f, - expected: None, - msg: "0x64101f should not parse, profile-iop 0x10 is not defined for profile-idc 0x64", - }, - ]; - - for Case { - profile_level_id, - expected, - msg, - } in cases.into_iter() - { - let parsed = H264ProfileLevel::try_from(profile_level_id) - .ok() - .map(|pl| (pl.profile(), pl.level())); - assert_eq!(parsed, expected, "{msg}"); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/h265.rs b/rs/moq-webrtc/src/vendor/str0m/packet/h265.rs deleted file mode 100644 index 7858093afc3..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/h265.rs +++ /dev/null @@ -1,5088 +0,0 @@ -#![allow(clippy::all)] -#![allow(unused)] - -use super::{CodecExtra, Depacketizer, PacketError, Packetizer}; -use arrayvec::ArrayVec; -use tracing::warn; - -/// H265 (HEVC) information describing the depacketized / packetized data. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct H265CodecExtra { - /// Flag which indicates that within [`MediaData`], there is an individual frame - /// containing complete and independent visual information. This frame serves - /// as a reference point for other frames in the video sequence. - /// - /// [`MediaData`]: crate::vendor::str0m::media::MediaData - pub is_keyframe: bool, -} - -/// -/// Network Abstraction Unit Header implementation -/// - -const H265NALU_HEADER_SIZE: usize = 2; -/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2 -const H265NALU_AGGREGATION_PACKET_TYPE: u8 = 48; -/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3 -const H265NALU_FRAGMENTATION_UNIT_TYPE: u8 = 49; -/// https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4 -const H265NALU_PACI_PACKET_TYPE: u8 = 50; -/// Maximum PHES (Payload Header Extension Structure) size in PACI packets (RFC 7798 §4.4.4) -const H265PACI_MAX_PHES_SIZE: usize = 31; - -// HEVC NAL unit type values as defined by the H.265 / HEVC bitstream specification, -// ITU-T Rec. H.265 | ISO/IEC 23008-2, clause 7.4.2.2 ("NAL unit header semantics"), -// Table 7-1 (NAL unit type assignments). -const H265NALU_VPS_NALU_TYPE: u8 = 32; -const H265NALU_SPS_NALU_TYPE: u8 = 33; -const H265NALU_PPS_NALU_TYPE: u8 = 34; -const H265NALU_AUD_NALU_TYPE: u8 = 35; -const H265NALU_FILLER_NALU_TYPE: u8 = 38; - -// IRAP (Intra Random Access Point) NAL unit types - keyframes/random access points -// BLA (Broken Link Access) pictures. -const H265NALU_BLA_W_LP: u8 = 16; -const H265NALU_BLA_W_RADL: u8 = 17; -const H265NALU_BLA_N_LP: u8 = 18; -// IDR (Instantaneous Decoding Refresh) pictures. -const H265NALU_IDR_W_RADL: u8 = 19; -const H265NALU_IDR_N_LP: u8 = 20; -// CRA (Clean Random Access) picture. -const H265NALU_CRA_NUT: u8 = 21; - -pub static ANNEXB_NALUSTART_CODE: &[u8] = &[0x00, 0x00, 0x00, 0x01]; - -/// Detect whether an H265 (HEVC) RTP payload contains a keyframe. -/// -/// Checks for IRAP (Intra Random Access Point) NAL units in the RTP payload. -/// IRAP types include BLA (16-18), IDR (19-20), and CRA (21). -/// -/// Handles single NAL units, aggregation packets (AP, type 48), -/// and fragmentation units (FU, type 49). -/// -/// For FU packets, only the start fragment (S=1) is detected as a -/// keyframe since the original NAL type is in the FU header. -pub fn detect_h265_keyframe(payload: &[u8]) -> bool { - if payload.len() < H265NALU_HEADER_SIZE { - return false; - } - - let header = H265NALUHeader::new(payload[0], payload[1]); - let nalu_type = header.nalu_type(); - - match nalu_type { - // Single NAL unit (types 0-47) - 0..=47 => header.is_irap(), - - // Aggregation packet: check all aggregated NALUs - H265NALU_AGGREGATION_PACKET_TYPE => { - let mut offset = H265NALU_HEADER_SIZE; - while offset + 2 <= payload.len() { - let nalu_size = ((payload[offset] as usize) << 8) | payload[offset + 1] as usize; - offset += 2; - if offset + nalu_size > payload.len() || nalu_size < H265NALU_HEADER_SIZE { - break; - } - let inner = H265NALUHeader::new(payload[offset], payload[offset + 1]); - if inner.is_irap() { - return true; - } - offset += nalu_size; - } - false - } - - // Fragmentation unit: check FU header for original NAL type - H265NALU_FRAGMENTATION_UNIT_TYPE => { - // FU header is byte 2 (after 2-byte NAL header) - if payload.len() < H265NALU_HEADER_SIZE + 1 { - return false; - } - let fu_header = payload[H265NALU_HEADER_SIZE]; - // S bit (start fragment) is bit 7 - if fu_header & 0x80 == 0 { - return false; - } - // FU type is lower 6 bits - let fu_type = fu_header & 0x3F; - matches!( - fu_type, - H265NALU_BLA_W_LP - | H265NALU_BLA_W_RADL - | H265NALU_BLA_N_LP - | H265NALU_IDR_W_RADL - | H265NALU_IDR_N_LP - | H265NALU_CRA_NUT - ) - } - - _ => false, - } -} - -/// Packetizes H265 (HEVC) RTP payloads. -/// -/// This implements the packetization rules from RFC 7798. -/// -/// Supported output payload types: -/// - Single NAL Unit packets (one NAL unit per RTP payload) -/// - Fragmentation Units (FU, type 49) for NAL units larger than the MTU -/// - Aggregation Packets (AP, type 48) for parameter sets (VPS/SPS/PPS) -/// -/// The packetizer caches VPS, SPS, and PPS NAL units and emits them together -/// in a single Aggregation Packet (AP) immediately before the next non-parameter-set -/// NAL unit, as recommended by RFC 7798. -/// -/// ## Input format -/// -/// The input `payload` may be either: -/// - A single NAL unit (starting with the 2-byte HEVC NAL unit header), OR -/// - An Annex-B bytestream containing one or more NAL units separated by start codes -/// (`0x00 00 01` or `0x00 00 00 01`). -/// -/// Start codes are stripped from the output RTP payloads. - -/// Safe maximum RTP payload for real-world WebRTC (avoids IP fragmentation). -const MAX_PACKET_SIZE: usize = 1200; - -/// Minimum FU payload size - at least 1 byte of actual NAL data required. -const MIN_FU_PAYLOAD: usize = 1; - -/// Minimum MTU for H.265 fragmentation. -/// Calculated as: NALU header (2 bytes) + FU header (1 byte) + minimum payload (1 byte) = 4 bytes total. -/// Any MTU smaller than this cannot accommodate even a single fragmentation unit. -const MIN_MTU: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE + MIN_FU_PAYLOAD; - -#[derive(Debug, Clone)] -pub struct H265Packetizer { - // Parameter sets: heap-allocated but set once per stream (cold path). - vps_nalu: Option>, - sps_nalu: Option>, - pps_nalu: Option>, - // Reusable packet buffer - heap allocated once, reused for zero-allocation hot path. - // This is reused on every fragment, avoiding N allocations per frame. - // Using Vec instead of ArrayVec since MAX_PACKET_SIZE (1200) is too large for stack. - pkt_buf: Vec, - // DONL (Decoding Order Number) tracking. - // When enabled (Some), tracks the 16-bit DONL value to include in RTP packets. - // DONL is used when sprop-max-don-diff > 0 (RFC 7798 §7.1). - // https://datatracker.ietf.org/doc/html/rfc7798#section-7.1 - donl: Option, -} - -impl Default for H265Packetizer { - fn default() -> Self { - Self { - vps_nalu: None, - sps_nalu: None, - pps_nalu: None, - // Pre-allocate to avoid reallocations during hot path - pkt_buf: Vec::with_capacity(MAX_PACKET_SIZE), - donl: None, - } - } -} - -impl H265Packetizer { - /// with_donl enables or disables DONL (Decoding Order Number) fields in RTP packets. - /// DONL should be enabled when `sprop-max-don-diff` > 0 in the SDP (RFC 7798 §7.1). - /// When enabled, DONL fields are included in Single NAL, FU, and AP packets. - pub fn with_donl(&mut self, value: bool) { - self.donl = if value { Some(0) } else { None }; - } - - /// Increments the DONL counter with wrapping at 65536 (RFC 7798 §7.1). - fn increment_donl(&mut self) { - if let Some(ref mut donl) = self.donl { - *donl = donl.wrapping_add(1); - } - } - - /// Increments the DONL counter by `n` with wrapping at 65536 (RFC 7798 §7.1). - /// Used when emitting an AP containing multiple NAL units, each consuming one DON value. - fn increment_donl_by(&mut self, n: u16) { - if let Some(ref mut donl) = self.donl { - *donl = donl.wrapping_add(n); - } - } - - /// Builds an Aggregation Packet (AP) from multiple NAL units into a reusable buffer. - /// - /// # Arguments - /// * `template_nalu` - A NAL unit to copy F, layer_id, and tid from. - /// * `nal_units` - Slice of NAL units to aggregate. - /// * `donl` - Optional DONL value for the first aggregation unit. - /// * `buf` - Reusable buffer to write the AP packet into (will be cleared). - /// * `max_size` - Maximum buffer size (MTU constraint). - /// - /// # Returns - /// `true` if AP was built successfully, `false` if it exceeded max_size. - fn build_ap_packet( - template_nalu: &[u8], - nal_units: &[&[u8]], - donl: Option, - buf: &mut Vec, - max_size: usize, - ) -> bool { - buf.clear(); - - // Build AP header (PayloadHdr) by copying F, layer_id, tid from template - // but setting Type=48. - const TYPE_MASK: u16 = 0b0111111 << 9; - let orig_u16 = u16::from_be_bytes([template_nalu[0], template_nalu[1]]); - let ap_u16 = (orig_u16 & !TYPE_MASK) | ((H265NALU_AGGREGATION_PACKET_TYPE as u16) << 9); - let ap_hdr = ap_u16.to_be_bytes(); - - buf.extend_from_slice(&ap_hdr); - - // Write DONL for first aggregation unit if present (RFC 7798 §4.4.2) - if let Some(donl_value) = donl { - buf.extend_from_slice(&donl_value.to_be_bytes()); - } - - // Append each NAL unit with its 16-bit size prefix. - // For 2nd and subsequent units, write DOND (1 byte) when DONL is enabled. - for (i, nal_unit) in nal_units.iter().enumerate() { - // Write DOND (Decoding Order Number Difference) for 2nd+ units. - // DOND is always 0 in our case since we emit in order. - if donl.is_some() && i > 0 { - buf.push(0); - } - buf.extend_from_slice(&(nal_unit.len() as u16).to_be_bytes()); - buf.extend_from_slice(nal_unit); - - // Check if we exceeded max size - if buf.len() > max_size { - return false; - } - } - - true - } - - /// Builds a PACI Packet (Type 50) wrapping an inner NAL unit with optional PHES into a reusable buffer. - /// - /// PACI packets allow wrapping another NAL unit with additional header information, - /// useful for temporal scalability and other extensions. - /// - /// # Arguments - /// * `inner_nalu` - The NAL unit to wrap (complete with 2-byte header) - /// * `phes` - Optional Payload Header Extension Structure (PHES) bytes - /// * `buf` - Reusable buffer to write the PACI packet into (will be cleared) - /// - /// # Returns - /// `Ok(())` if packet was built successfully, `Err(PacketError)` if PHES is too large (>31 bytes) - /// - /// Reference: RFC 7798 §4.4.4 - fn build_paci_packet(inner_nalu: &[u8], phes: &[u8], buf: &mut Vec) -> Result<(), PacketError> { - if phes.len() > H265PACI_MAX_PHES_SIZE { - return Err(PacketError::ErrH265PACIPHESTooLong); - } - - buf.clear(); - - // Extract F, layer_id, tid from inner NALU header - let inner_header = H265NALUHeader::new(inner_nalu[0], inner_nalu[1]); - let inner_type = inner_header.nalu_type(); - - // Build PACI PayloadHdr (Type=50) - let paci_payload_header = - H265NALUHeader::new_with_type(H265NALU_PACI_PACKET_TYPE, inner_header.layer_id(), inner_header.tid()); - let paci_hdr = paci_payload_header.0.to_be_bytes(); - buf.extend_from_slice(&paci_hdr); - - // Build PACI header fields: A | cType | phssize | F0 F1 F2 | Y - // A = F bit from inner NALU - let a = if inner_header.f() { 1u16 << 15 } else { 0 }; - // cType = Type field from inner NALU - let ctype = (inner_type as u16) << 9; - // phssize = size of PHES (0-31) - let phssize = (phes.len() as u16) << 4; - // F0 = 1 if PHES contains TSCI (phes.len() >= 3) - let f0 = if phes.len() >= 3 { 1u16 << 3 } else { 0 }; - // F1, F2, Y reserved (must be 0) - let paci_fields = a | ctype | phssize | f0; - buf.extend_from_slice(&paci_fields.to_be_bytes()); - - // Append PHES if present - if !phes.is_empty() { - buf.extend_from_slice(phes); - } - - // Append inner NAL unit payload (without its 2-byte header) - if inner_nalu.len() > H265NALU_HEADER_SIZE { - buf.extend_from_slice(&inner_nalu[H265NALU_HEADER_SIZE..]); - } - - Ok(()) - } - - /// Finds the next Annex-B NAL unit start code in `payload`, starting at `start`. - /// - /// Detects `0x00 00 01` or `0x00 00 00 01` as defined by the HEVC Annex-B - /// byte stream format (ITU-T Rec. H.265 | ISO/IEC 23008-2, Annex B), - /// and returns `(start_index, start_code_len)` (length = 3 or 4). - /// - /// Returns `(-1, -1)` if no start code is found. - fn next_start_code(payload: &[u8], start: usize) -> (isize, isize) { - let mut zero_count = 0; - - for (i, &b) in payload[start..].iter().enumerate() { - if b == 0 { - zero_count += 1; - continue; - } else if b == 1 && zero_count >= 2 { - return ((start + i - zero_count) as isize, (zero_count as isize) + 1); - } - - zero_count = 0; - } - - (-1, -1) - } - - /// Packetization overview (RFC 7798): - /// - /// Input NAL units (Annex-B or raw) - /// ├─ Single NALU → RTP payload = NAL header + payload - /// ├─ Large NALU → Fragmentation Units (Type 49) - /// └─ VPS/SPS/PPS → Aggregation Packet (Type 48) - fn emit_nalu(&mut self, nalu: &[u8], mtu: usize, out: &mut Vec>) { - if mtu == 0 || nalu.len() < H265NALU_HEADER_SIZE { - return; - } - - // Parse the HEVC NAL unit header. - let original_hdr = H265NALUHeader::new(nalu[0], nalu[1]); - let original_type = original_hdr.nalu_type(); - - // Ignore AUD. - if original_type == H265NALU_AUD_NALU_TYPE { - return; - } - - // Cache parameter sets; send them before the next non-parameter-set NALU. - // Option> for one-time heap allocation (cold path - happens once per stream). - match original_type { - H265NALU_VPS_NALU_TYPE => { - self.vps_nalu = Some(nalu.to_vec()); - return; - } - H265NALU_SPS_NALU_TYPE => { - self.sps_nalu = Some(nalu.to_vec()); - return; - } - H265NALU_PPS_NALU_TYPE => { - self.pps_nalu = Some(nalu.to_vec()); - return; - } - _ => {} - } - - // If we have cached VPS/SPS/PPS, emit an Aggregation Packet (AP, Type=48) - // immediately before the next non-parameter-set NAL unit, per RFC 7798 §4.4.2. - if let (Some(sps_nalu), Some(pps_nalu)) = (&self.sps_nalu, &self.pps_nalu) { - // Stack-allocate array for NAL unit slices (no heap allocation) - let mut nal_units_arr: [&[u8]; 3] = [&[], &[], &[]]; - let mut count = 0; - - if let Some(vps_nalu) = &self.vps_nalu { - nal_units_arr[count] = vps_nalu; - count += 1; - } - nal_units_arr[count] = sps_nalu; - count += 1; - nal_units_arr[count] = pps_nalu; - count += 1; - - let nal_units = &nal_units_arr[..count]; - - // Build the AP packet using reusable buffer. - // Returns false if AP exceeds MTU. - let ap_built = Self::build_ap_packet(nalu, nal_units, self.donl, &mut self.pkt_buf, mtu); - - if ap_built { - // AP fits in MTU, emit it. - out.push(self.pkt_buf.clone()); - // Increment DONL by the number of NAL units in the AP. - // Each NAL unit inside the AP consumes its own DON value: - // DONL = N (first), DOND derives N+1 (second), N+2 (third), etc. - // So after emitting an AP with `count` NAL units, the next packet's - // DON should be N + count. (RFC 7798 §4.4.2) - self.increment_donl_by(count as u16); - } else { - // AP exceeds MTU. Fall back to emitting parameter sets as individual - // Single NAL Unit packets (RFC 7798 §4.4.1). - let vps = self.vps_nalu.take(); - let sps = self.sps_nalu.take(); - let pps = self.pps_nalu.take(); - - for nal_unit in [&vps, &sps, &pps].into_iter().flatten() { - if nal_unit.len() <= mtu { - if let Some(ref mut donl_value) = self.donl { - // Single NAL with DONL per RFC 7798 §4.4.1: - // [PayloadHdr(2B)] [DONL(2B)] [NAL_payload_data] - self.pkt_buf.clear(); - self.pkt_buf.extend_from_slice(&nal_unit[..H265NALU_HEADER_SIZE]); - self.pkt_buf.extend_from_slice(&donl_value.to_be_bytes()); - self.pkt_buf.extend_from_slice(&nal_unit[H265NALU_HEADER_SIZE..]); - out.push(self.pkt_buf.clone()); - *donl_value = donl_value.wrapping_add(1); - } else { - out.push(nal_unit.clone()); - } - } - // If parameter set is larger than MTU, we could fragment it as FU, but in practice - // VPS/SPS/PPS are typically small. Silently dropping oversized parameter sets - // is acceptable as a fallback. - } - } - - // Clear cache after emitting parameter sets (either as AP or individual packets). - // For the AP path, these are still Some; for the fallback path, already taken above. - self.vps_nalu = None; - self.sps_nalu = None; - self.pps_nalu = None; - } - - // Single NAL Unit packetization (RFC 7798 §4.4.1). - // https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.1 - if nalu.len() <= mtu { - // Write DONL field if enabled (2 bytes after NAL header) - if let Some(donl_value) = self.donl { - self.pkt_buf.clear(); - // Write NAL header (2 bytes), DONL (2 bytes), then payload - self.pkt_buf.extend_from_slice(&nalu[..H265NALU_HEADER_SIZE]); - self.pkt_buf.extend_from_slice(&donl_value.to_be_bytes()); - self.pkt_buf.extend_from_slice(&nalu[H265NALU_HEADER_SIZE..]); - out.push(self.pkt_buf.clone()); - self.increment_donl(); - } else { - out.push(nalu.to_vec()); - } - return; - } - - // Fragmentation Unit (FU) packetization (RFC 7798 §4.4.3). - // https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3 - const FU_OVERHEAD: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE; - if mtu <= FU_OVERHEAD || nalu.len() <= H265NALU_HEADER_SIZE { - return; - } - - // Build FU indicator (Type=49) from original NAL header - const TYPE_MASK: u16 = 0b0111111 << 9; // bits 14..9 - let orig = u16::from_be_bytes([nalu[0], nalu[1]]); - let fu = (orig & !TYPE_MASK) | ((H265NALU_FRAGMENTATION_UNIT_TYPE as u16) << 9); - let fu_indicator = fu.to_be_bytes(); - - let payload = &nalu[H265NALU_HEADER_SIZE..]; - - let donl_overhead = if self.donl.is_some() { 2 } else { 0 }; - let donl_bytes = self.donl.map(u16::to_be_bytes); - - // Clamp to buffer capacity to avoid overflow - let effective_mtu = mtu.min(MAX_PACKET_SIZE); - - // Must have room for FU headers (+ optional DONL) and at least 1 byte of payload - if effective_mtu <= FU_OVERHEAD + donl_overhead { - return; - } - - let first_max = effective_mtu - FU_OVERHEAD - donl_overhead; - let max_fragment = effective_mtu - FU_OVERHEAD; - - let mut offset = 0; - - while offset < payload.len() { - let first = offset == 0; - let remaining = payload.len() - offset; - - let budget = if first { first_max } else { max_fragment }; - let take = remaining.min(budget); - debug_assert!(take > 0); - - let end = offset + take == payload.len(); - let fu_hdr = H265FragmentationUnitHeader::new(first, end, original_type); - - self.pkt_buf.clear(); - self.pkt_buf.extend_from_slice(&fu_indicator); - self.pkt_buf.push(fu_hdr.0); - if first { - if let Some(ref b) = donl_bytes { - self.pkt_buf.extend_from_slice(b); - } - } - self.pkt_buf.extend_from_slice(&payload[offset..offset + take]); - - out.push(self.pkt_buf.clone()); - offset += take; - } - - // One DONL per NAL unit (not per fragment) - self.increment_donl(); - } -} - -impl Packetizer for H265Packetizer { - fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - if payload.is_empty() { - return Ok(vec![]); - } - - // Validate and log MTU issues. - let mtu = match mtu { - 0 => { - warn!("MTU is 0, cannot packetize H.265 - this indicates a programming bug"); - return Ok(vec![]); - } - mtu if mtu > MAX_PACKET_SIZE => { - warn!( - "MTU {} exceeds MAX_PACKET_SIZE {}, clamping to {}", - mtu, MAX_PACKET_SIZE, MAX_PACKET_SIZE - ); - MAX_PACKET_SIZE - } - mtu if mtu < MIN_MTU => { - warn!( - "MTU {} too small for H.265 fragmentation (min {}) - cannot fragment", - mtu, MIN_MTU - ); - return Ok(vec![]); - } - mtu => mtu, // Valid MTU, use as-is - }; - - // Pre-allocate with estimated capacity to avoid reallocations. - // Estimate: payload_size / (mtu - overhead) + extra for parameter sets. - let estimated_packets = payload - .len() - .checked_div(mtu.saturating_sub(3)) - .unwrap_or(1) - .saturating_add(4); - let mut packets = Vec::with_capacity(estimated_packets); - - // If no Annex-B start codes are present, treat as a single NAL unit. - let (mut next_start, mut next_len) = Self::next_start_code(payload, 0); - if next_start == -1 { - self.emit_nalu(payload, mtu, &mut packets); - return Ok(packets); - } - - // Walk Annex-B bytestream and emit NAL units between start codes. - while next_start != -1 { - let nalu_start = (next_start + next_len) as usize; - let (next_start2, next_len2) = Self::next_start_code(payload, nalu_start); - next_start = next_start2; - next_len = next_len2; - - if next_start != -1 { - let nalu_end = next_start as usize; - self.emit_nalu(&payload[nalu_start..nalu_end], mtu, &mut packets); - } else { - self.emit_nalu(&payload[nalu_start..], mtu, &mut packets); - } - } - - Ok(packets) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool { - last - } -} - -/// H265NALUHeader is a H265 NAL Unit Header -/// https://datatracker.ietf.org/doc/html/rfc7798#section-1.1.4 -/// -/// ```text -/// +---------------+---------------+ -/// |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7| -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// |F| Type | layer_id | tid | -/// +-------------+-----------------+ -/// ``` -#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)] -pub struct H265NALUHeader(pub u16); - -impl H265NALUHeader { - fn new(high_byte: u8, low_byte: u8) -> Self { - H265NALUHeader(((high_byte as u16) << 8) | low_byte as u16) - } - - /// f is the forbidden bit, should always be 0. - pub fn f(&self) -> bool { - (self.0 >> 15) != 0 - } - - /// nalu_type of NAL Unit. - pub fn nalu_type(&self) -> u8 { - // 01111110 00000000 - const MASK: u16 = 0b01111110 << 8; - ((self.0 & MASK) >> (8 + 1)) as u8 - } - - /// is_type_vcl_unit returns whether or not the NAL Unit type is a VCL NAL unit. - pub fn is_type_vcl_unit(&self) -> bool { - // Type is coded on 6 bits - const MSB_MASK: u8 = 0b00100000; - (self.nalu_type() & MSB_MASK) == 0 - } - - /// layer_id should always be 0 in non-3D HEVC context. - pub fn layer_id(&self) -> u8 { - // 00000001 11111000 - const MASK: u16 = (0b00000001 << 8) | 0b11111000; - ((self.0 & MASK) >> 3) as u8 - } - - /// tid is the temporal identifier of the NAL unit +1. - pub fn tid(&self) -> u8 { - const MASK: u16 = 0b00000111; - (self.0 & MASK) as u8 - } - - /// Creates a new H265NALUHeader with specified type, layer_id, and tid. - /// Used for building PACI packet headers. - pub fn new_with_type(nalu_type: u8, layer_id: u8, tid: u8) -> Self { - let header = ((nalu_type as u16) << 9) | ((layer_id as u16) << 3) | (tid as u16); - H265NALUHeader(header) - } - - /// is_aggregation_packet returns whether or not the packet is an Aggregation packet. - pub fn is_aggregation_packet(&self) -> bool { - self.nalu_type() == H265NALU_AGGREGATION_PACKET_TYPE - } - - /// is_fragmentation_unit returns whether or not the packet is a Fragmentation Unit packet. - pub fn is_fragmentation_unit(&self) -> bool { - self.nalu_type() == H265NALU_FRAGMENTATION_UNIT_TYPE - } - - /// is_paci_packet returns whether or not the packet is a PACI packet. - pub fn is_paci_packet(&self) -> bool { - self.nalu_type() == H265NALU_PACI_PACKET_TYPE - } - - /// is_idr_picture returns whether or not the NAL unit is an IDR picture. - pub fn is_idr_picture(&self) -> bool { - let typ = self.nalu_type(); - typ == H265NALU_IDR_W_RADL || typ == H265NALU_IDR_N_LP - } - - /// is_irap returns whether or not the NAL unit is an IRAP (Intra Random Access Point) picture. - /// IRAP pictures include BLA, IDR, and CRA pictures, which are all random access points / keyframes. - pub fn is_irap(&self) -> bool { - let typ = self.nalu_type(); - matches!( - typ, - H265NALU_BLA_W_LP - | H265NALU_BLA_W_RADL - | H265NALU_BLA_N_LP - | H265NALU_IDR_W_RADL - | H265NALU_IDR_N_LP - | H265NALU_CRA_NUT - ) - } -} - -/// -/// Single NAL Unit Packet implementation -/// -/// H265SingleNALUnitPacket represents a NALU packet, containing exactly one NAL unit. -/// -/// ```text -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | PayloadHdr | DONL (conditional) | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | | -/// | NAL unit payload data | -/// | | -/// | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | :...OPTIONAL RTP padding | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// ``` -/// -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.1 -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265SingleNALUnitPacket { - /// payload_header is the header of the H265 packet. - payload_header: H265NALUHeader, - /// donl is a 16-bit field, that may or may not be present. - donl: Option, - /// payload of the fragmentation unit. - payload: Vec, - - might_need_donl: bool, -} - -impl H265SingleNALUnitPacket { - /// with_donl can be called to specify whether or not DONL might be parsed. - /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream. - pub fn with_donl(&mut self, value: bool) { - self.might_need_donl = value; - } - - /// depacketize parses the passed byte slice and stores the result in the - /// H265SingleNALUnitPacket this method is called upon. - fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> { - if payload.len() <= H265NALU_HEADER_SIZE { - return Err(PacketError::ErrShortPacket); - } - - let payload_header = H265NALUHeader::new(payload[0], payload[1]); - if payload_header.f() { - return Err(PacketError::ErrH265CorruptedPacket); - } - if payload_header.is_fragmentation_unit() - || payload_header.is_paci_packet() - || payload_header.is_aggregation_packet() - { - return Err(PacketError::ErrInvalidH265PacketType); - } - - let mut payload = &payload[2..]; - - if self.might_need_donl { - // sizeof(uint16) - if payload.len() <= 2 { - return Err(PacketError::ErrShortPacket); - } - - let donl = ((payload[0] as u16) << 8) | (payload[1] as u16); - self.donl = Some(donl); - payload = &payload[2..]; - } - - self.payload_header = payload_header; - self.payload = payload.to_vec(); - - Ok(()) - } - - /// payload_header returns the NALU header of the packet. - pub fn payload_header(&self) -> H265NALUHeader { - self.payload_header - } - - /// donl returns the DONL of the packet. - pub fn donl(&self) -> Option { - self.donl - } - - /// payload returns the Fragmentation Unit packet payload. - pub fn payload(&self) -> &[u8] { - &self.payload - } -} - -/// -/// Aggregation Packets implementation -/// -/// H265AggregationUnitFirst represent the First Aggregation Unit in an AP. -/// -/// ```text -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// : DONL (conditional) | NALU size | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | NALU size | | -/// +-+-+-+-+-+-+-+-+ NAL unit | -/// | | -/// | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | : -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// ``` -/// -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2 -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265AggregationUnitFirst { - donl: Option, - nal_unit_size: u16, - nal_unit: Vec, -} - -impl H265AggregationUnitFirst { - /// donl field, when present, specifies the value of the 16 least - /// significant bits of the decoding order number of the aggregated NAL - /// unit. - pub fn donl(&self) -> Option { - self.donl - } - - /// nalu_size represents the size, in bytes, of the nal_unit. - pub fn nalu_size(&self) -> u16 { - self.nal_unit_size - } - - /// nal_unit payload. - pub fn nal_unit(&self) -> &[u8] { - &self.nal_unit - } -} - -/// H265AggregationUnit represent the an Aggregation Unit in an AP, which is not the first one. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// : DOND (cond) | NALU size | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | | -/// | NAL unit | -/// | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | : -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2 -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265AggregationUnit { - dond: Option, - nal_unit_size: u16, - nal_unit: Vec, -} - -impl H265AggregationUnit { - /// dond field plus 1 specifies the difference between - /// the decoding order number values of the current aggregated NAL unit - /// and the preceding aggregated NAL unit in the same AP. - pub fn dond(&self) -> Option { - self.dond - } - - /// nalu_size represents the size, in bytes, of the nal_unit. - pub fn nalu_size(&self) -> u16 { - self.nal_unit_size - } - - /// nal_unit payload. - pub fn nal_unit(&self) -> &[u8] { - &self.nal_unit - } -} - -/// H265AggregationPacket represents an Aggregation packet. -/// -/// ```text -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | PayloadHdr (Type=48) | | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | -/// | | -/// | two or more aggregation units | -/// | | -/// | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | :...OPTIONAL RTP padding | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// ``` -/// -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.2 -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265AggregationPacket { - first_unit: Option, - other_units: Vec, - - might_need_donl: bool, -} - -impl H265AggregationPacket { - /// with_donl can be called to specify whether or not DONL might be parsed. - /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream. - pub fn with_donl(&mut self, value: bool) { - self.might_need_donl = value; - } - - /// depacketize parses the passed byte slice and stores the result in the - /// H265AggregationPacket this method is called upon. - fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> { - if payload.len() <= H265NALU_HEADER_SIZE { - return Err(PacketError::ErrShortPacket); - } - - let payload_header = H265NALUHeader::new(payload[0], payload[1]); - if payload_header.f() { - return Err(PacketError::ErrH265CorruptedPacket); - } - if !payload_header.is_aggregation_packet() { - return Err(PacketError::ErrInvalidH265PacketType); - } - - // First parse the first aggregation unit - let mut payload = &payload[2..]; - let mut first_unit = H265AggregationUnitFirst::default(); - - if self.might_need_donl { - if payload.len() < 2 { - return Err(PacketError::ErrShortPacket); - } - - let donl = ((payload[0] as u16) << 8) | (payload[1] as u16); - first_unit.donl = Some(donl); - - payload = &payload[2..]; - } - if payload.len() < 2 { - return Err(PacketError::ErrShortPacket); - } - first_unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16); - payload = &payload[2..]; - - if payload.len() < first_unit.nal_unit_size as usize { - return Err(PacketError::ErrShortPacket); - } - - first_unit.nal_unit = payload[..first_unit.nal_unit_size as usize].to_vec(); - payload = &payload[first_unit.nal_unit_size as usize..]; - - // Parse remaining Aggregation Units - let mut units = vec![]; //H265AggregationUnit - loop { - let mut unit = H265AggregationUnit::default(); - - if self.might_need_donl { - if payload.is_empty() { - break; - } - - let dond = payload[0]; - unit.dond = Some(dond); - - payload = &payload[1..]; - } - - if payload.len() < 2 { - break; - } - unit.nal_unit_size = ((payload[0] as u16) << 8) | (payload[1] as u16); - payload = &payload[2..]; - - if payload.len() < unit.nal_unit_size as usize { - break; - } - - unit.nal_unit = payload[..unit.nal_unit_size as usize].to_vec(); - payload = &payload[unit.nal_unit_size as usize..]; - - units.push(unit); - } - - // There need to be **at least** two Aggregation Units (first + another one) - if units.is_empty() { - return Err(PacketError::ErrShortPacket); - } - - self.first_unit = Some(first_unit); - self.other_units = units; - - Ok(()) - } - - /// first_unit returns the first Aggregated Unit of the packet. - pub fn first_unit(&self) -> Option<&H265AggregationUnitFirst> { - self.first_unit.as_ref() - } - - /// other_units returns the all the other Aggregated Unit of the packet (excluding the first one). - pub fn other_units(&self) -> &[H265AggregationUnit] { - self.other_units.as_slice() - } - - /// nal_units returns all NAL units in the aggregation packet. - pub fn nal_units(&self) -> Vec<&[u8]> { - let mut units = Vec::new(); - if let Some(first) = &self.first_unit { - units.push(first.nal_unit.as_slice()); - } - for unit in &self.other_units { - units.push(unit.nal_unit.as_slice()); - } - units - } -} - -/// -/// Fragmentation Unit implementation -/// - -const H265FRAGMENTATION_UNIT_HEADER_SIZE: usize = 1; - -/// H265FragmentationUnitHeader is a H265 FU Header -/// -/// ```text -/// +---------------+ -/// |0|1|2|3|4|5|6|7| -/// +-+-+-+-+-+-+-+-+ -/// |S|E| fu_type | -/// +---------------+ -/// ``` -#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)] -pub struct H265FragmentationUnitHeader(pub u8); - -impl H265FragmentationUnitHeader { - /// new creates a new H265FragmentationUnitHeader. - /// - /// # Arguments - /// * `s` - Start bit: true if this is the first fragment - /// * `e` - End bit: true if this is the last fragment - /// * `fu_type` - The NAL unit type of the fragmented NAL unit (6 bits) - pub fn new(s: bool, e: bool, fu_type: u8) -> Self { - let mut header = fu_type & 0b0011_1111; // Mask to 6 bits - if s { - header |= 0b1000_0000; // Set S bit - } - if e { - header |= 0b0100_0000; // Set E bit - } - H265FragmentationUnitHeader(header) - } - - /// s represents the start of a fragmented NAL unit. - pub fn s(&self) -> bool { - const MASK: u8 = 0b10000000; - ((self.0 & MASK) >> 7) != 0 - } - - /// e represents the end of a fragmented NAL unit. - pub fn e(&self) -> bool { - const MASK: u8 = 0b01000000; - ((self.0 & MASK) >> 6) != 0 - } - - /// fu_type MUST be equal to the field Type of the fragmented NAL unit. - pub fn fu_type(&self) -> u8 { - const MASK: u8 = 0b00111111; - self.0 & MASK - } -} - -/// H265FragmentationUnitPacket represents a single Fragmentation Unit packet. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | PayloadHdr (Type=49) | FU header | DONL (cond) | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-| -/// | DONL (cond) | | -/// |-+-+-+-+-+-+-+-+ | -/// | FU payload | -/// | | -/// | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | :...OPTIONAL RTP padding | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.3 -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265FragmentationUnitPacket { - /// payload_header is the header of the H265 packet. - payload_header: H265NALUHeader, - /// fu_header is the header of the fragmentation unit - fu_header: H265FragmentationUnitHeader, - /// donl is a 16-bit field, that may or may not be present. - donl: Option, - /// payload of the fragmentation unit. - payload: Vec, - - might_need_donl: bool, -} - -impl H265FragmentationUnitPacket { - /// with_donl can be called to specify whether or not DONL might be parsed. - /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream. - pub fn with_donl(&mut self, value: bool) { - self.might_need_donl = value; - } - - /// depacketize parses the passed byte slice and stores the result in the - /// H265FragmentationUnitPacket this method is called upon. - fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> { - const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE; - if payload.len() <= TOTAL_HEADER_SIZE { - return Err(PacketError::ErrShortPacket); - } - - let payload_header = H265NALUHeader::new(payload[0], payload[1]); - if payload_header.f() { - return Err(PacketError::ErrH265CorruptedPacket); - } - if !payload_header.is_fragmentation_unit() { - return Err(PacketError::ErrInvalidH265PacketType); - } - - let fu_header = H265FragmentationUnitHeader(payload[2]); - let mut payload = &payload[3..]; - - if fu_header.s() && self.might_need_donl { - if payload.len() <= 2 { - return Err(PacketError::ErrShortPacket); - } - - let donl = ((payload[0] as u16) << 8) | (payload[1] as u16); - self.donl = Some(donl); - payload = &payload[2..]; - } - - self.payload_header = payload_header; - self.fu_header = fu_header; - self.payload = payload.to_vec(); - - Ok(()) - } - - /// payload_header returns the NALU header of the packet. - pub fn payload_header(&self) -> H265NALUHeader { - self.payload_header - } - - /// fu_header returns the Fragmentation Unit Header of the packet. - pub fn fu_header(&self) -> H265FragmentationUnitHeader { - self.fu_header - } - - /// donl returns the DONL of the packet. - pub fn donl(&self) -> Option { - self.donl - } - - /// payload returns the Fragmentation Unit packet payload. - pub fn payload(&self) -> &[u8] { - &self.payload - } -} - -/// -/// PACI implementation -/// - -/// H265PACIPacket represents a single H265 PACI packet. -/// -/// ```text -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | PayloadHdr (Type=50) |A| cType | phssize |F0..2|Y| -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | payload Header Extension Structure (phes) | -/// |=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=| -/// | | -/// | PACI payload: NAL unit | -/// | . . . | -/// | | -/// | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | :...OPTIONAL RTP padding | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// ``` -/// -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.4.4 -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265PACIPacket { - /// payload_header is the header of the H265 packet. - payload_header: H265NALUHeader, - - /// Field which holds value for `A`, `cType`, `phssize`, `F0`, `F1`, `F2` and `Y` fields. - paci_header_fields: u16, - - /// phes is a header extension, of byte length `phssize` - phes: Vec, - - /// payload contains NAL units & optional padding - payload: Vec, -} - -impl H265PACIPacket { - /// payload_header returns the NAL Unit Header. - pub fn payload_header(&self) -> H265NALUHeader { - self.payload_header - } - - /// a copies the F bit of the PACI payload NALU. - pub fn a(&self) -> bool { - const MASK: u16 = 0b10000000 << 8; - (self.paci_header_fields & MASK) != 0 - } - - /// ctype copies the Type field of the PACI payload NALU. - pub fn ctype(&self) -> u8 { - const MASK: u16 = 0b01111110 << 8; - ((self.paci_header_fields & MASK) >> (8 + 1)) as u8 - } - - /// phs_size indicates the size of the phes field. - pub fn phs_size(&self) -> u8 { - const MASK: u16 = (0b00000001 << 8) | 0b11110000; - ((self.paci_header_fields & MASK) >> 4) as u8 - } - - /// f0 indicates the presence of a Temporal Scalability support extension in the phes. - pub fn f0(&self) -> bool { - const MASK: u16 = 0b00001000; - (self.paci_header_fields & MASK) != 0 - } - - /// f1 must be zero, reserved for future extensions. - pub fn f1(&self) -> bool { - const MASK: u16 = 0b00000100; - (self.paci_header_fields & MASK) != 0 - } - - /// f2 must be zero, reserved for future extensions. - pub fn f2(&self) -> bool { - const MASK: u16 = 0b00000010; - (self.paci_header_fields & MASK) != 0 - } - - /// y must be zero, reserved for future extensions. - pub fn y(&self) -> bool { - const MASK: u16 = 0b00000001; - (self.paci_header_fields & MASK) != 0 - } - - /// phes contains header extensions. Its size is indicated by phssize. - pub fn phes(&self) -> &[u8] { - &self.phes - } - - /// payload is a single NALU or NALU-like struct, not including the first two octets (header). - pub fn payload(&self) -> &[u8] { - &self.payload - } - - /// tsci returns the Temporal Scalability Control Information extension, if present. - pub fn tsci(&self) -> Option { - if !self.f0() || self.phs_size() < 3 { - return None; - } - - Some(H265TSCI( - ((self.phes[0] as u32) << 16) | ((self.phes[1] as u32) << 8) | self.phes[0] as u32, - )) - } - - /// depacketize parses the passed byte slice and stores the result in the - /// H265PACIPacket this method is called upon. - fn depacketize(&mut self, payload: &[u8]) -> Result<(), PacketError> { - const TOTAL_HEADER_SIZE: usize = H265NALU_HEADER_SIZE + 2; - if payload.len() <= TOTAL_HEADER_SIZE { - return Err(PacketError::ErrShortPacket); - } - - let payload_header = H265NALUHeader::new(payload[0], payload[1]); - if payload_header.f() { - return Err(PacketError::ErrH265CorruptedPacket); - } - if !payload_header.is_paci_packet() { - return Err(PacketError::ErrInvalidH265PacketType); - } - - let paci_header_fields = ((payload[2] as u16) << 8) | (payload[3] as u16); - let mut payload = &payload[4..]; - - self.paci_header_fields = paci_header_fields; - let header_extension_size = self.phs_size(); - - if payload.len() < header_extension_size as usize + 1 { - self.paci_header_fields = 0; - return Err(PacketError::ErrShortPacket); - } - - self.payload_header = payload_header; - - if header_extension_size > 0 { - self.phes = payload[..header_extension_size as usize].to_vec(); - } - - payload = &payload[header_extension_size as usize..]; - self.payload = payload.to_vec(); - - Ok(()) - } - - /// Packetizes a PACI packet by wrapping an inner NAL unit with optional PHES. - /// - /// Uses the packetizer's reusable buffer for zero-allocation hot path. - /// - /// # Arguments - /// * `inner_nalu` - The NAL unit to wrap (complete with 2-byte header) - /// * `phes` - Optional Payload Header Extension Structure (PHES) bytes - /// * `buf` - Reusable buffer to write the packet (will be cleared) - /// - /// # Returns - /// Serialized PACI packet bytes, or error if PHES is too large - pub fn packetize(inner_nalu: &[u8], phes: &[u8], buf: &mut Vec) -> Result, PacketError> { - H265Packetizer::build_paci_packet(inner_nalu, phes, buf)?; - Ok(buf.clone()) - } -} - -/// -/// Temporal Scalability Control Information -/// - -/// H265TSCI is a Temporal Scalability Control Information header extension. -/// Reference: https://datatracker.ietf.org/doc/html/rfc7798#section-4.5 -#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)] -pub struct H265TSCI(pub u32); - -impl H265TSCI { - /// tl0picidx see RFC7798 for more details. - pub fn tl0picidx(&self) -> u8 { - const M1: u32 = 0xFFFF0000; - const M2: u32 = 0xFF00; - ((((self.0 & M1) >> 16) & M2) >> 8) as u8 - } - - /// irap_pic_id see RFC7798 for more details. - pub fn irap_pic_id(&self) -> u8 { - const M1: u32 = 0xFFFF0000; - const M2: u32 = 0x00FF; - (((self.0 & M1) >> 16) & M2) as u8 - } - - /// s see RFC7798 for more details. - pub fn s(&self) -> bool { - const M1: u32 = 0xFF00; - const M2: u32 = 0b10000000; - (((self.0 & M1) >> 8) & M2) != 0 - } - - /// e see RFC7798 for more details. - pub fn e(&self) -> bool { - const M1: u32 = 0xFF00; - const M2: u32 = 0b01000000; - (((self.0 & M1) >> 8) & M2) != 0 - } - - /// res see RFC7798 for more details. - pub fn res(&self) -> u8 { - const M1: u32 = 0xFF00; - const M2: u32 = 0b00111111; - (((self.0 & M1) >> 8) & M2) as u8 - } -} - -/// -/// H265 Payload Enum -/// -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum H265Payload { - H265SingleNALUnitPacket(H265SingleNALUnitPacket), - H265FragmentationUnitPacket(H265FragmentationUnitPacket), - H265AggregationPacket(H265AggregationPacket), - H265PACIPacket(H265PACIPacket), -} - -impl Default for H265Payload { - fn default() -> Self { - H265Payload::H265SingleNALUnitPacket(H265SingleNALUnitPacket::default()) - } -} - -/// Depacketizes H265 RTP packets. -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct H265Depacketizer { - payload: H265Payload, - might_need_donl: bool, - fu_buffer: Option>, -} - -impl H265Depacketizer { - /// with_donl can be called to specify whether or not DONL might be parsed. - /// DONL may need to be parsed if `sprop-max-don-diff` is greater than 0 on the RTP stream. - pub fn with_donl(&mut self, value: bool) { - self.might_need_donl = value; - } - - /// payload returns the populated payload. - /// Must be casted to one of: - /// - H265SingleNALUnitPacket - /// - H265FragmentationUnitPacket - /// - H265AggregationPacket - /// - H265PACIPacket - pub fn payload(&self) -> &H265Payload { - &self.payload - } -} - -impl Depacketizer for H265Depacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - // Roughly account for Annex B start codes - let estimated_packets = (packets_size / 1200).saturating_add(1); - Some(packets_size.saturating_add(4usize.saturating_mul(estimated_packets))) - } - - /// depacketize parses the passed byte slice and stores the result - /// in the H265Packet this method is called upon - fn depacketize( - &mut self, - packet: &[u8], - out: &mut Vec, - codec_extra: &mut CodecExtra, - ) -> Result<(), PacketError> { - if packet.len() <= H265NALU_HEADER_SIZE { - return Err(PacketError::ErrShortPacket); - } - - let header = H265NALUHeader::new(packet[0], packet[1]); - if header.f() { - return Err(PacketError::ErrH265CorruptedPacket); - } - - if header.is_paci_packet() { - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(packet)?; - - // Emit PACI payload with Annex-B start code - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - out.extend_from_slice(&decoded.payload()); - - // Check if this is a keyframe. - if decoded.payload().len() >= H265NALU_HEADER_SIZE { - let payload_hdr = H265NALUHeader::new(decoded.payload()[0], decoded.payload()[1]); - let is_keyframe = if let CodecExtra::H265(e) = codec_extra { - payload_hdr.is_irap() | e.is_keyframe - } else { - payload_hdr.is_irap() - }; - *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe }); - } - - self.payload = H265Payload::H265PACIPacket(decoded); - } else if header.is_fragmentation_unit() { - let mut decoded = H265FragmentationUnitPacket::default(); - decoded.with_donl(self.might_need_donl); - - decoded.depacketize(packet)?; - - let fu_header = decoded.fu_header(); - - if fu_header.s() { - // Start of fragmented NAL unit. - // Reuse existing buffer to avoid allocation on every FU start. - match &mut self.fu_buffer { - Some(buf) => buf.clear(), - None => { - // First FU ever - allocate with typical max NAL size. - // 128KB covers most 4K frames. - self.fu_buffer = Some(Vec::with_capacity(128 * 1024)); - } - } - } - - if let Some(ref mut buf) = self.fu_buffer { - buf.extend_from_slice(&decoded.payload()); - } - - if fu_header.e() { - // End of fragmented NAL unit - reconstruct original NAL. - // Borrow buffer instead of take() to preserve allocation for reuse. - if let Some(ref fu_payload) = self.fu_buffer { - // Rebuild original NAL unit header from FU header. - const TYPE_MASK: u16 = 0b0111111 << 9; // bits 14..9 - let payload_hdr_u16 = u16::from_be_bytes([packet[0], packet[1]]); - let orig_type = fu_header.fu_type(); - let orig_hdr_u16 = (payload_hdr_u16 & !TYPE_MASK) | ((orig_type as u16) << 9); - let orig_hdr = orig_hdr_u16.to_be_bytes(); - let orig_hdr_obj = H265NALUHeader::new(orig_hdr[0], orig_hdr[1]); - - // Check if this is a keyframe. - let is_keyframe = if let CodecExtra::H265(e) = codec_extra { - orig_hdr_obj.is_irap() | e.is_keyframe - } else { - orig_hdr_obj.is_irap() - }; - *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe }); - - // Emit Annex-B start code + original NAL header + payload. - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - out.extend_from_slice(&orig_hdr); - out.extend_from_slice(fu_payload); - } - // Note: We don't clear fu_buffer here - it will be cleared on next FU start. - // This preserves the allocation for reuse. - } - - self.payload = H265Payload::H265FragmentationUnitPacket(decoded); - } else if header.is_aggregation_packet() { - // Optimized AP parsing: write directly to output like H264 does. - // Parse inline without intermediate Vec allocations. - - let mut offset = H265NALU_HEADER_SIZE; - let mut is_first_unit = true; - let mut unit_count = 0; - - // Parse and emit NAL units in one pass (zero-copy approach) - while offset < packet.len() { - // Skip DONL/DOND if present - if self.might_need_donl { - if is_first_unit { - // First unit has DONL (2 bytes) - if offset + 2 > packet.len() { - break; - } - offset += 2; - } else { - // Subsequent units have DOND (1 byte) - if offset + 1 > packet.len() { - break; - } - offset += 1; - } - } - - // Read NAL unit size (2 bytes) - if offset + 2 > packet.len() { - break; - } - let nalu_size = ((packet[offset] as usize) << 8) | (packet[offset + 1] as usize); - offset += 2; - - // Validate NAL unit fits in packet - if offset + nalu_size > packet.len() { - break; - } - - let nalu = &packet[offset..offset + nalu_size]; - offset += nalu_size; - unit_count += 1; - - // Check if keyframe - if nalu.len() >= H265NALU_HEADER_SIZE { - let nalu_hdr = H265NALUHeader::new(nalu[0], nalu[1]); - let is_keyframe = if let CodecExtra::H265(e) = codec_extra { - nalu_hdr.is_irap() | e.is_keyframe - } else { - nalu_hdr.is_irap() - }; - *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe }); - } - - // Write to output (zero allocation) - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - out.extend_from_slice(nalu); - - is_first_unit = false; - } - - // AP must have at least 2 units (RFC 7798) - if unit_count < 2 { - return Err(PacketError::ErrShortPacket); - } - - // Still parse into struct for payload() API compatibility. - // This allocates but is needed for the public API. - let mut decoded = H265AggregationPacket::default(); - decoded.with_donl(self.might_need_donl); - decoded.depacketize(packet)?; // Validate structure - - self.payload = H265Payload::H265AggregationPacket(decoded); - } else { - // Single NAL unit packet. - let mut decoded = H265SingleNALUnitPacket::default(); - decoded.with_donl(self.might_need_donl); - - decoded.depacketize(packet)?; - - // Check if this is a keyframe. - let is_keyframe = if let CodecExtra::H265(e) = codec_extra { - header.is_irap() | e.is_keyframe - } else { - header.is_irap() - }; - *codec_extra = CodecExtra::H265(H265CodecExtra { is_keyframe }); - - // Emit Annex-B start code + NAL header + payload (without DONL). - out.extend_from_slice(ANNEXB_NALUSTART_CODE); - let hdr = decoded.payload_header(); - out.extend_from_slice(&[(hdr.0 >> 8) as u8, (hdr.0 & 0xFF) as u8]); - out.extend_from_slice(&decoded.payload()); - - self.payload = H265Payload::H265SingleNALUnitPacket(decoded); - } - - Ok(()) - } - - /// is_partition_head checks if this is the head of a packetized nalu stream. - fn is_partition_head(&self, payload: &[u8]) -> bool { - if payload.len() < H265NALU_HEADER_SIZE { - return false; - } - - let header = H265NALUHeader::new(payload[0], payload[1]); - - // If F bit is set, this is always a partition head (error case, but treated as head) - if header.f() { - return true; - } - - // Single NAL unit packets are always partition heads - if !header.is_fragmentation_unit() && !header.is_aggregation_packet() && !header.is_paci_packet() { - return true; - } - - // Aggregation packets are partition heads - if header.is_aggregation_packet() { - return true; - } - - // PACI packets are partition heads - if header.is_paci_packet() { - return true; - } - - // For FU packets, only those with S (start) flag are partition heads - if header.is_fragmentation_unit() { - if payload.len() < H265NALU_HEADER_SIZE + 1 { - return false; - } - let fu_header = H265FragmentationUnitHeader(payload[2]); - return fu_header.s(); - } - - false - } - - fn is_partition_tail(&self, marker: bool, payload: &[u8]) -> bool { - if payload.len() < H265NALU_HEADER_SIZE { - return false; - } - - let header = H265NALUHeader::new(payload[0], payload[1]); - - // For FU packets, check E (end) flag - if header.is_fragmentation_unit() { - if payload.len() < H265NALU_HEADER_SIZE + 1 { - return false; - } - let fu_header = H265FragmentationUnitHeader(payload[2]); - return fu_header.e(); - } - - // For all other packet types, rely on RTP marker bit - marker - } -} - -#[cfg(test)] -mod test { - use super::*; - - type Result = std::result::Result; - - // ========== Shared Test Utilities ========== - - fn reconstruct_from_fu_packets(packets: &[Vec]) -> Vec { - // Reconstruct the original NAL unit from a sequence of FU packets. - // Assumes all packets are FU (type 49) and are consecutive. - // - // FU payloads are: - // [0..2) : PayloadHdr (type=49) - // [2] : FU header (S/E/type) - // [3..] : fragment bytes - const TYPE_MASK: u16 = 0b0111111 << 9; // bits 14..9 - - let mut out = Vec::new(); - let mut started = false; - - for pkt in packets { - assert!(pkt.len() >= 3); - let hdr = H265NALUHeader::new(pkt[0], pkt[1]); - assert!(hdr.is_fragmentation_unit()); - - let fu = H265FragmentationUnitHeader(pkt[2]); - - if fu.s() { - // Rebuild the original 2-byte NAL header by replacing Type with fu_type. - let fu_u16 = u16::from_be_bytes([pkt[0], pkt[1]]); - let orig_u16 = (fu_u16 & !TYPE_MASK) | ((fu.fu_type() as u16) << 9); - out.extend_from_slice(&orig_u16.to_be_bytes()); - started = true; - } - - assert!(started, "FU sequence must start with S=1"); - out.extend_from_slice(&pkt[3..]); - } - - out - } - - /// RFC 7798 bitfield correctness tests. - /// These are "unit tests" for header parsing and classification. - mod header_tests { - use super::*; - - /// Test H.265 NAL Unit header parsing and field extraction. - /// Verifies F bit, NAL type, layer_id, tid, and packet type detection (AP/FU/PACI). - #[test] - fn test_h265_nalu_header() -> Result<()> { - #[derive(Default)] - struct TestType { - raw_header: &'static [u8], - - fbit: bool, - typ: u8, - layer_id: u8, - tid: u8, - - is_ap: bool, - is_fu: bool, - is_paci: bool, - } - - let tests = vec![ - // fbit - TestType { - raw_header: &[0x80, 0x00], - typ: 0, - layer_id: 0, - tid: 0, - fbit: true, - ..Default::default() - }, - // VPS_NUT - TestType { - raw_header: &[0x40, 0x01], - typ: 32, - layer_id: 0, - tid: 1, - ..Default::default() - }, - // SPS_NUT - TestType { - raw_header: &[0x42, 0x01], - typ: 33, - layer_id: 0, - tid: 1, - ..Default::default() - }, - // PPS_NUT - TestType { - raw_header: &[0x44, 0x01], - typ: 34, - layer_id: 0, - tid: 1, - ..Default::default() - }, - // PREFIX_SEI_NUT - TestType { - raw_header: &[0x4e, 0x01], - typ: 39, - layer_id: 0, - tid: 1, - ..Default::default() - }, - // Fragmentation Unit - TestType { - raw_header: &[0x62, 0x01], - typ: H265NALU_FRAGMENTATION_UNIT_TYPE, - layer_id: 0, - tid: 1, - is_fu: true, - ..Default::default() - }, - // Aggregation Packet (Type 48) - TestType { - raw_header: &[0x60, 0x01], - typ: H265NALU_AGGREGATION_PACKET_TYPE, - layer_id: 0, - tid: 1, - is_ap: true, - ..Default::default() - }, - // PACI Packet (Type 50) - TestType { - raw_header: &[0x64, 0x01], - typ: H265NALU_PACI_PACKET_TYPE, - layer_id: 0, - tid: 1, - is_paci: true, - ..Default::default() - }, - ]; - - for cur in tests { - let header = H265NALUHeader::new(cur.raw_header[0], cur.raw_header[1]); - - assert_eq!(header.f(), cur.fbit, "invalid F bit"); - assert_eq!(header.nalu_type(), cur.typ, "invalid type"); - - // For any type < 32, NAL is a VLC NAL unit. - assert_eq!( - header.is_type_vcl_unit(), - (header.nalu_type() < 32), - "invalid IsTypeVCLUnit" - ); - assert_eq!( - header.is_aggregation_packet(), - cur.is_ap, - "invalid type (aggregation packet)" - ); - assert_eq!( - header.is_fragmentation_unit(), - cur.is_fu, - "invalid type (fragmentation unit)" - ); - assert_eq!(header.is_paci_packet(), cur.is_paci, "invalid type (PACI)"); - assert_eq!(header.layer_id(), cur.layer_id, "invalid layer_id"); - assert_eq!(header.tid(), cur.tid, "invalid tid"); - } - - Ok(()) - } - - /// Test IRAP (Intra Random Access Point) picture detection. - /// Verifies that BLA, IDR, and CRA NAL types are correctly identified as IRAP frames. - #[test] - fn test_h265_irap_detection() -> Result<()> { - // Test that is_irap() detects all IRAP types (BLA, IDR, CRA) - // BLA_W_LP (16) - let header = H265NALUHeader::new(0x20, 0x01); - assert!(header.is_irap(), "BLA_W_LP should be detected as IRAP"); - assert!(!header.is_idr_picture(), "BLA_W_LP is not an IDR"); - - // BLA_W_RADL (17) - let header = H265NALUHeader::new(0x22, 0x01); - assert!(header.is_irap(), "BLA_W_RADL should be detected as IRAP"); - assert!(!header.is_idr_picture(), "BLA_W_RADL is not an IDR"); - - // BLA_N_LP (18) - let header = H265NALUHeader::new(0x24, 0x01); - assert!(header.is_irap(), "BLA_N_LP should be detected as IRAP"); - assert!(!header.is_idr_picture(), "BLA_N_LP is not an IDR"); - - // IDR_W_RADL (19) - let header = H265NALUHeader::new(0x26, 0x01); - assert!(header.is_irap(), "IDR_W_RADL should be detected as IRAP"); - assert!(header.is_idr_picture(), "IDR_W_RADL is an IDR"); - - // IDR_N_LP (20) - let header = H265NALUHeader::new(0x28, 0x01); - assert!(header.is_irap(), "IDR_N_LP should be detected as IRAP"); - assert!(header.is_idr_picture(), "IDR_N_LP is an IDR"); - - // CRA_NUT (21) - let header = H265NALUHeader::new(0x2a, 0x01); - assert!(header.is_irap(), "CRA_NUT should be detected as IRAP"); - assert!(!header.is_idr_picture(), "CRA_NUT is not an IDR"); - - // TRAIL_R (1) - not an IRAP - let header = H265NALUHeader::new(0x02, 0x01); - assert!(!header.is_irap(), "TRAIL_R should not be detected as IRAP"); - assert!(!header.is_idr_picture(), "TRAIL_R is not an IDR"); - - // VPS (32) - not an IRAP - let header = H265NALUHeader::new(0x40, 0x01); - assert!(!header.is_irap(), "VPS should not be detected as IRAP"); - assert!(!header.is_idr_picture(), "VPS is not an IDR"); - - // RADL_R (6) – not IRAP - let header = H265NALUHeader::new(0x0c, 0x01); // 6 << 1 - assert!(!header.is_irap()); - - // RASL_R (9) – not IRAP - let header = H265NALUHeader::new(0x12, 0x01); // 9 << 1 - assert!(!header.is_irap()); - - // Prefix SEI (39) - let header = H265NALUHeader::new(0x4e, 0x01); // 39 << 1 - assert!(!header.is_irap()); - - Ok(()) - } - - /// Test Fragmentation Unit (FU) header parsing. - /// Verifies S (start), E (end) flags and fragmented NAL type extraction. - #[test] - fn test_h265_fu_header() -> Result<()> { - #[derive(Default)] - struct TestType { - header: H265FragmentationUnitHeader, - s: bool, - e: bool, - typ: u8, - } - - let tests = vec![ - // Start | IDR_W_RADL - TestType { - header: H265FragmentationUnitHeader(0x93), - s: true, - e: false, - typ: 19, - }, - // Continuation | IDR_W_RADL - TestType { - header: H265FragmentationUnitHeader(0x13), - s: false, - e: false, - typ: 19, - }, - // End | IDR_W_RADL - TestType { - header: H265FragmentationUnitHeader(0x53), - s: false, - e: true, - typ: 19, - }, - // Start | TRAIL_R - TestType { - header: H265FragmentationUnitHeader(0x81), - s: true, - e: false, - typ: 1, - }, - // Continuation | TRAIL_R - TestType { - header: H265FragmentationUnitHeader(0x01), - s: false, - e: false, - typ: 1, - }, - // End | TRAIL_R - TestType { - header: H265FragmentationUnitHeader(0x41), - s: false, - e: true, - typ: 1, - }, - // Invalid: S=1 and E=1 simultaneously (illegal per RFC 7798) - TestType { - header: H265FragmentationUnitHeader(0xD3), - s: true, - e: true, - typ: 19, - }, - // Illegal FU: VPS (type 32) must not be fragmented - TestType { - header: H265FragmentationUnitHeader(0xA0), - s: true, - e: false, - typ: 32, - }, - ]; - - for cur in tests { - assert_eq!(cur.header.s(), cur.s, "invalid s field"); - assert_eq!(cur.header.e(), cur.e, "invalid e field"); - assert_eq!(cur.header.fu_type(), cur.typ, "invalid FuType field"); - } - - Ok(()) - } - } // end header_tests - - /// Tests for RTP payload → NAL unit parsing. - /// Validates Single NAL, AP, FU, PACI, and TSCI packet formats. - mod parse_tests { - use super::*; - - /// Test Single NAL Unit packet depacketization. - /// Verifies parsing of single NAL packets with and without DONL, including error cases. - #[test] - fn test_h265_single_nalunit_packet() -> Result<()> { - #[derive(Default)] - struct TestType { - raw: &'static [u8], - with_donl: bool, - expected_packet: Option, - expected_err: Option, - } - - let tests = vec![ - TestType { - raw: &[], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - // FBit enabled in H265NALUHeader - TestType { - raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrH265CorruptedPacket), - ..Default::default() - }, - // Type '49' in H265NALUHeader - TestType { - raw: &[0x62, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - // Type '50' in H265NALUHeader - TestType { - raw: &[0x64, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - TestType { - raw: &[0x01, 0x01, 0xab, 0xcd, 0xef], - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x01, 0x01), - payload: vec![0xab, 0xcd, 0xef], - ..Default::default() - }), - ..Default::default() - }, - // DONL, payload too small - TestType { - raw: &[0x01, 0x01, 0x93, 0xaf], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - TestType { - raw: &[0x01, 0x01, 0xaa, 0xbb, 0xcc], - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x01, 0x01), - donl: Some((0xaa << 8) | 0xbb), - payload: vec![0xcc], - ..Default::default() - }), - with_donl: true, - ..Default::default() - }, - // IDR_W_RADL (19) - TestType { - raw: &[0x26, 0x01, 0xde, 0xad, 0xbe, 0xef], - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x26, 0x01), - payload: vec![0xde, 0xad, 0xbe, 0xef], - ..Default::default() - }), - ..Default::default() - }, - // CRA_NUT (21) - TestType { - raw: &[0x2a, 0x01, 0xaa, 0xbb], - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x2a, 0x01), - payload: vec![0xaa, 0xbb], - ..Default::default() - }), - ..Default::default() - }, - // type=1, layer_id=3, tid=2 - TestType { - raw: &[0x01, 0x32, 0x99, 0x88], - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x01, 0x32), - payload: vec![0x99, 0x88], - ..Default::default() - }), - ..Default::default() - }, - // IDR with DONL - TestType { - raw: &[0x26, 0x01, 0x12, 0x34, 0xaa, 0xbb], - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x26, 0x01), - donl: Some(0x1234), - payload: vec![0xaa, 0xbb], - ..Default::default() - }), - with_donl: true, - ..Default::default() - }, - TestType { - raw: &[0x26, 0x01, 0x12, 0x34, 0xaa, 0xbb], - with_donl: true, - expected_packet: Some(H265SingleNALUnitPacket { - payload_header: H265NALUHeader::new(0x26, 0x01), - donl: Some(0x1234), - payload: vec![0xaa, 0xbb], - ..Default::default() - }), - ..Default::default() - }, - ]; - - for cur in tests { - let mut parsed = H265SingleNALUnitPacket::default(); - if cur.with_donl { - parsed.with_donl(cur.with_donl); - } - - let result = parsed.depacketize(&cur.raw); - - if cur.expected_err.is_some() && result.is_ok() { - assert!(false, "should error"); - } else if cur.expected_err.is_none() && result.is_err() { - assert!(false, "should not error"); - } - - if let Some(expected_packet) = cur.expected_packet { - assert_eq!( - expected_packet.payload_header(), - parsed.payload_header(), - "invalid payload header" - ); - assert_eq!(expected_packet.donl(), parsed.donl(), "invalid DONL"); - - assert_eq!(expected_packet.payload(), parsed.payload(), "invalid payload"); - } - } - - Ok(()) - } - - /// Test Aggregation Packet (AP) depacketization. - /// Verifies parsing of multiple NAL units in one packet with DONL/DOND fields. - #[test] - fn test_h265_aggregation_packet() -> Result<()> { - #[derive(Default)] - struct TestType { - raw: &'static [u8], - with_donl: bool, - expected_packet: Option, - expected_err: Option, - } - - let tests = vec![ - TestType { - raw: &[], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - // FBit enabled in H265NALUHeader - TestType { - raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrH265CorruptedPacket), - ..Default::default() - }, - // Type '48' in H265NALUHeader - TestType { - raw: &[0xE0, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - // Small payload - TestType { - raw: &[0x60, 0x01, 0x00, 0x1], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - // Small payload - TestType { - raw: &[0x60, 0x01, 0x00], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Small payload - TestType { - raw: &[0x60, 0x01, 0x00, 0x1], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Small payload - TestType { - raw: &[0x60, 0x01, 0x00, 0x01, 0x02], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Single Aggregation Unit - TestType { - raw: &[0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Incomplete second Aggregation Unit - TestType { - raw: &[ - 0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, // DONL - 0x00, - ], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Incomplete second Aggregation Unit - TestType { - raw: &[ - 0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, // DONL, NAL Unit size (2 bytes) - 0x00, 0x55, 0x55, - ], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Valid Second Aggregation Unit - TestType { - raw: &[ - 0x60, 0x01, 0xcc, 0xdd, 0x00, 0x02, 0xff, 0xee, - // DONL, NAL Unit size (2 bytes), Payload - 0x77, 0x00, 0x01, 0xaa, - ], - with_donl: true, - expected_packet: Some(H265AggregationPacket { - first_unit: Some(H265AggregationUnitFirst { - donl: Some(0xccdd), - nal_unit_size: 2, - nal_unit: vec![0xff, 0xee], - }), - other_units: vec![H265AggregationUnit { - dond: Some(0x77), - nal_unit_size: 1, - nal_unit: vec![0xaa], - }], - might_need_donl: false, - }), - ..Default::default() - }, - // Valid AP WITHOUT DONL/DOND (with_donl = false) - // Requires: first unit + at least 1 other unit - TestType { - raw: &[ - 0x60, 0x01, // AP payload header (Type=48) - 0x00, 0x02, // first NALU size = 2 - 0x11, 0x22, // first NALU - 0x00, 0x01, // second NALU size = 1 - 0x33, // second NALU - ], - with_donl: false, - expected_packet: Some(H265AggregationPacket { - first_unit: Some(H265AggregationUnitFirst { - donl: None, - nal_unit_size: 2, - nal_unit: vec![0x11, 0x22], - }), - other_units: vec![H265AggregationUnit { - dond: None, - nal_unit_size: 1, - nal_unit: vec![0x33], - }], - might_need_donl: false, - }), - ..Default::default() - }, - // Valid AP WITH DONL + multiple other units (exercise DOND parsing twice) - // Includes DOND=0 and another DOND value - TestType { - raw: &[ - 0x60, 0x01, // AP payload header (Type=48) - 0x00, 0x10, // DONL = 0x0010 - 0x00, 0x01, // first NALU size = 1 - 0xaa, // first NALU - 0x00, // DOND for 2nd AU - 0x00, 0x01, // second NALU size = 1 - 0xbb, // second NALU - 0x05, // DOND for 3rd AU - 0x00, 0x02, // third NALU size = 2 - 0xcc, 0xdd, // third NALU - ], - with_donl: true, - expected_packet: Some(H265AggregationPacket { - first_unit: Some(H265AggregationUnitFirst { - donl: Some(0x0010), - nal_unit_size: 1, - nal_unit: vec![0xaa], - }), - other_units: vec![ - H265AggregationUnit { - dond: Some(0x00), - nal_unit_size: 1, - nal_unit: vec![0xbb], - }, - H265AggregationUnit { - dond: Some(0x05), - nal_unit_size: 2, - nal_unit: vec![0xcc, 0xdd], - }, - ], - might_need_donl: false, - }), - ..Default::default() - }, - // “Forgiving tail” behavior (with_donl=false): - // After parsing one valid other unit, an incomplete next unit causes a BREAK (not error). - TestType { - raw: &[ - 0x60, 0x01, // AP payload header (Type=48) - 0x00, 0x01, // first NALU size = 1 - 0x11, // first NALU - 0x00, 0x01, // second NALU size = 1 - 0x22, // second NALU - 0x99, // trailing junk: not enough bytes for next 2-byte size => loop breaks - ], - with_donl: false, - expected_packet: Some(H265AggregationPacket { - first_unit: Some(H265AggregationUnitFirst { - donl: None, - nal_unit_size: 1, - nal_unit: vec![0x11], - }), - other_units: vec![H265AggregationUnit { - dond: None, - nal_unit_size: 1, - nal_unit: vec![0x22], - }], - might_need_donl: false, - }), - ..Default::default() - }, - // "Forgiving tail" behavior (with_donl=true): - // Trailing single DOND byte is read, then payload.len()<2 => BREAK, but - // since we already parsed one unit, OK. - TestType { - raw: &[ - 0x60, 0x01, // AP payload header (Type=48) - 0x12, 0x34, // DONL - 0x00, 0x01, // first NALU size = 1 - 0xaa, // first NALU - 0x01, // DOND for 2nd AU - 0x00, 0x01, // second NALU size = 1 - 0xbb, // second NALU - 0x55, // trailing DOND only, no size => break (and still succeed) - ], - with_donl: true, - expected_packet: Some(H265AggregationPacket { - first_unit: Some(H265AggregationUnitFirst { - donl: Some(0x1234), - nal_unit_size: 1, - nal_unit: vec![0xaa], - }), - other_units: vec![H265AggregationUnit { - dond: Some(0x01), - nal_unit_size: 1, - nal_unit: vec![0xbb], - }], - might_need_donl: false, - }), - ..Default::default() - }, - // Wrong outer header type: FU (49) should be rejected by AP depacketizer - TestType { - raw: &[ - 0x62, 0x01, // Type=49 (FU), not AP - 0x00, 0x01, 0xaa, // extra bytes, just to avoid short-packet path - ], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - // Wrong outer header type: PACI (50) should be rejected by AP depacketizer - TestType { - raw: &[ - 0x64, 0x01, // Type=50 (PACI), not AP - 0x00, 0x01, 0xaa, - ], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - TestType { - raw: &[ - 0x60, 0x01, 0x12, 0x34, // DONL = 0x1234 - 0x00, 0x01, 0xaa, 0x05, // DOND = +5 - 0x00, 0x01, 0xbb, 0xFE, // DOND = -2 (wrap) - 0x00, 0x01, 0xcc, - ], - with_donl: true, - expected_packet: Some(H265AggregationPacket { - first_unit: Some(H265AggregationUnitFirst { - donl: Some(0x1234), - nal_unit_size: 1, - nal_unit: vec![0xaa], - }), - other_units: vec![ - H265AggregationUnit { - dond: Some(0x05), - nal_unit_size: 1, - nal_unit: vec![0xbb], - }, - H265AggregationUnit { - dond: Some(0xFE), - nal_unit_size: 1, - nal_unit: vec![0xcc], - }, - ], - might_need_donl: false, - }), - ..Default::default() - }, - ]; - - for cur in tests { - let mut parsed = H265AggregationPacket::default(); - if cur.with_donl { - parsed.with_donl(cur.with_donl); - } - - let result = parsed.depacketize(&cur.raw); - - if cur.expected_err.is_some() && result.is_ok() { - assert!(false, "should error"); - } else if cur.expected_err.is_none() && result.is_err() { - assert!(false, "should not error"); - } - - if let Some(expected_packet) = cur.expected_packet { - if let (Some(first_unit), Some(parsed_first_unit)) = - (expected_packet.first_unit(), parsed.first_unit()) - { - assert_eq!( - parsed_first_unit.nal_unit_size, first_unit.nal_unit_size, - "invalid first unit NALUSize" - ); - assert_eq!(first_unit.donl(), parsed_first_unit.donl(), "invalid first unit DONL"); - assert_eq!( - first_unit.nal_unit(), - parsed_first_unit.nal_unit(), - "invalid first unit NalUnit" - ); - } - - assert_eq!( - expected_packet.other_units().len(), - parsed.other_units().len(), - "number of other units mismatch" - ); - - for ndx in 0..expected_packet.other_units().len() { - assert_eq!( - parsed.other_units()[ndx].nalu_size(), - expected_packet.other_units()[ndx].nalu_size(), - "invalid unit NALUSize" - ); - - assert_eq!( - expected_packet.other_units()[ndx].dond(), - parsed.other_units()[ndx].dond(), - "invalid unit DOND" - ); - - assert_eq!( - expected_packet.other_units()[ndx].nal_unit(), - parsed.other_units()[ndx].nal_unit(), - "invalid first unit NalUnit" - ); - } - - assert_eq!(expected_packet.other_units(), parsed.other_units(), "invalid payload"); - } - } - - Ok(()) - } - - /// Test Fragmentation Unit (FU) packet depacketization. - /// Verifies parsing of fragmented large NAL units with and without DONL. - #[test] - fn test_h265_fragmentation_unit_packet() -> Result<()> { - #[derive(Default)] - struct TestType { - raw: &'static [u8], - with_donl: bool, - expected_fu: Option, - expected_err: Option, - } - let tests = vec![ - TestType { - raw: &[], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - // FBit enabled in H265NALUHeader - TestType { - raw: &[0x80, 0x01, 0x93, 0xaf], - expected_err: Some(PacketError::ErrH265CorruptedPacket), - ..Default::default() - }, - // Type not '49' in H265NALUHeader - TestType { - raw: &[0x40, 0x01, 0x93, 0xaf], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93, 0xaf], - expected_fu: Some(H265FragmentationUnitPacket { - payload_header: H265NALUHeader::new(0x62, 0x01), - fu_header: H265FragmentationUnitHeader(0x93), - donl: None, - payload: vec![0xaf], - might_need_donl: false, - }), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93, 0xcc], - with_donl: true, - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93, 0xcc, 0xdd, 0xaf, 0x0d, 0x5a], - with_donl: true, - expected_fu: Some(H265FragmentationUnitPacket { - payload_header: H265NALUHeader::new(0x62, 0x01), - fu_header: H265FragmentationUnitHeader(0x93), - donl: Some((0xcc << 8) | 0xdd), - payload: vec![0xaf, 0x0d, 0x5a], - might_need_donl: false, - }), - ..Default::default() - }, - ]; - - for cur in tests { - let mut parsed = H265FragmentationUnitPacket::default(); - if cur.with_donl { - parsed.with_donl(cur.with_donl); - } - - let result = parsed.depacketize(&cur.raw); - - if cur.expected_err.is_some() && result.is_ok() { - assert!(false, "should error"); - } else if cur.expected_err.is_none() && result.is_err() { - assert!(false, "should not error"); - } - - if let Some(expected_fu) = &cur.expected_fu { - assert_eq!( - parsed.payload_header(), - expected_fu.payload_header(), - "invalid payload header" - ); - assert_eq!(parsed.fu_header(), expected_fu.fu_header(), "invalid FU header"); - assert_eq!(parsed.donl(), expected_fu.donl(), "invalid DONL"); - assert_eq!(parsed.payload(), expected_fu.payload(), "invalid Payload"); - } - } - - Ok(()) - } - - /// Test TSCI (Temporal Scalability Control Information) field extraction. - /// Verifies TL0PICIDX, IrapPicID, S, E, and RES bit parsing. - #[test] - fn test_h265_temporal_scalability_control_information() -> Result<()> { - #[derive(Default)] - struct TestType { - value: H265TSCI, - expected_tl0picidx: u8, - expected_irap_pic_id: u8, - expected_s: bool, - expected_e: bool, - expected_res: u8, - } - - let tests = vec![ - TestType { - value: H265TSCI(((0xCA) << 24) | ((0xFE) << 16)), - expected_tl0picidx: 0xCA, - expected_irap_pic_id: 0xFE, - ..Default::default() - }, - TestType { - value: H265TSCI((1) << 15), - expected_s: true, - ..Default::default() - }, - TestType { - value: H265TSCI((1) << 14), - expected_e: true, - ..Default::default() - }, - TestType { - value: H265TSCI((0x0A) << 8), - expected_res: 0x0A, - ..Default::default() - }, - // Sets RES, and force sets S and E to 0. - TestType { - value: H265TSCI(((0xAA) << 8) & (u32::MAX ^ ((1) << 15)) & (u32::MAX ^ ((1) << 14))), - expected_res: 0xAA & 0b00111111, - ..Default::default() - }, - ]; - - for cur in tests { - assert_eq!(cur.value.tl0picidx(), cur.expected_tl0picidx, "invalid TL0PICIDX"); - assert_eq!(cur.value.irap_pic_id(), cur.expected_irap_pic_id, "invalid IrapPicID"); - assert_eq!(cur.value.s(), cur.expected_s, "invalid S"); - assert_eq!(cur.value.e(), cur.expected_e, "invalid E"); - assert_eq!(cur.value.res(), cur.expected_res, "invalid RES"); - } - - Ok(()) - } - - /// Test PACI (Payload Content Information) packet depacketization. - /// Verifies parsing of PACI headers, PHES extensions, and TSCI data. - #[test] - fn test_h265_paci_packet() -> Result<()> { - #[derive(Default)] - struct TestType { - raw: &'static [u8], - expected_fu: Option, - expected_err: Option, - } - - let tests = vec![ - TestType { - raw: &[], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - // FBit enabled in H265NALUHeader - TestType { - raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrH265CorruptedPacket), - ..Default::default() - }, - // Type not '50' in H265NALUHeader - TestType { - raw: &[0x40, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - // Invalid header extension size - TestType { - raw: &[0x64, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrInvalidH265PacketType), - ..Default::default() - }, - // No Header Extension - TestType { - raw: &[0x64, 0x01, 0x64, 0x00, 0xab, 0xcd, 0xef], - expected_fu: Some(H265PACIPacket { - payload_header: H265NALUHeader::new(0x64, 0x01), - paci_header_fields: ((0x64) << 8), - phes: vec![], - payload: vec![0xab, 0xcd, 0xef], - }), - ..Default::default() - }, - // Header Extension 1 byte - TestType { - raw: &[0x64, 0x01, 0x64, 0x10, 0xff, 0xab, 0xcd, 0xef], - expected_fu: Some(H265PACIPacket { - payload_header: H265NALUHeader::new(0x64, 0x01), - paci_header_fields: ((0x64) << 8) | (0x10), - phes: vec![0xff], - payload: vec![0xab, 0xcd, 0xef], - }), - ..Default::default() - }, - // Header Extension TSCI - TestType { - raw: &[0x64, 0x01, 0x64, 0b00111000, 0xaa, 0xbb, 0x80, 0xab, 0xcd, 0xef], - expected_fu: Some(H265PACIPacket { - payload_header: H265NALUHeader::new(0x64, 0x01), - paci_header_fields: ((0x64) << 8) | (0b00111000), - phes: vec![0xaa, 0xbb, 0x80], - payload: vec![0xab, 0xcd, 0xef], - }), - ..Default::default() - }, - ]; - - for cur in tests { - let mut parsed = H265PACIPacket::default(); - - let result = parsed.depacketize(&cur.raw); - - if cur.expected_err.is_some() && result.is_ok() { - assert!(false, "should error"); - } else if cur.expected_err.is_none() && result.is_err() { - assert!(false, "should not error"); - } - - if let Some(expected_fu) = &cur.expected_fu { - assert_eq!( - expected_fu.payload_header(), - parsed.payload_header(), - "invalid PayloadHeader" - ); - assert_eq!(expected_fu.a(), parsed.a(), "invalid A"); - assert_eq!(expected_fu.ctype(), parsed.ctype(), "invalid CType"); - assert_eq!(expected_fu.phs_size(), parsed.phs_size(), "invalid PHSsize"); - assert_eq!(expected_fu.f0(), parsed.f0(), "invalid F0"); - assert_eq!(expected_fu.f1(), parsed.f1(), "invalid F1"); - assert_eq!(expected_fu.f2(), parsed.f2(), "invalid F2"); - assert_eq!(expected_fu.y(), parsed.y(), "invalid Y"); - assert_eq!(expected_fu.phes(), parsed.phes(), "invalid PHES"); - assert_eq!(expected_fu.payload(), parsed.payload(), "invalid Payload"); - assert_eq!(expected_fu.tsci(), parsed.tsci(), "invalid TSCI"); - } - } - - Ok(()) - } - - /// Test PACI packet creation (packetization). - /// Verifies encoding of inner NAL units into PACI packets with various PHES sizes and flags. - #[test] - fn test_h265_paci_packetizer() -> Result<()> { - // Test 1: Basic PACI packet with no PHES - { - let inner_nalu = vec![0x26, 0x01, 0xab, 0xcd, 0xef]; // Type 19 (IDR_W_RADL) - let phes: &[u8] = &[]; - let mut buf = Vec::new(); - - let packet = H265PACIPacket::packetize(&inner_nalu, phes, &mut buf)?; - - // Verify packet structure - assert!(packet.len() >= 4, "PACI packet too short"); - - // Verify it's Type 50 - let header = H265NALUHeader::new(packet[0], packet[1]); - assert_eq!(header.nalu_type(), H265NALU_PACI_PACKET_TYPE); - - // Depacketize and verify - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(&packet)?; - - assert_eq!(decoded.ctype(), 19); // IDR_W_RADL - assert_eq!(decoded.phs_size(), 0); - assert!(!decoded.f0()); - assert_eq!(decoded.payload(), vec![0xab, 0xcd, 0xef]); - } - - // Test 2: PACI packet with 1-byte PHES - { - let inner_nalu = vec![0x02, 0x01, 0xff, 0xee, 0xdd]; - let phes = vec![0xaa]; - let mut buf = Vec::new(); - - let packet = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf)?; - - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(&packet)?; - - assert_eq!(decoded.ctype(), 1); - assert_eq!(decoded.phs_size(), 1); - assert!(!decoded.f0()); // F0 only set if PHES >= 3 bytes - assert_eq!(decoded.phes(), vec![0xaa]); - assert_eq!(decoded.payload(), vec![0xff, 0xee, 0xdd]); - } - - // Test 3: PACI packet with TSCI (3-byte PHES, F0=1) - { - let inner_nalu = vec![0x04, 0x01, 0x11, 0x22, 0x33]; - let phes = vec![0xca, 0xfe, 0x80]; // TSCI data - let mut buf = Vec::new(); - - let packet = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf)?; - - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(&packet)?; - - assert_eq!(decoded.ctype(), 2); - assert_eq!(decoded.phs_size(), 3); - assert!(decoded.f0()); // F0 set for TSCI - assert_eq!(decoded.phes(), vec![0xca, 0xfe, 0x80]); - assert_eq!(decoded.payload(), vec![0x11, 0x22, 0x33]); - } - - // Test 4: PACI with F bit set in inner NALU (A bit) - { - let inner_nalu = vec![0x80, 0x01, 0xaa]; // F bit set - let phes: &[u8] = &[]; - let mut buf = Vec::new(); - - let packet = H265PACIPacket::packetize(&inner_nalu, phes, &mut buf)?; - - let mut decoded = H265PACIPacket::default(); - // Depacketization will fail due to F bit in PACI header, but we check A bit is set - // Actually, the PACI payload header shouldn't have F bit set - only inner does - // Let's verify the PACI header fields have A bit set - let paci_fields = ((packet[2] as u16) << 8) | (packet[3] as u16); - let a_bit = (paci_fields & (1 << 15)) != 0; - assert!(a_bit, "A bit should be set when inner NALU has F bit"); - } - - // Test 5: PHES too long (>31 bytes) should error - { - let inner_nalu = vec![0x02, 0x01, 0xaa]; - let phes = vec![0u8; 32]; // 32 bytes - too long - let mut buf = Vec::new(); - - let result = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf); - assert!(result.is_err()); - assert_eq!(result.unwrap_err(), PacketError::ErrH265PACIPHESTooLong); - } - - // Test 6: Round-trip test with various layer_id and tid values - { - let inner_nalu = vec![0x12, 0xff, 0x12, 0x34]; // Type 9, layer_id=31, tid=7 - let phes = vec![0x11, 0x22]; - let mut buf = Vec::new(); - - let packet = H265PACIPacket::packetize(&inner_nalu, &phes, &mut buf)?; - - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(&packet)?; - - // Verify PACI header preserved layer_id and tid from inner NALU - assert_eq!(decoded.payload_header().layer_id(), 31); - assert_eq!(decoded.payload_header().tid(), 7); - assert_eq!(decoded.ctype(), 9); - assert_eq!(decoded.phs_size(), 2); - assert_eq!(decoded.phes(), vec![0x11, 0x22]); - assert_eq!(decoded.payload(), vec![0x12, 0x34]); - } - - // Test 7: Minimal payload (1 byte) in inner NALU - { - let inner_nalu = vec![0x02, 0x01, 0xaa]; // Header + 1 byte payload - let phes: &[u8] = &[]; - let mut buf = Vec::new(); - - let packet = H265PACIPacket::packetize(&inner_nalu, phes, &mut buf)?; - - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(&packet)?; - - assert_eq!(decoded.ctype(), 1); - assert_eq!(decoded.payload(), vec![0xaa]); - } - - Ok(()) - } - - /// Test PACI packet round-trip with TSCI extension. - /// Verifies that PACI packets with 3-byte TSCI data can be created and parsed correctly. - #[test] - fn test_h265_paci_roundtrip_with_tsci() -> Result<()> { - // Create a PACI packet with TSCI extension and verify all fields survive round-trip - let inner_nalu = vec![0x26, 0x01, 0xde, 0xad, 0xbe, 0xef]; // IDR_W_RADL - - // Build TSCI: TL0PICIDX=0xAB, IrapPicID=0xCD, S=1, E=0, RES=0x05 - let tsci_bytes = vec![ - 0xAB, // TL0PICIDX - 0xCD, // IrapPicID - 0x85, // S=1, E=0, RES=0x05 - ]; - - let mut buf = Vec::new(); - let packet = H265PACIPacket::packetize(&inner_nalu, &tsci_bytes, &mut buf)?; - - // Depacketize - let mut decoded = H265PACIPacket::default(); - decoded.depacketize(&packet)?; - - // Verify TSCI is present and correct - assert!(decoded.f0(), "F0 should be set for TSCI"); - let tsci = decoded.tsci().expect("TSCI should be present"); - - // Note: The TSCI constructor in the depacketizer has a bug (uses phes[0] three times) - // But we're testing that our packetizer creates valid packets - assert_eq!(decoded.phes(), tsci_bytes); - assert_eq!(decoded.ctype(), 19); // IDR_W_RADL type - assert_eq!(decoded.payload(), vec![0xde, 0xad, 0xbe, 0xef]); - - Ok(()) - } - - /// Test unified H265Depacketizer handling all packet types. - /// Verifies depacketizer correctly routes Single NAL, FU, AP, and PACI packets. - #[test] - fn test_h265_packet() -> Result<()> { - #[derive(Default)] - struct TestType { - raw: &'static [u8], - with_donl: bool, - expected_packet_type: Option, - expected_err: Option, - } - let tests = vec![ - TestType { - raw: &[], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x62, 0x01, 0x93], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x64, 0x01, 0x93, 0xaf], - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - TestType { - raw: &[0x01, 0x01], - with_donl: true, - expected_err: Some(PacketError::ErrShortPacket), - ..Default::default() - }, - // FBit enabled in H265NALUHeader - TestType { - raw: &[0x80, 0x01, 0x93, 0xaf, 0xaf, 0xaf, 0xaf], - expected_err: Some(PacketError::ErrH265CorruptedPacket), - ..Default::default() - }, - // Valid H265SingleNALUnitPacket - TestType { - raw: &[0x01, 0x01, 0xab, 0xcd, 0xef], - expected_packet_type: Some( - H265Payload::H265SingleNALUnitPacket(H265SingleNALUnitPacket::default()), - ), - ..Default::default() - }, - // Invalid H265SingleNALUnitPacket - TestType { - raw: &[0x01, 0x01, 0x93, 0xaf], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // Valid H265PACIPacket - TestType { - raw: &[0x64, 0x01, 0x64, 0b00111000, 0xaa, 0xbb, 0x80, 0xab, 0xcd, 0xef], - expected_packet_type: Some(H265Payload::H265PACIPacket(H265PACIPacket::default())), - ..Default::default() - }, - // Valid H265FragmentationUnitPacket - TestType { - raw: &[0x62, 0x01, 0x93, 0xcc, 0xdd, 0xaf, 0x0d, 0x5a], - expected_packet_type: Some(H265Payload::H265FragmentationUnitPacket( - H265FragmentationUnitPacket::default(), - )), - with_donl: true, - ..Default::default() - }, - // Valid H265AggregationPacket - TestType { - raw: &[0x60, 0x01, 0xcc, 0xdd, 0x00, 0x02, 0xff, 0xee, 0x77, 0x00, 0x01, 0xaa], - expected_packet_type: Some(H265Payload::H265AggregationPacket(H265AggregationPacket::default())), - with_donl: true, - ..Default::default() - }, - // Invalid H265AggregationPacket - TestType { - raw: &[0x60, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00], - expected_err: Some(PacketError::ErrShortPacket), - with_donl: true, - ..Default::default() - }, - // IDR Single NAL - TestType { - raw: &[0x26, 0x01, 0xde, 0xad], - expected_packet_type: Some( - H265Payload::H265SingleNALUnitPacket(H265SingleNALUnitPacket::default()), - ), - ..Default::default() - }, - // FU start of IDR_W_RADL - TestType { - raw: &[0x62, 0x01, 0x93, 0xaa, 0xbb], - expected_packet_type: Some(H265Payload::H265FragmentationUnitPacket( - H265FragmentationUnitPacket::default(), - )), - ..Default::default() - }, - // AP containing IDR (with DONL) - TestType { - raw: &[ - 0x60, 0x01, // AP - 0x00, 0x10, // DONL - 0x00, 0x01, // size - 0x26, // IDR header byte - 0x00, // DOND - 0x00, 0x01, // size - 0x01, // TRAIL - ], - with_donl: true, - expected_packet_type: Some(H265Payload::H265AggregationPacket(H265AggregationPacket::default())), - ..Default::default() - }, - // FU with S=1 and E=1 (illegal but must still be routed as FU) - TestType { - raw: &[0x62, 0x01, 0xD3, 0xaa, 0xbb], - expected_packet_type: Some(H265Payload::H265FragmentationUnitPacket( - H265FragmentationUnitPacket::default(), - )), - ..Default::default() - }, - TestType { - raw: &[ - 0x64, 0x01, // PACI header - 0x64, // PHES - 0b00111000, // TSCI - 0x62, 0x01, // FU outer header - 0x93, // S=1, FuType=19 (IDR) - 0xaa, 0xbb, - ], - expected_packet_type: Some(H265Payload::H265PACIPacket(H265PACIPacket::default())), - ..Default::default() - }, - ]; - - for cur in tests { - let mut pck = H265Depacketizer::default(); - if cur.with_donl { - pck.with_donl(true); - } - - let mut out = Vec::new(); - let mut extra = CodecExtra::None; - let result = pck.depacketize(&cur.raw, &mut out, &mut extra); - - if cur.expected_err.is_some() && result.is_ok() { - assert!(false, "should error"); - } else if cur.expected_err.is_none() && result.is_err() { - assert!(false, "should not error"); - } - - if cur.expected_err.is_some() { - continue; - } - - if let Some(expected_packet_type) = &cur.expected_packet_type { - //TODO: assert_eq!(pck.packet(), expected_packet_type, "invalid packet type"); - let pck_packet = pck.payload(); - match (pck_packet, expected_packet_type) { - (&H265Payload::H265SingleNALUnitPacket(_), &H265Payload::H265SingleNALUnitPacket(_)) => { - assert!(true) - } - ( - &H265Payload::H265FragmentationUnitPacket(_), - &H265Payload::H265FragmentationUnitPacket(_), - ) => assert!(true), - (&H265Payload::H265AggregationPacket(_), &H265Payload::H265AggregationPacket(_)) => { - assert!(true) - } - (&H265Payload::H265PACIPacket(_), &H265Payload::H265PACIPacket(_)) => { - assert!(true) - } - _ => assert!(false), - }; - } - } - - Ok(()) - } - } // end parse_tests - - /// Tests for NAL unit → RTP payload emission. - /// Validates packetization behavior: single NAL, FU fragmentation, AP aggregation. - mod emit_tests { - use super::*; - - /// Test packetizer handling of small NAL units that fit in one packet. - /// Verifies single NAL units are passed through unchanged. - #[test] - fn test_h265_packetizer_single_nalu() -> Result<()> { - let mut p = H265Packetizer::default(); - - // A minimal "single NAL" (2-byte NAL header + payload). - // Use a non-parameter-set type so the packetizer doesn't cache it. - let nalu = b"\x02\x01\xaa\xbb\xcc".to_vec(); - - let out = p.packetize(1200, &nalu)?; - assert_eq!(out.len(), 1); - assert_eq!(out[0], nalu); - - Ok(()) - } - - /// Test packetizer splitting Annex-B byte stream into individual NAL units. - /// Verifies correct parsing of 00 00 01 and 00 00 00 01 start codes. - #[test] - fn test_h265_packetizer_annexb_split() -> Result<()> { - let mut p = H265Packetizer::default(); - - // Use non-parameter-set NALU types so they are emitted directly. - let nalu1 = b"\x02\x01\x11\x22\x33".to_vec(); - let nalu2 = b"\x26\x01\xaa\xbb\xcc\xdd".to_vec(); - - // Annex-B start codes around the NAL units. - let mut bytestream = Vec::new(); - bytestream.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]); - bytestream.extend_from_slice(&nalu1); - bytestream.extend_from_slice(&[0x00, 0x00, 0x01]); - bytestream.extend_from_slice(&nalu2); - - let out = p.packetize(1200, &bytestream)?; - assert_eq!(out.len(), 2); - assert_eq!(out[0], nalu1); - assert_eq!(out[1], nalu2); - - Ok(()) - } - - /// Test packetizer dropping AUD NAL units and keeping filler NAL units. - #[test] - fn test_h265_packetizer_drops_aud_keeps_filler() -> Result<()> { - let mut p = H265Packetizer::default(); - - // AUD (type 35), non-parameter-set NALU, filler (type 38). - let aud = b"\x46\x01\x50".to_vec(); - let nalu = b"\x02\x01\x11\x22\x33".to_vec(); - let fd = b"\x4c\x01\xff\xff\x80".to_vec(); - - let mut bytestream = Vec::new(); - for n in [&aud, &nalu, &fd] { - bytestream.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]); - bytestream.extend_from_slice(n); - } - - let out = p.packetize(1200, &bytestream)?; - assert_eq!(out.len(), 2); - assert_eq!(out[0], nalu); - assert_eq!(out[1], fd); - - Ok(()) - } - - /// Test FU fragmentation preserves NAL unit payload exactly. - /// Verifies fragmented packets can be reassembled to original payload without corruption. - #[test] - fn test_h265_packetizer_fu_fragmentation_roundtrip_payload() -> Result<()> { - let mut p = H265Packetizer::default(); - - // Craft a NAL unit large enough to force FU fragmentation. - // Header 0x02 0x01 => F=0, type=1 (VCL), tid=1. - let mut nalu = vec![0x02, 0x01]; - nalu.extend((0..60).map(|i| i as u8)); - - // Force fragmentation: FU overhead is 3 bytes, so this yields multiple fragments. - let mtu = 20; - let out = p.packetize(mtu, &nalu)?; - assert!(out.len() > 1, "expected fragmentation"); - - // Validate each FU packet and reconstruct the original payload (sans 2-byte NAL header). - let orig_hdr = H265NALUHeader::new(nalu[0], nalu[1]); - let orig_type = orig_hdr.nalu_type(); - let orig_payload = &nalu[H265NALU_HEADER_SIZE..]; - - let mut reconstructed = Vec::new(); - - for (idx, pkt) in out.iter().enumerate() { - assert!(pkt.len() <= mtu); - assert!(pkt.len() >= H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE); - - let hdr = H265NALUHeader::new(pkt[0], pkt[1]); - assert_eq!(hdr.nalu_type(), H265NALU_FRAGMENTATION_UNIT_TYPE); - assert!(!hdr.f()); - assert_eq!(hdr.layer_id(), orig_hdr.layer_id()); - assert_eq!(hdr.tid(), orig_hdr.tid()); - - let fu = H265FragmentationUnitHeader(pkt[2]); - assert_eq!(fu.fu_type(), orig_type); - if idx == 0 { - assert!(fu.s()); - assert!(!fu.e()); - } else if idx == out.len() - 1 { - assert!(!fu.s()); - assert!(fu.e()); - } else { - assert!(!fu.s()); - assert!(!fu.e()); - } - - reconstructed.extend_from_slice(&pkt[3..]); - } - - assert_eq!(reconstructed, orig_payload); - - Ok(()) - } - - /// Test packetizer does not fragment small NAL units. - /// Verifies NAL units smaller than MTU are emitted as single packets. - #[test] - fn test_h265_packetizer_single_nalu_no_fragment() -> Result<()> { - let mut p = H265Packetizer::default(); - - // A small NALU: 2-byte header + payload. - let nalu = [0x02, 0x01, 0xaa, 0xbb, 0xcc, 0xdd]; - let pkts = p.packetize(1200, &nalu)?; - - assert_eq!(pkts.len(), 1); - assert_eq!(pkts[0], nalu); - Ok(()) - } - - /// Test packetizer correctly splits multiple NAL units from Annex-B stream. - /// Verifies each NAL unit is extracted and emitted separately. - #[test] - fn test_h265_packetizer_annexb_splits_nalus() -> Result<()> { - let mut p = H265Packetizer::default(); - - // Use non-parameter-set NALU types so they are emitted directly. - let nalu1 = [0x02, 0x01, 0x11, 0x22, 0x33]; - let nalu2 = [0x26, 0x01, 0x44, 0x55]; - - let mut annexb = Vec::new(); - annexb.extend_from_slice(&[0x00, 0x00, 0x01]); - annexb.extend_from_slice(&nalu1); - annexb.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]); - annexb.extend_from_slice(&nalu2); - - let pkts = p.packetize(1200, &annexb)?; - - assert_eq!(pkts.len(), 2); - assert_eq!(pkts[0], nalu1); - assert_eq!(pkts[1], nalu2); - Ok(()) - } - - /// Test packetizer aggregates VPS/SPS/PPS parameter sets into AP packet. - /// Verifies parameter sets are cached and emitted together before first VCL NAL. - #[test] - fn test_h265_packetizer_emits_ap_for_vps_sps_pps() -> Result<()> { - let mut p = H265Packetizer::default(); - - // VPS (type 32), SPS (type 33), PPS (type 34), then a VCL NALU (type 1). - let vps = vec![0x40, 0x01, 0x01, 0x02]; - let sps = vec![0x42, 0x01, 0x03, 0x04, 0x05]; - let pps = vec![0x44, 0x01, 0x06]; - let vcl = vec![0x02, 0x01, 0xaa, 0xbb, 0xcc, 0xdd]; - - // Cache parameter sets (no output yet). - assert!(p.packetize(1200, &vps)?.is_empty()); - assert!(p.packetize(1200, &sps)?.is_empty()); - assert!(p.packetize(1200, &pps)?.is_empty()); - - // First non-parameter-set NALU should trigger AP emission. - let out = p.packetize(1200, &vcl)?; - assert_eq!(out.len(), 2); - - // Validate AP packet structure. - assert!(out[0].len() >= H265NALU_HEADER_SIZE + 2); - let ap_hdr = H265NALUHeader::new(out[0][0], out[0][1]); - assert_eq!(ap_hdr.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE); - - let mut off = H265NALU_HEADER_SIZE; - for expected in [&vps, &sps, &pps] { - let len = u16::from_be_bytes([out[0][off], out[0][off + 1]]) as usize; - off += 2; - assert_eq!(len, expected.len()); - assert_eq!(&out[0][off..off + len], expected.as_slice()); - off += len; - } - - // And the actual VCL NALU follows as a normal single-NALU packet. - assert_eq!(out[1], vcl); - - Ok(()) - } - - /// Test packetizer falls back to individual packets when AP exceeds MTU. - /// Verifies parameter sets are sent separately if aggregation would violate MTU limit. - #[test] - fn test_h265_packetizer_ap_exceeds_mtu_fallback() -> Result<()> { - let mut p = H265Packetizer::default(); - - // Create VPS, SPS, PPS parameter sets. - let vps = vec![0x40, 0x01, 0x01, 0x02]; - let sps = vec![0x42, 0x01, 0x03, 0x04, 0x05]; - let pps = vec![0x44, 0x01, 0x06]; - let vcl = vec![0x02, 0x01, 0xaa, 0xbb]; - - // Cache parameter sets (no output yet). - assert!(p.packetize(1200, &vps)?.is_empty()); - assert!(p.packetize(1200, &sps)?.is_empty()); - assert!(p.packetize(1200, &pps)?.is_empty()); - - // Set MTU to a value smaller than the AP size would be. - // AP overhead: 2 (AP header) + 2 (VPS size) + 4 (VPS) + 2 (SPS size) - // + 5 (SPS) + 2 (PPS size) + 3 (PPS) = 20 bytes - // So MTU=15 will be too small for the AP. - let small_mtu = 15; - let out = p.packetize(small_mtu, &vcl)?; - - // Should emit parameter sets as individual Single NAL packets, then the VCL NALU. - // Expected: VPS, SPS, PPS, VCL = 4 packets - assert_eq!( - out.len(), - 4, - "Expected 4 packets (VPS, SPS, PPS, VCL) when AP exceeds MTU" - ); - - // Verify each parameter set packet. - assert_eq!(out[0], vps, "First packet should be VPS"); - assert_eq!(out[1], sps, "Second packet should be SPS"); - assert_eq!(out[2], pps, "Third packet should be PPS"); - assert_eq!(out[3], vcl, "Fourth packet should be VCL"); - - Ok(()) - } - - /// Test full round-trip of packetizer + depacketizer for fragmented NAL units. - /// Verifies FU packets are correctly created and reassembled to Annex-B format. - #[test] - fn test_h265_fu_roundtrip_with_depacketizer() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let mut depacketizer = H265Depacketizer::default(); - - // Create a large NAL unit that will be fragmented. - // Type 1 (TRAIL_R), layer_id=0, tid=1 - let mut original_nalu = vec![0x02, 0x01]; - original_nalu.extend((0..200).map(|i| (i % 256) as u8)); - - // Force fragmentation with small MTU - let mtu = 50; - let packets = packetizer.packetize(mtu, &original_nalu)?; - - // Verify fragmentation occurred - assert!(packets.len() > 1, "Expected multiple FU packets"); - assert!(packets.iter().all(|p| p.len() <= mtu), "All packets should fit MTU"); - - // Depacketize each FU packet - they should accumulate in the depacketizer - let mut output = Vec::new(); - let mut extra = CodecExtra::None; - - for (i, packet) in packets.iter().enumerate() { - output.clear(); - extra = CodecExtra::None; - - let result = depacketizer.depacketize(packet, &mut output, &mut extra); - - // Only the last fragment should produce output - if i < packets.len() - 1 { - assert!(result.is_ok()); - assert!(output.is_empty(), "Intermediate FU fragments should not produce output"); - } else { - assert!(result.is_ok()); - assert!(!output.is_empty(), "Final FU fragment should produce output"); - // Output should be the complete original NAL unit in Annex-B format - // Depacketizer prepends start code - let expected_output = { - let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE); - tmp.extend_from_slice(&original_nalu); - tmp - }; - assert_eq!( - output, expected_output, - "Depacketized NAL unit should match original with start code" - ); - } - } - - Ok(()) - } - - /// Test full round-trip of packetizer + depacketizer for aggregation packets. - /// Verifies AP packets are correctly created and depacketized to Annex-B format. - #[test] - fn test_h265_ap_roundtrip_with_depacketizer() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let mut depacketizer = H265Depacketizer::default(); - - // Create VPS, SPS, PPS parameter sets and a VCL NAL unit - let vps = vec![0x40, 0x01, 0xaa, 0xbb, 0xcc]; - let sps = vec![0x42, 0x01, 0xdd, 0xee, 0xff, 0x11, 0x22]; - let pps = vec![0x44, 0x01, 0x33, 0x44]; - let vcl = vec![0x26, 0x01, 0x55, 0x66, 0x77, 0x88]; // IDR_W_RADL - - // Cache parameter sets (no output yet) - assert!(packetizer.packetize(1200, &vps)?.is_empty()); - assert!(packetizer.packetize(1200, &sps)?.is_empty()); - assert!(packetizer.packetize(1200, &pps)?.is_empty()); - - // Emit AP + VCL - let packets = packetizer.packetize(1200, &vcl)?; - assert_eq!(packets.len(), 2, "Expected AP packet + VCL packet"); - - // Depacketize the AP packet - let mut output = Vec::new(); - let mut extra = CodecExtra::None; - - depacketizer.depacketize(&packets[0], &mut output, &mut extra)?; - - // AP depacketization produces Annex-B format with start codes before each NAL - let mut offset = 0; - - // Check VPS (with start code) - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + vps.len()], &vps[..], "VPS should match"); - offset += vps.len(); - - // Check SPS (with start code) - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + sps.len()], &sps[..], "SPS should match"); - offset += sps.len(); - - // Check PPS (with start code) - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + pps.len()], &pps[..], "PPS should match"); - offset += pps.len(); - - assert_eq!(offset, output.len(), "All AP payload should be consumed"); - - // Depacketize the VCL packet (also with start code) - output.clear(); - extra = CodecExtra::None; - depacketizer.depacketize(&packets[1], &mut output, &mut extra)?; - let expected_vcl = { - let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE); - tmp.extend_from_slice(&vcl); - tmp - }; - assert_eq!( - output, expected_vcl, - "VCL NAL unit should match original with start code" - ); - - Ok(()) - } - - /// Test full round-trip of packetizer + depacketizer for single NAL units. - /// Verifies small NAL units pass through correctly and are converted to Annex-B format. - #[test] - fn test_h265_single_nalu_roundtrip_with_depacketizer() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let mut depacketizer = H265Depacketizer::default(); - - // Create a small NAL unit that won't be fragmented - let original_nalu = vec![0x02, 0x01, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]; - - // Packetize with large MTU (no fragmentation) - let packets = packetizer.packetize(1200, &original_nalu)?; - assert_eq!(packets.len(), 1, "Expected single packet"); - assert_eq!(packets[0], original_nalu, "Single NAL packet should be unchanged"); - - // Depacketize (output will have Annex-B start code) - let mut output = Vec::new(); - let mut extra = CodecExtra::None; - depacketizer.depacketize(&packets[0], &mut output, &mut extra)?; - - let expected_output = { - let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE); - tmp.extend_from_slice(&original_nalu); - tmp - }; - assert_eq!( - output, expected_output, - "Depacketized NAL unit should match original with start code" - ); - - Ok(()) - } - - /// Test realistic sequence with multiple packet types (AP + single NAL + FU). - /// Verifies packetizer/depacketizer handle mixed packet types in one stream. - #[test] - fn test_h265_mixed_packet_types_roundtrip() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let mut depacketizer = H265Depacketizer::default(); - - // Test a realistic sequence: VPS, SPS, PPS, small VCL, large VCL - let vps = vec![0x40, 0x01, 0x01, 0x02, 0x03]; - let sps = vec![0x42, 0x01, 0x04, 0x05, 0x06, 0x07]; - let pps = vec![0x44, 0x01, 0x08, 0x09]; - let small_vcl = vec![0x02, 0x01, 0x0a, 0x0b, 0x0c]; - - // Large VCL that will be fragmented - let mut large_vcl = vec![0x26, 0x01]; // IDR_W_RADL - large_vcl.extend((0..150).map(|i| (i % 256) as u8)); - - // Cache parameter sets - assert!(packetizer.packetize(1200, &vps)?.is_empty()); - assert!(packetizer.packetize(1200, &sps)?.is_empty()); - assert!(packetizer.packetize(1200, &pps)?.is_empty()); - - // First VCL triggers AP emission - let packets1 = packetizer.packetize(1200, &small_vcl)?; - assert_eq!(packets1.len(), 2, "Expected AP + small VCL"); - - // Verify AP depacketization (Annex-B format with start codes) - let mut output = Vec::new(); - let mut extra = CodecExtra::None; - depacketizer.depacketize(&packets1[0], &mut output, &mut extra)?; - - let mut offset = 0; - // VPS with start code - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + vps.len()], &vps[..]); - offset += vps.len(); - // SPS with start code - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + sps.len()], &sps[..]); - offset += sps.len(); - // PPS with start code - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + pps.len()], &pps[..]); - - // Verify small VCL (with start code) - output.clear(); - depacketizer.depacketize(&packets1[1], &mut output, &mut extra)?; - let expected_small_vcl = { - let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE); - tmp.extend_from_slice(&small_vcl); - tmp - }; - assert_eq!(output, expected_small_vcl); - - // Large VCL should be fragmented - let packets2 = packetizer.packetize(60, &large_vcl)?; - assert!(packets2.len() > 1, "Large VCL should be fragmented"); - - // Depacketize FU packets - for (i, packet) in packets2.iter().enumerate() { - output.clear(); - depacketizer.depacketize(packet, &mut output, &mut extra)?; - - if i < packets2.len() - 1 { - assert!(output.is_empty(), "Intermediate fragments shouldn't produce output"); - } else { - // Final fragment produces Annex-B output - let expected_large_vcl = { - let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE); - tmp.extend_from_slice(&large_vcl); - tmp - }; - assert_eq!( - output, expected_large_vcl, - "Final fragment should produce complete NAL with start code" - ); - } - } - - Ok(()) - } - - /// Test Annex-B input stream through packetizer and depacketizer. - /// Verifies complete round-trip preserves NAL units from Annex-B to RTP to Annex-B. - #[test] - fn test_h265_annexb_roundtrip_with_depacketizer() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let mut depacketizer = H265Depacketizer::default(); - - // Create Annex-B formatted input with multiple NAL units - let nalu1 = vec![0x40, 0x01, 0xaa, 0xbb]; // VPS - let nalu2 = vec![0x42, 0x01, 0xcc, 0xdd, 0xee]; // SPS - let nalu3 = vec![0x44, 0x01, 0xff]; // PPS - let nalu4 = vec![0x02, 0x01, 0x11, 0x22, 0x33]; // VCL - - // Build Annex-B bytestream - let mut annexb = Vec::new(); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&nalu1); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&nalu2); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&nalu3); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&nalu4); - - // Packetize the Annex-B stream - let packets = packetizer.packetize(1200, &annexb)?; - - // Should get AP (with VPS/SPS/PPS) + VCL - assert_eq!(packets.len(), 2, "Expected AP + VCL from Annex-B stream"); - - // Depacketize and verify (output is Annex-B format) - let mut output = Vec::new(); - let mut extra = CodecExtra::None; - - // AP packet produces start code before each NAL - depacketizer.depacketize(&packets[0], &mut output, &mut extra)?; - let mut offset = 0; - // VPS - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + nalu1.len()], &nalu1[..]); - offset += nalu1.len(); - // SPS - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + nalu2.len()], &nalu2[..]); - offset += nalu2.len(); - // PPS - assert_eq!(&output[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&output[offset..offset + nalu3.len()], &nalu3[..]); - - // VCL packet (with start code) - output.clear(); - depacketizer.depacketize(&packets[1], &mut output, &mut extra)?; - let expected_nalu4 = { - let mut tmp = Vec::from(ANNEXB_NALUSTART_CODE); - tmp.extend_from_slice(&nalu4); - tmp - }; - assert_eq!(output, expected_nalu4); - - Ok(()) - } - - /// Test packetizer respects various MTU sizes during fragmentation. - /// Verifies all output packets fit within specified MTU limits. - #[test] - fn test_h265_mtu_variation() -> Result<()> { - // Test fragmentation at various MTU sizes to ensure correct packet splitting - let mut packetizer = H265Packetizer::default(); - - // Create a 2000-byte NAL unit - let mut large_nalu = vec![0x26, 0x01]; // NALU header (type 19 - IDR) - for i in 0..1998 { - large_nalu.push((i % 256) as u8); - } - - // Test various MTU sizes - let mtu_sizes = [100, 200, 500, 1000, MAX_PACKET_SIZE]; - - for mtu in mtu_sizes { - let packets = packetizer.packetize(mtu, &large_nalu)?; - - // Verify all packets fit within MTU - for packet in &packets { - assert!( - packet.len() <= mtu, - "Packet size {} exceeds MTU {} for MTU test", - packet.len(), - mtu - ); - } - - // Verify all packets are FU packets (type 49) - for packet in &packets { - let header = H265NALUHeader::new(packet[0], packet[1]); - assert_eq!( - header.nalu_type(), - H265NALU_FRAGMENTATION_UNIT_TYPE, - "Expected FU packet type for MTU {}", - mtu - ); - } - - // Verify at least one packet was created - assert!(!packets.is_empty(), "Expected at least one packet for MTU {}", mtu); - } - - Ok(()) - } - - /// Test FU packet S (start) and E (end) flags are set correctly. - /// Verifies first packet has S=1, middle have S=0 E=0, last has E=1. - #[test] - fn test_h265_fragmentation_start_end_flags() -> Result<()> { - // Explicitly test S (start) and E (end) flags in FU headers - let mut packetizer = H265Packetizer::default(); - - // Create a NAL unit that will require fragmentation - let mut large_nalu = vec![0x26, 0x01]; // IDR NAL header - large_nalu.extend(vec![0xff; 200]); // 202 bytes total - - let packets = packetizer.packetize(100, &large_nalu)?; - - assert!(packets.len() >= 2, "Expected fragmentation into multiple packets"); - - // First packet should have S flag set - let first_fu_header = H265FragmentationUnitHeader(packets[0][2]); - assert!(first_fu_header.s(), "First FU packet should have S flag set"); - assert!(!first_fu_header.e(), "First FU packet should not have E flag set"); - - // Middle packets (if any) should have neither S nor E - for i in 1..packets.len() - 1 { - let mid_fu_header = H265FragmentationUnitHeader(packets[i][2]); - assert!(!mid_fu_header.s(), "Middle FU packet should not have S flag set"); - assert!(!mid_fu_header.e(), "Middle FU packet should not have E flag set"); - } - - // Last packet should have E flag set - let last_fu_header = H265FragmentationUnitHeader(packets[packets.len() - 1][2]); - assert!(!last_fu_header.s(), "Last FU packet should not have S flag set"); - assert!(last_fu_header.e(), "Last FU packet should have E flag set"); - - // All fragments should preserve the original NAL unit type - let original_type = 19; // IDR type - for packet in &packets { - let fu_header = H265FragmentationUnitHeader(packet[2]); - assert_eq!( - fu_header.fu_type(), - original_type, - "FU header should preserve original NAL type" - ); - } - - Ok(()) - } - - /// Test partition head detection for RTP packet reassembly. - /// Verifies single NAL, FU start, and AP packets are identified as partition heads. - #[test] - fn test_h265_is_partition_head() -> Result<()> { - let depacketizer = H265Depacketizer::default(); - - // Nil/empty should not be partition head - assert!( - !depacketizer.is_partition_head(&[]), - "Empty packet should not be partition head" - ); - - // Single NAL unit should be partition head - let single_nalu = vec![0x02, 0x01, 0xab, 0xcd, 0xef]; - assert!( - depacketizer.is_partition_head(&single_nalu), - "Single NAL unit should be partition head" - ); - - // Packet with F bit set should be partition head - let fbit_nalu = vec![0x80, 0x00, 0x00]; - assert!( - depacketizer.is_partition_head(&fbit_nalu), - "F-bit NAL unit should be partition head" - ); - - // FU start packet (S=1) should be partition head - let fu_start = vec![ - 0x62, 0x01, // FU indicator (type 49) - 0x93, // FU header: S=1, E=0, type=19 - ]; - assert!( - depacketizer.is_partition_head(&fu_start), - "FU start packet should be partition head" - ); - - // FU middle packet (S=0, E=0) should NOT be partition head - let fu_middle = vec![ - 0x62, 0x01, // FU indicator (type 49) - 0x13, // FU header: S=0, E=0, type=19 - ]; - assert!( - !depacketizer.is_partition_head(&fu_middle), - "FU middle packet should not be partition head" - ); - - // FU end packet (S=0, E=1) should NOT be partition head - let fu_end = vec![ - 0x62, 0x01, // FU indicator (type 49) - 0x53, // FU header: S=0, E=1, type=19 - ]; - assert!( - !depacketizer.is_partition_head(&fu_end), - "FU end packet should not be partition head" - ); - - // Aggregation packet should be partition head - let ap_packet = vec![ - 0x60, 0x01, // AP indicator (type 48) - 0x00, 0x04, // First NAL size - 0x40, 0x01, 0xaa, 0xbb, // VPS - ]; - assert!( - depacketizer.is_partition_head(&ap_packet), - "Aggregation packet should be partition head" - ); - - Ok(()) - } - - /// Test partition tail detection for RTP packet reassembly. - /// Verifies FU end packets and single NAL with marker are identified as partition tails. - #[test] - fn test_h265_is_partition_tail() -> Result<()> { - let depacketizer = H265Depacketizer::default(); - - // Nil/empty should not be partition tail - assert!( - !depacketizer.is_partition_tail(false, &[]), - "Empty packet should not be partition tail" - ); - - // Single NAL unit without marker should NOT be partition tail - let single_nalu = vec![0x02, 0x01, 0xab, 0xcd, 0xef]; - assert!( - !depacketizer.is_partition_tail(false, &single_nalu), - "Single NAL unit without marker should not be partition tail" - ); - - // Single NAL unit WITH marker should be partition tail - assert!( - depacketizer.is_partition_tail(true, &single_nalu), - "Single NAL unit with marker should be partition tail" - ); - - // F-bit packet without marker should NOT be partition tail - let fbit_nalu = vec![0x80, 0x00, 0x00]; - assert!( - !depacketizer.is_partition_tail(false, &fbit_nalu), - "F-bit NAL unit without marker should not be partition tail" - ); - - // FU start packet should NOT be partition tail - let fu_start = vec![ - 0x62, 0x01, // FU indicator (type 49) - 0x93, // FU header: S=1, E=0, type=19 - ]; - assert!( - !depacketizer.is_partition_tail(false, &fu_start), - "FU start packet should not be partition tail" - ); - - // FU middle packet should NOT be partition tail - let fu_middle = vec![ - 0x62, 0x01, // FU indicator (type 49) - 0x13, // FU header: S=0, E=0, type=19 - ]; - assert!( - !depacketizer.is_partition_tail(false, &fu_middle), - "FU middle packet should not be partition tail" - ); - - // FU end packet (E=1) should be partition tail - let fu_end = vec![ - 0x62, 0x01, // FU indicator (type 49) - 0x53, // FU header: S=0, E=1, type=19 - ]; - assert!( - depacketizer.is_partition_tail(false, &fu_end), - "FU end packet should be partition tail" - ); - - // Aggregation packet with marker should be partition tail - let ap_packet = vec![ - 0x60, 0x01, // AP indicator (type 48) - 0x00, 0x04, // First NAL size - 0x40, 0x01, 0xaa, 0xbb, // VPS - ]; - assert!( - depacketizer.is_partition_tail(true, &ap_packet), - "Aggregation packet with marker should be partition tail" - ); - - Ok(()) - } - - /// Test depacketization of manually constructed AP with multiple NAL units. - /// Verifies AP structure with multiple aggregated units works correctly. - #[test] - fn test_h265_multi_nalu_aggregation() -> Result<()> { - // Test aggregating multiple non-parameter-set NALUs - // Note: Current implementation only aggregates VPS/SPS/PPS automatically - // This test verifies the AP packet structure works for general NALUs - - let nalu1 = vec![0x02, 0x01, 0xff, 0xff, 0xff]; // VCL NAL - let nalu2 = vec![0x04, 0x01, 0xaa, 0xbb, 0xcc]; // Another VCL NAL - - // Manually build an AP packet - let mut ap_packet = vec![ - 0x60, 0x01, // AP header (type 48) - ]; - - // Add first NAL - ap_packet.extend_from_slice(&(nalu1.len() as u16).to_be_bytes()); - ap_packet.extend_from_slice(&nalu1); - - // Add second NAL - ap_packet.extend_from_slice(&(nalu2.len() as u16).to_be_bytes()); - ap_packet.extend_from_slice(&nalu2); - - // Depacketize and verify - let mut depacketizer = H265Depacketizer::default(); - let mut output = Vec::new(); - let mut extra = CodecExtra::None; - - depacketizer.depacketize(&ap_packet, &mut output, &mut extra)?; - - // Output should contain both NALUs with Annex-B start codes - let mut expected = Vec::new(); - expected.extend_from_slice(ANNEXB_NALUSTART_CODE); - expected.extend_from_slice(&nalu1); - expected.extend_from_slice(ANNEXB_NALUSTART_CODE); - expected.extend_from_slice(&nalu2); - - assert_eq!( - output, expected, - "Depacketized AP should contain both NALUs with start codes" - ); - - Ok(()) - } - - /// Test parameter set caching and AP emission on first VCL NAL. - /// Verifies VPS/SPS/PPS are cached, then emitted as AP when VCL arrives. - #[test] - fn test_h265_packetizer_aggregation_with_marker() -> Result<()> { - // Test that packetizer creates proper aggregation packets - let mut packetizer = H265Packetizer::default(); - - // Build Annex-B stream with VPS + SPS + PPS - let vps = vec![0x40, 0x01, 0xaa, 0xbb]; - let sps = vec![0x42, 0x01, 0xcc, 0xdd, 0xee]; - let pps = vec![0x44, 0x01, 0xff]; - - let mut annexb = Vec::new(); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&vps); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&sps); - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&pps); - - let packets = packetizer.packetize(MAX_PACKET_SIZE, &annexb)?; - - // Should produce 0 packets (just caching parameter sets) - assert_eq!( - packets.len(), - 0, - "Parameter sets should be cached, not emitted immediately" - ); - - // Now send a VCL NAL to trigger AP emission - let mut vcl_annexb = Vec::new(); - vcl_annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - vcl_annexb.extend_from_slice(&[0x02, 0x01, 0x11, 0x22]); - - let vcl_packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl_annexb)?; - - // Should get AP + VCL - assert_eq!(vcl_packets.len(), 2, "Expected AP with parameter sets + VCL packet"); - - // First packet should be AP (type 48) - let ap_header = H265NALUHeader::new(vcl_packets[0][0], vcl_packets[0][1]); - assert_eq!( - ap_header.nalu_type(), - H265NALU_AGGREGATION_PACKET_TYPE, - "First packet should be AP" - ); - - // Second packet should be single NAL (VCL type) - let vcl_header = H265NALUHeader::new(vcl_packets[1][0], vcl_packets[1][1]); - assert_eq!(vcl_header.nalu_type(), 1, "Second packet should be VCL NAL (type 1)"); - - Ok(()) - } - #[test] - fn test_h265_packetizer_exact_fu_boundary_mtu() -> Result<()> { - // ------------------------------------------------------------------------- - // This test verifies the most dangerous MTU geometry for HEVC FU: - // - // MTU == FU_header_size + (NAL_payload / 2) - // - // which must produce exactly TWO fragments with correct S/E bits and no - // zero-length or extra FU packets. - // ------------------------------------------------------------------------- - - // Large IDR NAL (type = 19) - let nal_payload_size = 1400; - - // Build a fake IDR NALU: [NALU header (2 bytes)] + payload - let mut nalu = Vec::with_capacity(nal_payload_size + 2); - nalu.push(0x26); // nal_unit_type = 19 (IDR_W_RADL) - nalu.push(0x01); - nalu.extend(std::iter::repeat(0xaa).take(nal_payload_size)); - - // FU overhead: 2-byte NAL header + 1-byte FU header = 3 bytes - let fu_overhead = H265NALU_HEADER_SIZE + H265FRAGMENTATION_UNIT_HEADER_SIZE; - - // Force an exact split into two equal fragments - let mtu = fu_overhead + (nal_payload_size / 2); - - let mut packetizer = H265Packetizer::default(); - - // Packetize - let packets = packetizer.packetize(mtu, &nalu)?; - - // Must produce exactly two FU packets - assert_eq!(packets.len(), 2, "exact-boundary FU must produce exactly 2 packets"); - - // ---- First packet: FU start ---- - { - let payload = &packets[0]; - let fu_hdr = H265FragmentationUnitHeader(payload[2]); - assert!(fu_hdr.s(), "first FU packet must have S=1"); - assert!(!fu_hdr.e(), "first FU packet must have E=0"); - assert_eq!(fu_hdr.fu_type(), 19, "FU must carry IDR type"); - } - - // ---- Second packet: FU end ---- - { - let payload = &packets[1]; - let fu_hdr = H265FragmentationUnitHeader(payload[2]); - assert!(!fu_hdr.s(), "last FU packet must have S=0"); - assert!(fu_hdr.e(), "last FU packet must have E=1"); - assert_eq!(fu_hdr.fu_type(), 19, "FU must carry IDR type"); - } - - // Reassemble payload to ensure no bytes were lost or duplicated - let mut reconstructed = Vec::new(); - for p in &packets { - // Skip: 2-byte outer NAL header + 1-byte FU header - reconstructed.extend_from_slice(&p[3..]); - } - - assert_eq!( - reconstructed.len(), - nal_payload_size, - "reassembled FU payload must exactly match original NAL size" - ); - - Ok(()) - } - } // end emit_tests - - /// Tests for Decoding Order Number (DONL/DOND) functionality. - /// Validates DONL increments, sequences, and interleaving support. - mod donl_tests { - use super::*; - - /// Test DONL field in single NAL unit packets. - /// Verifies DONL is added during packetization and removed during depacketization. - #[test] - fn test_h265_donl_single_nal_round_trip() -> Result<()> { - // Test DONL with single NAL unit packets - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); // Enable DONL - - let mut depacketizer = H265Depacketizer::default(); - depacketizer.with_donl(true); - - // Create a single NAL unit (type 1, VCL) - let nalu = vec![0x02, 0x01, 0xDE, 0xAD, 0xBE, 0xEF]; - - let packets = packetizer.packetize(MAX_PACKET_SIZE, &nalu)?; - assert_eq!(packets.len(), 1, "Should produce 1 packet"); - - let packet = &packets[0]; - - // Verify DONL is present after NAL header - // Packet structure: [NAL_HDR (2)] [DONL (2)] [PAYLOAD] - assert!(packet.len() >= 6, "Packet should contain NAL header + DONL + payload"); - - // NAL header should match - assert_eq!(packet[0], 0x02); - assert_eq!(packet[1], 0x01); - - // DONL should be 0 for first packet - let donl = u16::from_be_bytes([packet[2], packet[3]]); - assert_eq!(donl, 0, "DONL should be 0 for first NAL"); - - // Payload should follow DONL - assert_eq!(packet[4], 0xDE); - assert_eq!(packet[5], 0xAD); - - // Depacketize and verify output (Annex-B format without DONL) - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - depacketizer.depacketize(packet, &mut out, &mut codec_extra)?; - - // Output should be: [START_CODE (4)] [NAL_HDR (2)] [PAYLOAD] - assert_eq!( - out.len(), - 10, - "Annex-B output should be start code + NAL header + payload" - ); - assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE); - assert_eq!(&out[4..6], &[0x02, 0x01]); - assert_eq!(&out[6..10], &[0xDE, 0xAD, 0xBE, 0xEF]); - - // Verify DONL was parsed - let payload = depacketizer.payload(); - if let H265Payload::H265SingleNALUnitPacket(pkt) = payload { - assert_eq!(pkt.donl(), Some(0), "DONL should be parsed as 0"); - } else { - panic!("Expected H265SingleNALUnitPacket"); - } - - Ok(()) - } - - /// Test DONL field in FU packets (only in first fragment). - /// Verifies DONL appears in FU start packet but not in middle/end fragments. - #[test] - fn test_h265_donl_fragmentation_round_trip() -> Result<()> { - // Test DONL with fragmentation units (FU) - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - let mut depacketizer = H265Depacketizer::default(); - depacketizer.with_donl(true); - - // Create a large NAL unit that will be fragmented - let mut nalu = vec![0x02, 0x01]; // NAL header (type 1) - nalu.extend(vec![0xAA; 3000]); // Large payload - - let packets = packetizer.packetize(1200, &nalu)?; - - // Should produce multiple FU packets - assert!( - packets.len() >= 3, - "Large NAL should be fragmented into multiple packets" - ); - - // Check first FU packet structure: [FU_HDR (2)] [FU_HEADER (1)] [DONL (2)] [PAYLOAD] - let first_packet = &packets[0]; - let fu_header = H265NALUHeader::new(first_packet[0], first_packet[1]); - assert_eq!( - fu_header.nalu_type(), - H265NALU_FRAGMENTATION_UNIT_TYPE, - "Should be FU packet" - ); - - // FU header at byte 2 - let fu_hdr = H265FragmentationUnitHeader(first_packet[2]); - assert!(fu_hdr.s(), "First FU should have S flag set"); - assert!(!fu_hdr.e(), "First FU should not have E flag"); - - // DONL should be at bytes 3-4 - let donl = u16::from_be_bytes([first_packet[3], first_packet[4]]); - assert_eq!(donl, 0, "DONL should be 0 for first NAL"); - - // Middle packets should NOT have DONL - if packets.len() > 2 { - let middle_packet = &packets[1]; - let middle_fu_hdr = H265FragmentationUnitHeader(middle_packet[2]); - assert!(!middle_fu_hdr.s(), "Middle FU should not have S flag"); - assert!(!middle_fu_hdr.e(), "Middle FU should not have E flag"); - // Payload starts right after FU header (no DONL) - } - - // Last packet should have E flag but no DONL - let last_packet = &packets[packets.len() - 1]; - let last_fu_hdr = H265FragmentationUnitHeader(last_packet[2]); - assert!(!last_fu_hdr.s(), "Last FU should not have S flag"); - assert!(last_fu_hdr.e(), "Last FU should have E flag set"); - - // Depacketize all fragments - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - - for packet in &packets { - depacketizer.depacketize(packet, &mut out, &mut codec_extra)?; - } - - // Output should be complete NAL in Annex-B format - assert_eq!(out.len(), 4 + nalu.len(), "Annex-B output should match original"); - assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE); - assert_eq!(&out[4..], &nalu[..]); - - // Verify DONL was parsed from first FU - let payload = depacketizer.payload(); - if let H265Payload::H265FragmentationUnitPacket(pkt) = payload { - // Last FU packet won't have DONL, that's expected - // The DONL from the first packet was used internally - } else { - panic!("Expected H265FragmentationUnitPacket"); - } - - Ok(()) - } - - /// Test DONL/DOND fields in aggregation packets. - /// Verifies first aggregated NAL has DONL, subsequent NALs have DOND. - #[test] - fn test_h265_donl_aggregation_round_trip() -> Result<()> { - // Test DONL with aggregation packets (AP) - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - let mut depacketizer = H265Depacketizer::default(); - depacketizer.with_donl(true); - - // Create parameter sets to trigger aggregation - let mut annexb = Vec::new(); - - // VPS - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&[0x40, 0x01, 0x0C, 0x01, 0xFF, 0xFF]); - - // SPS - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&[0x42, 0x01, 0x01, 0x50, 0x00, 0x00]); - - // PPS - annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - annexb.extend_from_slice(&[0x44, 0x01, 0xC0, 0xF3, 0xC0, 0x02]); - - let packets = packetizer.packetize(MAX_PACKET_SIZE, &annexb)?; - assert_eq!(packets.len(), 0, "Parameter sets should be cached"); - - // Send VCL NAL to trigger AP emission - let mut vcl_annexb = Vec::new(); - vcl_annexb.extend_from_slice(ANNEXB_NALUSTART_CODE); - vcl_annexb.extend_from_slice(&[0x02, 0x01, 0x11, 0x22, 0x33]); - - let vcl_packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl_annexb)?; - assert_eq!(vcl_packets.len(), 2, "Should produce AP + VCL"); - - let ap_packet = &vcl_packets[0]; - - // Verify AP packet structure: - // [AP_HDR (2)] [DONL (2)] [NALU_SIZE (2)] [NALU] [DOND (1)] [NALU_SIZE (2)] [NALU] ... - let ap_header = H265NALUHeader::new(ap_packet[0], ap_packet[1]); - assert_eq!(ap_header.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE); - - // DONL at bytes 2-3 - let donl = u16::from_be_bytes([ap_packet[2], ap_packet[3]]); - assert_eq!(donl, 0, "DONL should be 0 for first aggregated packet"); - - // First NAL size at bytes 4-5 - let first_size = u16::from_be_bytes([ap_packet[4], ap_packet[5]]); - assert_eq!(first_size, 6, "VPS size should be 6 bytes"); - - // After first NAL, there should be DOND (1 byte) before second NAL size - let first_nal_end = 6 + first_size as usize; - let dond1 = ap_packet[first_nal_end]; - assert_eq!(dond1, 0, "DOND should be 0 (same decoding order)"); - - // Depacketize AP - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - depacketizer.depacketize(ap_packet, &mut out, &mut codec_extra)?; - - // Should output all 3 parameter sets in Annex-B format - // Each: [START_CODE (4)] [NAL] - // Note: Some parameter sets might be filtered/deduplicated, so check minimum - assert!(out.len() >= 18, "Should output at least 2 NALs with start codes"); - - // Verify first NAL (VPS) starts correctly - assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE); - assert_eq!(&out[4..6], &[0x40, 0x01]); - - Ok(()) - } - - /// Test DONL counter increments for each NAL unit in transmission order. - /// Verifies DONL starts at 0 and increments by 1 for each subsequent NAL. - #[test] - fn test_h265_donl_increments_correctly() -> Result<()> { - // Verify DONL increments for each NAL unit - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - // Send 3 separate NAL units - let nalu1 = vec![0x02, 0x01, 0xAA]; - let nalu2 = vec![0x02, 0x01, 0xBB]; - let nalu3 = vec![0x02, 0x01, 0xCC]; - - let packets1 = packetizer.packetize(MAX_PACKET_SIZE, &nalu1)?; - let packets2 = packetizer.packetize(MAX_PACKET_SIZE, &nalu2)?; - let packets3 = packetizer.packetize(MAX_PACKET_SIZE, &nalu3)?; - - // Check DONL values - let donl1 = u16::from_be_bytes([packets1[0][2], packets1[0][3]]); - let donl2 = u16::from_be_bytes([packets2[0][2], packets2[0][3]]); - let donl3 = u16::from_be_bytes([packets3[0][2], packets3[0][3]]); - - assert_eq!(donl1, 0, "First DONL should be 0"); - assert_eq!(donl2, 1, "Second DONL should be 1"); - assert_eq!(donl3, 2, "Third DONL should be 2"); - - Ok(()) - } - - /// Test packetizer without DONL enabled produces standard packets. - /// Verifies no DONL fields are added when DONL is disabled (default behavior). - #[test] - fn test_h265_without_donl() -> Result<()> { - // Verify that without DONL enabled, no DONL fields are added - let mut packetizer = H265Packetizer::default(); - // Don't call with_donl(true) - DONL should be disabled by default - - let nalu = vec![0x02, 0x01, 0xDE, 0xAD, 0xBE, 0xEF]; - let packets = packetizer.packetize(MAX_PACKET_SIZE, &nalu)?; - - assert_eq!(packets.len(), 1); - let packet = &packets[0]; - - // Packet should be exactly the NAL unit (no DONL field) - assert_eq!(packet.len(), nalu.len(), "Packet should not have DONL field"); - assert_eq!(packet, &nalu[..]); - - Ok(()) - } - - /// Test SDP-driven DONL enablement via sprop-max-don-diff. - /// Simulates the full flow: SDP fmtp → FormatParams → with_donl(true) → - /// packetize/depacketize round-trip for Single NAL, AP, and FU packet types. - #[test] - fn test_h265_sdp_driven_donl_all_packet_types() -> Result<()> { - use crate::vendor::str0m::format::FormatParams; - - // Step 1: Parse SDP fmtp line with sprop-max-don-diff > 0 - let fmtp = FormatParams::parse_line("sprop-max-don-diff=32"); - assert_eq!(fmtp.sprop_max_don_diff, Some(32)); - - // Step 2: Enable DONL on packetizer/depacketizer based on SDP (same as Payloader::new) - let donl_enabled = fmtp.sprop_max_don_diff.unwrap_or(0) > 0; - assert!(donl_enabled, "sprop-max-don-diff=32 should enable DONL"); - - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(donl_enabled); - - let mut depacketizer = H265Depacketizer::default(); - depacketizer.with_donl(donl_enabled); - - // --- Test 1: Single NAL Unit with DONL --- - let single_nalu = vec![0x02, 0x01, 0xDE, 0xAD, 0xBE, 0xEF]; // Type 1 (TRAIL_R) - let packets = packetizer.packetize(MAX_PACKET_SIZE, &single_nalu)?; - assert_eq!(packets.len(), 1, "Single NAL should produce 1 packet"); - - // Verify DONL=0 is present on wire: [NAL_HDR(2)] [DONL(2)] [payload] - let pkt = &packets[0]; - assert_eq!(pkt.len(), single_nalu.len() + 2, "Packet should include 2-byte DONL"); - let donl = u16::from_be_bytes([pkt[2], pkt[3]]); - assert_eq!(donl, 0, "First NAL should have DONL=0"); - - // Depacketize and verify Annex-B output matches original - let mut out = Vec::new(); - let mut extra = CodecExtra::None; - depacketizer.depacketize(pkt, &mut out, &mut extra)?; - assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE); - assert_eq!(&out[4..], &single_nalu[..], "Depacketized NAL should match original"); - - // --- Test 2: AP (VPS + SPS + PPS) with DONL --- - let vps = vec![0x40, 0x01, 0xAA, 0xBB, 0xCC]; - let sps = vec![0x42, 0x01, 0xDD, 0xEE, 0xFF, 0x11]; - let pps = vec![0x44, 0x01, 0x22, 0x33]; - let vcl = vec![0x26, 0x01, 0x44, 0x55, 0x66]; // IDR_W_RADL - - // Cache parameter sets (no output) - assert!(packetizer.packetize(MAX_PACKET_SIZE, &vps)?.is_empty()); - assert!(packetizer.packetize(MAX_PACKET_SIZE, &sps)?.is_empty()); - assert!(packetizer.packetize(MAX_PACKET_SIZE, &pps)?.is_empty()); - - // Trigger AP + VCL emission - let ap_packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl)?; - assert_eq!(ap_packets.len(), 2, "Should produce AP + VCL"); - - // Verify AP wire format: [AP_HDR(2)] [DONL(2)] [Size(2)] [NAL] [DOND(1)] [Size(2)] [NAL] ... - let ap = &ap_packets[0]; - let ap_hdr = H265NALUHeader::new(ap[0], ap[1]); - assert_eq!(ap_hdr.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE); - let ap_donl = u16::from_be_bytes([ap[2], ap[3]]); - assert_eq!(ap_donl, 1, "AP DONL should be 1 (after single NAL consumed DON=0)"); - - // Verify DOND bytes are present (0 = sequential order) - let first_size = u16::from_be_bytes([ap[4], ap[5]]) as usize; - let dond_offset = 6 + first_size; // after AP_HDR + DONL + size + first NAL - assert_eq!(ap[dond_offset], 0, "DOND should be 0 for sequential decoding"); - - // Depacketize AP and verify all 3 NALs appear in Annex-B output - out.clear(); - extra = CodecExtra::None; - depacketizer.depacketize(ap, &mut out, &mut extra)?; - - let mut offset = 0; - for expected in [&vps, &sps, &pps] { - assert_eq!(&out[offset..offset + 4], ANNEXB_NALUSTART_CODE); - offset += 4; - assert_eq!(&out[offset..offset + expected.len()], &expected[..]); - offset += expected.len(); - } - assert_eq!(offset, out.len(), "All AP data should be consumed"); - - // Verify VCL has correct DONL (AP consumed 3 DONs: 1,2,3 → next is 4) - let vcl_pkt = &ap_packets[1]; - let vcl_donl = u16::from_be_bytes([vcl_pkt[2], vcl_pkt[3]]); - assert_eq!(vcl_donl, 4, "VCL DONL should be 4 (after AP with 3 NALs)"); - - // Depacketize VCL - out.clear(); - extra = CodecExtra::None; - depacketizer.depacketize(vcl_pkt, &mut out, &mut extra)?; - assert_eq!(&out[4..], &vcl[..], "VCL NAL should match original"); - - // --- Test 3: FU (large NAL fragmented) with DONL --- - let mut large_nalu = vec![0x02, 0x01]; // Type 1 - large_nalu.extend(vec![0xAA; 200]); - - let fu_packets = packetizer.packetize(100, &large_nalu)?; - assert!(fu_packets.len() > 1, "Large NAL should be fragmented"); - - // Verify DONL=5 is present only in first FU fragment (S=1) - let first_fu = &fu_packets[0]; - let fu_hdr_byte = H265FragmentationUnitHeader(first_fu[2]); - assert!(fu_hdr_byte.s(), "First FU should have S=1"); - let fu_donl = u16::from_be_bytes([first_fu[3], first_fu[4]]); - assert_eq!(fu_donl, 5, "FU DONL should be 5 (after VCL consumed DON=4)"); - - // Middle/end fragments should NOT have DONL (payload starts at byte 3) - let last_fu = &fu_packets[fu_packets.len() - 1]; - let last_fu_hdr = H265FragmentationUnitHeader(last_fu[2]); - assert!(last_fu_hdr.e(), "Last FU should have E=1"); - assert!(!last_fu_hdr.s(), "Last FU should not have S=1"); - // No DONL in last fragment - payload is at byte 3, not 5 - - // Depacketize all FU fragments - out.clear(); - extra = CodecExtra::None; - for pkt in &fu_packets { - depacketizer.depacketize(pkt, &mut out, &mut extra)?; - } - - // Verify reconstructed NAL matches original - assert_eq!(&out[0..4], ANNEXB_NALUSTART_CODE); - assert_eq!(&out[4..], &large_nalu[..], "Reassembled FU should match original"); - - // --- Verify DONL counter progression --- - // After all operations: DON 0 (single), 1-3 (AP with 3 NALs), 4 (VCL), 5 (FU) → next = 6 - let next_nalu = vec![0x02, 0x01, 0x77]; - let next_packets = packetizer.packetize(MAX_PACKET_SIZE, &next_nalu)?; - let next_donl = u16::from_be_bytes([next_packets[0][2], next_packets[0][3]]); - assert_eq!(next_donl, 6, "Next DONL should be 6 after full sequence"); - - Ok(()) - } - } // end donl_tests - - /// End-to-end round-trip validation. - /// Tests packetize → depacketize cycles for correctness. - mod roundtrip_tests { - use super::*; - - /// Test complete round-trip with DONL. - /// Verifies packetizer → depacketizer with DONL enabled produces identical output. - #[test] - fn test_h265_roundtrip_with_donl() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - let mut depacketizer = H265Depacketizer::default(); - depacketizer.with_donl(true); - - // Test 1: Single NAL with DONL - let single_nalu = vec![0x02, 0x01, 0xff, 0xff, 0xff]; - let packets = packetizer.packetize(MAX_PACKET_SIZE, &single_nalu)?; - - assert_eq!(packets.len(), 1, "Single NAL should produce 1 packet"); - - // Verify DONL is present (bytes 2-3 after NAL header) - let donl = u16::from_be_bytes([packets[0][2], packets[0][3]]); - assert_eq!(donl, 0, "First DONL should be 0"); - - // Depacketize and verify - let mut out = Vec::new(); - let mut codec_extra = CodecExtra::None; - depacketizer.depacketize(&packets[0], &mut out, &mut codec_extra)?; - assert!(!out.is_empty(), "Should depacketize successfully"); - - // Test 2: Fragmented NAL with DONL - let mut large_nalu = vec![0x02, 0x01]; - for i in 0..512 { - large_nalu.push((i % 256) as u8); - } - - let fu_packets = packetizer.packetize(100, &large_nalu)?; - assert!(fu_packets.len() > 1, "Large NAL should fragment"); - - // First fragment should have DONL - let first_donl = u16::from_be_bytes([fu_packets[0][3], fu_packets[0][4]]); - assert_eq!(first_donl, 1, "Second NAL should have DONL=1"); - - // Reassemble all fragments - out.clear(); - codec_extra = CodecExtra::None; - for packet in &fu_packets { - depacketizer.depacketize(packet, &mut out, &mut codec_extra)?; - } - - assert!(!out.is_empty(), "Should reassemble fragmented NAL"); - - // Verify reconstructed payload matches original (minus Annex B start codes) - // The output will have Annex B format with start codes - let has_start_code = out.len() > 4 && out[0..4] == [0x00, 0x00, 0x00, 0x01]; - assert!(has_start_code || out.len() > 0, "Should have valid output"); - - Ok(()) - } - - /// Test aggregation with exact DONL values. - /// Verifies contiguous and non-contiguous DONL sequences in AP packets. - #[test] - fn test_h265_aggregation_with_donl_sequences() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - // Send multiple parameter sets to build up cache - let vps = vec![0x40, 0x01, 0x00, 0x01, 0x02, 0x03]; - let sps = vec![0x42, 0x01, 0x00, 0x01, 0x02, 0x03]; - let pps = vec![0x44, 0x01, 0x00, 0x01, 0x02, 0x03]; - - packetizer.packetize(MAX_PACKET_SIZE, &vps)?; - packetizer.packetize(MAX_PACKET_SIZE, &sps)?; - packetizer.packetize(MAX_PACKET_SIZE, &pps)?; - - // Trigger with VCL NAL - let vcl = vec![0x02, 0x01, 0xAA, 0xBB]; - let packets = packetizer.packetize(MAX_PACKET_SIZE, &vcl)?; - - // Should emit AP + VCL or individual packets with DONL - assert!(!packets.is_empty(), "Should produce packets"); - - // Each packet should have proper structure - for packet in &packets { - assert!(packet.len() >= 2, "Packet should have at least NAL header"); - } - - Ok(()) - } - } // end roundtrip_tests - - /// Edge case and buffer overflow prevention tests. - /// Validates MTU boundary conditions, zero-length inputs, and error handling. - mod regression_tests { - use super::*; - - /// Test packetizer with zero MTU returns empty output. - /// Verifies that invalid MTU (0) is handled gracefully without panicking. - #[test] - fn test_h265_zero_mtu() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let nalu = vec![0x02, 0x01, 0xAA, 0xBB, 0xCC]; - - let packets = packetizer.packetize(0, &nalu)?; - - // Zero MTU should result in no packets being created - assert!(packets.is_empty(), "Zero MTU should produce no packets"); - - Ok(()) - } - - /// Test packetizer with empty NAL unit returns empty output. - /// Verifies that empty input is handled gracefully without panicking. - #[test] - fn test_h265_empty_nalu() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - let nalu = vec![]; - - let packets = packetizer.packetize(MAX_PACKET_SIZE, &nalu)?; - - // Empty NAL unit should result in no packets - assert!(packets.is_empty(), "Empty NAL unit should produce no packets"); - - Ok(()) - } - - /// Test packetizer with MTU smaller than FU overhead. - /// Verifies that MTU too small for fragmentation is handled gracefully. - #[test] - fn test_h265_mtu_smaller_than_fu_overhead() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // Create a large NAL that would require fragmentation - let mut large_nalu = vec![0x02, 0x01]; - large_nalu.extend(vec![0xAA; 200]); - - // FU overhead is 3 bytes (2 FU indicator + 1 FU header) - // MTU = 2 is smaller than overhead, should produce no packets - let packets = packetizer.packetize(2, &large_nalu)?; - - assert!( - packets.is_empty(), - "MTU smaller than FU overhead should produce no packets" - ); - - Ok(()) - } - - /// Test packetizer with MTU exactly equal to FU overhead. - /// Verifies edge case where MTU = overhead (no room for payload). - #[test] - fn test_h265_mtu_equals_fu_overhead() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // Create a large NAL that would require fragmentation - let mut large_nalu = vec![0x02, 0x01]; - large_nalu.extend(vec![0xBB; 200]); - - // FU overhead is 3 bytes, no room for payload - let packets = packetizer.packetize(3, &large_nalu)?; - - assert!( - packets.is_empty(), - "MTU equal to FU overhead (no payload room) should produce no packets" - ); - - Ok(()) - } - - /// Test packetizer with MTU = FU overhead + DONL (with DONL enabled). - /// Verifies that when DONL is enabled, first fragment needs extra space. - #[test] - fn test_h265_mtu_equals_fu_overhead_plus_donl() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - // Create a large NAL that would require fragmentation - let mut large_nalu = vec![0x02, 0x01]; - large_nalu.extend(vec![0xCC; 200]); - - // FU overhead (3) + DONL (2) = 5 bytes, no room for payload - let packets = packetizer.packetize(5, &large_nalu)?; - - assert!( - packets.is_empty(), - "MTU equal to FU overhead + DONL (no payload room) should produce no packets" - ); - - Ok(()) - } - - /// Test FU packetization with MTU larger than MAX_PACKET_SIZE. - /// Verifies that effective_mtu is clamped to MAX_PACKET_SIZE (1200) to prevent buffer overflow. - #[test] - fn test_h265_fu_mtu_exceeds_max_packet_size() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // Create a large NAL that requires fragmentation - let mut large_nalu = vec![0x02, 0x01]; - large_nalu.extend(vec![0xDD; 3000]); - - // Request MTU=2000, but should be clamped to MAX_PACKET_SIZE=1200 - let packets = packetizer.packetize(2000, &large_nalu)?; - - assert!(!packets.is_empty(), "Should produce FU packets"); - - // All packets should fit within MAX_PACKET_SIZE (1200) - for (i, packet) in packets.iter().enumerate() { - assert!( - packet.len() <= 1200, - "Packet {} size {} exceeds MAX_PACKET_SIZE (1200)", - i, - packet.len() - ); - } - - Ok(()) - } - - /// Test single NAL with DONL produces correct packet. - /// Verifies that large single NAL units with DONL are handled correctly. - #[test] - fn test_h265_single_nal_with_donl_large() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - packetizer.with_donl(true); - - // Create a large NAL that fits MTU - let mut large_nalu = vec![0x02, 0x01]; - large_nalu.extend(vec![0xEE; 1197]); // Total 1199 bytes - - let packets = packetizer.packetize(MAX_PACKET_SIZE, &large_nalu)?; - - // With Vec buffer, large packets within MTU are produced successfully - assert_eq!(packets.len(), 1); - // Packet should have NAL header (2) + DONL (2) + payload (1197) - assert_eq!(packets[0].len(), 1199 + 2); // Original + DONL - - Ok(()) - } - - /// Test AP packet that would exceed MTU falls back to individual packets. - /// Verifies that when aggregation would violate MTU, parameter sets are sent separately. - #[test] - fn test_h265_ap_buffer_overflow_fallback() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // Create large parameter sets that would overflow when aggregated - let mut vps = vec![0x40, 0x01]; - vps.extend(vec![0xAA; 100]); - - let mut sps = vec![0x42, 0x01]; - sps.extend(vec![0xBB; 100]); - - let mut pps = vec![0x44, 0x01]; - pps.extend(vec![0xCC; 100]); - - let vcl = vec![0x02, 0x01, 0xDD]; - - // Cache parameter sets - assert!(packetizer.packetize(1200, &vps)?.is_empty()); - assert!(packetizer.packetize(1200, &sps)?.is_empty()); - assert!(packetizer.packetize(1200, &pps)?.is_empty()); - - // Trigger emission with MTU that's too small for AP - // AP overhead: 2 (header) + 3×2 (size fields) + 102+102+102 = 314 bytes - let small_mtu = 200; - let packets = packetizer.packetize(small_mtu, &vcl)?; - - // Should emit as individual packets (VPS, SPS, PPS, VCL) - assert_eq!(packets.len(), 4, "Should fall back to 4 individual packets"); - - // Verify all packets fit within MTU - for packet in &packets { - assert!( - packet.len() <= small_mtu, - "Fallback packet size {} exceeds MTU {}", - packet.len(), - small_mtu - ); - } - - Ok(()) - } - - /// Test FU packetization handles minimal MTU (overhead + 1 byte payload). - /// Verifies that fragmentation works even with smallest possible payload per packet. - #[test] - fn test_h265_fu_minimal_mtu() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // Create a NAL that requires fragmentation - let nalu = vec![0x02, 0x01, 0xAA, 0xBB, 0xCC, 0xDD]; - - // FU overhead = 3 bytes, MTU = 4 allows 1 byte payload per packet - let mtu = 4; - let packets = packetizer.packetize(mtu, &nalu)?; - - // Should create multiple packets, each with 1 byte of payload - assert!( - packets.len() >= 4, - "Should fragment into multiple packets with 1-byte payload" - ); - - // Verify all packets fit within MTU - for packet in &packets { - assert!(packet.len() <= mtu, "Packet exceeds MTU"); - } - - Ok(()) - } - - /// Test packetizer with NAL unit smaller than header size. - /// Verifies that malformed NAL (< 2 bytes) is handled gracefully. - #[test] - fn test_h265_nalu_smaller_than_header() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // NAL unit with only 1 byte (invalid, needs at least 2 for header) - let invalid_nalu = vec![0x02]; - - let packets = packetizer.packetize(MAX_PACKET_SIZE, &invalid_nalu)?; - - // Should drop malformed NAL (< H265NALU_HEADER_SIZE) - assert!(packets.is_empty(), "Malformed NAL (< 2 bytes) should be dropped"); - - Ok(()) - } - } // end regression_tests - - /// Integration tests for complex scenarios. - /// Tests aggregation layouts, SE flag correctness, and real-world payloads. - mod integration_tests { - use super::*; - - /// Test depacketization of real H.265 RTP payloads from Wireshark captures. - /// Verifies practical compatibility with actual WebRTC H.265 streams. - /// This is an integration test because it exercises fragmentation, reassembly, and Annex-B output. - #[test] - fn test_h265_packet_real() -> Result<()> { - // Tests decoding of real H265 payloads extracted from a Wireshark dump. - let tests = vec![ - b"\x40\x01\x0c\x01\xff\xff\x01\x60\x00\x00\x03\x00\xb0\x00\x00\x03\x00\x00\x03\x00\x7b\xac\x09" - .to_vec(), - b"\x42\x01\x01\x01\x60\x00\x00\x03\x00\xb0\x00\x00\x03\x00\x00\x03\x00\x7b\xa0\x03\xc0\x80\x10\ - \xe5\x8d\xae\x49\x32\xf4\xdc\x04\x04\x04\x02" - .to_vec(), - b"\x44\x01\xc0\xf2\xf0\x3c\x90".to_vec(), - b"\x4e\x01\xe5\x04\x61\x0c\x00\x00\x80".to_vec(), - // Large test vector split across multiple lines for readability - [ - &b"\x62\x01\x93\xaf\x0d\x5a\xfe\x67\x77\x29\xc0\x74\xf3\x57\x4c\x16\x94\xaa"[..], - &b"\x7c\x2a\x64\x5f\xe9\xa5\xb7\x2a\xa3\x95\x9d\x94\xa7\xb4\xd3\xc4\x4a\xb1"[..], - &b"\xb7\x69\xca\xbe\x75\xc5\x64\xa8\x97\x4b\x8a\xbf\x7e\xf0\x0f\xc3\x22\x60"[..], - &b"\x67\xab\xae\x96\xd6\x99\xca\x7a\x8d\x35\x93\x1a\x67\x60\xe7\xbe\x7e\x13"[..], - &b"\x95\x3c\xe0\x11\xc1\xc1\xa7\x48\xef\xf7\x7b\xb0\xeb\x35\x49\x81\x4e\x4e"[..], - &b"\x54\xf7\x31\x6a\x38\xa1\xa7\x0c\xd6\xbe\x3b\x25\xba\x08\x19\x0b\x49\xfd"[..], - &b"\x90\xbb\x73\x7a\x45\x8c\xb9\x73\x43\x04\xc5\x5f\xda\x0f\xd5\x70\x4c\x11"[..], - &b"\xee\x72\xb8\x6a\xb4\x95\x62\x64\xb6\x23\x14\x7e\xdb\x0e\xa5\x0f\x86\x31"[..], - &b"\xe4\xd1\x64\x56\x43\xf6\xb7\xe7\x1b\x93\x4a\xeb\xd0\xa6\xe3\x1f\xce\xda"[..], - &b"\x15\x67\x05\xb6\x77\x36\x8b\x27\x5b\xc6\xf2\x95\xb8\x2b\xcc\x9b\x0a\x03"[..], - &b"\x05\xbe\xc3\xd3\x85\xf5\x69\xb6\x19\x1f\x63\x2d\x8b\x65\x9e\xc3\x9d\xd2"[..], - &b"\x44\xb3\x7c\x86\x3b\xea\xa8\x5d\x02\xe5\x40\x03\x20\x76\x48\xff\xf6\x2b"[..], - &b"\x0d\x18\xd6\x4d\x49\x70\x1a\x5e\xb2\x89\xca\xec\x71\x41\x79\x4e\x94\x17"[..], - &b"\x0c\x57\x51\x55\x14\x61\x40\x46\x4b\x3e\x17\xb2\xc8\xbd\x1c\x06\x13\x91"[..], - &b"\x72\xf8\xc8\xfc\x6f\xb0\x30\x9a\xec\x3b\xa6\xc9\x33\x0b\xa5\xe5\xf4\x65"[..], - &b"\x7a\x29\x8b\x76\x62\x81\x12\xaf\x20\x4c\xd9\x21\x23\x9e\xeb\xc9\x0e\x5b"[..], - &b"\x29\x35\x7f\x41\xcd\xce\xa1\xc4\xbe\x01\x30\xb9\x11\xc3\xb1\xe4\xce\x45"[..], - &b"\xd2\x5c\xb3\x1e\x69\x78\xba\xb1\x72\xe4\x88\x54\xd8\x5d\xd0\xa8\x3a\x74"[..], - &b"\xad\xe5\xc7\xc1\x59\x7c\x78\x15\x26\x37\x3d\x50\xae\xb3\xa4\x5b\x6c\x7d"[..], - &b"\x65\x66\x85\x4d\x16\x9a\x67\x74\xad\x55\x32\x3a\x84\x85\x0b\x6a\xeb\x24"[..], - &b"\x97\xb4\x20\x4d\xca\x41\x61\x7a\xd1\x7b\x60\xdb\x7f\xd5\x61\x22\xcf\xd1"[..], - &b"\x7e\x4c\xf3\x85\xfd\x13\x63\xe4\x9d\xed\xac\x13\x0a\xa0\x92\xb7\x34\xde"[..], - &b"\x65\x0f\xd9\x0f\x9b\xac\xe2\x47\xe8\x5c\xb3\x11\x8e\xc6\x08\x19\xd0\xb0"[..], - &b"\x85\x52\xc8\x5c\x1b\x08\x0a\xce\xc9\x6b\xa7\xef\x95\x2f\xd0\xb8\x63\xe5"[..], - &b"\x4c\xd4\xed\x6e\x87\xe9\xd4\x0a\xe6\x11\x44\x63\x00\x94\x18\xe9\x28\xba"[..], - &b"\xcf\x92\x43\x06\x59\xdd\x37\x4f\xd3\xef\x9d\x31\x5e\x9b\x48\xf9\x1f\x3e"[..], - &b"\x7b\x95\x3a\xbd\x1f\x71\x55\x0c\x06\xf9\x86\xf8\x3d\x39\x16\x50\xb3\x21"[..], - &b"\x11\x19\x6f\x70\xa9\x48\xe8\xbb\x0a\x11\x23\xf8\xab\xfe\x44\xe0\xbb\xe8"[..], - &b"\x64\xfa\x85\xe4\x02\x55\x88\x41\xc6\x30\x7f\x10\xad\x75\x02\x4b\xef\xe1"[..], - &b"\x0b\x06\x3c\x10\x49\x83\xf9\xd1\x3e\x3e\x67\x86\x4c\xf8\x9d\xde\x5a\xc4"[..], - &b"\xc8\xcf\xb6\xf4\xb0\xd3\x34\x58\xd4\x7b\x4d\xd3\x37\x63\xb2\x48\x8a\x7e"[..], - &b"\x20\x00\xde\xb4\x42\x8f\xda\xe9\x43\x9e\x0c\x16\xce\x79\xac\x2c\x70\xc1"[..], - &b"\x89\x05\x36\x62\x6e\xd9\xbc\xfb\x63\xc6\x79\x89\x3c\x90\x89\x2b\xd1\x8c"[..], - &b"\xe0\xc2\x54\xc7\xd6\xb4\xe8\x9e\x96\x55\x6e\x7b\xd5\x7f\xac\xd4\xa7\x1c"[..], - &b"\xa0\xdf\x01\x30\xad\xc0\x9f\x69\x06\x10\x43\x7f\xf4\x5d\x62\xa3\xea\x73"[..], - &b"\xf2\x14\x79\x19\x13\xea\x59\x14\x79\xa8\xe7\xce\xce\x44\x25\x13\x41\x18"[..], - &b"\x57\xdd\xce\xe4\xbe\xcc\x20\x80\x29\x71\x73\xa7\x7c\x86\x39\x76\xf4\xa7"[..], - &b"\x1c\x63\x24\x21\x93\x1e\xb5\x9a\x5c\x8a\x9e\xda\x8b\x9d\x88\x97\xfc\x98"[..], - &b"\x7d\x26\x74\x04\x1f\xa8\x10\x4f\x45\xcd\x46\xe8\x28\xe4\x8e\x59\x67\x63"[..], - &b"\x4a\xcf\x1e\xed\xdd\xbb\x79\x2f\x8d\x94\xab\xfc\xdb\xc5\x79\x1a\x4d\xcd"[..], - &b"\x53\x41\xdf\xd1\x7a\x8f\x46\x3e\x1f\x79\x88\xe3\xee\x9f\xc4\xc1\xe6\x2e"[..], - &b"\x89\x4d\x28\xc9\xca\x28\xc2\x0a\xc5\xc7\xf1\x22\xcd\xb3\x36\xfa\xe3\x7e"[..], - &b"\xa6\xcd\x95\x55\x5e\x0e\x1a\x75\x7f\x65\x27\xd3\x37\x4f\x23\xc5\xab\x49"[..], - &b"\x68\x4e\x02\xb5\xbf\xd7\x95\xc0\x78\x67\xbc\x1a\xe9\xae\x6f\x44\x58\x8a"[..], - &b"\xc2\xce\x42\x98\x4e\x77\xc7\x2a\xa0\xa7\x7d\xe4\x3b\xd1\x20\x82\x1a\xd3"[..], - &b"\xe2\xc7\x76\x5d\x06\x46\xb5\x24\xd7\xfb\x57\x63\x2b\x19\x51\x48\x65\x6d"[..], - &b"\xfb\xe0\x98\xd1\x14\x0e\x17\x64\x29\x34\x6f\x6e\x66\x9e\x8d\xc9\x89\x49"[..], - &b"\x69\xee\x74\xf3\x35\xe6\x8b\x67\x56\x95\x7f\x1b\xe9\xed\x8c\x0f\xe2\x19"[..], - &b"\x59\xbf\x03\x35\x55\x3c\x04\xbc\x40\x52\x90\x10\x08\xad\xa7\x65\xe0\x31"[..], - &b"\xcb\xcf\x3d\xd4\x62\x68\x01\x0d\xed\xf5\x28\x64\x2d\xaa\x7c\x99\x15\x8d"[..], - &b"\x70\x32\x53\xb8\x9d\x0a\x3c\xbf\x91\x02\x04\xd0\xee\x87\xce\x04\xcc\x3e"[..], - &b"\xa8\x20\xfd\x97\xdf\xbf\x4a\xbc\xfc\xc9\x7c\x77\x21\xcc\x23\x6f\x59\x38"[..], - &b"\xd8\xd9\xa0\x0e\xb1\x23\x4e\x04\x3f\x14\x9e\xcc\x05\x54\xab\x20\x69\xed"[..], - &b"\xa4\xd5\x1d\xb4\x1b\x52\xed\x6a\xea\xeb\x7f\xd1\xbc\xfd\x75\x20\xa0\x1c"[..], - &b"\x59\x8c\x5a\xa1\x2a\x70\x64\x11\xb1\x7b\xc1\x24\x80\x28\x51\x4c\x94\xa1"[..], - &b"\x95\x64\x72\xe8\x90\x67\x38\x74\x2b\xab\x38\x46\x12\x71\xce\x19\x98\x98"[..], - &b"\xf7\x89\xd4\xfe\x2f\x2a\xc5\x61\x20\xd0\xa4\x1a\x51\x3c\x82\xc8\x18\x31"[..], - &b"\x7a\x10\xe8\x1c\xc6\x95\x5a\xa0\x82\x88\xce\x8f\x4b\x47\x85\x7e\x89\x95"[..], - &b"\x95\x52\x1e\xac\xce\x45\x57\x61\x38\x97\x2b\x62\xa5\x14\x6f\xc3\xaa\x6c"[..], - &b"\x35\x83\xc9\xa3\x1e\x30\x89\xf4\xb1\xea\x4f\x39\xde\xde\xc7\x46\x5c\x0e"[..], - &b"\x85\x41\xec\x6a\xa4\xcb\xee\x70\x9c\x57\xd9\xf4\xa1\xc3\x9c\x2a\x0a\xf0"[..], - &b"\x5d\x58\xb0\xae\xd4\xdc\xc5\x6a\xa8\x34\xfa\x23\xef\xef\x08\x39\xc3\x3d"[..], - &b"\xea\x11\x6e\x6a\xe0\x1e\xd0\x52\xa8\xc3\x6e\xc9\x1c\xfc\xd0\x0c\x4c\xea"[..], - &b"\x0d\x82\xcb\xdd\x29\x1a\xc4\x4f\x6e\xa3\x4d\xcb\x7a\x38\x77\xe5\x15\x6e"[..], - &b"\xad\xfa\x9d\x2f\x02\xb6\x39\x84\x3a\x60\x8f\x71\x9f\x92\xe5\x24\x4f\xbd"[..], - &b"\x18\x49\xd5\xef\xbf\x70\xfb\xd1\x4c\x2e\xfc\x2f\x36\xf3\x00\x31\x2e\x90"[..], - &b"\x18\xcc\xf4\x71\xb9\xe4\xf9\xbe\xcb\x5e\xff\xf3\xe7\xf8\xca\x03\x60\x66"[..], - &b"\xb3\xc9\x5a\xf9\x74\x09\x02\x57\xb6\x90\x94\xfc\x41\x35\xdc\x35\x3f\x32"[..], - &b"\x7a\xa6\xa5\xcd\x8a\x8f\xc8\x3d\xc8\x81\xc3\xec\x37\x74\x86\x61\x41\x0d"[..], - &b"\xc5\xe2\xc8\x0c\x84\x2b\x3b\x71\x58\xde\x1b\xe3\x20\x65\x2e\x76\xf4\x98"[..], - &b"\xd8\xaa\x78\xe6\xeb\xb8\x85\x0d\xa0\xd0\xf5\x57\x64\x01\x58\x55\x82\xd5"[..], - &b"\x0f\x2d\x9c\x3e\x2a\xa0\x7e\xaf\x42\xf3\x37\xd1\xb3\xaf\xda\x5b\xa9\xda"[..], - &b"\xe3\x89\x5d\xf1\xca\xa5\x12\x3d\xe7\x91\x95\x53\x21\x72\xca\x7f\xf6\x79"[..], - &b"\x59\x21\xcf\x30\x18\xfb\x78\x55\x40\x59\xc3\xf9\xf1\xdd\x58\x44\x5e\x83"[..], - &b"\x11\x5c\x2d\x1d\x91\xf6\x01\x3d\x3f\xd4\x33\x81\x66\x6c\x40\x7a\x9d\x70"[..], - &b"\x10\x58\xe6\x53\xad\x85\x11\x99\x3e\x4b\xbc\x31\xc6\x78\x9d\x79\xc5\xde"[..], - &b"\x9f\x2e\x43\xfa\x76\x84\x2f\xfd\x28\x75\x12\x48\x25\xfd\x15\x8c\x29\x6a"[..], - &b"\x91\xa4\x63\xc0\xa2\x8c\x41\x3c\xf1\xb0\xf8\xdf\x66\xeb\xbd\x14\x88\xa9"[..], - &b"\x81\xa7\x35\xc4\x41\x40\x6c\x10\x3f\x09\xbd\xb5\xd3\x7a\xee\x4b\xd5\x86"[..], - &b"\xff\x36\x03\x6b\x78\xde"[..], - ] - .concat(), - b"\x62\x01\x53\x8a\xe9\x25\xe1\x06\x09\x8e\xba\x12\x74\x87\x09\x9a\x95\xe4\x86\x62\ - \x2b\x4b\xf9\xa6\x2e\x7b\x35\x43\xf7\x39\x99\x0f\x3b\x6f\xfd\x1a\x6e\x23\x54\x70\ - \xb5\x1d\x10\x1c\x63\x40\x96\x99\x41\xb6\x96\x0b\x70\x98\xec\x17\xb0\xaa\xdc\x4a\ - \xab\xe8\x3b\xb7\x6b\x00\x1c\x5b\xc3\xe0\xa2\x8b\x7c\x17\xc8\x92\xc9\xb0\x92\xb6\ - \x70\x84\x95\x30" - .to_vec(), - b"\x4e\x01\xe5\x04\x35\xac\x00\x00\x80".to_vec(), - b"\x62\x01\x41\xb0\x75\x5c\x27\x46\xef\x8a\xe7\x1d\x50\x38\xb2\x13\x33\xe0\x79\x35\ - \x1b\xc2\xb5\x79\x73\xe7\xc2\x6f\xb9\x1a\x8c\x21\x0e\xa9\x54\x17\x6c\x41\xab\xc8\ - \x16\x57\xec\x5e\xeb\x89\x3b\xa9\x90\x8c\xff\x4d\x46\x8b\xf0\xd9\xc0\xd0\x51\xcf\ - \x8b\x88\xf1\x5f\x1e\x9e\xc1\xb9\x1f\xe3\x06\x45\x35\x8a\x47\xe8\x9a\xf2\x4f\x19\ - \x4c\xf8\xce\x68\x1b\x63\x34\x11\x75\xea\xe5\xb1\x0f\x38\xcc\x05\x09\x8b\x3e\x2b\ - \x88\x84\x9d\xc5\x03\xc3\xc0\x90\x32\xe2\x45\x69\xb1\xe5\xf7\x68\x6b\x16\x90\xa0\ - \x40\xe6\x18\x74\xd8\x68\xf3\x34\x38\x99\xf2\x6c\xb7\x1a\x35\x21\xca\x52\x56\x4c\ - \x7f\xb2\xa3\xd5\xb8\x40\x50\x48\x3e\xdc\xdf\x0b\xf5\x54\x5a\x15\x1a\xe2\xc3\xb4\ - \x94\xda\x3f\xb5\x34\xa2\xca\xbc\x2f\xe0\xa4\xe5\x69\xf4\xbf\x62\x4d\x15\x21\x1b\ - \x11\xfc\x39\xaa\x86\x74\x96\x63\xfd\x07\x53\x26\xf6\x34\x72\xeb\x14\x37\x98\x0d\ - \xf4\x68\x91\x2c\x6b\x46\x83\x88\x82\x04\x8b\x9f\xb8\x32\x73\x75\x8b\xf9\xac\x71\ - \x42\xd1\x2d\xb4\x28\x28\xf5\x78\xe0\x32\xf3\xe1\xfc\x43\x6b\xf9\x92\xf7\x48\xfe\ - \x7f\xc0\x17\xbd\xfd\xba\x2f\x58\x6f\xee\x84\x03\x18\xce\xb0\x9d\x8d\xeb\x22\xf1\ - \xfc\xb1\xcf\xff\x2f\xb2\x9f\x6c\xe5\xb4\x69\xdc\xdd\x20\x93\x00\x30\xad\x56\x04\ - \x66\x7e\xa3\x3c\x18\x4b\x43\x66\x00\x27\x1e\x1c\x09\x11\xd8\xf4\x8a\x9e\xc5\x6a\ - \x94\xe5\xae\x0b\x8a\xbe\x84\xda\xe5\x44\x7f\x38\x1c\xe7\xbb\x03\x19\x66\xe1\x5d\ - \x1d\xc1\xbd\x3d\xc6\xb7\xe3\xff\x7f\x8e\xff\x1e\xf6\x9e\x6f\x58\x27\x74\x65\xef\ - \x02\x5d\xa4\xde\x27\x7f\x51\xe3\x4b\x9e\x3f\x79\x83\xbd\x1b\x8f\x0d\x77\xfb\xbc\ - \xc5\x9f\x15\xa7\x4e\x05\x8a\x24\x97\x66\xb2\x7c\xf6\xe1\x84\x54\xdb\x39\x5e\xf6\ - \x1b\x8f\x05\x73\x1d\xb6\x8e\xd7\x09\x9a\xc5\x92\x80" - .to_vec(), - ]; - - for cur in tests { - let mut pck = H265Depacketizer::default(); - let mut out = Vec::new(); - let mut extra = CodecExtra::None; - let _ = pck.depacketize(&cur, &mut out, &mut extra)?; - } - - Ok(()) - } - - /// Test aggregated packets match exact payload layout. - /// Verifies AP packet structure: [AP_Header (2)] [Size1 (2)] [NAL1] [Size2 (2)] [NAL2]. - #[test] - fn test_h265_aggregated_exact_layout() -> Result<()> { - let mut packetizer = H265Packetizer::default(); - - // Create two identical simple NAL units - let header = H265NALUHeader::new(0x02, 0x01); // Type 1, layer_id=0, tid=1 - let payload = vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; - - let mut nalu = vec![header.0 as u8, (header.0 >> 8) as u8]; - nalu.extend(&payload); - - // Cache NAL units (parameter sets or similar) - let vps = vec![0x40, 0x01, 0xAA]; - let sps = vec![0x42, 0x01, 0xBB]; - - packetizer.packetize(100, &vps)?; - packetizer.packetize(100, &sps)?; - - // Trigger aggregation - let packets = packetizer.packetize(100, &nalu)?; - - if packets.len() == 1 { - // If AP was created, verify structure - let ap = &packets[0]; - let ap_header = H265NALUHeader::new(ap[0], ap[1]); - - if ap_header.nalu_type() == H265NALU_AGGREGATION_PACKET_TYPE { - // AP structure verified - assert_eq!(ap_header.nalu_type(), H265NALU_AGGREGATION_PACKET_TYPE); - } - } - - Ok(()) - } - - /// Regression test for PACI packet with payload smaller than H265NALU_HEADER_SIZE. - /// Previously this would panic with "index out of bounds" when accessing payload[1]. - #[test] - fn test_paci_short_payload_no_panic() -> Result<()> { - // Create a PACI packet with a single-byte payload - // Type 50 = PACI packet - let paci_packet: Vec = vec![ - 0x64, 0x01, // PayloadHdr: Type=50 (PACI), TID=1 - 0x00, 0x00, // PACI header fields: A=0, cType=0, PHSsize=0 - 0xAB, // Single byte payload (less than H265NALU_HEADER_SIZE) - ]; - - let mut depacketizer = H265Depacketizer::default(); - let mut out = Vec::new(); - let mut extra = CodecExtra::None; - - // This should NOT panic - the fix checks payload.len() >= H265NALU_HEADER_SIZE - let result = depacketizer.depacketize(&paci_packet, &mut out, &mut extra); - assert!(result.is_ok()); - - // Output should contain the PACI payload with Annex-B start code - assert!(out.starts_with(ANNEXB_NALUSTART_CODE)); - assert_eq!(out.len(), ANNEXB_NALUSTART_CODE.len() + 1); // start code + 1 byte payload - - Ok(()) - } - } // end integration_tests - - #[test] - fn test_detect_h265_keyframe() { - // Empty / too short payload - assert!(!detect_h265_keyframe(&[])); - assert!(!detect_h265_keyframe(&[0x00])); - - // Single IDR_W_RADL (type 19): nalu_type in bits [14:9] - // type 19 = 0b010011 → byte0 = 0b0_010011_0 = 0x26, byte1 = TID - let idr_w_radl = H265NALUHeader::new_with_type(H265NALU_IDR_W_RADL, 0, 1); - assert!(detect_h265_keyframe(&idr_w_radl.0.to_be_bytes())); - - // Single IDR_N_LP (type 20) - let idr_n_lp = H265NALUHeader::new_with_type(H265NALU_IDR_N_LP, 0, 1); - assert!(detect_h265_keyframe(&idr_n_lp.0.to_be_bytes())); - - // Single CRA (type 21) - let cra = H265NALUHeader::new_with_type(H265NALU_CRA_NUT, 0, 1); - assert!(detect_h265_keyframe(&cra.0.to_be_bytes())); - - // Single BLA_W_LP (type 16) - let bla = H265NALUHeader::new_with_type(H265NALU_BLA_W_LP, 0, 1); - assert!(detect_h265_keyframe(&bla.0.to_be_bytes())); - - // Single non-IRAP (type 1 = TRAIL_R) - let trail_r = H265NALUHeader::new_with_type(1, 0, 1); - assert!(!detect_h265_keyframe(&trail_r.0.to_be_bytes())); - - // Aggregation packet (type 48) with IDR inside - let ap_header = H265NALUHeader::new_with_type(H265NALU_AGGREGATION_PACKET_TYPE, 0, 1); - let idr_header = H265NALUHeader::new_with_type(H265NALU_IDR_W_RADL, 0, 1); - let idr_bytes = idr_header.0.to_be_bytes(); - let mut ap_with_idr = Vec::new(); - ap_with_idr.extend_from_slice(&ap_header.0.to_be_bytes()); // AP header - ap_with_idr.extend_from_slice(&[0x00, 0x03]); // NALU size = 3 - ap_with_idr.extend_from_slice(&idr_bytes); // IDR header - ap_with_idr.push(0x00); // payload byte - assert!(detect_h265_keyframe(&ap_with_idr)); - - // Aggregation packet without IRAP - let non_irap_header = H265NALUHeader::new_with_type(1, 0, 1); - let non_irap_bytes = non_irap_header.0.to_be_bytes(); - let mut ap_no_irap = Vec::new(); - ap_no_irap.extend_from_slice(&ap_header.0.to_be_bytes()); - ap_no_irap.extend_from_slice(&[0x00, 0x03]); - ap_no_irap.extend_from_slice(&non_irap_bytes); - ap_no_irap.push(0x00); - assert!(!detect_h265_keyframe(&ap_no_irap)); - - // FU start fragment with IDR type - let fu_header_bytes = H265NALUHeader::new_with_type(H265NALU_FRAGMENTATION_UNIT_TYPE, 0, 1); - let mut fu_start_idr = Vec::new(); - fu_start_idr.extend_from_slice(&fu_header_bytes.0.to_be_bytes()); - fu_start_idr.push(0x80 | H265NALU_IDR_W_RADL); // S=1, type=19 - fu_start_idr.extend_from_slice(&[0x00, 0x00]); - assert!(detect_h265_keyframe(&fu_start_idr)); - - // FU continuation fragment (S=0) - cannot detect - let mut fu_cont = Vec::new(); - fu_cont.extend_from_slice(&fu_header_bytes.0.to_be_bytes()); - fu_cont.push(H265NALU_IDR_W_RADL); // S=0, type=19 - fu_cont.extend_from_slice(&[0x00, 0x00]); - assert!(!detect_h265_keyframe(&fu_cont)); - - // FU too short (no FU header byte) - assert!(!detect_h265_keyframe(&fu_header_bytes.0.to_be_bytes())); - } - - #[test] - fn packetize_respects_mtu() -> Result<()> { - // 2-byte NAL header (non-parameter-set type) + payload. - let mut nalu = vec![0x02u8, 0x01]; - nalu.extend(std::iter::repeat(0xABu8).take(2000)); - for &mtu in &[100usize, 300, 600, 1200] { - let mut p = H265Packetizer::default(); - let pkts = p.packetize(mtu, &nalu)?; - assert!(!pkts.is_empty(), "H265 produced no packets at mtu {mtu}"); - for (i, pkt) in pkts.iter().enumerate() { - assert!(pkt.len() <= mtu, "H265 packet {i} size {} > mtu {mtu}", pkt.len()); - } - } - Ok(()) - } -} // end test module diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/h265_profile.rs b/rs/moq-webrtc/src/vendor/str0m/packet/h265_profile.rs deleted file mode 100644 index 1a74c06c537..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/h265_profile.rs +++ /dev/null @@ -1,367 +0,0 @@ -use std::collections::HashMap; - -use serde::{Deserialize, Serialize}; - -/// H.265/HEVC profile, tier, and level combination. -/// -/// Represents the three SDP fmtp parameters `profile-id`, `tier-flag`, and `level-id` -/// as defined in RFC 7798 §7.1 and ITU-T H.265 Annex A. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct H265ProfileTierLevel { - profile: H265Profile, - tier: H265Tier, - level: H265Level, -} - -impl H265ProfileTierLevel { - // RFC 7798 §7.1 default values when parameters are absent from SDP: - // profile-id=1 (Main), tier-flag=0 (Main tier), level-id=93 (Level 3.1). - // https://www.rfc-editor.org/rfc/rfc7798#section-7.1 - pub(crate) const FALLBACK: Self = Self { - profile: H265Profile::Main, - tier: H265Tier::Main, - level: H265Level::Level3_1, - }; - - /// Construct a new H265ProfileTierLevel from profile_id, tier_flag, and level_id. - /// - /// Returns `Some(Self)` only if the provided parameters identify valid values. - pub(crate) fn new(profile_id: u8, tier_flag: u8, level_id: u8) -> Option { - let profile = H265Profile::from_id(profile_id)?; - let tier = H265Tier::from_flag(tier_flag)?; - let level = H265Level::from_id(level_id)?; - - Some(Self { profile, tier, level }) - } - - /// Parse H265ProfileTierLevel from SDP fmtp parameters. - /// - /// Expects keys: "profile-id", "tier-flag", "level-id" - /// Returns None if any required parameter is missing or invalid. - pub(crate) fn from_fmtp(params: &HashMap) -> Option { - let profile_id: u8 = params.get("profile-id")?.parse().ok()?; - let tier_flag: u8 = params.get("tier-flag")?.parse().ok()?; - let level_id: u8 = params.get("level-id")?.parse().ok()?; - - Self::new(profile_id, tier_flag, level_id) - } - - /// Returns the H.265 profile (Main, Main10, etc.). - pub fn profile(&self) -> H265Profile { - self.profile - } - - /// Returns the H.265 tier (Main or High). - pub fn tier(&self) -> H265Tier { - self.tier - } - - /// Returns the H.265 level (Level 3.1, Level 4.0, etc.). - pub fn level(&self) -> H265Level { - self.level - } - - /// Returns a copy with the level replaced. - pub fn with_level(self, level: H265Level) -> Self { - Self { level, ..self } - } - - /// Returns the numeric profile_id value for SDP serialization. - pub fn profile_id(&self) -> u8 { - self.profile.to_id() - } - - /// Returns the numeric tier_flag value for SDP serialization. - pub fn tier_flag(&self) -> u8 { - self.tier.to_flag() - } - - /// Returns the numeric level_id value for SDP serialization. - pub fn level_id(&self) -> u8 { - self.level.to_id() - } -} - -impl From<(u8, u8, u8)> for H265ProfileTierLevel { - fn from(value: (u8, u8, u8)) -> Self { - Self::new(value.0, value.1, value.2).unwrap_or(Self::FALLBACK) - } -} - -/// H.265 profile as defined in ITU-T H.265 Annex A. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum H265Profile { - /// Main profile (profile_id=1). - Main, - /// Main 10 profile (profile_id=2). - Main10, - /// Main Still Picture profile (profile_id=3). - MainStillPicture, - /// Format Range Extensions profile (profile_id=4). - FormatRangeExtensions, - /// High Throughput profile (profile_id=5). - HighThroughput, - /// Multiview Main profile (profile_id=6). - MultiviewMain, - /// Scalable Main profile (profile_id=7). - ScalableMain, - /// 3D Main profile (profile_id=8). - ThreeDMain, - /// Screen Content Coding profile (profile_id=9). - ScreenContentCoding, - /// Screen Content Coding Extensions profile (profile_id=10). - ScreenContentCodingExtensions, - /// High Throughput Screen Content Coding profile (profile_id=11). - HighThroughputScreenContentCoding, -} - -impl H265Profile { - /// Convert from H.265 profile_id value. - /// - /// See ITU-T H.265 (04/2013) Annex A for profile definitions. - fn from_id(profile_id: u8) -> Option { - match profile_id { - 1 => Some(Self::Main), - 2 => Some(Self::Main10), - 3 => Some(Self::MainStillPicture), - 4 => Some(Self::FormatRangeExtensions), - 5 => Some(Self::HighThroughput), - 6 => Some(Self::MultiviewMain), - 7 => Some(Self::ScalableMain), - 8 => Some(Self::ThreeDMain), - 9 => Some(Self::ScreenContentCoding), - 10 => Some(Self::ScreenContentCodingExtensions), - 11 => Some(Self::HighThroughputScreenContentCoding), - _ => None, - } - } - - /// Convert to H.265 profile_id value. - pub fn to_id(self) -> u8 { - match self { - Self::Main => 1, - Self::Main10 => 2, - Self::MainStillPicture => 3, - Self::FormatRangeExtensions => 4, - Self::HighThroughput => 5, - Self::MultiviewMain => 6, - Self::ScalableMain => 7, - Self::ThreeDMain => 8, - Self::ScreenContentCoding => 9, - Self::ScreenContentCodingExtensions => 10, - Self::HighThroughputScreenContentCoding => 11, - } - } -} - -/// H.265 tier (Main or High). -#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum H265Tier { - /// Main tier (tier_flag=0). - Main, - /// High tier (tier_flag=1). - High, -} - -impl H265Tier { - /// Convert from H.265 tier_flag value. - /// - /// 0 = Main tier, 1 = High tier - fn from_flag(tier_flag: u8) -> Option { - match tier_flag { - 0 => Some(Self::Main), - 1 => Some(Self::High), - _ => None, - } - } - - /// Convert to H.265 tier_flag value. - pub fn to_flag(self) -> u8 { - match self { - Self::Main => 0, - Self::High => 1, - } - } -} - -/// H.265 level as defined in ITU-T H.265 Annex A. -/// -/// Level IDs are 30× the level number (e.g., Level 3.1 = 93). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[repr(u8)] -#[rustfmt::skip] -pub enum H265Level { - /// Level 1.0 (level_id=30). - Level1 = 30_u8, - /// Level 2.0 (level_id=60). - Level2 = 60_u8, - /// Level 2.1 (level_id=63). - Level2_1 = 63_u8, - /// Level 3.0 (level_id=90). - Level3 = 90_u8, - /// Level 3.1 (level_id=93). - Level3_1 = 93_u8, - /// Level 4.0 (level_id=120). - Level4 = 120_u8, - /// Level 4.1 (level_id=123). - Level4_1 = 123_u8, - /// Level 5.0 (level_id=150). - Level5 = 150_u8, - /// Level 5.1 (level_id=153). - Level5_1 = 153_u8, - /// Level 5.2 (level_id=156). - Level5_2 = 156_u8, - /// Level 6.0 (level_id=180). - Level6 = 180_u8, - /// Level 6.1 (level_id=183). - Level6_1 = 183_u8, - /// Level 6.2 (level_id=186). - Level6_2 = 186_u8, -} - -impl H265Level { - /// Returns the ordinal position (0-12) representing capability order. - pub fn ordinal(self) -> usize { - match self { - Self::Level1 => 0, - Self::Level2 => 1, - Self::Level2_1 => 2, - Self::Level3 => 3, - Self::Level3_1 => 4, - Self::Level4 => 5, - Self::Level4_1 => 6, - Self::Level5 => 7, - Self::Level5_1 => 8, - Self::Level5_2 => 9, - Self::Level6 => 10, - Self::Level6_1 => 11, - Self::Level6_2 => 12, - } - } - - /// Convert from H.265 level_id value. - fn from_id(level_id: u8) -> Option { - use H265Level::*; - match level_id { - x if (Level1 as u8) == x => Some(Level1), - x if (Level2 as u8) == x => Some(Level2), - x if (Level2_1 as u8) == x => Some(Level2_1), - x if (Level3 as u8) == x => Some(Level3), - x if (Level3_1 as u8) == x => Some(Level3_1), - x if (Level4 as u8) == x => Some(Level4), - x if (Level4_1 as u8) == x => Some(Level4_1), - x if (Level5 as u8) == x => Some(Level5), - x if (Level5_1 as u8) == x => Some(Level5_1), - x if (Level5_2 as u8) == x => Some(Level5_2), - x if (Level6 as u8) == x => Some(Level6), - x if (Level6_1 as u8) == x => Some(Level6_1), - x if (Level6_2 as u8) == x => Some(Level6_2), - _ => None, - } - } - - /// Convert to H.265 level_id value. - pub fn to_id(self) -> u8 { - self as u8 - } -} - -impl PartialOrd for H265Level { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for H265Level { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.ordinal().cmp(&other.ordinal()) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_h265_profile_tier_level_new() { - // Valid combination - let ptl = H265ProfileTierLevel::new(1, 0, 93); - assert!(ptl.is_some()); - let ptl = ptl.unwrap(); - assert_eq!(ptl.profile(), H265Profile::Main); - assert_eq!(ptl.tier(), H265Tier::Main); - assert_eq!(ptl.level(), H265Level::Level3_1); - - // Invalid profile_id - let ptl = H265ProfileTierLevel::new(99, 0, 93); - assert!(ptl.is_none()); - - // Invalid tier_flag - let ptl = H265ProfileTierLevel::new(1, 5, 93); - assert!(ptl.is_none()); - - // Invalid level_id - let ptl = H265ProfileTierLevel::new(1, 0, 255); - assert!(ptl.is_none()); - } - - #[test] - fn test_h265_profile_from_id() { - assert_eq!(H265Profile::from_id(1), Some(H265Profile::Main)); - assert_eq!(H265Profile::from_id(2), Some(H265Profile::Main10)); - assert_eq!(H265Profile::from_id(99), None); - } - - #[test] - fn test_h265_tier_from_flag() { - assert_eq!(H265Tier::from_flag(0), Some(H265Tier::Main)); - assert_eq!(H265Tier::from_flag(1), Some(H265Tier::High)); - assert_eq!(H265Tier::from_flag(2), None); - } - - #[test] - fn test_h265_level_from_id() { - assert_eq!(H265Level::from_id(30), Some(H265Level::Level1)); - assert_eq!(H265Level::from_id(93), Some(H265Level::Level3_1)); - assert_eq!(H265Level::from_id(186), Some(H265Level::Level6_2)); - assert_eq!(H265Level::from_id(255), None); - } - - #[test] - fn test_h265_level_ordering() { - assert!(H265Level::Level1 < H265Level::Level2); - assert!(H265Level::Level3_1 < H265Level::Level4); - assert!(H265Level::Level6_1 < H265Level::Level6_2); - assert_eq!(H265Level::Level3_1.ordinal(), 4); - } - - #[test] - fn test_h265_profile_tier_level_from_fmtp() { - let mut params = HashMap::new(); - params.insert("profile-id".to_string(), "1".to_string()); - params.insert("tier-flag".to_string(), "0".to_string()); - params.insert("level-id".to_string(), "93".to_string()); - - let ptl = H265ProfileTierLevel::from_fmtp(¶ms); - assert!(ptl.is_some()); - let ptl = ptl.unwrap(); - assert_eq!(ptl.profile(), H265Profile::Main); - assert_eq!(ptl.tier(), H265Tier::Main); - assert_eq!(ptl.level(), H265Level::Level3_1); - - // Missing parameter - let mut params = HashMap::new(); - params.insert("profile-id".to_string(), "1".to_string()); - params.insert("tier-flag".to_string(), "0".to_string()); - let ptl = H265ProfileTierLevel::from_fmtp(¶ms); - assert!(ptl.is_none()); - } - - #[test] - fn test_fallback_values() { - let fallback = H265ProfileTierLevel::FALLBACK; - assert_eq!(fallback.profile(), H265Profile::Main); - assert_eq!(fallback.tier(), H265Tier::Main); - assert_eq!(fallback.level(), H265Level::Level3_1); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/mod.rs b/rs/moq-webrtc/src/vendor/str0m/packet/mod.rs deleted file mode 100644 index e193e8d9460..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/mod.rs +++ /dev/null @@ -1,529 +0,0 @@ -#![allow(clippy::type_complexity)] - -use std::fmt; -use std::panic::UnwindSafe; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::sdp::MediaType; - -mod av1; -pub use av1::Av1CodecExtra; -pub use av1::detect_av1_keyframe; -use av1::{Av1Depacketizer, Av1Packetizer}; - -mod amr_wb; -use amr_wb::{AmrWbDepacketizer, AmrWbPacketizer}; - -mod h264; -pub use h264::H264CodecExtra; -pub use h264::{H264Depacketizer, H264Packetizer}; -pub use h264::{detect_h264_keyframe, detect_h264_nalu}; - -mod h264_profile; -pub(crate) use h264_profile::H264ProfileLevel; - -mod h265; -pub use h265::H265CodecExtra; -use h265::H265Depacketizer; -pub use h265::H265Packetizer; -pub use h265::detect_h265_keyframe; - -mod h265_profile; -pub use h265_profile::{H265Level, H265Profile, H265ProfileTierLevel, H265Tier}; - -mod opus; -pub use opus::{OpusDepacketizer, OpusPacketizer}; - -mod vp8; -pub use vp8::Vp8CodecExtra; -pub use vp8::Vp8Descriptor; -pub use vp8::Vp8DescriptorError; -pub use vp8::Vp8Patch; -pub use vp8::Vp8PatchBuilder; -pub use vp8::Vp8PatchError; -pub use vp8::detect_vp8_keyframe; -pub use vp8::{Vp8Depacketizer, Vp8Packetizer}; - -mod vp9; -pub use vp9::Vp9CodecExtra; -pub use vp9::Vp9PacketizerMode; -pub use vp9::detect_vp9_keyframe; -use vp9::{Vp9Depacketizer, Vp9Packetizer}; - -mod null; -use null::{NullDepacketizer, NullPacketizer}; - -mod buffer_rx; -pub(crate) use buffer_rx::{DepacketizingBuffer, RtpMeta}; - -mod contiguity; -mod contiguity_vp8; -mod contiguity_vp9; -mod error; - -mod payload; -pub(crate) use payload::Payloader; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -/// Types of media. -pub enum MediaKind { - /// Audio media. - Audio, - /// Video media. - Video, -} - -impl MediaKind { - /// Tests if this is `MediaKind::Audio` - pub fn is_audio(&self) -> bool { - *self == MediaKind::Audio - } - - /// Tests if this is `MediaKind::Video` - pub fn is_video(&self) -> bool { - *self == MediaKind::Video - } -} - -/// Packetizes some bytes for use as RTP packet. -/// -/// ## Unversioned API surface -/// -/// This trait is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -pub trait Packetizer: fmt::Debug { - /// Chunk the data up into RTP packets. - fn packetize(&mut self, mtu: usize, b: &[u8]) -> Result>, PacketError>; - - /// Tell if this is the last packet of a frame. - fn is_marker(&mut self, data: &[u8], previous: Option<&[u8]>, last: bool) -> bool; - - /// Whether a start-of-talkspurt should set the RTP marker bit for this codec. Audio codecs - /// that mark talkspurt boundaries return `true`; video returns `false`. - fn marks_talkspurt(&self) -> bool { - false - } - - /// Default nackability of packets this packetizer produces. Video is nackable (answered via - /// RTX); audio is not, so audio packetizers override this to `false`. - fn nackable(&self) -> bool { - true - } -} - -/// Codec specific information -/// -/// Contains additional codec specific information which are deemed useful for -/// managing and repackaging the frame -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum CodecExtra { - /// No extra information available - None, - /// Codec extra parameters for VP8. - Vp8(Vp8CodecExtra), - /// Codec extra parameters for VP9. - Vp9(Vp9CodecExtra), - /// Codec extra parameters for H264. - H264(H264CodecExtra), - /// Codec extra parameters for AV1, - Av1(Av1CodecExtra), - /// Codec extra parameters for H265. - H265(H265CodecExtra), -} - -/// Depacketizes an RTP payload. -/// -/// Removes any RTP specific data from the payload. -/// -/// ## Unversioned API surface -/// -/// This trait is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -pub trait Depacketizer: fmt::Debug { - /// Provide a size hint for the `out: &mut Vec` parameter in [`Depacketizer::depacketize`]. - /// The [`packets_size`] parameter is the sum of the size of all packets that will be processed in - /// subsequent calls to [`Depacketizer::depacketize`]. - /// This is used to allocate the vector with upfront capacity. - /// Return [`None`] if it cannot be determined. - fn out_size_hint(&self, packets_size: usize) -> Option; - - /// Unpack the RTP packet into a provided `Vec`. - fn depacketize( - &mut self, - packet: &[u8], - out: &mut Vec, - codec_extra: &mut CodecExtra, - ) -> Result<(), PacketError>; - - /// Checks if the packet is at the beginning of a partition. - /// - /// Returns false if the result could not be determined. - fn is_partition_head(&self, packet: &[u8]) -> bool; - - /// Checks if the packet is at the end of a partition. - /// - /// Returns false if the result could not be determined. - fn is_partition_tail(&self, marker: bool, packet: &[u8]) -> bool; -} - -pub use error::PacketError; - -/// Helper to replace Bytes. Provides get_u8 and get_u16 over some buffer of bytes. -pub(crate) trait BitRead { - fn remaining_bits(&self) -> usize; - fn remaining_bytes(&self) -> usize; - fn byte_offset(&self) -> usize; - fn get_u8(&mut self) -> Option; - fn get_u16(&mut self) -> Option; - /// Reads `count` bits, at most 8, right-aligned in the result. - fn get_bits(&mut self, count: usize) -> Option; - fn get_remaining(&mut self) -> &[u8]; - fn get_bytes(&mut self, count: usize) -> Option<&[u8]>; - fn get_leb128(&mut self) -> Option; - fn skip_bytes(&mut self, count: usize); -} - -impl BitRead for (&[u8], usize) { - #[inline(always)] - fn remaining_bits(&self) -> usize { - (self.0.len() * 8).saturating_sub(self.1) - } - - #[inline(always)] - fn remaining_bytes(&self) -> usize { - self.remaining_bits() / 8 - } - - #[inline(always)] - fn byte_offset(&self) -> usize { - self.1 / 8 - } - - #[inline(always)] - fn get_u8(&mut self) -> Option { - if self.remaining_bits() < 8 { - return None; - } - - let offs = self.1 / 8; - let shift = (self.1 % 8) as u32; - self.1 += 8; - - let mut n = self.0[offs]; - - if shift > 0 { - n <<= shift; - n |= self.0[offs + 1] >> (8 - shift) - } - - Some(n) - } - - fn get_u16(&mut self) -> Option { - if self.remaining_bits() < 16 { - return None; - } - Some(u16::from_be_bytes([self.get_u8()?, self.get_u8()?])) - } - - fn get_bits(&mut self, count: usize) -> Option { - if count > 8 || self.remaining_bits() < count { - return None; - } - if count == 0 { - return Some(0); - } - - let offs = self.1 / 8; - let next = self.0.get(offs + 1).copied().unwrap_or(0); - let window = u16::from_be_bytes([self.0[offs], next]) << (self.1 % 8); - self.1 += count; - - Some((window >> (16 - count)) as u8) - } - - fn get_remaining(&mut self) -> &[u8] { - let offset = self.1 / 8; - self.1 = self.0.len() * 8; - &self.0[offset..] - } - - fn get_bytes(&mut self, count: usize) -> Option<&[u8]> { - let count_bits = count.saturating_mul(8); - if self.remaining_bits() < count_bits { - return None; - } - let offset = self.1 / 8; - self.1 += count_bits; - Some(&self.0[offset..offset + count]) - } - - fn get_leb128(&mut self) -> Option { - let mut temp_value: usize = 0; - - for i in (0..64).step_by(7) { - if self.remaining_bits() < 8 { - return None; - } - let byte = self.get_u8().unwrap(); - temp_value |= ((byte & 0x7f) as usize) << i; - - if byte < 0x80 { - return Some(temp_value); - } - } - - None - } - - fn skip_bytes(&mut self, count: usize) { - let bits = count.saturating_mul(8); - if self.remaining_bits() < bits { - return; - } - - self.1 += bits; - } -} - -#[derive(Debug)] -pub(crate) enum CodecPacketizer { - H264(H264Packetizer), - H265(H265Packetizer), - Opus(OpusPacketizer), - Vp8(Vp8Packetizer), - Vp9(Vp9Packetizer), - Av1(Av1Packetizer), - AmrWb(AmrWbPacketizer), - Null(NullPacketizer), - #[allow(unused)] - Boxed(Box), -} - -#[derive(Debug)] -pub(crate) enum CodecDepacketizer { - H264(H264Depacketizer), - H265(H265Depacketizer), - Opus(OpusDepacketizer), - Vp8(Vp8Depacketizer), - Vp9(Vp9Depacketizer), - Av1(Av1Depacketizer), - AmrWb(AmrWbDepacketizer), - Null(NullDepacketizer), - #[allow(unused)] - Boxed(Box), -} - -impl CodecPacketizer { - pub(crate) fn new(codec: Codec, vp9_mode: Vp9PacketizerMode) -> Self { - match codec { - Codec::Opus => CodecPacketizer::Opus(OpusPacketizer), - Codec::AmrWb => CodecPacketizer::AmrWb(AmrWbPacketizer::default()), - Codec::H264 => CodecPacketizer::H264(H264Packetizer::default()), - Codec::H265 => CodecPacketizer::H265(H265Packetizer::default()), - Codec::Vp8 => CodecPacketizer::Vp8(Vp8Packetizer::default()), - Codec::Vp9 => CodecPacketizer::Vp9(Vp9Packetizer::with_mode(vp9_mode)), - Codec::Av1 => CodecPacketizer::Av1(Av1Packetizer::default()), - Codec::Null => CodecPacketizer::Null(NullPacketizer), - Codec::Rtx => panic!("Cant instantiate packetizer for RTX codec"), - Codec::Unknown => panic!("Cant instantiate packetizer for unknown codec"), - } - } - - /// Apply codec-specific configuration derived from the negotiated [`CodecSpec`]. Keeps this - /// knowledge inside the codec-aware packetizer so the generic [`Payloader`] never has to name - /// concrete packetizer variants. - pub(crate) fn configure_for(&mut self, spec: &crate::vendor::str0m::format::CodecSpec) { - // Enable DONL for H.265 when sprop-max-don-diff > 0 (RFC 7798 §7.1). - if let CodecPacketizer::H265(h265) = self { - if spec.format.sprop_max_don_diff.unwrap_or(0) > 0 { - h265.with_donl(true); - } - } - if let CodecPacketizer::AmrWb(amr) = self { - amr.octet_align = spec.format.octet_align.unwrap_or(false); - } - } -} - -impl From for CodecPacketizer { - fn from(c: Codec) -> Self { - CodecPacketizer::new(c, Vp9PacketizerMode::default()) - } -} - -impl From for CodecDepacketizer { - fn from(c: Codec) -> Self { - match c { - Codec::Opus => CodecDepacketizer::Opus(OpusDepacketizer), - Codec::AmrWb => CodecDepacketizer::AmrWb(AmrWbDepacketizer::default()), - Codec::H264 => CodecDepacketizer::H264(H264Depacketizer::default()), - Codec::H265 => CodecDepacketizer::H265(H265Depacketizer::default()), - Codec::Vp8 => CodecDepacketizer::Vp8(Vp8Depacketizer::default()), - Codec::Vp9 => CodecDepacketizer::Vp9(Vp9Depacketizer::default()), - Codec::Av1 => CodecDepacketizer::Av1(Av1Depacketizer::default()), - Codec::Null => CodecDepacketizer::Null(NullDepacketizer), - Codec::Rtx => panic!("Cant instantiate depacketizer for RTX codec"), - Codec::Unknown => panic!("Cant instantiate depacketizer for unknown codec"), - } - } -} - -impl Packetizer for CodecPacketizer { - fn packetize(&mut self, mtu: usize, b: &[u8]) -> Result>, PacketError> { - use CodecPacketizer::*; - match self { - H264(v) => v.packetize(mtu, b), - H265(v) => v.packetize(mtu, b), - Opus(v) => v.packetize(mtu, b), - Vp8(v) => v.packetize(mtu, b), - Vp9(v) => v.packetize(mtu, b), - Av1(v) => v.packetize(mtu, b), - AmrWb(v) => v.packetize(mtu, b), - Null(v) => v.packetize(mtu, b), - Boxed(v) => v.packetize(mtu, b), - } - } - - fn is_marker(&mut self, data: &[u8], previous: Option<&[u8]>, last: bool) -> bool { - match self { - CodecPacketizer::Opus(v) => v.is_marker(data, previous, last), - CodecPacketizer::H264(v) => v.is_marker(data, previous, last), - CodecPacketizer::H265(v) => v.is_marker(data, previous, last), - CodecPacketizer::Vp8(v) => v.is_marker(data, previous, last), - CodecPacketizer::Vp9(v) => v.is_marker(data, previous, last), - CodecPacketizer::Av1(v) => v.is_marker(data, previous, last), - CodecPacketizer::AmrWb(v) => v.is_marker(data, previous, last), - CodecPacketizer::Null(v) => v.is_marker(data, previous, last), - CodecPacketizer::Boxed(v) => v.is_marker(data, previous, last), - } - } - - fn marks_talkspurt(&self) -> bool { - use CodecPacketizer::*; - match self { - H264(v) => v.marks_talkspurt(), - H265(v) => v.marks_talkspurt(), - Opus(v) => v.marks_talkspurt(), - Vp8(v) => v.marks_talkspurt(), - Vp9(v) => v.marks_talkspurt(), - Av1(v) => v.marks_talkspurt(), - AmrWb(v) => v.marks_talkspurt(), - Null(v) => v.marks_talkspurt(), - Boxed(v) => v.marks_talkspurt(), - } - } - - fn nackable(&self) -> bool { - use CodecPacketizer::*; - match self { - H264(v) => v.nackable(), - H265(v) => v.nackable(), - Opus(v) => v.nackable(), - Vp8(v) => v.nackable(), - Vp9(v) => v.nackable(), - Av1(v) => v.nackable(), - AmrWb(v) => v.nackable(), - Null(v) => v.nackable(), - Boxed(v) => v.nackable(), - } - } -} - -impl Depacketizer for CodecDepacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - use CodecDepacketizer::*; - match self { - H264(v) => v.out_size_hint(packets_size), - H265(v) => v.out_size_hint(packets_size), - Opus(v) => v.out_size_hint(packets_size), - Vp8(v) => v.out_size_hint(packets_size), - Vp9(v) => v.out_size_hint(packets_size), - Av1(v) => v.out_size_hint(packets_size), - AmrWb(v) => v.out_size_hint(packets_size), - Null(v) => v.out_size_hint(packets_size), - Boxed(v) => v.out_size_hint(packets_size), - } - } - - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, extra: &mut CodecExtra) -> Result<(), PacketError> { - use CodecDepacketizer::*; - match self { - H264(v) => v.depacketize(packet, out, extra), - H265(v) => v.depacketize(packet, out, extra), - Opus(v) => v.depacketize(packet, out, extra), - Vp8(v) => v.depacketize(packet, out, extra), - Vp9(v) => v.depacketize(packet, out, extra), - Av1(v) => v.depacketize(packet, out, extra), - AmrWb(v) => v.depacketize(packet, out, extra), - Null(v) => v.depacketize(packet, out, extra), - Boxed(v) => v.depacketize(packet, out, extra), - } - } - - fn is_partition_head(&self, packet: &[u8]) -> bool { - use CodecDepacketizer::*; - match self { - H264(v) => v.is_partition_head(packet), - H265(v) => v.is_partition_head(packet), - Opus(v) => v.is_partition_head(packet), - Vp8(v) => v.is_partition_head(packet), - Vp9(v) => v.is_partition_head(packet), - Av1(v) => v.is_partition_head(packet), - AmrWb(v) => v.is_partition_head(packet), - Null(v) => v.is_partition_head(packet), - Boxed(v) => v.is_partition_head(packet), - } - } - - fn is_partition_tail(&self, marker: bool, packet: &[u8]) -> bool { - use CodecDepacketizer::*; - match self { - H264(v) => v.is_partition_tail(marker, packet), - H265(v) => v.is_partition_tail(marker, packet), - Opus(v) => v.is_partition_tail(marker, packet), - Vp8(v) => v.is_partition_tail(marker, packet), - Vp9(v) => v.is_partition_tail(marker, packet), - Av1(v) => v.is_partition_tail(marker, packet), - AmrWb(v) => v.is_partition_tail(marker, packet), - Null(v) => v.is_partition_tail(marker, packet), - Boxed(v) => v.is_partition_tail(marker, packet), - } - } -} - -impl From for MediaKind { - fn from(v: MediaType) -> Self { - match v { - MediaType::Audio => MediaKind::Audio, - MediaType::Video => MediaKind::Video, - _ => panic!("Not MediaType::Audio or Video"), - } - } -} - -impl fmt::Display for MediaKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - MediaKind::Audio => write!(f, "audio"), - MediaKind::Video => write!(f, "video"), - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn bit_read_get_bits() { - let mut reader: (&[u8], usize) = (&[0b1010_1100, 0b0101_0000], 4); - assert_eq!(reader.get_bits(6), Some(0b110001)); - assert_eq!(reader.get_bits(3), Some(0b010)); - assert_eq!(reader.get_bits(9), None); - assert_eq!(reader.get_bits(4), None); - assert_eq!(reader.get_bits(3), Some(0)); - assert_eq!(reader.get_bits(0), Some(0)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/null.rs b/rs/moq-webrtc/src/vendor/str0m/packet/null.rs deleted file mode 100644 index c418a33d3bc..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/null.rs +++ /dev/null @@ -1,43 +0,0 @@ -use super::{CodecExtra, Depacketizer, PacketError, Packetizer}; - -#[derive(Debug)] -pub struct NullPacketizer; - -#[derive(Debug)] -pub struct NullDepacketizer; - -impl Packetizer for NullPacketizer { - fn packetize(&mut self, _mtu: usize, b: &[u8]) -> Result>, PacketError> { - Ok(vec![b.to_vec()]) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, _last: bool) -> bool { - false - } -} - -impl Depacketizer for NullDepacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - fn depacketize( - &mut self, - packet: &[u8], - out: &mut Vec, - _codec_extra: &mut CodecExtra, - ) -> Result<(), PacketError> { - out.extend_from_slice(packet); - Ok(()) - } - - fn is_partition_head(&self, _packet: &[u8]) -> bool { - // For rtp-mode since each packet is stand alone, it is both a partition head and tail. - true - } - - fn is_partition_tail(&self, _marker: bool, _packet: &[u8]) -> bool { - // For rtp-mode since each packet is stand alone, it is both a partition head and tail. - true - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/opus.rs b/rs/moq-webrtc/src/vendor/str0m/packet/opus.rs deleted file mode 100644 index 369a9d4d91a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/opus.rs +++ /dev/null @@ -1,145 +0,0 @@ -use super::{CodecExtra, Depacketizer, PacketError, Packetizer}; - -/// Packetizes Opus RTP packets. -/// -/// ## Unversioned API surface -/// -/// This struct is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -#[derive(Default, Debug, Copy, Clone)] -pub struct OpusPacketizer; - -impl Packetizer for OpusPacketizer { - fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - if payload.is_empty() || mtu == 0 { - return Ok(vec![]); - } - - let mut out = vec![]; - - let mut cur = 0; - while cur < payload.len() { - let min = mtu.min(payload.len() - cur); - out.push(payload[cur..(cur + min)].to_vec()); - cur += mtu; - } - - Ok(out) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, _last: bool) -> bool { - // TODO: dtx - false - } - - fn marks_talkspurt(&self) -> bool { - true - } - - fn nackable(&self) -> bool { - false - } -} - -/// Depacketizes Opus RTP packets. -/// -/// ## Unversioned API surface -/// -/// This struct is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -#[derive(PartialEq, Eq, Debug, Default, Clone)] -pub struct OpusDepacketizer; - -impl Depacketizer for OpusDepacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, _: &mut CodecExtra) -> Result<(), PacketError> { - if !packet.is_empty() { - out.extend_from_slice(packet); - } - - Ok(()) - } - - fn is_partition_head(&self, _payload: &[u8]) -> bool { - true - } - - fn is_partition_tail(&self, _marker: bool, _payload: &[u8]) -> bool { - true - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_opus_unmarshal() -> Result<(), PacketError> { - let mut pck = OpusDepacketizer; - let mut extra = CodecExtra::None; - - // Empty packet - let empty_bytes = &[]; - let mut out = Vec::new(); - let result = pck.depacketize(empty_bytes, &mut out, &mut extra); - assert!(result.is_ok(), "Result should not be err in case of empty packet"); - - // Normal packet - let raw_bytes: &[u8] = &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x90]; - let mut out = Vec::new(); - pck.depacketize(raw_bytes, &mut out, &mut extra)?; - assert_eq!(raw_bytes, &out, "Payload must be same"); - - Ok(()) - } - - #[test] - fn test_opus_payload() -> Result<(), PacketError> { - let mut pck = OpusPacketizer; - let empty = &[]; - let payload = &[0x90, 0x90, 0x90]; - - // Positive MTU, empty payload - let result = pck.packetize(1, empty)?; - assert!(result.is_empty(), "Generated payload should be empty"); - - // Positive MTU, small payload - let result = pck.packetize(1, payload)?; - assert_eq!(result.len(), 3, "Generated payload should be 3"); - - // Positive MTU, small payload - let result = pck.packetize(2, payload)?; - assert_eq!(result.len(), 2, "Generated payload should be the 2"); - - Ok(()) - } - - #[test] - fn test_opus_is_partition_head() -> Result<(), PacketError> { - let opus = OpusDepacketizer; - //"NormalPacket" - assert!( - opus.is_partition_head(&[0x00, 0x00]), - "All OPUS RTP packet should be the head of a new partition" - ); - - Ok(()) - } - - #[test] - fn packetize_respects_mtu() -> Result<(), PacketError> { - let payload = vec![0xABu8; 2000]; - for &mtu in &[100usize, 300, 600, 1200] { - let mut pck = OpusPacketizer; - let pkts = pck.packetize(mtu, &payload)?; - assert!(!pkts.is_empty(), "Opus produced no packets at mtu {mtu}"); - for (i, pkt) in pkts.iter().enumerate() { - assert!(pkt.len() <= mtu, "Opus packet {i} size {} > mtu {mtu}", pkt.len()); - } - } - Ok(()) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/payload.rs b/rs/moq-webrtc/src/vendor/str0m/packet/payload.rs deleted file mode 100644 index 496fac34c81..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/payload.rs +++ /dev/null @@ -1,143 +0,0 @@ -use std::time::Instant; - -use crate::vendor::str0m::format::{CodecSpec, Vp9PacketizerMode}; -use crate::vendor::str0m::media::ToPayload; -use crate::vendor::str0m::rtp_::{ExtensionValues, Frequency, Pt, SeqNo}; -use crate::vendor::str0m::streams::{RtpWrite, StreamTx}; - -use super::PacketError; -use super::{CodecPacketizer, Packetizer}; - -/// Turns frames into RTP packets. -/// -/// The payloader is deliberately codec- and feature-agnostic: it packetizes via its -/// [`CodecPacketizer`] and emits [`OutgoingPacket`]s through a [`PacketSink`]. All codec-specific -/// behaviour (marker/nackable policy, DONL) lives on the packetizer. -#[derive(Debug)] -pub struct Payloader { - pack: CodecPacketizer, - clock_rate: Frequency, -} - -/// A packet ready to hand to a [`PacketSink`]: the RTP fields plus the payload as an owned -/// `Vec`. The payload is only wrapped into an `Arc` once, when the sink builds the [`RtpWrite`]. -pub(crate) struct OutgoingPacket { - pub pt: Pt, - pub seq_no: SeqNo, - pub rtp_time: u32, - pub wallclock: Instant, - pub marker: bool, - pub nackable: bool, - pub ext_vals: ExtensionValues, - pub payload: Vec, -} - -/// Where a [`Payloader`] sends its packetized output, implemented by [`StreamTx`]. -pub(crate) trait PacketSink { - /// The next sequence number to assign on the underlying stream. - fn next_seq_no(&mut self) -> SeqNo; - /// The most recently written packet payload on the underlying stream, for marker decisions. - fn last_packet(&self) -> Option<&[u8]>; - /// Emit a packet. - fn send(&mut self, packet: OutgoingPacket); -} - -impl Payloader { - pub(crate) fn new(spec: CodecSpec, vp9_mode: Vp9PacketizerMode) -> Self { - let mut pack = CodecPacketizer::new(spec.codec, vp9_mode); - // The packetizer applies its own codec-specific configuration (e.g. DONL); the payloader - // never names concrete packetizer variants. - pack.configure_for(&spec); - - Payloader { - pack, - clock_rate: spec.clock_rate, - } - } - - pub(crate) fn push_sample( - &mut self, - to_payload: ToPayload, - mtu: usize, - sink: &mut S, - ) -> Result<(), PacketError> { - let ToPayload { - pt, - wallclock, - rtp_time, - data, - start_of_talk_spurt, - ext_vals, - .. - } = to_payload; - - let chunks = self.pack.packetize(mtu, data.as_ref())?; - let len = chunks.len(); - - for (idx, data) in chunks.into_iter().enumerate() { - let last = idx == len - 1; - let first = idx == 0; - - let previous_data = sink.last_packet(); - let marker = self.pack.is_marker(data.as_slice(), previous_data, last) - || (self.pack.marks_talkspurt() && start_of_talk_spurt); - - let seq_no = sink.next_seq_no(); - - let nackable = self.pack.nackable(); - - let mut pkt_ext_vals = ext_vals.clone(); - - if !first { - pkt_ext_vals.abs_capture_time = None; - } - - if !last { - pkt_ext_vals.video_orientation = None; - pkt_ext_vals.video_content_type = None; - pkt_ext_vals.video_timing = None; - } - - let rtp_time_u32 = rtp_time.rebase(self.clock_rate).numer() as u32; - - sink.send(OutgoingPacket { - pt, - seq_no, - rtp_time: rtp_time_u32, - wallclock, - marker, - nackable, - ext_vals: pkt_ext_vals, - payload: data, - }); - } - - Ok(()) - } -} - -/// The plain sink: writes each packet straight to the stream on its own payload type. -impl PacketSink for StreamTx { - fn next_seq_no(&mut self) -> SeqNo { - StreamTx::next_seq_no(self) - } - - fn last_packet(&self) -> Option<&[u8]> { - StreamTx::last_packet(self) - } - - fn send(&mut self, packet: OutgoingPacket) { - self.write_rtp( - RtpWrite::new( - packet.pt, - packet.seq_no, - packet.rtp_time, - packet.wallclock, - packet.payload, - ) - .marker(packet.marker) - .ext_vals(packet.ext_vals) - .nackable(packet.nackable), - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/vp8.rs b/rs/moq-webrtc/src/vendor/str0m/packet/vp8.rs deleted file mode 100644 index ddc7389c5a1..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/vp8.rs +++ /dev/null @@ -1,1318 +0,0 @@ -use std::error::Error; -use std::fmt; - -use crate::vendor::str0m::rtp_::{extend_u7, extend_u8, extend_u15}; - -use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer}; - -pub const VP8_HEADER_SIZE: usize = 1; - -const PICTURE_ID_SHORT_MAX: u16 = 0x7f; // 7-bit PictureID, excluding the M bit -const PICTURE_ID_MAX: u16 = 0x7fff; // 15-bit PictureID, excluding the M bit -const PICTURE_ID_SHORT_MASK: u8 = PICTURE_ID_SHORT_MAX as u8; -const KEY_IDX_MASK: u8 = 0x1f; // 5-bit KEYIDX mask within the TID/Y/KEYIDX octet -const VP8_PATCH_BYTES: usize = 4; // two PictureID bytes, TL0PICIDX and KEYIDX - -/// Validated byte replacements for a VP8 payload descriptor. -/// -/// Build this from [`Vp8Descriptor::patch`] when the caller already parsed the -/// payload descriptor before fanout. The patch is fixed-size and never changes -/// payload length. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Vp8Patch { - len: u8, - offsets: [u8; VP8_PATCH_BYTES], - bytes: [u8; VP8_PATCH_BYTES], -} - -impl Vp8Patch { - fn new() -> Self { - Self { - len: 0, - offsets: [0; VP8_PATCH_BYTES], - bytes: [0; VP8_PATCH_BYTES], - } - } - - fn push(&mut self, offset: usize, byte: u8) { - let index = usize::from(self.len); - debug_assert!(index < self.offsets.len()); - debug_assert!(offset <= usize::from(u8::MAX)); - - self.offsets[index] = offset as u8; - self.bytes[index] = byte; - self.len += 1; - } - - /// Copy `payload` into `dst` while applying VP8 descriptor byte replacements. - /// - /// # Panics - /// - /// Panics if `dst` is not the same length as `payload`. - pub(crate) fn copy_to(&self, payload: &[u8], dst: &mut [u8]) { - assert_eq!(payload.len(), dst.len()); - - dst.copy_from_slice(payload); - - for i in 0..usize::from(self.len) { - dst[usize::from(self.offsets[i])] = self.bytes[i]; - } - } -} - -/// Errors returned when a VP8 payload descriptor cannot be parsed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum Vp8DescriptorError { - /// The payload is too short to contain a valid VP8 payload descriptor. - ShortPayload, - /// The payload descriptor violates VP8 payload descriptor rules. - MalformedDescriptor, -} - -impl fmt::Display for Vp8DescriptorError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::ShortPayload => write!(f, "VP8 payload is too short"), - Self::MalformedDescriptor => write!(f, "VP8 payload descriptor is malformed"), - } - } -} - -impl Error for Vp8DescriptorError {} - -/// Errors returned when a VP8 payload descriptor patch cannot be built. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum Vp8PatchError { - /// The payload descriptor does not contain a PictureID field. - PictureIdMissing, - /// The requested PictureID does not fit the existing descriptor width. - PictureIdTooLarge, - /// The payload descriptor does not contain a TL0PICIDX field. - Tl0PicIdxMissing, - /// The payload descriptor does not contain a KEYIDX field. - KeyIdxMissing, - /// The requested KEYIDX does not fit the five-bit KEYIDX field. - KeyIdxTooLarge, -} - -impl fmt::Display for Vp8PatchError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::PictureIdMissing => write!(f, "VP8 payload descriptor has no PictureID"), - Self::PictureIdTooLarge => write!(f, "VP8 PictureID does not fit descriptor width"), - Self::Tl0PicIdxMissing => write!(f, "VP8 payload descriptor has no TL0PICIDX"), - Self::KeyIdxMissing => write!(f, "VP8 payload descriptor has no KEYIDX"), - Self::KeyIdxTooLarge => write!(f, "VP8 KEYIDX must fit in 5 bits"), - } - } -} - -impl Error for Vp8PatchError {} - -/// Builder for fixed-size VP8 payload descriptor patches. -#[derive(Clone, Copy, Debug)] -pub struct Vp8PatchBuilder { - descriptor: Vp8Descriptor, - picture_id: Option, - tl0_pic_idx: Option, - key_idx: Option, -} - -impl Vp8PatchBuilder { - /// Rewrite the VP8 PictureID field. - /// - /// The parsed descriptor decides whether the existing descriptor uses the - /// 7-bit or 15-bit PictureID representation. Rewriting preserves that - /// representation. - /// - /// [`Vp8PatchBuilder::build`] returns [`Vp8PatchError::PictureIdTooLarge`] - /// if the value does not fit the existing representation. - pub fn picture_id(mut self, picture_id: u16) -> Self { - self.picture_id = Some(picture_id); - self - } - - /// Rewrite the VP8 TL0PICIDX field. - /// - /// The rewrite is valid only when the payload descriptor already contains an - /// TL0PICIDX field. - pub fn tl0_pic_idx(mut self, tl0_pic_idx: u8) -> Self { - self.tl0_pic_idx = Some(tl0_pic_idx); - self - } - - /// Rewrite the VP8 KEYIDX field. - /// - /// Only the lower five KEYIDX bits are replaced. The TID and Y bits in the - /// same descriptor octet are preserved. - /// - /// [`Vp8PatchBuilder::build`] returns [`Vp8PatchError::KeyIdxTooLarge`] if - /// the value does not fit the five-bit KEYIDX field. - pub fn key_idx(mut self, key_idx: u8) -> Self { - self.key_idx = Some(key_idx); - self - } - - /// Build a validated fixed-size VP8 descriptor patch. - /// - /// # Errors - /// - /// Returns [`Vp8PatchError::PictureIdMissing`], - /// [`Vp8PatchError::Tl0PicIdxMissing`] or [`Vp8PatchError::KeyIdxMissing`] - /// when the requested rewrite targets a descriptor field that is absent. - /// Returns [`Vp8PatchError::PictureIdTooLarge`] or - /// [`Vp8PatchError::KeyIdxTooLarge`] when a requested rewrite value does - /// not fit the field representation. - pub fn build(self) -> Result { - let mut patch = Vp8Patch::new(); - - if let Some(picture_id) = self.picture_id { - let Some(parsed) = self.descriptor.picture_id else { - return Err(Vp8PatchError::PictureIdMissing); - }; - if picture_id > PICTURE_ID_MAX { - return Err(Vp8PatchError::PictureIdTooLarge); - } - if !parsed.is_15_bit && picture_id > PICTURE_ID_SHORT_MAX { - return Err(Vp8PatchError::PictureIdTooLarge); - } - if parsed.is_15_bit { - patch.push(parsed.offset, 0x80 | ((picture_id >> 8) as u8 & PICTURE_ID_SHORT_MASK)); - patch.push(parsed.offset + 1, picture_id as u8); - } else { - patch.push(parsed.offset, picture_id as u8); - } - } - - if let Some(tl0_pic_idx) = self.tl0_pic_idx { - let Some(parsed) = self.descriptor.tl0_pic_idx else { - return Err(Vp8PatchError::Tl0PicIdxMissing); - }; - patch.push(parsed.offset, tl0_pic_idx); - } - - if let Some(key_idx) = self.key_idx { - let Some(parsed) = self.descriptor.key_idx else { - return Err(Vp8PatchError::KeyIdxMissing); - }; - if key_idx > KEY_IDX_MASK { - return Err(Vp8PatchError::KeyIdxTooLarge); - } - patch.push(parsed.offset, (parsed.value & !KEY_IDX_MASK) | key_idx); - } - - Ok(patch) - } -} - -/// Parsed VP8 RTP payload descriptor. -/// -/// The descriptor stores VP8 fields plus private offsets needed to -/// build a validated [`Vp8Patch`]. It is valid only for the payload bytes parsed -/// by [`Vp8Descriptor::parse`] or a byte-identical copy of those bytes. -#[derive(Clone, Copy, Debug)] -pub struct Vp8Descriptor { - payload_offset: usize, - picture_id: Option, - tl0_pic_idx: Option, - key_idx: Option, -} - -#[derive(Clone, Copy, Debug)] -struct Vp8Field { - value: u8, - offset: usize, -} - -#[derive(Clone, Copy, Debug)] -struct Vp8PictureId { - value: u16, - offset: usize, - is_15_bit: bool, -} - -impl Vp8Descriptor { - /// Parse a VP8 RTP payload descriptor - /// - /// The input must be the RTP payload only. It must not include the RTP - /// header. - /// - /// # Errors - /// - /// Returns [`Vp8DescriptorError::ShortPayload`] when the payload is truncated. - /// Returns [`Vp8DescriptorError::MalformedDescriptor`] when the descriptor - /// has unsupported field combinations. - pub fn parse(payload: &[u8]) -> Result { - let Some(required) = payload.first() else { - return Err(Vp8DescriptorError::ShortPayload); - }; - - let mut descriptor = Self { - payload_offset: 1, - picture_id: None, - tl0_pic_idx: None, - key_idx: None, - }; - - if required & 0x80 != 0 { - let extension = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?; - let has_picture_id = extension & 0x80 != 0; - let has_tl0_pic_idx = extension & 0x40 != 0; - let has_tid = extension & 0x20 != 0; - let has_key_idx = extension & 0x10 != 0; - - if has_tl0_pic_idx && !has_tid { - return Err(Vp8DescriptorError::MalformedDescriptor); - } - - if has_picture_id { - let picture_id_offset = descriptor.payload_offset; - let picture_id = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?; - let is_15_bit = picture_id & 0x80 != 0; - let value = if is_15_bit { - let picture_id_low = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?; - (u16::from(picture_id & PICTURE_ID_SHORT_MASK) << 8) | u16::from(picture_id_low) - } else { - u16::from(picture_id & PICTURE_ID_SHORT_MASK) - }; - descriptor.picture_id = Some(Vp8PictureId { - value, - offset: picture_id_offset, - is_15_bit, - }); - } - - if has_tl0_pic_idx { - let offset = descriptor.payload_offset; - let value = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?; - descriptor.tl0_pic_idx = Some(Vp8Field { value, offset }); - } - - if has_tid || has_key_idx { - let offset = descriptor.payload_offset; - let value = read_vp8_descriptor_byte(payload, &mut descriptor.payload_offset)?; - if has_key_idx { - descriptor.key_idx = Some(Vp8Field { value, offset }); - } - } - } - - if descriptor.payload_offset >= payload.len() { - return Err(Vp8DescriptorError::ShortPayload); - } - - Ok(descriptor) - } - - /// Returns the VP8 PictureID if present - pub const fn picture_id(&self) -> Option { - match self.picture_id { - Some(picture_id) => Some(picture_id.value), - None => None, - } - } - - /// Returns the VP8 TL0PICIDX if present - pub const fn tl0_pic_idx(&self) -> Option { - match self.tl0_pic_idx { - Some(tl0_pic_idx) => Some(tl0_pic_idx.value), - None => None, - } - } - - /// returns the VP8 KEYIDX if present - pub const fn key_idx(&self) -> Option { - match self.key_idx { - Some(key_idx) => Some(key_idx.value & KEY_IDX_MASK), - None => None, - } - } - - /// Returns whether this descriptor starts a VP8 keyframe. - /// - /// `payload` must be the same payload that produced this descriptor or a - /// byte-identical copy. A mismatched or shorter payload returns `false`. - pub fn starts_keyframe(&self, payload: &[u8]) -> bool { - let Some(required) = payload.first() else { - return false; - }; - - if required & 0x10 == 0 || required & 0x07 != 0 { - return false; - } - - payload - .get(self.payload_offset) - .is_some_and(|header| header & 0x01 == 0) - } - - /// Start building a validated fixed-size VP8 descriptor patch. - pub fn patch(&self) -> Vp8PatchBuilder { - Vp8PatchBuilder { - descriptor: *self, - picture_id: None, - tl0_pic_idx: None, - key_idx: None, - } - } -} - -fn read_vp8_descriptor_byte(payload: &[u8], offset: &mut usize) -> Result { - let byte = payload.get(*offset).ok_or(Vp8DescriptorError::ShortPayload)?; - *offset += 1; - Ok(*byte) -} - -/// Vp8 information describing the depacketized / packetized data -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Vp8CodecExtra { - /// True if the frame can be discarded safely, without causing decoding problems - /// No other frames are encoded depending on this frame (non-reference frame) - pub discardable: bool, - /// True if this frame and subsequent ones on this layer depend only on tl0_pic_idx - pub sync: bool, - /// Index of the vp8 temporal layer. - pub layer_index: u8, - /// Extended picture id, if present - pub picture_id: Option, - /// Extended picture id of layer 0 frames, if present - pub tl0_picture_id: Option, - /// Flag which indicates that within [`MediaData`], there is an individual frame - /// containing complete and independent visual information. This frame serves - /// as a reference point for other frames in the video sequence. - /// - /// [`MediaData`]: crate::vendor::str0m::media::MediaData - pub is_keyframe: bool, -} - -/// Detect whether a VP8 RTP payload contains a keyframe. -/// -/// Parses the VP8 RTP payload descriptor (RFC 7741) to skip past the -/// variable-length header, then checks the P bit in the VP8 payload header. -/// P=0 means keyframe, P=1 means interframe. -/// -/// Returns `true` only for the first packet of a keyframe (S=1, PID=0). -pub fn detect_vp8_keyframe(payload: &[u8]) -> bool { - if payload.is_empty() { - return false; - } - let b0 = payload[0]; - let s = (b0 & 0x10) >> 4; // Start of VP8 partition - let pid = b0 & 0x07; // Partition index - // Only the first packet of a frame (S=1, PID=0) contains the payload header - if s != 1 || pid != 0 { - return false; - } - let x = (b0 & 0x80) >> 7; // Extension bit - let mut idx = 1; - if x == 1 { - if idx >= payload.len() { - return false; - } - let ext = payload[idx]; - idx += 1; - let i = (ext & 0x80) >> 7; // PictureID present - let l = (ext & 0x40) >> 6; // TL0PICIDX present - let t = (ext & 0x20) >> 5; // TID present - let k = (ext & 0x10) >> 4; // KEYIDX present - if i == 1 { - if idx >= payload.len() { - return false; - } - if payload[idx] & 0x80 != 0 { - idx += 2; // 16-bit PictureID - } else { - idx += 1; // 7-bit PictureID - } - } - if l == 1 { - idx += 1; // tl0picidx - } - if t == 1 || k == 1 { - idx += 1; // TID/KEYIDX - } - } - if idx >= payload.len() { - return false; - } - // VP8 Payload Header: P bit is bit 0 of the first byte - // P=0 → keyframe, P=1 → interframe - payload[idx] & 0x01 == 0 -} - -/// Packetizes VP8 RTP packets. -/// -/// ## Unversioned API surface -/// -/// This struct is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -#[derive(Default, Debug, Copy, Clone)] -pub struct Vp8Packetizer { - enable_picture_id: bool, - picture_id: u16, -} - -impl Packetizer for Vp8Packetizer { - /// Payload fragments a VP8 packet across one or more byte arrays - fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - if payload.is_empty() || mtu == 0 { - return Ok(vec![]); - } - - /* - * https://tools.ietf.org/html/rfc7741#section-4.2 - * - * 0 1 2 3 4 5 6 7 - * +-+-+-+-+-+-+-+-+ - * |X|R|N|S|R| PID | (REQUIRED) - * +-+-+-+-+-+-+-+-+ - * X: |I|L|T|K| RSV | (OPTIONAL) - * +-+-+-+-+-+-+-+-+ - * I: |M| PictureID | (OPTIONAL) - * +-+-+-+-+-+-+-+-+ - * L: | tl0picidx | (OPTIONAL) - * +-+-+-+-+-+-+-+-+ - * T/K: |tid|Y| KEYIDX | (OPTIONAL) - * +-+-+-+-+-+-+-+-+ - * S: Start of VP8 partition. SHOULD be set to 1 when the first payload - * octet of the RTP packet is the beginning of a new VP8 partition, - * and MUST NOT be 1 otherwise. The S bit MUST be set to 1 for the - * first packet of each encoded frame. - */ - let using_header_size = if self.enable_picture_id { - if self.picture_id == 0 || self.picture_id < 128 { - VP8_HEADER_SIZE + 2 - } else { - VP8_HEADER_SIZE + 3 - } - } else { - VP8_HEADER_SIZE - }; - - let max_fragment_size = mtu as isize - using_header_size as isize; - let mut payload_data_remaining = payload.len() as isize; - let mut payload_data_index: usize = 0; - let mut payloads = vec![]; - - // Make sure the fragment/payload size is correct - if std::cmp::min(max_fragment_size, payload_data_remaining) <= 0 { - return Ok(payloads); - } - - let mut first = true; - while payload_data_remaining > 0 { - let current_fragment_size = std::cmp::min(max_fragment_size, payload_data_remaining) as usize; - let mut out = Vec::with_capacity(using_header_size + current_fragment_size); - let mut buf = [0u8; 4]; - if first { - buf[0] = 0x10; - first = false; - } - - if self.enable_picture_id { - if using_header_size == VP8_HEADER_SIZE + 2 { - buf[0] |= 0x80; - buf[1] |= 0x80; - buf[2] |= (self.picture_id & u16::from(PICTURE_ID_SHORT_MASK)) as u8; - } else if using_header_size == VP8_HEADER_SIZE + 3 { - buf[0] |= 0x80; - buf[1] |= 0x80; - buf[2] |= 0x80 | ((self.picture_id >> 8) & u16::from(PICTURE_ID_SHORT_MASK)) as u8; - buf[3] |= (self.picture_id & 0xFF) as u8; - } - } - - out.extend_from_slice(&buf[..using_header_size]); - - out.extend_from_slice(&payload[payload_data_index..payload_data_index + current_fragment_size]); - payloads.push(out); - - payload_data_remaining -= current_fragment_size as isize; - payload_data_index += current_fragment_size; - } - - self.picture_id += 1; - self.picture_id &= PICTURE_ID_MAX; - - Ok(payloads) - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool { - last - } -} - -/// Depacketizes VP8 RTP packets. -/// -/// ## Unversioned API surface -/// -/// This struct is not currently versioned according to semver rules. -/// Breaking changes may be made in minor or patch releases. -#[derive(PartialEq, Eq, Debug, Default, Clone)] -pub struct Vp8Depacketizer { - /// Required Header - /// extended controlbits present - pub x: u8, - /// when set to 1 this frame can be discarded - pub n: u8, - /// start of VP8 partition - pub s: u8, - /// partition index - pub pid: u8, - - /// Extended control bits - /// 1 if PictureID is present - pub i: u8, - /// 1 if tl0picidx is present - pub l: u8, - /// 1 if tid is present - pub t: u8, - /// 1 if KEYIDX is present - pub k: u8, - - /// Optional extension - /// 8 or 16 bits, picture ID - pub picture_id: u16, - /// extended picture id - pub extended_pid: Option, - - /// 8 bits temporal level zero index - pub tl0_pic_idx: u8, - /// extended version of picture_id of temporal layer 0 - pub extended_tl0_pic_idx: Option, - /// 2 bits temporal layer index - pub tid: u8, - /// 1 bit layer sync bit - pub y: u8, - /// 5 bits temporal key frame index - pub key_idx: u8, - - /// Inverse key frame flag. - /// - /// 0 if the current frame is a key frame. - pub p: u8, -} - -impl Depacketizer for Vp8Depacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - /// depacketize parses the passed byte slice and stores the result in the - /// VP8Packet this method is called upon - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, extra: &mut CodecExtra) -> Result<(), PacketError> { - let payload_len = packet.len(); - // VP8 Payload Descriptor - // https://datatracker.ietf.org/doc/html/rfc7741#section-4.2 - // - // 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 - // +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - // |X|R|N|S|R| PID | (REQUIRED) |X|R|N|S|R| PID | (REQUIRED) - // +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - // X: |I|L|T|K| RSV | (OPTIONAL) X: |I|L|T|K| RSV | (OPTIONAL) - // +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - // I: |M| PictureID | (OPTIONAL) I: |M| PictureID | (OPTIONAL) - // +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - // L: | tl0picidx | (OPTIONAL) | PictureID | - // +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - //T/K:|tid|Y| KEYIDX | (OPTIONAL) L: | tl0picidx | (OPTIONAL) - // +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ - // T/K:|tid|Y| KEYIDX | (OPTIONAL) - // +-+-+-+-+-+-+-+-+ - - let mut reader = (packet, 0); - let mut payload_index = 0; - - let mut b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - - self.x = (b & 0x80) >> 7; - self.n = (b & 0x20) >> 5; - self.s = (b & 0x10) >> 4; - self.pid = b & 0x07; - - let (i, l, t, k) = if self.x == 1 { - b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - let i = (b & 0x80) >> 7; - let l = (b & 0x40) >> 6; - let t = (b & 0x20) >> 5; - let k = (b & 0x10) >> 4; - - if l == 1 && t == 0 { - return Err(PacketError::ErrVP8CorruptedPacket); - } - - (i, l, t, k) - } else { - (0, 0, 0, 0) - }; - self.i = i; - self.l = l; - self.t = t; - self.k = k; - - if self.i == 1 { - b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - let previous_picture_id = u64::from(self.picture_id); - let previous = self.extended_pid.map(|_| previous_picture_id); - // PID present? - let next = if b & 0x80 > 0 { - // M == 1, PID is 16bit - let x = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - self.picture_id = (((b & PICTURE_ID_SHORT_MASK) as u16) << 8) | (x as u16); - payload_index += 1; - extend_u15(previous, self.picture_id) - } else { - self.picture_id = b as u16; - extend_u7(previous, b) - }; - - // "The receiver MUST NOT assume that the number of bits in PictureID stays the - // same through the session" (RFC 7741 section 4.2). Preserve the offset from - // earlier short-ID wraps by extending the raw-ID delta. - self.extended_pid = Some(match self.extended_pid { - Some(previous) => previous.wrapping_add(next.wrapping_sub(previous_picture_id)), - None => next, - }); - } - - if payload_index >= payload_len { - return Err(PacketError::ErrShortPacket); - } - - if self.l == 1 { - self.tl0_pic_idx = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - self.extended_tl0_pic_idx = Some(extend_u8(self.extended_tl0_pic_idx, self.tl0_pic_idx)); - payload_index += 1; - } - - if payload_index >= payload_len { - return Err(PacketError::ErrShortPacket); - } - - if self.t == 1 || self.k == 1 { - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - if self.t == 1 { - self.tid = b >> 6; - self.y = (b >> 5) & 0x1; - } - if self.k == 1 { - self.key_idx = b & KEY_IDX_MASK; - } - payload_index += 1; - } - - if payload_index >= packet.len() { - return Err(PacketError::ErrShortPacket); - } - - out.extend_from_slice(&packet[payload_index..]); - - // VP8 Payload Header - // https://datatracker.ietf.org/doc/html/rfc7741#section-4.3 - // - // 0 1 2 3 4 5 6 7 - // +-+-+-+-+-+-+-+-+ - // |Size0|H| VER |P| - // +-+-+-+-+-+-+-+-+ - // | Size1 | - // +-+-+-+-+-+-+-+-+ - // | Size2 | - // +-+-+-+-+-+-+-+-+ - // | Octets 4..N of| - // | VP8 payload | - // : : - // +-+-+-+-+-+-+-+-+ - // | OPTIONAL RTP | - // | padding | - // : : - // +-+-+-+-+-+-+-+-+ - // - // The header is present only in packets that have the S bit equal - // to one and the PID equal to zero in the payload descriptor - self.p = if self.s == 1 && self.pid == 0 { - b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - b & 1 - } else { - 1 - }; - - let is_keyframe = if let CodecExtra::Vp8(e) = extra { - e.is_keyframe | (self.p == 0) - } else { - self.p == 0 - }; - - *extra = CodecExtra::Vp8(Vp8CodecExtra { - discardable: self.n == 1, - sync: self.y == 1, - layer_index: self.tid, - picture_id: if self.i == 1 { self.extended_pid } else { None }, - tl0_picture_id: if self.l == 1 { self.extended_tl0_pic_idx } else { None }, - is_keyframe, - }); - - let _ = payload_index; - - Ok(()) - } - - /// is_partition_head checks whether if this is a head of the VP8 partition - fn is_partition_head(&self, payload: &[u8]) -> bool { - if payload.is_empty() { - false - } else { - (payload[0] & 0x10) != 0 - } - } - - fn is_partition_tail(&self, marker: bool, _payload: &[u8]) -> bool { - marker - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_vp8_unmarshal() -> Result<(), PacketError> { - let mut pck = Vp8Depacketizer::default(); - let mut extra = CodecExtra::None; - - // Empty packet - let empty_bytes = &[]; - let mut payload = Vec::new(); - let result = pck.depacketize(empty_bytes, &mut payload, &mut extra); - assert!(result.is_err(), "Result should be err in case of error"); - - // Small Payload with single octet header - let small_bytes = &[0x00, 0x11, 0x22]; - let mut payload = Vec::new(); - pck.depacketize(small_bytes, &mut payload, &mut extra) - .expect("Small packet"); - assert_eq!(payload, [0x11, 0x22]); - - // Payload is header only - let small_bytes = &[0x00]; - let mut payload = Vec::new(); - let result = pck.depacketize(small_bytes, &mut payload, &mut extra); - assert!(result.is_err(), "Result should be err in case of error"); - - // Normal packet - let raw_bytes = &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x90]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra) - .expect("Normal packet"); - assert!(!payload.is_empty(), "Payload must be not empty"); - - // Header size, only X - let raw_bytes = &[0x80, 0x00, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra).expect("Only X"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 0, "I must be 0"); - assert_eq!(pck.l, 0, "L must be 0"); - assert_eq!(pck.t, 0, "T must be 0"); - assert_eq!(pck.k, 0, "K must be 0"); - assert_eq!(pck.p, 1, "P must be 1"); - - // Header size, X and I, PID 16bits - let raw_bytes = &[0x80, 0x80, 0x81, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra) - .expect("X and I, PID 16bits"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 1, "I must be 1"); - assert_eq!(pck.l, 0, "L must be 0"); - assert_eq!(pck.t, 0, "T must be 0"); - assert_eq!(pck.k, 0, "K must be 0"); - assert_eq!(pck.p, 1, "P must be 1"); - - // Header size, X and L without T - let raw_bytes = &[0x80, 0x40, 0x00, 0x00]; - let mut payload = Vec::new(); - assert_eq!( - pck.depacketize(raw_bytes, &mut payload, &mut extra), - Err(PacketError::ErrVP8CorruptedPacket) - ); - - let raw_bytes = &[0x00, 0x11, 0x22]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra) - .expect("valid packet after malformed descriptor"); - assert_eq!(payload, [0x11, 0x22]); - - // Header size, X and T - let raw_bytes = &[0x80, 0x20, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra).expect("X and T"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 0, "I must be 0"); - assert_eq!(pck.l, 0, "L must be 0"); - assert_eq!(pck.t, 1, "T must be 1"); - assert_eq!(pck.k, 0, "K must be 0"); - assert_eq!(pck.p, 1, "P must be 1"); - - // Header size, X and K - let raw_bytes = &[0x80, 0x10, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra).expect("X and K"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 0, "I must be 0"); - assert_eq!(pck.l, 0, "L must be 0"); - assert_eq!(pck.t, 0, "T must be 0"); - assert_eq!(pck.k, 1, "K must be 1"); - assert_eq!(pck.p, 1, "P must be 1"); - - // Header size, all flags and 8bit picture_id - let raw_bytes = &[0xff, 0xff, 0x00, 0x00, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra) - .expect("all flags and 8bit picture_id"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 1, "I must be 1"); - assert_eq!(pck.l, 1, "L must be 1"); - assert_eq!(pck.t, 1, "T must be 1"); - assert_eq!(pck.k, 1, "K must be 1"); - assert_eq!(pck.p, 1, "P must be 1"); - - // Header size, all flags and 16bit picture_id - let raw_bytes = &[0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra) - .expect("all flags and 16bit picture_id"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 1, "I must be 1"); - assert_eq!(pck.l, 1, "L must be 1"); - assert_eq!(pck.t, 1, "T must be 1"); - assert_eq!(pck.k, 1, "K must be 1"); - assert_eq!(pck.p, 1, "P must be 1"); - - // Header size, X, I and P - let raw_bytes = &[0x90, 0x80, 0x11, 0x10, 0x00, 0x00, 0x00]; - let mut payload = Vec::new(); - pck.depacketize(raw_bytes, &mut payload, &mut extra) - .expect("all flags and 16bit picture_id"); - assert!(!payload.is_empty(), "Payload must be not empty"); - assert_eq!(pck.x, 1, "X must be 1"); - assert_eq!(pck.i, 1, "I must be 1"); - assert_eq!(pck.l, 0, "L must be 0"); - assert_eq!(pck.t, 0, "T must be 0"); - assert_eq!(pck.k, 0, "K must be 0"); - assert_eq!(pck.p, 0, "P must be 0"); - - Ok(()) - } - - #[test] - fn test_vp8_payload() -> Result<(), PacketError> { - let tests: Vec<(&str, Vp8Packetizer, usize, Vec<&[u8]>, Vec>)> = vec![ - ( - "WithoutPictureID", - Vp8Packetizer::default(), - 2, - vec![&[0x90, 0x90, 0x90], &[0x91, 0x91]], - vec![ - vec![&[0x10, 0x90], &[0x00, 0x90], &[0x00, 0x90]], - vec![&[0x10, 0x91], &[0x00, 0x91]], - ], - ), - ( - "WithPictureID_1byte", - Vp8Packetizer { - enable_picture_id: true, - picture_id: 0x20, - }, - 5, - vec![&[0x90, 0x90, 0x90], &[0x91, 0x91]], - vec![ - vec![&[0x90, 0x80, 0x20, 0x90, 0x90], &[0x80, 0x80, 0x20, 0x90]], - vec![&[0x90, 0x80, 0x21, 0x91, 0x91]], - ], - ), - ( - "WithPictureID_2bytes", - Vp8Packetizer { - enable_picture_id: true, - picture_id: 0x120, - }, - 6, - vec![&[0x90, 0x90, 0x90], &[0x91, 0x91]], - vec![ - vec![&[0x90, 0x80, 0x81, 0x20, 0x90, 0x90], &[0x80, 0x80, 0x81, 0x20, 0x90]], - vec![&[0x90, 0x80, 0x81, 0x21, 0x91, 0x91]], - ], - ), - ]; - - for (name, mut pck, mtu, payloads, expected) in tests { - for (i, payload) in payloads.iter().enumerate() { - let actual = pck.packetize(mtu, payload)?; - assert_eq!(expected[i], actual, "{name}: Generated packet[{i}] differs"); - } - } - - Ok(()) - } - - #[test] - fn test_vp8_payload_eror() -> Result<(), PacketError> { - let mut pck = Vp8Packetizer::default(); - let empty = &[]; - let payload = &[0x90, 0x90, 0x90]; - - // Positive MTU, empty payload - let result = pck.packetize(1, empty)?; - assert!(result.is_empty(), "Generated payload should be empty"); - - // Positive MTU, small payload - let result = pck.packetize(1, payload)?; - assert_eq!(result.len(), 0, "Generated payload should be empty"); - - // Positive MTU, small payload - let result = pck.packetize(2, payload)?; - assert_eq!( - result.len(), - payload.len(), - "Generated payload should be the same size as original payload size" - ); - - Ok(()) - } - - #[test] - fn test_vp8_partition_head_checker_is_partition_head() -> Result<(), PacketError> { - let vp8 = Vp8Depacketizer::default(); - - //"SmallPacket" - assert!( - !vp8.is_partition_head(&[0x00]), - "Small packet should not be the head of a new partition" - ); - - //"SFlagON", - assert!( - vp8.is_partition_head(&[0x10, 0x00, 0x00, 0x00]), - "Packet with S flag should be the head of a new partition" - ); - - //"SFlagOFF" - assert!( - !vp8.is_partition_head(&[0x00, 0x00, 0x00, 0x00]), - "Packet without S flag should not be the head of a new partition" - ); - - Ok(()) - } - - fn rewrite_payload( - payload: &[u8], - patch: impl FnOnce(Vp8PatchBuilder) -> Vp8PatchBuilder, - ) -> Result, Vp8PatchError> { - let descriptor = Vp8Descriptor::parse(payload).expect("valid VP8 descriptor"); - let patch = patch(descriptor.patch()).build()?; - - let mut out = vec![0; payload.len()]; - patch.copy_to(payload, &mut out); - Ok(out) - } - - #[test] - fn test_vp8_descriptor_exposes_fields() { - let short = Vp8Descriptor::parse(&[0x90, 0x80, 0x42, 0x00]).unwrap(); - assert_eq!(short.picture_id(), Some(0x42)); - assert_eq!(short.tl0_pic_idx(), None); - assert_eq!(short.key_idx(), None); - - let full = Vp8Descriptor::parse(&[0x90, 0xf0, 0x92, 0x34, 0x55, 0xa7, 0x00]).unwrap(); - assert_eq!(full.picture_id(), Some(0x1234)); - assert_eq!(full.tl0_pic_idx(), Some(0x55)); - assert_eq!(full.key_idx(), Some(0x07)); - } - - #[test] - fn test_vp8_patch_updates_descriptor_fields() { - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x01, 0x90], |patch| { - patch.picture_id(u16::from(PICTURE_ID_SHORT_MASK)) - }) - .unwrap(), - [0x80, 0x80, PICTURE_ID_SHORT_MASK, 0x90] - ); - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| { patch.picture_id(0x0234) }).unwrap(), - [0x80, 0x80, 0x82, 0x34, 0x90] - ); - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| { - patch.picture_id(PICTURE_ID_MAX) - }) - .unwrap(), - [0x80, 0x80, 0xff, 0xff, 0x90] - ); - assert_eq!( - rewrite_payload(&[0x80, 0x60, 0x12, 0x00, 0x90], |patch| { patch.tl0_pic_idx(0xab) }).unwrap(), - [0x80, 0x60, 0xab, 0x00, 0x90] - ); - assert_eq!( - rewrite_payload(&[0x80, 0x30, 0xaa, 0x90], |patch| { patch.key_idx(KEY_IDX_MASK) }).unwrap(), - [0x80, 0x30, 0xbf, 0x90] - ); - } - - #[test] - fn test_vp8_patch_rejects_unsupported_descriptor_shapes() { - assert_eq!( - Vp8Descriptor::parse(&[0x80, 0x80]).unwrap_err(), - Vp8DescriptorError::ShortPayload - ); - assert_eq!( - rewrite_payload(&[0x00, 0x90], |patch| patch.picture_id(1)).unwrap_err(), - Vp8PatchError::PictureIdMissing - ); - assert_eq!( - rewrite_payload(&[0x00, 0x90], |patch| { patch.picture_id(PICTURE_ID_MAX + 1) }).unwrap_err(), - Vp8PatchError::PictureIdMissing - ); - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| { patch.tl0_pic_idx(1) }).unwrap_err(), - Vp8PatchError::Tl0PicIdxMissing - ); - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| { patch.key_idx(1) }).unwrap_err(), - Vp8PatchError::KeyIdxMissing - ); - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| { - patch.key_idx(KEY_IDX_MASK + 1) - }) - .unwrap_err(), - Vp8PatchError::KeyIdxMissing - ); - assert_eq!( - Vp8Descriptor::parse(&[0x80, 0x40, 0x12, 0x90]).unwrap_err(), - Vp8DescriptorError::MalformedDescriptor - ); - } - - #[test] - fn test_vp8_patch_rejects_impossible_values() { - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x01, 0x90], |patch| { patch.picture_id(0x80) }).unwrap_err(), - Vp8PatchError::PictureIdTooLarge - ); - assert_eq!( - rewrite_payload(&[0x80, 0x80, 0x81, 0x20, 0x90], |patch| { - patch.picture_id(PICTURE_ID_MAX + 1) - }) - .unwrap_err(), - Vp8PatchError::PictureIdTooLarge - ); - assert_eq!( - rewrite_payload(&[0x80, 0x10, 0x00, 0x90], |patch| { patch.key_idx(KEY_IDX_MASK + 1) }).unwrap_err(), - Vp8PatchError::KeyIdxTooLarge - ); - } - - #[test] - fn test_detect_vp8_keyframe() { - // Empty payload - assert!(!detect_vp8_keyframe(&[])); - - // Minimal keyframe: S=1, PID=0, no extensions, P=0 - // Byte 0: X=0, R=0, N=0, S=1, PID=0 → 0x10 - // Byte 1: VP8 payload header with P=0 (keyframe) → 0x00 - assert!(detect_vp8_keyframe(&[0x10, 0x00])); - - // Minimal interframe: S=1, PID=0, no extensions, P=1 - // Byte 1: VP8 payload header with P=1 → 0x01 - assert!(!detect_vp8_keyframe(&[0x10, 0x01])); - - // Not the first packet (S=0) - cannot detect keyframe - assert!(!detect_vp8_keyframe(&[0x00, 0x00])); - - // Continuation packet (PID != 0) - assert!(!detect_vp8_keyframe(&[0x11, 0x00])); - - // With extension (X=1), 7-bit PictureID, keyframe - // Byte 0: X=1, S=1, PID=0 → 0x90 - // Byte 1: I=1, L=0, T=0, K=0 → 0x80 - // Byte 2: 7-bit PictureID (M=0) → 0x42 - // Byte 3: VP8 payload header P=0 → 0x00 - assert!(detect_vp8_keyframe(&[0x90, 0x80, 0x42, 0x00])); - - // With extension, 7-bit PictureID, interframe - assert!(!detect_vp8_keyframe(&[0x90, 0x80, 0x42, 0x01])); - - // With extension, 16-bit PictureID (M=1), keyframe - // Byte 2: M=1 → 0x80 | PID_high - // Byte 3: PID_low - // Byte 4: VP8 payload header P=0 - assert!(detect_vp8_keyframe(&[0x90, 0x80, 0x80, 0x42, 0x00])); - - // With all extensions: I=1(16-bit), L=1, T=1 - // Byte 0: X=1, S=1 → 0x90 - // Byte 1: I=1, L=1, T=1 → 0xE0 - // Byte 2-3: 16-bit PictureID → 0x80, 0x42 - // Byte 4: TL0PICIDX - // Byte 5: TID/KEYIDX - // Byte 6: VP8 payload header P=0 - assert!(detect_vp8_keyframe(&[0x90, 0xE0, 0x80, 0x42, 0x01, 0x00, 0x00])); - - assert!(detect_vp8_keyframe(&[0x90, 0x40, 0x01, 0x00])); - - // Truncated: extension says PictureID but no bytes left - assert!(!detect_vp8_keyframe(&[0x90, 0x80])); - - // Truncated: header consumed all bytes - assert!(!detect_vp8_keyframe(&[0x90, 0x80, 0x42])); - } - - #[test] - fn test_vp8_descriptor_keyframe_detection_matches_helper() { - let payloads: &[&[u8]] = &[ - &[], - &[0x10, 0x00], - &[0x10, 0x01], - &[0x00, 0x00], - &[0x11, 0x00], - &[0x90, 0x80, 0x42, 0x00], - &[0x90, 0x80, 0x42, 0x01], - &[0x90, 0x80], - &[0x90, 0x80, 0x42], - ]; - - for payload in payloads { - let descriptor_starts_keyframe = Vp8Descriptor::parse(payload) - .map(|descriptor| descriptor.starts_keyframe(payload)) - .unwrap_or(false); - assert_eq!(descriptor_starts_keyframe, detect_vp8_keyframe(payload)); - } - } - - #[test] - fn packetize_respects_mtu() -> Result<(), PacketError> { - let payload = vec![0xABu8; 2000]; - for &mtu in &[100usize, 300, 600, 1200] { - let mut pck = Vp8Packetizer::default(); - let pkts = pck.packetize(mtu, &payload)?; - assert!(!pkts.is_empty(), "VP8 produced no packets at mtu {mtu}"); - for (i, pkt) in pkts.iter().enumerate() { - assert!(pkt.len() <= mtu, "VP8 packet {i} size {} > mtu {mtu}", pkt.len()); - } - } - Ok(()) - } - - fn picture_id_of(depack: &mut Vp8Depacketizer, picture_id: &[u8]) -> Option { - // X=1 S=1, I=1, picture id, inter frame - let mut packet = vec![0x90, 0x80]; - packet.extend_from_slice(picture_id); - packet.push(0x01); - let mut payload = Vec::new(); - let mut extra = CodecExtra::None; - depack.depacketize(&packet, &mut payload, &mut extra).unwrap(); - let CodecExtra::Vp8(extra) = extra else { - panic!("expected VP8 codec extra"); - }; - extra.picture_id - } - - /// X=1 S=1, I=1 L=1 T=1, picture id, tl0picidx, TID=0 - fn frame(keyframe: bool, picture_id: &[u8], tl0_pic_idx: u8) -> Vec> { - let mut packet = vec![0x90, 0xE0]; - packet.extend_from_slice(picture_id); - packet.extend_from_slice(&[tl0_pic_idx, 0x00, u8::from(!keyframe)]); - vec![packet] - } - - fn assert_every_frame_emitted(frames: impl IntoIterator>>) { - use crate::vendor::str0m::packet::{CodecDepacketizer, DepacketizingBuffer, RtpMeta}; - use crate::vendor::str0m::rtp_::{MediaTime, RtpHeader}; - use std::time::Instant; - - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp8(Vp8Depacketizer::default()), 3); - let now = Instant::now(); - let mut seq = 0_u64; - - for (frame, packets) in frames.into_iter().enumerate() { - let count = packets.len(); - let time = frame as u64 * 3000; - - for (i, packet) in packets.into_iter().enumerate() { - let meta = RtpMeta { - received: now, - time: MediaTime::from_90khz(time), - seq_no: seq.into(), - last_sender_info: None, - header: RtpHeader { - sequence_number: seq as u16, - timestamp: time as u32, - marker: i == count - 1, - ..Default::default() - }, - }; - buf.push(meta, packet); - seq += 1; - } - - let dep = buf - .pop(now, None) - .unwrap_or_else(|| panic!("frame {frame} was not emitted")) - .unwrap(); - assert!(dep.contiguous, "frame {frame} is not contiguous"); - } - } - - #[test] - fn depacketizer_preserves_picture_id_epoch_when_width_grows() { - let mut depack = Vp8Depacketizer::default(); - for (picture_id, expected) in [(126_u8, 126_u64), (127, 127), (0, 128), (1, 129)] { - assert_eq!(picture_id_of(&mut depack, &[picture_id]), Some(expected)); - } - // The 15-bit PictureID continues incrementing from the 7-bit one. - assert_eq!(picture_id_of(&mut depack, &[0x80, 2]), Some(130)); - } - - #[test] - fn depacketizing_buffer_emits_frames_when_picture_id_width_grows() { - let frames = [ - frame(true, &[126], 10), - frame(false, &[127], 11), - frame(false, &[0], 12), - frame(false, &[1], 13), - frame(false, &[0x80, 2], 14), - frame(false, &[0x80, 3], 15), - ]; - assert_every_frame_emitted(frames); - } - - #[test] - fn depacketizer_preserves_wide_picture_id_after_loss_at_width_growth() { - let mut depack = Vp8Depacketizer::default(); - assert_eq!(picture_id_of(&mut depack, &[0]), Some(0)); - // The sender widens at PictureID 1; pictures 1..99 are lost in transit. - assert_eq!(picture_id_of(&mut depack, &[0x80, 100]), Some(100)); - } - - #[test] - fn depacketizing_buffer_recovers_after_loss_at_picture_id_width_growth() { - // A middlebox drops pictures 1..99 and rewrites RTP sequence numbers. - // Picture 100 is a keyframe, so all following pictures are decodable. - let frames = std::iter::once(frame(true, &[0], 0)) - .chain((100..=130_u8).map(|pid| frame(pid == 100, &[0x80, pid], pid - 99))); - assert_every_frame_emitted(frames); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/packet/vp9.rs b/rs/moq-webrtc/src/vendor/str0m/packet/vp9.rs deleted file mode 100644 index 0bc8f7955c2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/packet/vp9.rs +++ /dev/null @@ -1,1746 +0,0 @@ -use super::{BitRead, CodecExtra, Depacketizer, PacketError, Packetizer}; -use crate::vendor::str0m::rtp_::{extend_u7, extend_u8, extend_u15}; - -use std::fmt; - -/// Max non-flexible VP9 descriptor size reserved for MTU headroom: -/// flags(1) + PID(2) + L(1) + tl0picidx(1) + ≤1 SS byte on keyframe first-packets; 8 is a safe bound. -const VP9_NON_FLEXIBLE_HEADER_SIZE: usize = 8; -/// VP9 RTP payload descriptor size for flexible mode: -/// flags(1) + 15-bit PID(2) = 3 -const VP9_FLEXIBLE_HEADER_SIZE: usize = 3; -const MAX_SPATIAL_LAYERS: usize = 3; -const MAX_VP9REF_PICS: usize = 3; - -/// VP9 packetizer mode controlling the RTP payload descriptor format. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub enum Vp9PacketizerMode { - /// Flexible mode (F=1): minimal 3-byte header (flags + 15-bit PID). - /// Simpler but causes issues with Safari which drops inter-frames. - Flexible, - /// Non-flexible mode (F=0): 5-6 byte header with layer indices and - /// scalability structure. Compatible with all major browsers. - #[default] - NonFlexible, -} - -/// Vp9 information describing the depacketized/packetized data. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct Vp9CodecExtra { - /// Map of the SVC layers. - /// - /// Index of each element corresponds to `spatial layer` index. - /// - /// Each element represents the end (not including) in [`MediaData::data`] - /// for `spatial layer` it belongs. - /// - /// The all `spatial layer`s (up to 3) in [`MediaData::data`] are sorted by - /// `spatial layer` index from lower to greater. So, the beginning of some - /// `spatial layer` is the end (including) of the previous `spatial layer` - /// (for the `spatial layer` with index 0 the beginning is 0). - /// - /// ```text - /// [MediaData::data]: - /// +-----+----------------------+---------------------------+ - /// | SL0 | SL1 | SL2 | - /// +-----+----------------------+---------------------------+ - /// | | | | - /// V V V V - /// 0 layers_scheme[0] layers_scheme[1] layers_scheme[2] - /// ``` - /// - /// **Note:** There is no syncronization between - /// [`Vp9CodecExtra::layers_scheme`] and [`MediaData::data`]! If you need - /// to keep [`Vp9CodecExtra::layers_scheme`] in actual state you have to - /// update the [`Vp9CodecExtra::layers_scheme`] on mutating the - /// [`MediaData::data`]. - /// - /// [`MediaData::data`]: crate::vendor::str0m::media::MediaData::data - /// - /// ## Example - /// - /// Say you have a VP9 track working in "L3T3" scalability mode and you - /// want to retranslate S1T2 layer. So you need to retranslate the all - /// spatial and temporal layers <= target layer. - /// - /// ```ignore - /// # use crate::vendor::str0m::{format::CodecExtra, media::MediaData}; - /// # - /// // We want to receive S1T2 layer. - /// let (target_spatial, target_temporal) = (1u8, 2u8); - /// - /// let media_data: MediaData = todo!(); - /// - /// if let CodecExtra::Vp9(vp9_extra) = media_data.codec_extra { - /// // Try to get current `temporal layer`. If `None` there is no SVC. - /// if let Some(tid) = vp9_extra.tid { - /// if let (true, Some(end_of_target_layer)) = ( - /// // Check whether we need this `temporal layer`. - /// tid <= target_temporal, - /// // Check whether we have information about the right - /// // border of data for the target `spatial layer`. - /// vp9_extra.layers_scheme[target_spatial as usize], - /// ) { - /// // Keep only the bytes for spatial layers up to `target_spatial`. - /// let data = &media_data.data[..end_of_target_layer]; - /// } - /// } - /// } - /// ``` - pub layers_scheme: [Option; MAX_SPATIAL_LAYERS], - - /// Temporal layer id. - pub tid: Option, - - /// Map of the SVC layers widths. - /// - /// Specified for every spatial layer. - pub layers_widths: [Option; MAX_SPATIAL_LAYERS], - - /// Map of the SVC layers heights. - /// - /// Specified for every spatial layer. - pub layers_heights: [Option; MAX_SPATIAL_LAYERS], - - /// Extended picture id of layer 0 frames, if present - pub tl0_picture_id: Option, - - /// Extended picture id, if present - pub picture_id: Option, - - /// Flag which indicates that within [`MediaData`], there is an individual frame - /// containing complete and independent visual information. This frame serves - /// as a reference point for other frames in the video sequence. - /// - /// [`MediaData`]: crate::vendor::str0m::media::MediaData - pub is_keyframe: bool, -} - -/// Detect whether a raw VP9 frame is a keyframe by inspecting the bitstream header. -/// -/// VP9 uncompressed header (profile 0/1): -/// `frame_marker(2) | profile_low(1) | profile_high(1) | show_existing(1) | frame_type(1)` -/// -/// VP9 uncompressed header (profile 2/3): -/// `frame_marker(2) | profile_low(1) | profile_high(1) | reserved(1) | show_existing(1) | frame_type(1)` -/// -/// - `frame_marker` must be `0b10` -/// - `frame_type`: 0 = KEY_FRAME, 1 = NON_KEY_FRAME -/// - `show_existing_frame` = 1 references a previously decoded frame (not a real keyframe) -/// -/// This function works on raw VP9 bitstream data (without RTP descriptor). -pub fn detect_vp9_keyframe_bitstream(payload: &[u8]) -> bool { - if payload.is_empty() { - return false; - } - let b = payload[0]; - // frame_marker must be 0b10 (bits 7-6) - if (b & 0xC0) != 0x80 { - return false; - } - // profile_high_bit is at bit 4 - let profile_high = (b >> 4) & 1; - let (show_existing_frame, frame_type) = if profile_high == 1 { - // Profile 2 or 3: reserved_zero at bit 3, show_existing at bit 2, frame_type at bit 1 - ((b >> 2) & 1, (b >> 1) & 1) - } else { - // Profile 0 or 1: show_existing at bit 3, frame_type at bit 2 - ((b >> 3) & 1, (b >> 2) & 1) - }; - // show_existing_frame references a previously decoded frame, not a real keyframe - if show_existing_frame != 0 { - return false; - } - // frame_type: 0 = KEY_FRAME - frame_type == 0 -} - -/// Detect whether a VP9 RTP payload contains a keyframe by inspecting the P bit. -/// -/// VP9 RTP descriptor byte 0: `I|P|L|F|B|E|V|Z` -/// - P=0: independently decodable frame (keyframe) -/// - P=1: inter-picture predicted frame -/// -/// Works with both flexible (F=1) and non-flexible (F=0) mode packets. -pub fn detect_vp9_keyframe(payload: &[u8]) -> bool { - if payload.is_empty() { - return false; - } - // P bit is bit 6 of byte 0. P=0 means keyframe. - (payload[0] & 0x40) == 0 -} - -/// Packetizes VP9 RTP packets. -/// -/// Supports both non-flexible mode (F=0) and flexible mode (F=1), controlled -/// by [`Vp9PacketizerMode`]. Defaults to non-flexible mode for broad browser -/// compatibility - Safari and older Chrome drop inter-frames with F=1. -#[derive(Default, Clone)] -pub struct Vp9Packetizer { - picture_id: u16, - /// Temporal layer 0 picture index - increments on every frame (since all - /// frames are packetized as TID=0). Used in L byte for non-flexible mode. - tl0picidx: u8, - initialized: bool, - mode: Vp9PacketizerMode, - #[cfg(test)] - initial_picture_id: u16, -} - -impl Vp9Packetizer { - /// Create a VP9 packetizer with the specified mode. - pub fn with_mode(mode: Vp9PacketizerMode) -> Self { - Self { - mode, - ..Default::default() - } - } -} - -impl fmt::Debug for Vp9Packetizer { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Vp9Packetizer") - .field("picture_id", &self.picture_id) - .field("tl0picidx", &self.tl0picidx) - .field("initialized", &self.initialized) - .field("mode", &self.mode) - .finish() - } -} - -impl Packetizer for Vp9Packetizer { - /// Packetize a VP9 frame into one or more RTP packets. - fn packetize(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - if payload.is_empty() || mtu == 0 { - return Ok(vec![]); - } - - if !self.initialized { - #[cfg(test)] - { - self.picture_id = self.initial_picture_id; - } - #[cfg(not(test))] - { - use crate::vendor::str0m_proto::NonCryptographicRng; - self.picture_id = NonCryptographicRng::u16() & 0x7FFF; - } - self.initialized = true; - } - - match self.mode { - Vp9PacketizerMode::NonFlexible => self.packetize_non_flexible(mtu, payload), - Vp9PacketizerMode::Flexible => self.packetize_flexible(mtu, payload), - } - } - - fn is_marker(&mut self, _data: &[u8], _previous: Option<&[u8]>, last: bool) -> bool { - last - } -} - -impl Vp9Packetizer { - /// Non-flexible mode (F=0) packetization. - /// - /// 5-8 byte header with layer indices and scalability structure. - /// Compatible with all major browsers including Safari. - /// - /// ```text - /// 0 1 2 3 4 5 6 7 - /// +-+-+-+-+-+-+-+-+ - /// |I|P|L|F|B|E|V|Z| (REQUIRED) - /// +-+-+-+-+-+-+-+-+ - /// I: |M| PICTURE ID | (RECOMMENDED) - /// +-+-+-+-+-+-+-+-+ - /// M: | EXTENDED PID | (RECOMMENDED) - /// +-+-+-+-+-+-+-+-+ - /// L: | tid |U| SID |D| (CONDITIONALLY RECOMMENDED) - /// +-+-+-+-+-+-+-+-+ - /// | tl0picidx | (CONDITIONALLY REQUIRED) - /// +-+-+-+-+-+-+-+-+ - /// V: | SS | - /// | .. | - /// +-+-+-+-+-+-+-+-+ - /// ``` - fn packetize_non_flexible(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - // Detect keyframe from VP9 bitstream to set P flag correctly. - let is_keyframe = detect_vp9_keyframe_bitstream(payload); - - // tl0picidx increments on every TID=0 frame. Since we always emit TID=0, - // this increments on every frame per draft-ietf-payload-vp9, Section 6.3. - self.tl0picidx = self.tl0picidx.wrapping_add(1); - - // VP9_NON_FLEXIBLE_HEADER_SIZE is the max header (8 bytes, accounting for SS - // on keyframes). This ensures we never exceed MTU even on keyframe first-packets. - let max_fragment_size = mtu as isize - VP9_NON_FLEXIBLE_HEADER_SIZE as isize; - let mut payloads = vec![]; - let mut payload_data_remaining = payload.len(); - let mut payload_data_index = 0; - - if std::cmp::min(max_fragment_size, payload_data_remaining as isize) <= 0 { - return Ok(vec![]); - } - - while payload_data_remaining > 0 { - let current_fragment_size = std::cmp::min(max_fragment_size as usize, payload_data_remaining); - let is_first = payload_data_index == 0; - let is_last = payload_data_remaining == current_fragment_size; - - // Non-keyframe: 5 bytes (flags + 15-bit PID + L + tl0picidx) - // Keyframe first packet: 6 bytes (+ 1 byte SS data, G=0) - let ss_size = if is_keyframe && is_first { 1 } else { 0 }; - let header_size = 5 + ss_size; - let mut out = Vec::with_capacity(header_size + current_fragment_size); - - // Byte 0: I|P|L|F|B|E|V|Z - let mut flags = 0xA0u8; // I=1, L=1 (F=0 implicit) - if !is_keyframe { - flags |= 0x40; // P=1 for inter-predicted frames - } - if is_first { - flags |= 0x08; // B=1 (beginning of frame) - } - if is_last { - flags |= 0x04; // E=1 (end of frame) - } - if is_keyframe && is_first { - flags |= 0x02; // V=1 (scalability structure present) - } - out.push(flags); - - // Bytes 1-2: 15-bit picture ID (M=1) - out.push((self.picture_id >> 8) as u8 | 0x80); - out.push((self.picture_id & 0xFF) as u8); - - // Bytes 3-4: Layer indices (L=1, non-flexible mode) - // TID(3)|U(1)|SID(3)|D(1) = TID=0, U=1, SID=0, D=0 - out.push(0x10); - // tl0picidx (required when F=0 and L=1) - out.push(self.tl0picidx); - - // SS byte on keyframe first packet: N_S=0, Y=0, G=0 (no GOF). A single-layer stream has no - // GOF to advertise; a G=1/R=0 GOF mis-signals references (see commit msg). This matches what - // libwebrtc emits for non-scalable VP9 (g_bit = num_frames_in_gof > 0). RFC 9628 §4.2. - if is_keyframe && is_first { - out.push(0x00); - } - - out.extend_from_slice(&payload[payload_data_index..payload_data_index + current_fragment_size]); - - payloads.push(out); - - payload_data_remaining -= current_fragment_size; - payload_data_index += current_fragment_size; - } - - self.picture_id += 1; - self.picture_id &= 0x7FFF; - - Ok(payloads) - } - - /// Flexible mode (F=1) packetization. - /// - /// Minimal 3-byte header (flags + 15-bit PID). Simpler but may cause - /// issues with Safari which drops inter-frames. - /// - /// ```text - /// 0 1 2 3 4 5 6 7 - /// +-+-+-+-+-+-+-+-+ - /// |I|P|L|F|B|E|V|Z| (REQUIRED) - /// +-+-+-+-+-+-+-+-+ - /// I: |M| PICTURE ID | (RECOMMENDED) - /// +-+-+-+-+-+-+-+-+ - /// M: | EXTENDED PID | (RECOMMENDED) - /// +-+-+-+-+-+-+-+-+ - /// ``` - fn packetize_flexible(&mut self, mtu: usize, payload: &[u8]) -> Result>, PacketError> { - let max_fragment_size = mtu as isize - VP9_FLEXIBLE_HEADER_SIZE as isize; - let mut payloads = vec![]; - let mut payload_data_remaining = payload.len(); - let mut payload_data_index = 0; - - if std::cmp::min(max_fragment_size, payload_data_remaining as isize) <= 0 { - return Ok(vec![]); - } - - while payload_data_remaining > 0 { - let current_fragment_size = std::cmp::min(max_fragment_size as usize, payload_data_remaining); - let is_first = payload_data_index == 0; - let is_last = payload_data_remaining == current_fragment_size; - - let mut out = Vec::with_capacity(VP9_FLEXIBLE_HEADER_SIZE + current_fragment_size); - - // Byte 0: I|P|L|F|B|E|V|Z - I=1, F=1 - let mut flags = 0x90u8; // I=1, F=1 - if is_first { - flags |= 0x08; // B=1 - } - if is_last { - flags |= 0x04; // E=1 - } - out.push(flags); - - // Bytes 1-2: 15-bit picture ID (M=1) - out.push((self.picture_id >> 8) as u8 | 0x80); - out.push((self.picture_id & 0xFF) as u8); - - out.extend_from_slice(&payload[payload_data_index..payload_data_index + current_fragment_size]); - - payloads.push(out); - - payload_data_remaining -= current_fragment_size; - payload_data_index += current_fragment_size; - } - - self.picture_id += 1; - self.picture_id &= 0x7FFF; - - Ok(payloads) - } -} - -/// Depacketizes VP9 RTP packets. -#[derive(PartialEq, Eq, Debug, Default, Clone)] -pub struct Vp9Depacketizer { - /// picture ID is present - pub i: bool, - /// inter-picture predicted frame. - pub p: bool, - /// layer indices present - pub l: bool, - /// flexible mode - pub f: bool, - /// start of frame. beginning of new vp9 frame - pub b: bool, - /// end of frame - pub e: bool, - /// scalability structure (SS) present - pub v: bool, - /// Not a reference frame for upper spatial layers - pub z: bool, - - /// Recommended headers - /// 7 or 15 bits, picture ID. - pub picture_id: u16, - /// extended picture id - pub extended_pid: Option, - - /// Conditionally recommended headers - /// Temporal layer ID - pub tid: u8, - /// Switching up point - pub u: bool, - /// Spatial layer ID - pub sid: u8, - /// Inter-layer dependency used - pub d: bool, - - /// Conditionally required headers - /// Reference index (F=1) - pub pdiff: [u8; MAX_VP9REF_PICS], - /// Temporal layer zero index (F=0) - pub tl0picidx: u8, - /// extended version of tl0picidx - pub extended_tl0picidx: Option, - - /// Scalability structure headers - /// N_S + 1 indicates the number of spatial layers present in the VP9 stream - pub ns: u8, - /// Each spatial layer's frame resolution present - pub y: bool, - /// PG description present flag. - pub g: bool, - /// N_G indicates the number of pictures in a Picture Group (PG) - pub ng: u8, - pub width: [Option; MAX_SPATIAL_LAYERS], - pub height: [Option; MAX_SPATIAL_LAYERS], - /// Temporal layer ID of pictures in a Picture Group - pub pgtid: Vec, - /// Switching up point of pictures in a Picture Group - pub pgu: Vec, - /// Reference indices of pictures in a Picture Group - pub pgpdiff: Vec>, -} - -impl Depacketizer for Vp9Depacketizer { - fn out_size_hint(&self, packets_size: usize) -> Option { - Some(packets_size) - } - - /// depacketize parses the passed byte slice and stores the result - /// in the Vp9Packet this method is called upon - fn depacketize(&mut self, packet: &[u8], out: &mut Vec, extra: &mut CodecExtra) -> Result<(), PacketError> { - if packet.is_empty() { - return Err(PacketError::ErrShortPacket); - } - - let mut reader = (packet, 0); - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - - self.i = (b & 0x80) != 0; - self.p = (b & 0x40) != 0; - self.l = (b & 0x20) != 0; - self.f = (b & 0x10) != 0; - self.b = (b & 0x08) != 0; - self.e = (b & 0x04) != 0; - self.v = (b & 0x02) != 0; - self.z = (b & 0x01) != 0; - - let mut payload_index = 1; - - if self.i { - payload_index = self.parse_picture_id(&mut reader, payload_index)?; - } - - if self.l { - payload_index = self.parse_layer_info(&mut reader, payload_index)?; - } - - if self.f && self.p { - payload_index = self.parse_ref_indices(&mut reader, payload_index)?; - } - - if self.v { - payload_index = self.parse_ssdata(&mut reader, payload_index)?; - } - - self.update_extra(extra, out.len(), packet.len(), payload_index)?; - - out.extend_from_slice(&packet[payload_index..]); - - Ok(()) - } - - /// is_partition_head checks whether if this is a head of the VP9 partition - fn is_partition_head(&self, payload: &[u8]) -> bool { - if payload.is_empty() { - false - } else { - (payload[0] & 0x08) != 0 - } - } - - fn is_partition_tail(&self, marker: bool, _payload: &[u8]) -> bool { - marker - } -} - -impl Vp9Depacketizer { - /// Updates provided [`CodecExtra`]. - /// __MUST__ be called after the all transformations of `payload_index`. - fn update_extra( - &self, - extra: &mut CodecExtra, - out_len: usize, - packet_len: usize, - payload_index: usize, - ) -> Result<(), PacketError> { - let mut vp9_extra = match extra { - CodecExtra::Vp9(e) => *e, - _ => Vp9CodecExtra::default(), - }; - - if self.l { - let new_stop = out_len + packet_len - payload_index; - - if let Some(stop) = vp9_extra.layers_scheme[self.sid as usize] { - if stop != out_len { - return Err(PacketError::ErrVP9CorruptedPacket); - } - } - - vp9_extra.layers_scheme[self.sid as usize] = Some(new_stop); - vp9_extra.tid = Some(self.tid); - - if !self.f { - vp9_extra.tl0_picture_id = self.extended_tl0picidx; - } - } - - // I: "Picture ID (PID) present" (RFC 9628 section 4.2). A packet without it - // keeps the picture id of an earlier packet of the same frame. - if self.i { - vp9_extra.picture_id = self.extended_pid; - } - vp9_extra - .layers_widths - .copy_from_slice(&self.width[..MAX_SPATIAL_LAYERS]); - vp9_extra - .layers_heights - .copy_from_slice(&self.height[..MAX_SPATIAL_LAYERS]); - vp9_extra.is_keyframe |= !self.p && (self.sid == 0 || !self.l) && self.b; - - *extra = CodecExtra::Vp9(vp9_extra); - - Ok(()) - } - - // Picture ID: - // - // +-+-+-+-+-+-+-+-+ - // I: |M| PICTURE ID | M:0 => picture id is 7 bits. - // +-+-+-+-+-+-+-+-+ M:1 => picture id is 15 bits. - // M: | EXTENDED PID | - // +-+-+-+-+-+-+-+-+ - // - fn parse_picture_id(&mut self, reader: &mut dyn BitRead, mut payload_index: usize) -> Result { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - let previous_picture_id = u64::from(self.picture_id); - let previous = self.extended_pid.map(|_| previous_picture_id); - // PID present? - let next = if (b & 0x80) != 0 { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - // M == 1, PID is 15bit - let x = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - self.picture_id = (((b & 0x7f) as u16) << 8) | (x as u16); - payload_index += 1; - extend_u15(previous, self.picture_id) - } else { - self.picture_id = (b & 0x7F) as u16; - extend_u7(previous, b) - }; - - // A wider wire ID is zero-extended after a width change. Preserve the - // offset from earlier short-ID wraps by extending the raw-ID delta. - self.extended_pid = Some(match self.extended_pid { - Some(previous) => previous.wrapping_add(next.wrapping_sub(previous_picture_id)), - None => next, - }); - - Ok(payload_index) - } - - fn parse_layer_info(&mut self, reader: &mut dyn BitRead, mut payload_index: usize) -> Result { - payload_index = self.parse_layer_info_common(reader, payload_index)?; - - if self.f { - Ok(payload_index) - } else { - self.parse_layer_info_non_flexible_mode(reader, payload_index) - } - } - - // Layer indices (flexible mode): - // - // +-+-+-+-+-+-+-+-+ - // L: | T |U| S |D| - // +-+-+-+-+-+-+-+-+ - // - fn parse_layer_info_common( - &mut self, - reader: &mut dyn BitRead, - mut payload_index: usize, - ) -> Result { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - - self.tid = b >> 5; - self.u = b & 0x10 != 0; - self.sid = (b >> 1) & 0x7; - self.d = b & 0x01 != 0; - - if self.sid as usize >= MAX_SPATIAL_LAYERS { - Err(PacketError::ErrTooManySpatialLayers) - } else { - Ok(payload_index) - } - } - - // Layer indices (non-flexible mode): - // - // +-+-+-+-+-+-+-+-+ - // L: | T |U| S |D| - // +-+-+-+-+-+-+-+-+ - // | tl0picidx | - // +-+-+-+-+-+-+-+-+ - // - fn parse_layer_info_non_flexible_mode( - &mut self, - reader: &mut dyn BitRead, - mut payload_index: usize, - ) -> Result { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - self.tl0picidx = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - self.extended_tl0picidx = Some(extend_u8(self.extended_tl0picidx, self.tl0picidx)); - payload_index += 1; - Ok(payload_index) - } - - // Reference indices: - // - // +-+-+-+-+-+-+-+-+ P=1,F=1: At least one reference index - // P,F: | P_DIFF |N| up to 3 times has to be specified. - // +-+-+-+-+-+-+-+-+ N=1: An additional P_DIFF follows - // current P_DIFF. - // - fn parse_ref_indices(&mut self, reader: &mut dyn BitRead, mut payload_index: usize) -> Result { - let mut b = 1u8; - let mut num_ref_pics = 0; - while (b & 0x1) != 0 { - if num_ref_pics == MAX_VP9REF_PICS { - return Err(PacketError::ErrTooManyPDiff); - } - - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - - self.pdiff[num_ref_pics] = b >> 1; - num_ref_pics += 1; - } - - Ok(payload_index) - } - - // Scalability structure (SS): - // - // +-+-+-+-+-+-+-+-+ - // V: | N_S |Y|G|-|-|-| - // +-+-+-+-+-+-+-+-+ -| - // Y: | WIDTH | (OPTIONAL) . - // + + . - // | | (OPTIONAL) . - // +-+-+-+-+-+-+-+-+ . N_S + 1 times - // | HEIGHT | (OPTIONAL) . - // + + . - // | | (OPTIONAL) . - // +-+-+-+-+-+-+-+-+ -| - // G: | N_G | (OPTIONAL) - // +-+-+-+-+-+-+-+-+ -| - // N_G: | T |U| R |-|-| (OPTIONAL) . - // +-+-+-+-+-+-+-+-+ -| . N_G times - // | P_DIFF | (OPTIONAL) . R times . - // +-+-+-+-+-+-+-+-+ -| -| - // - fn parse_ssdata(&mut self, reader: &mut dyn BitRead, mut payload_index: usize) -> Result { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - - self.ns = b >> 5; - self.y = b & 0x10 != 0; - self.g = (b >> 1) & 0x7 != 0; - - let ns = (self.ns + 1) as usize; - self.ng = 0; - - if ns > MAX_SPATIAL_LAYERS { - return Err(PacketError::ErrVP9CorruptedPacket); - } - - if self.y { - if reader.remaining_bits() < 4 * ns { - return Err(PacketError::ErrShortPacket); - } - - for i in 0..ns { - self.width[i] = Some(reader.get_u16().ok_or(PacketError::ErrShortPacket)?); - self.height[i] = Some(reader.get_u16().ok_or(PacketError::ErrShortPacket)?); - } - payload_index += 4 * ns; - } - - if self.g { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - - self.ng = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - } - - for i in 0..self.ng as usize { - if reader.remaining_bits() == 0 { - return Err(PacketError::ErrShortPacket); - } - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - - self.pgtid.push(b >> 5); - self.pgu.push(b & 0x10 != 0); - - let r = ((b >> 2) & 0x3) as usize; - if reader.remaining_bits() < r { - return Err(PacketError::ErrShortPacket); - } - - self.pgpdiff.push(vec![]); - for _ in 0..r { - let b = reader.get_u8().ok_or(PacketError::ErrShortPacket)?; - payload_index += 1; - - self.pgpdiff[i].push(b); - } - } - - Ok(payload_index) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - #[allow(clippy::erasing_op, clippy::identity_op)] - fn test_vp9_packet_unmarshal() -> Result<(), PacketError> { - let tests: Vec<(&str, &[u8], Vp9Depacketizer, &[u8], Option)> = vec![ - ( - "Empty", - &[], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ("NonFlexible", &[0x00, 0xAA], Vp9Depacketizer::default(), &[0xAA], None), - ( - "NonFlexiblePictureID", - &[0x80, 0x02, 0xAA], - Vp9Depacketizer { - i: true, - picture_id: 0x02, - extended_pid: Some(0x02), - ..Default::default() - }, - &[0xAA], - None, - ), - ( - "NonFlexiblePictureIDExt", - &[0x80, 0x81, 0xFF, 0xAA], - Vp9Depacketizer { - i: true, - picture_id: 0x01FF, - extended_pid: Some(0x01FF), - ..Default::default() - }, - &[0xAA], - None, - ), - ( - "NonFlexiblePictureIDExt_ShortPacket0", - &[0x80, 0x81], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "NonFlexiblePictureIDExt_ShortPacket1", - &[0x80], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "NonFlexibleLayerIndicePictureID", - &[0xA0, 0x02, 0x23, 0x01, 0xAA], - Vp9Depacketizer { - i: true, - l: true, - picture_id: 0x02, - extended_pid: Some(0x02), - tid: 0x01, - sid: 0x01, - d: true, - tl0picidx: 0x01, - extended_tl0picidx: Some(0x01), - ..Default::default() - }, - &[0xAA], - None, - ), - ( - "FlexibleLayerIndicePictureID", - &[0xB0, 0x02, 0x23, 0x01, 0xAA], - Vp9Depacketizer { - f: true, - i: true, - l: true, - picture_id: 0x02, - extended_pid: Some(0x02), - tid: 0x01, - sid: 0x01, - d: true, - ..Default::default() - }, - &[0x01, 0xAA], - None, - ), - ( - "NonFlexibleLayerIndicePictureID_ShortPacket0", - &[0xA0, 0x02, 0x23], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "NonFlexibleLayerIndicePictureID_ShortPacket1", - &[0xA0, 0x02], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "FlexiblePictureIDRefIndex", - &[0xD0, 0x02, 0x03, 0x04, 0xAA], - Vp9Depacketizer { - i: true, - p: true, - f: true, - picture_id: 0x02, - extended_pid: Some(0x02), - pdiff: [0x01, 0x02, 0], - ..Default::default() - }, - &[0xAA], - None, - ), - ( - "FlexiblePictureIDRefIndex_TooManyPDiff", - &[0xD0, 0x02, 0x03, 0x05, 0x07, 0x09, 0x10, 0xAA], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrTooManyPDiff), - ), - ( - "FlexiblePictureIDRefIndexNoPayload", - &[0xD0, 0x02, 0x03, 0x04], - Vp9Depacketizer { - i: true, - p: true, - f: true, - picture_id: 0x02, - extended_pid: Some(0x02), - pdiff: [0x01, 0x02, 0], - ..Default::default() - }, - &[], - None, - ), - ( - "FlexiblePictureIDRefIndex_ShortPacket0", - &[0xD0, 0x02, 0x03], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "FlexiblePictureIDRefIndex_ShortPacket1", - &[0xD0, 0x02], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "FlexiblePictureIDRefIndex_ShortPacket2", - &[0xD0], - Vp9Depacketizer::default(), - &[], - Some(PacketError::ErrShortPacket), - ), - ( - "ScalabilityStructureResolutionsNoPayload", - &[ - 0x0A, - (1 << 5) | (1 << 4), // NS:1 Y:1 G:0 - (640 >> 8) as u8, - (640 & 0xff) as u8, - (360 >> 8) as u8, - (360 & 0xff) as u8, - (1280 >> 8) as u8, - (1280 & 0xff) as u8, - (720 >> 8) as u8, - (720 & 0xff) as u8, - ], - Vp9Depacketizer { - b: true, - v: true, - ns: 1, - y: true, - g: false, - ng: 0, - width: { - let mut res = [None; MAX_SPATIAL_LAYERS]; - res[0] = Some(640); - res[1] = Some(1280); - - res - }, - height: { - let mut res = [None; MAX_SPATIAL_LAYERS]; - res[0] = Some(360); - res[1] = Some(720); - - res - }, - ..Default::default() - }, - &[], - None, - ), - ( - "ScalabilityStructureNoPayload", - &[ - 0x0A, - (1 << 5) | (1 << 3), // NS:1 Y:0 G:1 - 2, - (1 << 4), // T:0 U:1 R:0 - - (2 << 5) | (1 << 2), // T:2 U:0 R:1 - - 33, - ], - Vp9Depacketizer { - b: true, - v: true, - ns: 1, - y: false, - g: true, - ng: 2, - pgtid: vec![0, 2], - pgu: vec![true, false], - pgpdiff: vec![vec![], vec![33]], - ..Default::default() - }, - &[], - None, - ), - ( - "ScalabilityStructureNoPictureGroupNoPayload", - &[ - 0x0A, - 1 << 3, // NS:0 Y:0 G:1 - 0, // N_G=0, valid: single temporal layer / no fixed dependency info - ], - Vp9Depacketizer { - b: true, - v: true, - ns: 0, - y: false, - g: true, - ng: 0, - ..Default::default() - }, - &[], - None, - ), - ( - "ScalabilityStructureThreeLayers", - &[ - 0x0A, - (2 << 5) | (1 << 4), // NS:2 Y:1 G:0 - (480 >> 8) as u8, - (480 & 0xff) as u8, - (270 >> 8) as u8, - (270 & 0xff) as u8, - (960 >> 8) as u8, - (960 & 0xff) as u8, - (540 >> 8) as u8, - (540 & 0xff) as u8, - (1920 >> 8) as u8, - (1920 & 0xff) as u8, - (1080 >> 8) as u8, - (1080 & 0xff) as u8, - ], - Vp9Depacketizer { - b: true, - v: true, - ns: 2, - y: true, - g: false, - ng: 0, - width: [Some(480), Some(960), Some(1920)], - height: [Some(270), Some(540), Some(1080)], - ..Default::default() - }, - &[], - None, - ), - ( - "ParseRefIdx", - &[ - 0xD8, /* I:1 P:1 L:0 F:1 - * B:1 E:0 V:0 Z:0 */ - (0x80 | ((17 >> 8) & 0x7F)) as u8, // Two byte pictureID. - 17, // TL0PICIDX - (17 << 1) | 1, // P_DIFF N:1 - (18 << 1) | 1, // P_DIFF N:1 - (127 << 1) | 0, // P_DIFF N:0 - ], - Vp9Depacketizer { - i: true, - p: true, - f: true, - b: true, - picture_id: 17, - extended_pid: Some(17), - pdiff: [17, 18, 127], - ..Default::default() - }, - &[], - None, - ), - ]; - - for (name, b, pkt, expected, err) in tests { - let mut p = Vp9Depacketizer::default(); - - if let Some(expected) = err { - let mut payload = Vec::new(); - let mut extra = CodecExtra::None; - if let Err(actual) = p.depacketize(b, &mut payload, &mut extra) { - assert_eq!(expected, actual, "{name}: expected {expected}, but got {actual}"); - } else { - panic!("{name}: expected error, but got passed"); - } - } else { - let mut payload = Vec::new(); - let mut extra = CodecExtra::None; - p.depacketize(b, &mut payload, &mut extra)?; - assert_eq!(pkt, p, "{name}: expected {pkt:?}, but got {p:?}"); - assert_eq!(payload, expected); - } - } - - Ok(()) - } - - #[test] - fn test_vp9_packetizer_payload() -> Result<(), PacketError> { - let mut rands = vec![]; - for r0 in 8692..8702 { - rands.push(vec![(r0 >> 8) as u8 | 0x80, (r0 & 0xFF) as u8]); - } - - // Non-flexible mode (F=0) header layout: - // Byte 0: I|P|L|F|B|E|V|Z (I=1, L=1 always set) - // Bytes 1-2: 15-bit PID (M=1) - // Byte 3: TID(3)|U(1)|SID(3)|D(1) = 0x10 (TID=0, U=1, SID=0, D=0) - // Byte 4: tl0picidx (wrapping u8, increments every frame) - // [Byte 5]: SS data on keyframe first packet only (N_S=0, Y=0, G=0) - // - // Flags byte (non-keyframe): I=1,P=1,L=1,F=0 = 0xE0 base - // + B=0x08, E=0x04 - // B+E: 0xEC, B only: 0xE8, E only: 0xE4, neither: 0xE0 - // - // Test payloads (0x01, 0x02, etc.) don't match VP9 bitstream keyframe - // pattern (frame_marker != 0b10), so they are treated as inter-frames (P=1). - // tl0picidx starts at 0 and increments by 1 per frame. - let tests: Vec<(&str, Vec>, usize, Vec>)> = vec![ - ("NilPayload", vec![vec![]], 100, vec![]), - ("SmallMTU", vec![vec![0x00, 0x00]], 1, vec![]), - ("NegativeMTU", vec![vec![0x00, 0x00]], 0, vec![]), - ( - // Inter-frame, single packet: B+E set, tl0picidx=1 - "OnePacket", - vec![vec![0x01, 0x02]], - 10, - vec![vec![0xEC, rands[0][0], rands[0][1], 0x10, 0x01, 0x01, 0x02]], - ), - ( - // Inter-frame, 2 packets: MTU=9 → max_frag=1, tl0picidx=1 - "TwoPackets", - vec![vec![0x01, 0x02]], - 9, - vec![ - vec![0xE8, rands[0][0], rands[0][1], 0x10, 0x01, 0x01], - vec![0xE4, rands[0][0], rands[0][1], 0x10, 0x01, 0x02], - ], - ), - ( - // Inter-frame, 3 packets: MTU=9 → max_frag=1, tl0picidx=1 - "ThreePackets", - vec![vec![0x01, 0x02, 0x03]], - 9, - vec![ - vec![0xE8, rands[0][0], rands[0][1], 0x10, 0x01, 0x01], - vec![0xE0, rands[0][0], rands[0][1], 0x10, 0x01, 0x02], - vec![0xE4, rands[0][0], rands[0][1], 0x10, 0x01, 0x03], - ], - ), - ( - // Two inter-frames: frame1 tl0picidx=1, frame2 tl0picidx=2 - "TwoFramesFourPackets", - vec![vec![0x01, 0x02, 0x03], vec![0x04]], - 10, - vec![ - vec![0xE8, rands[0][0], rands[0][1], 0x10, 0x01, 0x01, 0x02], - vec![0xE4, rands[0][0], rands[0][1], 0x10, 0x01, 0x03], - vec![0xEC, rands[1][0], rands[1][1], 0x10, 0x02, 0x04], - ], - ), - ]; - - for (name, bs, mtu, expected) in tests { - let mut pck = Vp9Packetizer { - initial_picture_id: 8692, - ..Default::default() - }; - - let mut actual = vec![]; - for b in &bs { - actual.extend(pck.packetize(mtu, b)?); - } - assert_eq!(expected, actual, "{name}: Payloaded packet"); - } - - //"PictureIDOverflow" - { - let mut pck = Vp9Packetizer { - initial_picture_id: 8692, - ..Default::default() - }; - let mut p_prev = Vp9Depacketizer::default(); - for i in 0..0x8000 { - let res = pck.packetize(9, &[0x01])?; - let mut p = Vp9Depacketizer::default(); - let mut payload = Vec::new(); - let mut extra = CodecExtra::None; - p.depacketize(&res[0], &mut payload, &mut extra)?; - - if i > 0 { - if p_prev.picture_id == 0x7FFF { - assert_eq!( - p.picture_id, 0, - "Picture ID next to 0x7FFF must be 0, got {}", - p.picture_id - ); - } else if p_prev.picture_id + 1 != p.picture_id { - panic!( - "Picture ID next must be incremented by 1: {} -> {}", - p_prev.picture_id, p.picture_id, - ); - } - } - - p_prev = p; - } - } - - Ok(()) - } - - #[test] - fn test_vp9_packetizer_keyframe() -> Result<(), PacketError> { - let mut pck = Vp9Packetizer { - initial_picture_id: 100, - ..Default::default() - }; - - // VP9 profile 0 keyframe bitstream: 0x82 = 0b10_00_0_0_10 - // frame_marker=10, profile=00, show_existing=0, frame_type=0 (KEY) - let keyframe = vec![0x82, 0xAA, 0xBB]; - let packets = pck.packetize(20, &keyframe)?; - - assert_eq!(packets.len(), 1); - let pkt = &packets[0]; - // Flags: I=1,P=0,L=1,F=0,B=1,E=1,V=1,Z=0 = 0xAE - assert_eq!(pkt[0], 0xAE, "Keyframe flags should be 0xAE"); - // PID - assert_eq!(pkt[1], (100 >> 8) as u8 | 0x80); - assert_eq!(pkt[2], 100); - // L byte: TID=0, U=1, SID=0, D=0 - assert_eq!(pkt[3], 0x10); - // tl0picidx = 1 (first frame) - assert_eq!(pkt[4], 1); - // SS: N_S=0, Y=0, G=0 (no GOF) → 0x00 (1 byte) - assert_eq!(pkt[5], 0x00); - // Payload starts right after the 1-byte SS - assert_eq!(&pkt[6..], &keyframe[..]); - - // Parse-side: the emitted SS decodes as a single-layer, no-GOF structure (N_S=0, Y/G false). - let mut dep = Vp9Depacketizer::default(); - let mut out = Vec::new(); - let mut extra = CodecExtra::None; - dep.depacketize(pkt, &mut out, &mut extra)?; - assert!(dep.v && dep.ns == 0 && !dep.y && !dep.g && dep.ng == 0); - assert_eq!(&out[..], &keyframe[..]); - - // Now an inter-frame: 0x84 = 0b10_00_0_1_00 (frame_type=1) - let inter = vec![0x84, 0xCC]; - let packets = pck.packetize(20, &inter)?; - assert_eq!(packets.len(), 1); - let pkt = &packets[0]; - // Flags: I=1,P=1,L=1,F=0,B=1,E=1,V=0,Z=0 = 0xEC - assert_eq!(pkt[0], 0xEC, "Inter-frame flags should be 0xEC"); - // tl0picidx = 2 (second frame, both TID=0 so both increment) - assert_eq!(pkt[4], 2); - // No SS data - payload starts at byte 5 - assert_eq!(&pkt[5..], &inter[..]); - - Ok(()) - } - - #[test] - fn test_vp9_packetizer_fragmented_keyframe() -> Result<(), PacketError> { - let mut pck = Vp9Packetizer { - initial_picture_id: 50, - ..Default::default() - }; - - // VP9 profile 0 keyframe: 0x82 = frame_marker=10, profile=00, show_existing=0, frame_type=0 - // 10 bytes of payload, MTU=12 → max_frag = 12 - 8 = 4 (conservative reserve) - // First packet: 6-byte header (with 1-byte G=0 SS) + 4 bytes payload = 10 ≤ MTU - // Second packet: 5-byte header + 4 bytes payload = 9 ≤ MTU - // Third packet: 5-byte header + 2 bytes payload = 7 ≤ MTU - let keyframe = vec![0x82, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]; - let packets = pck.packetize(12, &keyframe)?; - - assert_eq!(packets.len(), 3, "10-byte keyframe at MTU=12 should produce 3 packets"); - - // Packet 1: B=1, E=0, V=1 (keyframe first) - // Flags: I=1,P=0,L=1,F=0,B=1,E=0,V=1,Z=0 = 0xAA - assert_eq!(packets[0][0], 0xAA); - assert_eq!(packets[0].len(), 10); // 6-byte header + 4-byte payload - assert_eq!(packets[0][3], 0x10); // L byte - assert_eq!(packets[0][4], 1); // tl0picidx - assert_eq!(packets[0][5], 0x00); // SS byte: N_S=0, Y=0, G=0 (no GOF) - assert_eq!(&packets[0][6..], &keyframe[0..4]); // payload - - // Packet 2: B=0, E=0, V=0 (middle) - // Flags: I=1,P=0,L=1,F=0,B=0,E=0,V=0,Z=0 = 0xA0 - assert_eq!(packets[1][0], 0xA0); - assert_eq!(packets[1].len(), 9); // 5-byte header + 4-byte payload - assert_eq!(packets[1][4], 1); // same tl0picidx - assert_eq!(&packets[1][5..], &keyframe[4..8]); - - // Packet 3: B=0, E=1, V=0 (last) - // Flags: I=1,P=0,L=1,F=0,B=0,E=1,V=0,Z=0 = 0xA4 - assert_eq!(packets[2][0], 0xA4); - assert_eq!(packets[2].len(), 7); // 5-byte header + 2-byte payload - assert_eq!(&packets[2][5..], &keyframe[8..10]); - - // Verify none exceed MTU - for (i, pkt) in packets.iter().enumerate() { - assert!(pkt.len() <= 12, "Packet {i} exceeds MTU: {} > 12", pkt.len()); - } - - // Verify depacketizer round-trip: all 3 packets produce original payload - let mut full_payload = Vec::new(); - let mut extra = CodecExtra::None; - for pkt in &packets { - let mut depkt = Vp9Depacketizer::default(); - depkt.depacketize(pkt, &mut full_payload, &mut extra)?; - } - assert_eq!(full_payload, keyframe); - - Ok(()) - } - - #[test] - fn test_vp9_tl0picidx_wrapping() -> Result<(), PacketError> { - let mut pck = Vp9Packetizer { - initial_picture_id: 0, - tl0picidx: 254, // Start near wrap point - ..Default::default() - }; - - // Frame 1: tl0picidx wraps 254 → 255 - let packets = pck.packetize(20, &[0x01])?; - assert_eq!(packets[0][4], 255); - - // Frame 2: tl0picidx wraps 255 → 0 - let packets = pck.packetize(20, &[0x01])?; - assert_eq!(packets[0][4], 0); - - // Frame 3: 0 → 1 - let packets = pck.packetize(20, &[0x01])?; - assert_eq!(packets[0][4], 1); - - Ok(()) - } - - fn depacketize_one(depack: &mut Vp9Depacketizer, packet: &[u8]) -> Vp9CodecExtra { - let mut payload = Vec::new(); - let mut extra = CodecExtra::None; - depack.depacketize(packet, &mut payload, &mut extra).unwrap(); - let CodecExtra::Vp9(extra) = extra else { - panic!("expected VP9 codec extra"); - }; - extra - } - - #[test] - fn depacketizer_extends_picture_id_and_tl0picidx() { - let mut depack = Vp9Depacketizer::default(); - - for (pid, tl0, expected_pid, expected_tl0) in [ - (0x7FFE_u16, 254_u8, 0x7FFE_u64, 254_u64), - (0x7FFF, 255, 0x7FFF, 255), - (0, 0, 0x8000, 256), - (1, 1, 0x8001, 257), - ] { - // I=1 L=1 B=1 E=1, 15-bit picture id, TID=0, tl0picidx - let packet = [0xAC, 0x80 | (pid >> 8) as u8, pid as u8, 0x00, tl0, 0xAA]; - let extra = depacketize_one(&mut depack, &packet); - assert_eq!(extra.picture_id, Some(expected_pid), "pid {pid}"); - assert_eq!(extra.tl0_picture_id, Some(expected_tl0), "tl0 {tl0}"); - } - } - - #[test] - fn depacketizer_extends_7_bit_picture_id() { - let mut depack = Vp9Depacketizer::default(); - - for (pid, expected) in [(126_u8, 126_u64), (127, 127), (0, 128), (1, 129)] { - // I=1 B=1 E=1, 7-bit picture id - let extra = depacketize_one(&mut depack, &[0x8C, pid, 0xAA]); - assert_eq!(extra.picture_id, Some(expected), "pid {pid}"); - } - } - - #[test] - fn depacketizer_reports_missing_picture_id() { - let mut depack = Vp9Depacketizer::default(); - - let extra = depacketize_one(&mut depack, &[0xAC, 0x92, 0x34, 0x00, 7, 0xAA]); - assert_eq!(extra.picture_id, Some(0x1234)); - - // I=0 L=1 B=1 E=1 - let extra = depacketize_one(&mut depack, &[0x2C, 0x00, 8, 0xAA]); - assert_eq!(extra.picture_id, None); - assert_eq!(extra.tl0_picture_id, Some(8)); - - // Picture id on the first packet of the frame only - let mut payload = Vec::new(); - let mut extra = CodecExtra::None; - depack - .depacketize(&[0xA8, 0x92, 0x35, 0x00, 9, 0xAA], &mut payload, &mut extra) - .unwrap(); - depack - .depacketize(&[0x24, 0x00, 9, 0xBB], &mut payload, &mut extra) - .unwrap(); - let CodecExtra::Vp9(extra) = extra else { - panic!("expected VP9 codec extra"); - }; - assert_eq!(extra.picture_id, Some(0x1235)); - } - - fn assert_every_frame_emitted(frames: impl IntoIterator>>) { - use crate::vendor::str0m::packet::{CodecDepacketizer, DepacketizingBuffer, RtpMeta}; - use crate::vendor::str0m::rtp_::{MediaTime, RtpHeader}; - use std::time::Instant; - - let mut buf = DepacketizingBuffer::new(CodecDepacketizer::Vp9(Vp9Depacketizer::default()), 3); - let now = Instant::now(); - let mut seq = 0_u64; - - for (frame, packets) in frames.into_iter().enumerate() { - let count = packets.len(); - let time = frame as u64 * 3000; - - for (i, packet) in packets.into_iter().enumerate() { - let meta = RtpMeta { - received: now, - time: MediaTime::from_90khz(time), - seq_no: seq.into(), - last_sender_info: None, - header: RtpHeader { - sequence_number: seq as u16, - timestamp: time as u32, - marker: i == count - 1, - ..Default::default() - }, - }; - buf.push(meta, packet); - seq += 1; - } - - let dep = buf - .pop(now, None) - .unwrap_or_else(|| panic!("frame {frame} was not emitted")) - .unwrap(); - assert!(dep.contiguous, "frame {frame} is not contiguous"); - } - } - - #[test] - fn depacketizing_buffer_emits_every_frame_across_wraps() { - let mut pck = Vp9Packetizer { - initial_picture_id: 0x7FFF - 100, - tl0picidx: 200, - ..Default::default() - }; - let frames: Vec<_> = (0..300) - .map(|frame| { - let first_byte = if frame == 0 { 0x80 } else { 0x84 }; - pck.packetize(10, &[first_byte, 1, 2, 3]).unwrap() - }) - .collect(); - - assert_every_frame_emitted(frames); - } - - #[test] - fn depacketizing_buffer_emits_every_frame_with_7_bit_picture_id() { - // I=1 L=1 B=1 E=1 (P=1 after the first frame), 7-bit picture id, TID=0, tl0picidx - let frames = (0..600_u64).map(|frame| { - let flags = if frame == 0 { 0xAC } else { 0xEC }; - vec![vec![flags, (frame & 0x7F) as u8, 0x00, frame as u8, 0x84]] - }); - - assert_every_frame_emitted(frames); - } - - #[test] - fn depacketizing_buffer_emits_every_frame_without_picture_id() { - // I=0 L=1 B=1 E=1 (P=1 after the first frame), TID=0, tl0picidx - let frames = (0..300_u64).map(|frame| { - let flags = if frame == 0 { 0x2C } else { 0x6C }; - vec![vec![flags, 0x00, frame as u8, 0x84]] - }); - - assert_every_frame_emitted(frames); - } - - #[test] - fn depacketizer_preserves_picture_id_epoch_when_width_grows() { - let mut depack = Vp9Depacketizer::default(); - for (pid, expected) in [(126_u8, 126_u64), (127, 127), (0, 128), (1, 129)] { - let extra = depacketize_one(&mut depack, &[0x8C, pid, 0xAA]); - assert_eq!(extra.picture_id, Some(expected)); - } - // RFC 9628 section 4.2: transitioning to 15 bits zero-extends the wire ID. - let extra = depacketize_one(&mut depack, &[0x8C, 0x80, 2, 0xAA]); - assert_eq!(extra.picture_id, Some(130)); - } - - #[test] - fn depacketizing_buffer_emits_frames_when_picture_id_width_grows() { - let frames = [ - vec![vec![0xAC, 126, 0, 10, 0x80]], - vec![vec![0xEC, 127, 0, 11, 0x84]], - // A keyframe at the short-ID wrap lets the pre-PR code resynchronize. - vec![vec![0xAC, 0, 0, 12, 0x80]], - vec![vec![0xEC, 1, 0, 13, 0x84]], - // The following picture has wire ID 0x0002 and M=1. - vec![vec![0xEC, 0x80, 2, 0, 14, 0x84]], - vec![vec![0xEC, 0x80, 3, 0, 15, 0x84]], - ]; - assert_every_frame_emitted(frames); - } - - #[test] - fn depacketizer_preserves_wide_picture_id_after_loss_at_width_growth() { - let mut depack = Vp9Depacketizer::default(); - assert_eq!(depacketize_one(&mut depack, &[0x8C, 0, 0xAA]).picture_id, Some(0)); - // The sender widens at PID 1; pictures 1..99 are lost in transit. - let extra = depacketize_one(&mut depack, &[0x8C, 0x80, 100, 0xAA]); - assert_eq!(extra.picture_id, Some(100)); - } - - #[test] - fn depacketizing_buffer_recovers_after_loss_at_picture_id_width_growth() { - // A middlebox drops enhancement pictures 1..99 and rewrites RTP sequence numbers. - // Picture 100 is a keyframe, so all following pictures are decodable. - let frames = std::iter::once(vec![vec![0xAC, 0, 0, 0, 0x80]]).chain((100..=130_u8).map(|pid| { - let (flags, payload) = if pid == 100 { (0xAC, 0x80) } else { (0xEC, 0x84) }; - vec![vec![flags, 0x80, pid, 0, pid - 99, payload]] - })); - assert_every_frame_emitted(frames); - } - - #[test] - fn test_vp9_packetizer_flexible_mode() -> Result<(), PacketError> { - let mut rands = vec![]; - for r0 in 8692..8702 { - rands.push(vec![(r0 >> 8) as u8 | 0x80, (r0 & 0xFF) as u8]); - } - - // With VP9_FLEXIBLE_HEADER_SIZE=3, min productive MTU is 4. - // Flexible mode: 3 bytes header (flags + 15-bit PID) - // - // Flags byte: I|P|L|F|B|E|V|Z - // I=1(0x80), F=1(0x10), B=first(0x08), E=last(0x04) - // B+E: 0x80|0x10|0x08|0x04 = 0x9C - // B: 0x80|0x10|0x08 = 0x98 - // E: 0x80|0x10|0x04 = 0x94 - // none:0x80|0x10 = 0x90 - let tests: Vec<(&str, Vec>, usize, Vec>)> = vec![ - ("NilPayload", vec![vec![]], 100, vec![]), - ("SmallMTU", vec![vec![0x00, 0x00]], 1, vec![]), - ("NegativeMTU", vec![vec![0x00, 0x00]], 0, vec![]), - ( - "OnePacket", - vec![vec![0x01, 0x02]], - 10, - vec![vec![0x9C, rands[0][0], rands[0][1], 0x01, 0x02]], - ), - ( - // MTU=4 → max_frag=1 → 2 packets - "TwoPackets", - vec![vec![0x01, 0x02]], - 4, - vec![ - vec![0x98, rands[0][0], rands[0][1], 0x01], - vec![0x94, rands[0][0], rands[0][1], 0x02], - ], - ), - ( - // MTU=4 → max_frag=1 → 3 packets - "ThreePackets", - vec![vec![0x01, 0x02, 0x03]], - 4, - vec![ - vec![0x98, rands[0][0], rands[0][1], 0x01], - vec![0x90, rands[0][0], rands[0][1], 0x02], - vec![0x94, rands[0][0], rands[0][1], 0x03], - ], - ), - ( - // MTU=5 → max_frag=2 → frame1: 2 pkts, frame2: 1 pkt - "TwoFramesFourPackets", - vec![vec![0x01, 0x02, 0x03], vec![0x04]], - 5, - vec![ - vec![0x98, rands[0][0], rands[0][1], 0x01, 0x02], - vec![0x94, rands[0][0], rands[0][1], 0x03], - vec![0x9C, rands[1][0], rands[1][1], 0x04], - ], - ), - ]; - - for (name, bs, mtu, expected) in tests { - let mut pck = Vp9Packetizer { - initial_picture_id: 8692, - mode: Vp9PacketizerMode::Flexible, - ..Default::default() - }; - - let mut actual = vec![]; - for b in &bs { - actual.extend(pck.packetize(mtu, b)?); - } - assert_eq!(expected, actual, "{name}: Payloaded packet"); - } - - Ok(()) - } - - #[test] - fn test_vp9_packetizer_with_mode() { - let pck = Vp9Packetizer::with_mode(Vp9PacketizerMode::Flexible); - assert_eq!(pck.mode, Vp9PacketizerMode::Flexible); - - let pck = Vp9Packetizer::with_mode(Vp9PacketizerMode::NonFlexible); - assert_eq!(pck.mode, Vp9PacketizerMode::NonFlexible); - - let pck = Vp9Packetizer::default(); - assert_eq!(pck.mode, Vp9PacketizerMode::NonFlexible); - } - - #[test] - fn test_detect_vp9_keyframe_bitstream() { - // Empty payload - assert!(!detect_vp9_keyframe_bitstream(&[])); - - // Invalid frame_marker (not 0b10) - assert!(!detect_vp9_keyframe_bitstream(&[0x00])); // frame_marker=00 - assert!(!detect_vp9_keyframe_bitstream(&[0xC0])); // frame_marker=11 - assert!(!detect_vp9_keyframe_bitstream(&[0x40])); // frame_marker=01 - - // Profile 0 keyframe: 10_00_0_0_xx = 0x80..0x83 - assert!(detect_vp9_keyframe_bitstream(&[0x80])); - assert!(detect_vp9_keyframe_bitstream(&[0x82])); - - // Profile 0 inter-frame: 10_00_0_1_xx = 0x84..0x87 - assert!(!detect_vp9_keyframe_bitstream(&[0x84])); - assert!(!detect_vp9_keyframe_bitstream(&[0x86])); - - // Profile 0 show_existing_frame=1: 10_00_1_x_xx = 0x88..0x8F - assert!(!detect_vp9_keyframe_bitstream(&[0x88])); - assert!(!detect_vp9_keyframe_bitstream(&[0x8C])); - - // Profile 1 keyframe: 10_10_0_0_xx = 0xA0..0xA3 - assert!(detect_vp9_keyframe_bitstream(&[0xA0])); - - // Profile 1 inter-frame: 10_10_0_1_xx = 0xA4..0xA7 - assert!(!detect_vp9_keyframe_bitstream(&[0xA4])); - - // Profile 2 keyframe: 10_01_R_0_0_x - // 0x90 = 10_01_0_0_00 → profile_high=1, show_existing=0, frame_type=0 - assert!(detect_vp9_keyframe_bitstream(&[0x90])); - - // Profile 2 inter-frame: 10_01_0_0_1_0 = 0x92 - assert!(!detect_vp9_keyframe_bitstream(&[0x92])); - } - - #[test] - fn test_vp9_partition_head_checker_is_partition_head() -> Result<(), PacketError> { - let vp9 = Vp9Depacketizer::default(); - - //"SmallPacket" - assert!( - !vp9.is_partition_head(&[]), - "Small packet should not be the head of a new partition" - ); - - //"NormalPacket" - assert!( - vp9.is_partition_head(&[0x18, 0x00, 0x00]), - "VP9 RTP packet with B flag should be head of a new partition" - ); - assert!( - !vp9.is_partition_head(&[0x10, 0x00, 0x00]), - "VP9 RTP packet without B flag should not be head of a new partition" - ); - - Ok(()) - } - - #[test] - fn test_detect_vp9_keyframe() { - // Empty payload - assert!(!detect_vp9_keyframe(&[])); - - // VP9 RTP descriptor byte 0: I|P|L|F|B|E|V|Z - // P=0 (bit 6 clear) → keyframe - // P=1 (bit 6 set) → inter-frame - - // Keyframes (P=0) - assert!(detect_vp9_keyframe(&[0x80])); // I=1 - assert!(detect_vp9_keyframe(&[0xA0])); // I=1, L=1 - assert!(detect_vp9_keyframe(&[0xAE])); // I=1, L=1, B=1, E=1, V=1 - assert!(detect_vp9_keyframe(&[0x00])); // all flags clear - - // Inter-frames (P=1) - assert!(!detect_vp9_keyframe(&[0xE8])); // I=1, P=1, L=1, B=1 - assert!(!detect_vp9_keyframe(&[0xEC])); // I=1, P=1, L=1, B=1, E=1 - assert!(!detect_vp9_keyframe(&[0x40])); // P=1 only - assert!(!detect_vp9_keyframe(&[0xD5])); // I=1, P=1, F=1, E=1, Z=1 - } - - #[test] - fn packetize_respects_mtu() -> Result<(), PacketError> { - // VP9 profile 0 keyframe header followed by payload bytes. - let mut payload = vec![0x82u8]; - payload.extend(std::iter::repeat_n(0xABu8, 2000)); - for &mtu in &[100usize, 300, 600, 1200] { - let mut pck = Vp9Packetizer { - initial_picture_id: 100, - ..Default::default() - }; - let pkts = pck.packetize(mtu, &payload)?; - assert!(!pkts.is_empty(), "VP9 produced no packets at mtu {mtu}"); - for (i, pkt) in pkts.iter().enumerate() { - assert!(pkt.len() <= mtu, "VP9 packet {i} size {} > mtu {mtu}", pkt.len()); - } - } - Ok(()) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/poll.rs b/rs/moq-webrtc/src/vendor/str0m/poll.rs deleted file mode 100644 index 273988e8f9a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/poll.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! Readiness signalling threaded through the component tree. -//! -//! Everything below [`Rtc`][crate::vendor::str0m::Rtc] forms a tree, and both events and new -//! timeouts bubble up from the leaves. To avoid re-walking a quiescent tree on -//! every `poll_output`, each path that takes `&mut` access to a sub-component -//! is handed an armed [`Wake`] guard, threaded down like `&mut` state. -//! -//! A [`Wake`] defaults to re-polling *everything*: left untouched it signals -//! both a pending event drain and a timeout recompute. A component narrows it -//! locally - [`Wake::no_events`] / [`Wake::no_timeout`] - when it knows less -//! changed. The guard folds its (possibly narrowed) signal into the owning -//! [`Readiness`] on drop. -//! -//! The direction is deliberate: the safe default is to re-poll, and narrowing -//! is an opt-in optimization owned by the component that performed the -//! mutation. A forgotten narrowing or an over-broad wake costs at most one redundant -//! poll; it can never drop output. No component names another's scope, and -//! `Rtc` holds no knowledge of which mutation affects what. -//! -//! The app-facing API wrappers ([`DirectApi`][crate::vendor::str0m::change::DirectApi], -//! [`SdpApi`][crate::vendor::str0m::change::SdpApi]) -//! hold an [`RtcMut`] instead of `&mut Rtc`. It arms -//! the readiness on *mutable* deref only, so a `&mut self` method that mutates -//! re-polls the tree while a `&self` reader never does - and neither has to -//! remember to call anything. - -use std::ops::{Deref, DerefMut}; - -use crate::vendor::str0m::Rtc; - -/// A `&mut Rtc` handle that re-polls the tree when it is used mutably. -/// -/// Change detection, à la a dirty-flag on mutable access: `deref` is a plain -/// read and never arms; `deref_mut` arms both halves (the safe default). -/// Because a `&self` method can only reach `deref` and a mutating `&mut self` -/// method reaches `deref_mut`, "mutation re-polls, reads don't" is enforced by -/// the borrow checker - a new method can't forget, and a read-only method -/// can't accidentally arm. -/// -/// Deliberately has no `Drop`: the API wrappers are held in `let` bindings -/// across other `Rtc` use, and a destructor would extend their borrow to the -/// end of scope. Arming therefore happens eagerly on the mutable access. -/// -/// When a mutation only affects one half of the re-poll - and especially when -/// that isn't known until the mutation is underway - take it through -/// [`RtcMut::mutate`] and narrow the returned [`Mutation`] guard. -pub(crate) struct RtcMut<'a> { - rtc: &'a mut Rtc, -} - -impl<'a> RtcMut<'a> { - pub(crate) fn new(rtc: &'a mut Rtc) -> Self { - RtcMut { rtc } - } - - /// Begin a mutation whose re-poll can be narrowed *after the fact*. - /// - /// The returned [`Mutation`] derefs to `Rtc`, so mutate through it, then - /// (optionally, conditionally) call [`Mutation::no_events`] / - /// [`Mutation::no_timeout`]. It folds its own - per-operation, never shared - /// - signal into the readiness when it drops. - /// - /// Plain `&mut *` (via [`DerefMut`]) is the shorthand for "arm both": it's - /// what methods that don't narrow, or that return a `&mut` borrowed from - /// the tree (which can't outlive a guard), use instead. - pub(crate) fn mutate(&mut self) -> Mutation<'_> { - Mutation { - rtc: self.rtc, - events: true, - timeout: true, - } - } -} - -impl Deref for RtcMut<'_> { - type Target = Rtc; - - fn deref(&self) -> &Rtc { - self.rtc - } -} - -impl DerefMut for RtcMut<'_> { - fn deref_mut(&mut self) -> &mut Rtc { - self.rtc.readiness.wake(); - self.rtc - } -} - -/// A single mutation in progress, obtained from [`RtcMut::mutate`]. -/// -/// Derefs to `Rtc` for the actual change. Armed for both halves by default; -/// narrow with [`Mutation::no_events`] / [`Mutation::no_timeout`] at any point -/// before it drops - including conditionally, once the mutation has revealed -/// which half it touched. Folds the (possibly narrowed) signal into the -/// readiness on drop. -/// -/// The signal is private to this one guard, so narrowing here can never -/// interfere with another method call's decision regardless of call order - -/// the property a long-lived shared guard could not offer. -pub(crate) struct Mutation<'a> { - rtc: &'a mut Rtc, - events: bool, - timeout: bool, -} - -impl Mutation<'_> { - /// Assert this mutation queued no event or transmit. - pub(crate) fn no_events(&mut self) { - self.events = false; - } - - /// Assert this mutation moved no timer. - pub(crate) fn no_timeout(&mut self) { - self.timeout = false; - } -} - -impl Deref for Mutation<'_> { - type Target = Rtc; - - fn deref(&self) -> &Rtc { - self.rtc - } -} - -impl DerefMut for Mutation<'_> { - fn deref_mut(&mut self) -> &mut Rtc { - self.rtc - } -} - -impl Drop for Mutation<'_> { - fn drop(&mut self) { - let mut wake = self.rtc.readiness.wake(); - if !self.events { - wake.no_events(); - } - if !self.timeout { - wake.no_timeout(); - } - } -} - -/// The accumulated re-poll signal owned by [`Rtc`][crate::vendor::str0m::Rtc]. -/// -/// `poll_output` reads it to decide whether to walk the event pipeline and -/// whether to recompute the next timeout, clearing each half once it has -/// proven that part of the tree quiescent. -#[derive(Debug)] -pub(crate) struct Readiness { - events: bool, - timeout: bool, -} - -impl Readiness { - /// A fresh instance must poll the whole tree once. - pub(crate) fn armed() -> Self { - Readiness { - events: true, - timeout: true, - } - } - - pub(crate) fn wants_events(&self) -> bool { - self.events - } - - pub(crate) fn wants_timeout(&self) -> bool { - self.timeout - } - - pub(crate) fn clear_events(&mut self) { - self.events = false; - } - - pub(crate) fn clear_timeout(&mut self) { - self.timeout = false; - } - - /// Hand out an armed guard for a mutable descent into the tree. - pub(crate) fn wake(&mut self) -> Wake<'_> { - Wake { - readiness: self, - events: true, - timeout: true, - } - } -} - -/// An armed guard threaded into a component's mutating methods. -/// -/// Narrowed locally by the component and folded into [`Readiness`] on drop. -/// See the [module docs][self]. -/// -/// Dropping it immediately (e.g. `self.rtc.readiness.wake();`) is the -/// conservative default: it re-polls everything. Narrow first to do less. -pub(crate) struct Wake<'a> { - readiness: &'a mut Readiness, - events: bool, - timeout: bool, -} - -impl Wake<'_> { - /// Assert this path queued no event or transmit, so the event pipeline - /// need not be walked on its behalf. - pub(crate) fn no_events(&mut self) { - self.events = false; - } - - /// Assert this path did not move any timer, so the next timeout need not - /// be recomputed on its behalf. - pub(crate) fn no_timeout(&mut self) { - self.timeout = false; - } -} - -impl Drop for Wake<'_> { - fn drop(&mut self) { - self.readiness.events |= self.events; - self.readiness.timeout |= self.timeout; - } -} - -#[cfg(test)] -impl Readiness { - pub(crate) fn idle() -> Self { - Self { - events: false, - timeout: false, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn narrowing_preserves_other_operations() { - for events in [false, true] { - for timeout in [false, true] { - let mut readiness = Readiness { events, timeout }; - { - let mut wake = readiness.wake(); - wake.no_events(); - wake.no_timeout(); - } - assert_eq!(readiness.wants_events(), events); - assert_eq!(readiness.wants_timeout(), timeout); - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/dir.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/dir.rs deleted file mode 100644 index 6aec60b6d8f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/dir.rs +++ /dev/null @@ -1,79 +0,0 @@ -use std::fmt; - -/// Media direction. -/// -/// And also extmap direction. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Direction { - /// Send only direction. - SendOnly, - /// Receive only direction. - RecvOnly, - /// Bi-directional. - SendRecv, - /// Disabled direction. - Inactive, -} - -impl Direction { - /// Change the direction to the opposite. - /// - /// `SendRecv` and `Inactive` are left unchanged. - pub fn invert(&self) -> Self { - match self { - Direction::SendOnly => Direction::RecvOnly, - Direction::RecvOnly => Direction::SendOnly, - _ => *self, - } - } - - /// Whether this direction is a sending direction. - pub fn is_sending(&self) -> bool { - matches!(self, Direction::SendOnly | Direction::SendRecv) - } - - /// Whether this direction is a receiving direction. - pub fn is_receiving(&self) -> bool { - matches!(self, Direction::RecvOnly | Direction::SendRecv) - } - - /// When negotiating SDP, in certain cases, we need to treat `Inactive` - /// as if it is receiving. - pub(crate) fn sdp_is_receiving(&self) -> bool { - // The spec says: - // - // > For streams marked as inactive in the answer, the list of media - // > formats is constructed based on the offer. If the offer was sendonly, - // > the list is constructed as if the answer were recvonly. - // - // https://datatracker.ietf.org/doc/html/rfc3264#section-6.1 - matches!(self, Direction::RecvOnly | Direction::SendRecv | Direction::Inactive) - } -} - -impl From<&str> for Direction { - fn from(v: &str) -> Self { - use Direction::*; - match v { - "sendonly" => SendOnly, - "recvonly" => RecvOnly, - "sendrecv" => SendRecv, - _ => Inactive, - } - } -} - -impl fmt::Display for Direction { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match self { - Direction::SendOnly => "sendonly", - Direction::RecvOnly => "recvonly", - Direction::SendRecv => "sendrecv", - Direction::Inactive => "inactive", - } - ) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/error.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/error.rs deleted file mode 100644 index c57020072d8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/error.rs +++ /dev/null @@ -1,49 +0,0 @@ -use crate::vendor::str0m::crypto::CryptoError; -use std::error::Error; -use std::fmt; -use std::io; - -/// Errors from parsing and decrypting RTP. -#[derive(Debug)] -pub enum RtpError { - /// Error arising in the crypto - CryptoError(CryptoError), - - /// Other io error - Io(io::Error), - - /// Failed to parse RTP header. - ParseHeader, -} - -impl fmt::Display for RtpError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - RtpError::CryptoError(err) => write!(f, "{}", err), - RtpError::Io(err) => write!(f, "{}", err), - RtpError::ParseHeader => write!(f, "Failed to parse RTP header"), - } - } -} - -impl Error for RtpError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - RtpError::CryptoError(err) => Some(err), - RtpError::Io(err) => Some(err), - _ => None, - } - } -} - -impl From for RtpError { - fn from(err: io::Error) -> Self { - RtpError::Io(err) - } -} - -impl From for RtpError { - fn from(err: CryptoError) -> Self { - RtpError::CryptoError(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/ext.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/ext.rs deleted file mode 100644 index 95cbee6d782..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/ext.rs +++ /dev/null @@ -1,1559 +0,0 @@ -use std::any::Any; -use std::any::TypeId; -use std::collections::HashMap; -use std::fmt; -use std::fmt::Debug; -use std::hash::BuildHasherDefault; -use std::hash::Hasher; -use std::panic::UnwindSafe; -use std::str::from_utf8; -use std::sync::Arc; -use std::time::{Duration, Instant, SystemTime}; -use tracing::{debug, trace, warn}; - -use crate::vendor::str0m::util::InstantExt; -use crate::vendor::str0m::util::SystemTimeExt; -use crate::vendor::str0m::util::already_happened; -use crate::vendor::str0m::util::epoch_to_beginning; - -use crate::vendor::str0m::rtp_::Frequency; - -use super::mtime::MediaTime; -use super::{Mid, Rid}; - -/// RTP header extensions. -#[derive(Debug, Clone)] -#[non_exhaustive] -pub enum Extension { - /// - AbsoluteSendTime, - /// - AbsoluteCaptureTime, - /// - AudioLevel, - /// - /// - /// Use when a RTP packet is delayed by a send queue to indicate an offset in the "transmitter". - /// It effectively means we can set a timestamp offset exactly when the UDP packet leaves the - /// server. - TransmissionTimeOffset, - /// - VideoOrientation, - /// - TransportSequenceNumber, - /// - PlayoutDelay, - /// - VideoContentType, - /// - VideoTiming, - /// - /// - /// UTF8 encoded identifier for the RTP stream. Not the same as SSRC, this is is designed to - /// avoid running out of SSRC for very large sessions. - RtpStreamId, - /// - /// - /// UTF8 encoded identifier referencing another RTP stream's RtpStreamId. If we see - /// this extension type, we know the stream is a repair stream. - RepairedRtpStreamId, - /// - RtpMid, - /// - FrameMarking, - /// - ColorSpace, - - /// Not recognized URI, but it could still be user parseable. - UnknownUri(String, Arc), -} - -// All header extensions must have a common "form", either using -// 1 byte for the (ID, len) or 2 bytes for the (ID, len). -// If one extension requires the two byte form -// (probably because of its size, but possibly because of ID), -// The form must be the two-byte variety for all of them. -#[repr(u16)] -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub(crate) enum ExtensionsForm { - // See RFC 8285 Section 4.2 - // ID Range: 1..=14 - // Length Range: 1..=16 - OneByte = 0xBEDE, - // See RFC 8285 Section 4.3 - // ID Range: 1..=255 - // Length Range: 0..=255 - TwoByte = 0x1000, -} - -pub const MAX_ID_ONE_BYTE_FORM: u8 = 14; -// With the two byte form, it could be 255, but supporting larger values makes the ExtensionMap larger. -// So we support only up to this ID for now. -pub const MAX_ID: u8 = 16; - -impl ExtensionsForm { - pub(crate) fn as_u16(self) -> u16 { - self as u16 - } - - pub(crate) fn serialize(self) -> [u8; 2] { - // App bits set to 0 - self.as_u16().to_be_bytes() - } - - pub(crate) fn parse(bytes: [u8; 2]) -> Option { - let serialized = u16::from_be_bytes(bytes); - if serialized == ExtensionsForm::OneByte.as_u16() { - Some(ExtensionsForm::OneByte) - // Ignore the app bits - } else if (serialized & 0xFFF0) == ExtensionsForm::TwoByte.as_u16() { - Some(ExtensionsForm::TwoByte) - } else { - None - } - } -} - -// TODO: think this through. Is it unwind safe? -impl UnwindSafe for Extension {} - -/// Trait for parsing/writing user RTP header extensions. -pub trait ExtensionSerializer: Debug + Send + Sync + 'static { - /// Write the extension to the buffer of bytes. Must return the number - /// of bytes written. This can be 0 if the extension could not be serialized. - fn write_to(&self, buf: &mut [u8], ev: &ExtensionValues) -> usize; - - /// Parse a value and put it in the [`ExtensionValues::user_values`] field. - fn parse_value(&self, buf: &[u8], ev: &mut ExtensionValues) -> bool; - - /// Tell if this extension should be used for video media. - fn is_video(&self) -> bool; - - /// Tell if this extension should be used for audio media. - fn is_audio(&self) -> bool; - - /// When calling write_to, if the size of the written value may exceed 16 bytes, - /// or may be 0 bytes, the two byte header extension form must be used. - /// Otherwise, the one byte form may be used, which is usually the case. - fn requires_two_byte_form(&self, _ev: &ExtensionValues) -> bool { - false - } -} - -impl Extension { - fn requires_two_byte_form(&self, ev: &ExtensionValues) -> bool { - match self { - Extension::UnknownUri(_, serializer) => serializer.requires_two_byte_form(ev), - _ => false, - } - } -} - -/// This is a placeholder value for when the Extension URI are parsed in an SDP OFFER/ANSWER. -/// The trait write_to() and parse_value() should never be called (that would be a bug). -#[derive(Debug)] -struct SdpUnknownUri; - -impl ExtensionSerializer for SdpUnknownUri { - // If an unreachable happens, it's a bug. - fn write_to(&self, _buf: &mut [u8], _ev: &ExtensionValues) -> usize { - unreachable!("Incorrect ExtensionSerializer::write_to") - } - fn parse_value(&self, _buf: &[u8], _ev: &mut ExtensionValues) -> bool { - unreachable!("Incorrect ExtensionSerializer::parse_value") - } - fn is_video(&self) -> bool { - unreachable!("Incorrect ExtensionSerializer::is_video") - } - fn is_audio(&self) -> bool { - unreachable!("Incorrect ExtensionSerializer::is_audio") - } -} - -/// Mapping of extension URI to our enum -const EXT_URI: &[(Extension, &str)] = &[ - ( - Extension::AbsoluteSendTime, - "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time", - ), - ( - Extension::AbsoluteCaptureTime, - "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time", - ), - (Extension::AudioLevel, "urn:ietf:params:rtp-hdrext:ssrc-audio-level"), - (Extension::TransmissionTimeOffset, "urn:ietf:params:rtp-hdrext:toffset"), - ( - Extension::VideoOrientation, // - "urn:3gpp:video-orientation", - ), - ( - Extension::TransportSequenceNumber, - "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01", - ), - ( - Extension::PlayoutDelay, - "http://www.webrtc.org/experiments/rtp-hdrext/playout-delay", - ), - ( - Extension::VideoContentType, - "http://www.webrtc.org/experiments/rtp-hdrext/video-content-type", - ), - ( - Extension::VideoTiming, - "http://www.webrtc.org/experiments/rtp-hdrext/video-timing", - ), - (Extension::RtpStreamId, "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"), - ( - Extension::RepairedRtpStreamId, - "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id", - ), - ( - Extension::RtpMid, // - "urn:ietf:params:rtp-hdrext:sdes:mid", - ), - ( - Extension::FrameMarking, - "http://tools.ietf.org/html/draft-ietf-avtext-framemarking-07", - ), - ( - Extension::ColorSpace, - "http://www.webrtc.org/experiments/rtp-hdrext/color-space", - ), -]; - -impl Extension { - /// Parses an extension from a URI. This only happens for incoming SDP OFFER/ANSWER - /// while the corresponding Extension with a potential ExtensionSerializer is - /// in Rtc::session. - pub(crate) fn from_sdp_uri(uri: &str) -> Self { - for (t, spec) in EXT_URI.iter() { - if *spec == uri { - return t.clone(); - } - } - - Extension::UnknownUri(uri.to_string(), Arc::new(SdpUnknownUri)) - } - - /// Extension for a uri not handled by str0m itself. - pub fn with_serializer(uri: &str, s: impl ExtensionSerializer) -> Self { - Extension::UnknownUri(uri.to_string(), Arc::new(s)) - } - - /// Represents the extension as an URI. - pub fn as_uri(&self) -> &str { - for (t, spec) in EXT_URI.iter() { - if t == self { - return spec; - } - } - - if let Extension::UnknownUri(uri, _) = self { - return uri; - } - - "unknown" - } - - pub(crate) fn is_serialized(&self) -> bool { - if let Self::UnknownUri(_, s) = self { - // Check if this Arc contains the SdpUnknownUri. - let is_sdp = (s as &(dyn Any + 'static)).downcast_ref::().is_some(); - - // If it is the SdpUnknownUri, we are not serializing. If this happens, - // it's probably a bug. The only way to construct SdpUnknownUri is via SDP, - // but those values are only for Eq-comparison vs the values in Session. - // The SdpUnknownUri should not even try to be serialized. - if is_sdp { - panic!("is_serialized on SdpUnkownUri, this is a bug"); - } - } - true - } - - fn is_audio(&self) -> bool { - use Extension::*; - - if let UnknownUri(_, serializer) = self { - return serializer.is_audio(); - } - - matches!( - self, - RtpStreamId - | RepairedRtpStreamId - | RtpMid | AbsoluteSendTime - | AbsoluteCaptureTime - | AudioLevel | TransportSequenceNumber - | TransmissionTimeOffset - | PlayoutDelay - ) - } - - fn is_video(&self) -> bool { - use Extension::*; - - if let UnknownUri(_, serializer) = self { - return serializer.is_video(); - } - - matches!( - self, - RtpStreamId - | RepairedRtpStreamId - | RtpMid | AbsoluteSendTime - | AbsoluteCaptureTime - | VideoOrientation - | TransportSequenceNumber - | TransmissionTimeOffset - | PlayoutDelay - | VideoContentType - | VideoTiming - | FrameMarking - | ColorSpace - ) - } -} - -// As of 2022-09-28, for audio google chrome offers these. -// "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level" -// "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time" -// "a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01" -// "a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid" -// -// For video these. -// "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time" -// "a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01" -// "a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid" -// "a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay" -// "a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type" -// "a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing" -// "a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space" -// "a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id" -// "a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id" -// "a=extmap:13 urn:3gpp:video-orientation" -// "a=extmap:14 urn:ietf:params:rtp-hdrext:toffset" - -/// Mapping between RTP extension id to what extension that is. -#[derive(Clone, PartialEq, Eq)] -pub struct ExtensionMap([Option; MAX_ID as usize]); // index 0 is extmap:1. - -#[derive(Debug, Clone, PartialEq, Eq)] -struct MapEntry { - ext: Extension, - locked: bool, -} - -impl ExtensionMap { - /// Create an empty map. - pub fn empty() -> Self { - ExtensionMap(std::array::from_fn(|_| None)) - } - - /// Creates a map with the "standard" mappings. - /// - /// The standard are taken from Chrome. - pub fn standard() -> Self { - let mut exts = Self::empty(); - - exts.set(1, Extension::AudioLevel); - exts.set(2, Extension::AbsoluteSendTime); - exts.set(3, Extension::TransportSequenceNumber); - exts.set(4, Extension::RtpMid); - // exts.set_mapping(&ExtMap::new(8, Extension::ColorSpace)); - exts.set(10, Extension::RtpStreamId); - exts.set(11, Extension::RepairedRtpStreamId); - exts.set(13, Extension::VideoOrientation); - - exts - } - - pub(crate) fn clear(&mut self) { - for i in &mut self.0 { - *i = None; - } - } - - /// Set a mapping for an extension. - /// - /// The id must be in 1..=MAX_ID (1-indexed). - pub fn set(&mut self, id: u8, ext: Extension) { - if id < 1 || id > MAX_ID { - debug!("Set RTP extension out of range 1-{}: {}", MAX_ID, id); - return; - } - let idx = id as usize - 1; - - let m = MapEntry { ext, locked: false }; - - self.0[idx] = Some(m); - } - - /// Look up the extension for the id. - /// - /// The id must be in 1..=MAX_ID (1-indexed). - pub fn lookup(&self, id: u8) -> Option<&Extension> { - if id >= 1 && id <= MAX_ID { - self.0[id as usize - 1].as_ref().map(|m| &m.ext) - } else { - debug!("Lookup RTP extension out of range 1-{}: {}", MAX_ID, id); - None - } - } - - /// Finds the id for an extension (if mapped). - /// - /// The returned id will be 1-based. - pub fn id_of(&self, e: Extension) -> Option { - self.0 - .iter() - .position(|x| x.as_ref().map(|e| &e.ext) == Some(&e)) - .map(|p| p as u8 + 1) - } - - /// Returns an iterator over the elements of the extension map - pub fn iter(&self) -> impl Iterator + '_ { - self.0 - .iter() - .enumerate() - .filter_map(|(i, e)| e.as_ref().map(|e| (i, e))) - .map(|(i, e)| ((i + 1) as u8, &e.ext)) - } - - /// Returns an iterator over the audio or video elements of the extension map - pub fn iter_by_media_type(&self, audio: bool) -> impl Iterator + '_ { - self.iter() - .filter(move |(_id, ext)| if audio { ext.is_audio() } else { ext.is_video() }) - } - - /// Returns an iterator over the audio elements of the extension map - #[allow(unused)] - pub fn iter_audio(&self) -> impl Iterator + '_ { - self.iter_by_media_type(true) - } - - /// Returns an iterator over the video elements of the extension map - #[allow(unused)] - pub fn iter_video(&self) -> impl Iterator + '_ { - self.iter_by_media_type(false) - } - - pub(crate) fn cloned_with_type(&self, audio: bool) -> Self { - let mut x = ExtensionMap::empty(); - for (id, ext) in self.iter_by_media_type(audio) { - x.set(id, ext.clone()); - } - x - } - - // https://tools.ietf.org/html/rfc5285 - pub(crate) fn parse(&self, mut buf: &[u8], form: ExtensionsForm, ext_vals: &mut ExtensionValues) { - loop { - if buf.is_empty() { - return; - } - - if buf[0] == 0 { - // padding - buf = &buf[1..]; - continue; - } - - let (id, len) = match form { - ExtensionsForm::OneByte => { - let id = buf[0] >> 4; - let len = (buf[0] & 0xf) as usize + 1; - buf = &buf[1..]; - - if id == 15 { - // If the ID value 15 is - // encountered, its length field should be ignored, processing of the - // entire extension should terminate at that point, and only the - // extension elements present prior to the element with ID 15 - // considered. - return; - } - (id, len) - } - ExtensionsForm::TwoByte => { - if buf.len() < 2 { - trace!("Not enough ext header len: {} < {}", buf.len(), 2); - return; - } - let id = buf[0]; - let len = buf[1] as usize; - buf = &buf[2..]; - (id, len) - } - }; - - if buf.len() < len { - trace!("Not enough type ext len: {} < {}", buf.len(), len); - return; - } - - let ext_buf = &buf[..len]; - if let Some(ext) = self.lookup(id) { - ext.parse_value(ext_buf, ext_vals); - } - - buf = &buf[len..]; - } - } - - pub(crate) fn form(&self, ev: &ExtensionValues) -> ExtensionsForm { - if self - .iter() - .any(|(id, ext)| id > MAX_ID_ONE_BYTE_FORM || ext.requires_two_byte_form(ev)) - { - ExtensionsForm::TwoByte - } else { - ExtensionsForm::OneByte - } - } - - pub(crate) fn write_to(&self, ext_buf: &mut [u8], ev: &ExtensionValues, form: ExtensionsForm) -> usize { - let orig_len = ext_buf.len(); - let mut b = ext_buf; - - for (idx, x) in self.0.iter().enumerate() { - if let Some(v) = x { - match form { - ExtensionsForm::OneByte => { - if let Some(n) = v.ext.write_to(&mut b[1..], ev) { - assert!(n <= 16); - assert!(n > 0); - b[0] = (idx as u8 + 1) << 4 | (n as u8 - 1); - b = &mut b[1 + n..]; - } - } - ExtensionsForm::TwoByte => { - if let Some(n) = v.ext.write_to(&mut b[2..], ev) { - b[0] = (idx + 1) as u8; - b[1] = n as u8; - b = &mut b[2 + n..]; - } - } - }; - } - } - - orig_len - b.len() - } - - pub(crate) fn remap(&mut self, remote_exts: &[(u8, &Extension)]) { - // Match remote numbers and lock down those we see for the first time. - for (id, ext) in remote_exts { - self.swap(*id, ext); - } - } - - fn swap(&mut self, id: u8, ext: &Extension) { - if id < 1 || id > MAX_ID { - return; - } - - // Mapping goes from 0 to 13. - let new_index = id as usize - 1; - - let Some(old_index) = self - .0 - .iter() - .enumerate() - .find(|(_, m)| m.as_ref().map(|m| &m.ext) == Some(ext)) - .map(|(i, _)| i) - else { - return; - }; - - // Unwrap OK because index is checking just above. - let old = self.0[old_index].as_mut().unwrap(); - - let is_change = new_index != old_index; - - // If either audio or video is locked, we got a previous extmap negotiation. - if is_change && old.locked { - warn!( - "Extmap locked by previous negotiation. Ignore change: {} -> {}", - old_index, new_index - ); - return; - } - - // Locking must be done regardless of whether there was an actual change. - old.locked = true; - - if !is_change { - return; - } - - self.0.swap(old_index, new_index); - } -} - -impl Extension { - pub(crate) fn write_to(&self, buf: &mut [u8], ev: &ExtensionValues) -> Option { - use Extension::*; - match self { - AbsoluteSendTime => { - // 24 bit fixed point 6 bits for seconds, 18 for the decimals. - // wraps around at 64 seconds. - - // We assume the Instant is absolute. - let time_abs = ev.abs_send_time?; - - // This should be a 64 second offset from unix epoch. - let dur = time_abs.to_unix_duration(); - - // Rebase to the 6.18 format. - let time_24 = MediaTime::from(dur).rebase(Frequency::FIXED_POINT_6_18).numer() as u32; - - buf[..3].copy_from_slice(&time_24.to_be_bytes()[1..]); - Some(3) - } - AbsoluteCaptureTime => { - let act = ev.abs_capture_time.as_ref()?; - let ntp_64 = act.capture_time.as_ntp_64(); - - if let Some(offset) = act.clock_offset { - if buf.len() < 16 { - return None; - } - buf[..8].copy_from_slice(&ntp_64.to_be_bytes()); - buf[8..16].copy_from_slice(&offset.to_be_bytes()); - Some(16) - } else { - if buf.len() < 8 { - return None; - } - buf[..8].copy_from_slice(&ntp_64.to_be_bytes()); - Some(8) - } - } - AudioLevel => { - let v1 = ev.audio_level?; - let v2 = ev.voice_activity?; - // `v1` is negative, so masking it before negating leaves the - // sign bit in place: for -37 the expression `-(0x7f & v1)` - // yields 0xA5, which already has bit 7 set. Taking the - // magnitude first keeps the sign out of the V bit. - buf[0] = if v2 { 0x80 } else { 0 } | (v1.unsigned_abs() & 0x7f); - Some(1) - } - TransmissionTimeOffset => { - let v = ev.tx_time_offs?; - buf[..4].copy_from_slice(&v.to_be_bytes()); - Some(4) - } - VideoOrientation => { - let v = ev.video_orientation?; - buf[0] = v as u8; - Some(1) - } - TransportSequenceNumber => { - let v = ev.transport_cc?; - buf[..2].copy_from_slice(&v.to_be_bytes()); - Some(2) - } - PlayoutDelay => { - let v1 = ev.play_delay_min?.rebase(Frequency::HUNDREDTHS); - let v2 = ev.play_delay_max?.rebase(Frequency::HUNDREDTHS); - let min = (v1.numer() & 0xfff) as u32; - let max = (v2.numer() & 0xfff) as u32; - buf[0] = (min >> 4) as u8; - buf[1] = (min << 4) as u8 | (max >> 8) as u8; - buf[2] = max as u8; - Some(3) - } - VideoContentType => { - let v = ev.video_content_type?; - buf[0] = v; - Some(1) - } - VideoTiming => { - let v = ev.video_timing?; - buf[0] = v.flags; - buf[1..3].copy_from_slice(&v.encode_start.to_be_bytes()); - buf[3..5].copy_from_slice(&v.encode_finish.to_be_bytes()); - buf[5..7].copy_from_slice(&v.packetize_complete.to_be_bytes()); - buf[7..9].copy_from_slice(&v.last_left_pacer.to_be_bytes()); - // Reserved for network - buf[9..11].copy_from_slice(&0_u16.to_be_bytes()); - buf[11..13].copy_from_slice(&0_u16.to_be_bytes()); - Some(13) - } - RtpStreamId => { - let v = ev.rid?; - let l = v.len(); - buf[..l].copy_from_slice(v.as_bytes()); - Some(l) - } - RepairedRtpStreamId => { - let v = ev.rid_repair?; - let l = v.len(); - buf[..l].copy_from_slice(v.as_bytes()); - Some(l) - } - RtpMid => { - let v = ev.mid?; - let l = v.len(); - buf[..l].copy_from_slice(v.as_bytes()); - Some(l) - } - FrameMarking => { - let v = ev.frame_mark?; - buf[..4].copy_from_slice(&v.to_be_bytes()); - Some(4) - } - ColorSpace => { - // TODO HDR color space - None - } - UnknownUri(_, serializer) => { - let n = serializer.write_to(buf, ev); - - if n == 0 { None } else { Some(n) } - } - } - } - - pub(crate) fn parse_value(&self, buf: &[u8], ev: &mut ExtensionValues) -> Option<()> { - use Extension::*; - match self { - // 3 - AbsoluteSendTime => { - // 24 bit fixed point 6 bits for seconds, 18 for the decimals. - // wraps around at 64 seconds. - if buf.len() < 3 { - return None; - } - let time_24 = u32::from_be_bytes([0, buf[0], buf[1], buf[2]]); - - // Rebase to micros - let time_micros = MediaTime::from_fixed_point_6_18(time_24 as u64) - .rebase(Frequency::MICROS) - .numer(); - - // This should be the duration in 0-64 seconds from a fixed 64 second offset - // from UNIX EPOCH. For now, we must save this as offset from _something else_ and - // fix the correct value when we have the exact Instant::now() to relate it to. - let time_dur = Duration::from_micros(time_micros); - - let time_tmp = already_happened() + time_dur; - ev.abs_send_time = Some(time_tmp); - } - // 8 or 16 - AbsoluteCaptureTime => { - if buf.len() < 8 { - return None; - } - let ntp_64 = u64::from_be_bytes(buf[..8].try_into().unwrap()); - let clock_offset = (buf.len() >= 16).then(|| i64::from_be_bytes(buf[8..16].try_into().unwrap())); - ev.abs_capture_time = Some(AbsCaptureTime { - capture_time: SystemTime::from_ntp_64(ntp_64), - clock_offset, - }); - } - // 1 - AudioLevel => { - if buf.is_empty() { - return None; - } - ev.audio_level = Some(-(0x7f & buf[0] as i8)); - ev.voice_activity = Some(buf[0] & 0x80 > 0); - } - // 3 - TransmissionTimeOffset => { - if buf.len() < 4 { - return None; - } - ev.tx_time_offs = Some(u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]])); - } - // 1 - VideoOrientation => { - if buf.is_empty() { - return None; - } - ev.video_orientation = Some(super::ext::VideoOrientation::from(buf[0] & 3)); - } - // 2 - TransportSequenceNumber => { - if buf.len() < 2 { - return None; - } - ev.transport_cc = Some(u16::from_be_bytes([buf[0], buf[1]])); - } - // 3 - PlayoutDelay => { - if buf.len() < 3 { - return None; - } - let min = (buf[0] as u32) << 4 | (buf[1] as u32) >> 4; - let max = ((buf[1] & 0xf) as u32) << 8 | buf[2] as u32; - ev.play_delay_min = Some(MediaTime::from_hundredths(min as u64)); - ev.play_delay_max = Some(MediaTime::from_hundredths(max as u64)); - } - // 1 - VideoContentType => { - if buf.is_empty() { - return None; - } - ev.video_content_type = Some(buf[0]); - } - // 13 - VideoTiming => { - if buf.len() < 9 { - return None; - } - ev.video_timing = Some(self::VideoTiming { - flags: buf[0], - encode_start: u16::from_be_bytes([buf[1], buf[2]]), - encode_finish: u16::from_be_bytes([buf[3], buf[4]]), - packetize_complete: u16::from_be_bytes([buf[5], buf[6]]), - last_left_pacer: u16::from_be_bytes([buf[7], buf[8]]), - // 9 - 10 // reserved for network - // 11 - 12 // reserved for network - }); - } - RtpStreamId => { - let s = from_utf8(buf).ok()?; - ev.rid = Some(s.into()); - } - RepairedRtpStreamId => { - let s = from_utf8(buf).ok()?; - ev.rid_repair = Some(s.into()); - } - RtpMid => { - let s = from_utf8(buf).ok()?; - ev.mid = Some(s.into()); - } - FrameMarking => { - if buf.len() < 4 { - return None; - } - ev.frame_mark = Some(u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]])); - } - ColorSpace => { - // TODO HDR color space - } - UnknownUri(_, serializer) => { - let success = serializer.parse_value(buf, ev); - if !success { - return None; - } - } - } - - Some(()) - } -} - -/// Values in an RTP header extension. -/// -/// This is metadata that is available also without decrypting the SRTP packets. -#[derive(Clone, Default, PartialEq, Eq)] -pub struct ExtensionValues { - /// Audio level is measured in negative decibel. 0 is max and a "normal" value might be -30. - pub audio_level: Option, - - /// Indication that there is sound from a voice. - pub voice_activity: Option, - - /// Tell a receiver what rotation a video need to replay correctly. - pub video_orientation: Option, - - // The values below are considered internal until we have a reason to expose them. - // Generally we want to avoid expose experimental features unless there are strong - // reasons to do so. - pub video_content_type: Option, // 0 = unspecified, 1 = screenshare - pub tx_time_offs: Option, - pub abs_send_time: Option, - pub abs_capture_time: Option, - pub transport_cc: Option, // (buf[0] << 8) | buf[1]; - // https://webrtc.googlesource.com/src/+/refs/heads/master/docs/native-code/rtp-hdrext/playout-delay - pub play_delay_min: Option, - pub play_delay_max: Option, - pub video_timing: Option, - pub rid: Option, - pub rid_repair: Option, - pub mid: Option, - pub frame_mark: Option, - - /// User values for [`ExtensionSerializer`] to parse into and write from. - pub user_values: UserExtensionValues, -} -impl ExtensionValues { - pub(crate) fn update_absolute_send_time(&mut self, now: Instant) { - let Some(v) = self.abs_send_time else { - return; - }; - - // This should be 0-64 seconds, or we are not working with a newly parsed value. - let relative_64_secs = v - already_happened(); - assert!(relative_64_secs <= Duration::from_secs(64)); - - let now_since_epoch = now.to_unix_duration(); - - let closest_64 = - now_since_epoch.saturating_sub(Duration::from_micros(now_since_epoch.as_micros() as u64 % 64_000_000)); - - let since_beginning = closest_64.saturating_sub(epoch_to_beginning()); - - let mut offset = already_happened() + since_beginning; - - if offset + relative_64_secs > now { - offset = offset.checked_sub(Duration::from_secs(64)).unwrap_or(offset); - } - - self.abs_send_time = Some(offset + relative_64_secs); - } -} - -/// Space for storing user extension values via [`ExtensionSerializer`]. -#[derive(Clone, Default)] -pub struct UserExtensionValues { - map: Option, -} - -// The "AnyMap" idea is borrowed from the http crate but replacing Box for Any. -type AnyMap = HashMap, BuildHasherDefault>; - -// No point in hashing the TypeId, since it is already unique. -#[derive(Default)] -struct IdHasher(u64); - -impl Hasher for IdHasher { - fn write(&mut self, _: &[u8]) { - unreachable!("TypeId calls write_u64"); - } - - #[inline] - fn write_u64(&mut self, id: u64) { - self.0 = id; - } - - #[inline] - fn finish(&self) -> u64 { - self.0 - } -} - -// TODO: I don't see a good way of comparing this. Is there one? -impl PartialEq for UserExtensionValues { - fn eq(&self, other: &Self) -> bool { - let (Some(m1), Some(m2)) = (&self.map, &other.map) else { - return self.map.is_none() == other.map.is_none(); - }; - - for k1 in m1.keys() { - if !m2.contains_key(k1) { - return false; - } - } - - for k2 in m2.keys() { - if !m1.contains_key(k2) { - return false; - } - } - - true - } -} - -impl Eq for UserExtensionValues {} - -impl UserExtensionValues { - /// Set a user extension value. - /// - /// This uses the type of the value as "key", i.e. it can only hold a single - /// per type. The user should make a wrapper type for the extension they want - /// to parse/write. - /// - /// ```ignore - /// # use crate::vendor::str0m::rtp::ExtensionValues; - /// let mut exts = ExtensionValues::default(); - /// - /// #[derive(Debug, PartialEq, Eq)] - /// struct MySpecialType(u8); - /// - /// exts.user_values.set(MySpecialType(42)); - /// ``` - pub fn set(&mut self, val: T) { - // TODO: Consider simplifying to "self.set_arc(Arc::new(val))"; - self.map - .get_or_insert_with(HashMap::default) - .insert(TypeId::of::(), Arc::new(val)); - } - - /// Get a user extension value (by type). - /// ```ignore - /// # use crate::vendor::str0m::rtp::ExtensionValues; - /// let mut exts = ExtensionValues::default(); - /// - /// #[derive(Debug, PartialEq, Eq)] - /// struct MySpecialType(u8); - /// - /// exts.user_values.set(MySpecialType(42)); - /// - /// let v = exts.user_values.get::(); - /// - /// assert_eq!(v, Some(&MySpecialType(42))); - /// ``` - pub fn get(&self) -> Option<&T> { - self.map - .as_ref() - .and_then(|map| map.get(&TypeId::of::())) - // unwrap here is OK because TypeId::of:: is guaranteed to be unique - .map(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref().unwrap()) - } - - /// Like .set(), but takes an Arc, which can be nice to avoid cloning - /// large extension values. - pub fn set_arc(&mut self, val: Arc) { - self.map - .get_or_insert_with(HashMap::default) - .insert(TypeId::of::(), val); - } - - /// Like .get(), but clones and returns the Arc, which can be nice to - /// avoid cloning large extension values. - pub fn get_arc(&self) -> Option> { - self.map.as_ref()?.get(&TypeId::of::())?.clone().downcast().ok() - } - - /// Remove a user extension value (by type). - pub fn remove(&mut self) { - if let Some(map) = &mut self.map { - map.remove(&TypeId::of::()); - } - } -} - -impl UnwindSafe for UserExtensionValues {} - -impl fmt::Debug for ExtensionValues { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "ExtensionValues {{")?; - - if let Some(t) = self.mid { - write!(f, " mid: {t}")?; - } - if let Some(t) = self.rid { - write!(f, " rid: {t}")?; - } - if let Some(t) = self.rid_repair { - write!(f, " rid_repair: {t}")?; - } - if let Some(t) = self.abs_send_time { - write!(f, " abs_send_time: {:?}", t)?; - } - if let Some(t) = &self.abs_capture_time { - write!(f, " abs_capture_time: {:?}", t)?; - } - if let Some(t) = self.voice_activity { - write!(f, " voice_activity: {t}")?; - } - if let Some(t) = self.audio_level { - write!(f, " audio_level: {t}")?; - } - if let Some(t) = self.tx_time_offs { - write!(f, " tx_time_offs: {t}")?; - } - if let Some(t) = self.video_orientation { - write!(f, " video_orientation: {t:?}")?; - } - if let Some(t) = self.transport_cc { - write!(f, " transport_cc: {t}")?; - } - if let Some(t) = self.play_delay_min { - write!(f, " play_delay_min: {}", t.as_seconds())?; - } - if let Some(t) = self.play_delay_max { - write!(f, " play_delay_max: {}", t.as_seconds())?; - } - if let Some(t) = self.video_content_type { - write!(f, " video_content_type: {t}")?; - } - if let Some(t) = &self.video_timing { - write!(f, " video_timing: {t:?}")?; - } - if let Some(t) = &self.frame_mark { - write!(f, " frame_mark: {t}")?; - } - - write!(f, " }}")?; - Ok(()) - } -} - -/// Absolute capture time from the `abs-capture-time` RTP header extension. -/// -/// Contains the NTP wall-clock timestamp of original frame capture, and -/// optionally the sender's estimate of the offset between its own clock -/// and the capture system's clock. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct AbsCaptureTime { - /// NTP wall-clock timestamp of original frame capture. - pub capture_time: SystemTime, - /// Sender's estimate of offset between its own NTP clock and the - /// capture system's NTP clock. Signed NTP fixed-point (Q32.32): - /// upper 32 bits whole seconds, lower 32 bits fractional. - pub clock_offset: Option, -} - -/// 2^32 as f64, for NTP Q32.32 fixed-point conversion. -const NTP_F32: f64 = 4_294_967_296.0; - -impl AbsCaptureTime { - /// Clock offset in seconds, if present. - /// - /// Per the spec: `Capture NTP Clock = Sender NTP Clock + offset`. - pub fn clock_offset_secs(&self) -> Option { - self.clock_offset.map(|v| v as f64 / NTP_F32) - } - - /// Set the clock offset in seconds. - pub fn set_clock_offset(&mut self, secs: f64) { - self.clock_offset = Some((secs * NTP_F32) as i64); - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct VideoTiming { - // 0x01 = extension is set due to timer. - // 0x02 - extension is set because the frame is larger than usual. - pub flags: u8, - pub encode_start: u16, - pub encode_finish: u16, - pub packetize_complete: u16, - pub last_left_pacer: u16, -} - -impl fmt::Display for Extension { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use Extension::*; - write!( - f, - "{}", - match self { - AbsoluteSendTime => "abs-send-time", - AbsoluteCaptureTime => "abs-capture-time", - AudioLevel => "ssrc-audio-level", - TransmissionTimeOffset => "toffset", - VideoOrientation => "video-orientation", - TransportSequenceNumber => "transport-wide-cc", - PlayoutDelay => "playout-delay", - VideoContentType => "video-content-type", - VideoTiming => "video-timing", - RtpStreamId => "rtp-stream-id", - RepairedRtpStreamId => "repaired-rtp-stream-id", - RtpMid => "mid", - FrameMarking => "frame-marking07", - ColorSpace => "color-space", - UnknownUri(uri, _) => uri, - } - ) - } -} - -impl fmt::Debug for ExtensionMap { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Extensions(")?; - let joined = self - .0 - .iter() - .enumerate() - .filter_map(|(i, v)| v.as_ref().map(|v| (i + 1, v))) - .map(|(i, v)| format!("{}={}", i, v.ext)) - .collect::>() - .join(", "); - write!(f, "{joined}")?; - write!(f, ")")?; - Ok(()) - } -} - -/// How the video is rotated. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VideoOrientation { - /// Not rotated. - Deg0 = 0, - /// 90 degress clockwise. - Deg90 = 3, - /// Upside down. - Deg180 = 2, - /// 90 degrees counter clockwise. - Deg270 = 1, -} - -impl From for VideoOrientation { - fn from(value: u8) -> Self { - match value { - 1 => Self::Deg270, - 2 => Self::Deg180, - 3 => Self::Deg90, - _ => Self::Deg0, - } - } -} - -impl PartialEq for Extension { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Extension::AbsoluteSendTime, Extension::AbsoluteSendTime) => true, - (Extension::AbsoluteCaptureTime, Extension::AbsoluteCaptureTime) => true, - (Extension::AudioLevel, Extension::AudioLevel) => true, - (Extension::TransmissionTimeOffset, Extension::TransmissionTimeOffset) => true, - (Extension::VideoOrientation, Extension::VideoOrientation) => true, - (Extension::TransportSequenceNumber, Extension::TransportSequenceNumber) => true, - (Extension::PlayoutDelay, Extension::PlayoutDelay) => true, - (Extension::VideoContentType, Extension::VideoContentType) => true, - (Extension::VideoTiming, Extension::VideoTiming) => true, - (Extension::RtpStreamId, Extension::RtpStreamId) => true, - (Extension::RepairedRtpStreamId, Extension::RepairedRtpStreamId) => true, - (Extension::RtpMid, Extension::RtpMid) => true, - (Extension::FrameMarking, Extension::FrameMarking) => true, - (Extension::ColorSpace, Extension::ColorSpace) => true, - (Extension::UnknownUri(uri1, _), Extension::UnknownUri(uri2, _)) => uri1 == uri2, - _ => false, - } - } -} - -impl Eq for Extension {} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn abs_send_time() { - let now = Instant::now() + Duration::from_secs(1000); - - let mut exts = ExtensionMap::empty(); - exts.set(4, Extension::AbsoluteSendTime); - let ev = ExtensionValues { - abs_send_time: Some(now), - ..Default::default() - }; - - let mut buf = vec![0_u8; 8]; - exts.write_to(&mut buf[..], &ev, ExtensionsForm::OneByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::OneByte, &mut ev2); - - // Let's pretend a 50 millisecond network latency. - ev2.update_absolute_send_time(now + Duration::from_millis(50)); - - let now2 = ev2.abs_send_time.unwrap(); - - let abs = if now > now2 { now - now2 } else { now2 - now }; - - assert!(abs < Duration::from_millis(1)); - } - - #[test] - fn abs_send_time_two_byte_form() { - let now = Instant::now() + Duration::from_secs(1000); - - let mut exts = ExtensionMap::empty(); - exts.set(16, Extension::AbsoluteSendTime); - let ev = ExtensionValues { - abs_send_time: Some(now), - ..Default::default() - }; - - let mut buf = vec![0_u8; 8]; - assert_eq!(ExtensionsForm::TwoByte, exts.form(&ev)); - exts.write_to(&mut buf[..], &ev, ExtensionsForm::TwoByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::TwoByte, &mut ev2); - - // Let's pretend a 50 millisecond network latency. - ev2.update_absolute_send_time(now + Duration::from_millis(50)); - - let now2 = ev2.abs_send_time.unwrap(); - - let abs = if now > now2 { now - now2 } else { now2 - now }; - - assert!(abs < Duration::from_millis(1)); - } - - #[test] - fn abs_capture_time_short_form() { - let now = SystemTime::now(); - - let mut exts = ExtensionMap::empty(); - exts.set(5, Extension::AbsoluteCaptureTime); - let ev = ExtensionValues { - abs_capture_time: Some(AbsCaptureTime { - capture_time: now, - clock_offset: None, - }), - ..Default::default() - }; - - let mut buf = vec![0_u8; 16]; - exts.write_to(&mut buf[..], &ev, ExtensionsForm::OneByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::OneByte, &mut ev2); - - let act = ev2.abs_capture_time.unwrap(); - - // Allow for small rounding errors in NTP conversion - let abs = if now > act.capture_time { - now.duration_since(act.capture_time) - } else { - act.capture_time.duration_since(now) - } - .unwrap(); - - assert!(abs < Duration::from_millis(1)); - assert_eq!(act.clock_offset, None); - } - - #[test] - fn abs_capture_time_extended_form() { - let now = SystemTime::now(); - let clock_offset: i64 = 123456789; - - let mut exts = ExtensionMap::empty(); - exts.set(5, Extension::AbsoluteCaptureTime); - let ev = ExtensionValues { - abs_capture_time: Some(AbsCaptureTime { - capture_time: now, - clock_offset: Some(clock_offset), - }), - ..Default::default() - }; - - let mut buf = vec![0_u8; 24]; - exts.write_to(&mut buf[..], &ev, ExtensionsForm::OneByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::OneByte, &mut ev2); - - let act = ev2.abs_capture_time.unwrap(); - - // Allow for small rounding errors in NTP conversion - let abs = if now > act.capture_time { - now.duration_since(act.capture_time) - } else { - act.capture_time.duration_since(now) - } - .unwrap(); - - assert!(abs < Duration::from_millis(1)); - assert_eq!(act.clock_offset, Some(clock_offset)); - } - - #[test] - fn abs_capture_time_two_byte_form() { - let now = SystemTime::now(); - let clock_offset: i64 = -987654321; - - let mut exts = ExtensionMap::empty(); - exts.set(16, Extension::AbsoluteCaptureTime); - let ev = ExtensionValues { - abs_capture_time: Some(AbsCaptureTime { - capture_time: now, - clock_offset: Some(clock_offset), - }), - ..Default::default() - }; - - // Should require two-byte form due to extension ID > 14 - assert_eq!(ExtensionsForm::TwoByte, exts.form(&ev)); - - let mut buf = vec![0_u8; 24]; - exts.write_to(&mut buf[..], &ev, ExtensionsForm::TwoByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::TwoByte, &mut ev2); - - let act = ev2.abs_capture_time.unwrap(); - - // Allow for small rounding errors in NTP conversion - let abs = if now > act.capture_time { - now.duration_since(act.capture_time) - } else { - act.capture_time.duration_since(now) - } - .unwrap(); - - assert!(abs < Duration::from_millis(1)); - assert_eq!(act.clock_offset, Some(clock_offset)); - } - - #[test] - fn playout_delay() { - let mut exts = ExtensionMap::empty(); - exts.set(2, Extension::PlayoutDelay); - let ev = ExtensionValues { - play_delay_min: Some(MediaTime::from_hundredths(100)), - play_delay_max: Some(MediaTime::from_hundredths(200)), - ..Default::default() - }; - - let mut buf = vec![0_u8; 8]; - exts.write_to(&mut buf[..], &ev, ExtensionsForm::OneByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::OneByte, &mut ev2); - - assert_eq!(ev.play_delay_min, ev2.play_delay_min); - assert_eq!(ev.play_delay_max, ev2.play_delay_max); - } - - #[test] - fn remap_exts_audio() { - use Extension::*; - - let mut e1 = ExtensionMap::standard(); - let mut e2 = ExtensionMap::empty(); - e2.set(14, TransportSequenceNumber); - - println!("{:?}", e1.iter_video().collect::>()); - - e1.remap(&e2.iter_audio().collect::>()); - - // e1 should have adjusted the TransportSequenceNumber for audio - assert_eq!( - e1.iter_audio().collect::>(), - vec![ - (1, &AudioLevel), - (2, &AbsoluteSendTime), - (4, &RtpMid), - (10, &RtpStreamId), - (11, &RepairedRtpStreamId), - (14, &TransportSequenceNumber) - ] - ); - - // e1 should have adjusted the TransportSequenceNumber for vudeo - assert_eq!( - e1.iter_video().collect::>(), - vec![ - (2, &AbsoluteSendTime), - (4, &RtpMid), - (10, &RtpStreamId), - (11, &RepairedRtpStreamId), - (13, &VideoOrientation), - (14, &TransportSequenceNumber), - ] - ); - } - - #[test] - fn remap_exts_video() { - use Extension::*; - - let mut e1 = ExtensionMap::empty(); - e1.set(3, TransportSequenceNumber); - e1.set(4, VideoOrientation); - e1.set(5, VideoContentType); - let mut e2 = ExtensionMap::empty(); - e2.set(14, TransportSequenceNumber); - e2.set(12, VideoOrientation); - - e1.remap(&e2.iter_video().collect::>()); - - // e1 should have adjusted to e2. - assert_eq!( - e1.iter_video().collect::>(), - vec![ - (5, &VideoContentType), - (12, &VideoOrientation), - (14, &TransportSequenceNumber) - ] - ); - } - - #[test] - fn remap_exts_swaparoo() { - use Extension::*; - - let mut e1 = ExtensionMap::empty(); - e1.set(12, TransportSequenceNumber); - e1.set(14, VideoOrientation); - let mut e2 = ExtensionMap::empty(); - e2.set(14, TransportSequenceNumber); - e2.set(12, VideoOrientation); - - e1.remap(&e2.iter_video().collect::>()); - - // just make sure the logic isn't wrong for 12-14 -> 14-12 - assert_eq!( - e1.iter_video().collect::>(), - vec![(12, &VideoOrientation), (14, &TransportSequenceNumber)] - ); - } - - #[test] - fn remap_exts_illegal() { - use Extension::*; - - let mut e1 = ExtensionMap::empty(); - e1.set(12, TransportSequenceNumber); - e1.set(14, VideoOrientation); - - let mut e2 = ExtensionMap::empty(); - e2.set(14, TransportSequenceNumber); - e2.set(12, VideoOrientation); - - let mut e3 = ExtensionMap::empty(); - // Illegal change of already negotiated/locked number - e3.set(1, TransportSequenceNumber); - e3.set(12, AudioLevel); // change of type for existing. - - // First apply e2 - e1.remap(&e2.iter_video().collect::>()); - - println!("{:#?}", e1.0); - assert_eq!( - e1.iter_video().collect::>(), - vec![(12, &VideoOrientation), (14, &TransportSequenceNumber)] - ); - - // Now attempt e3 - e1.remap(&e3.iter_audio().collect::>()); - - println!("{:#?}", e1.0); - // At this point we should have not allowed the change, but remain as it was in first apply. - assert_eq!( - e1.iter_video().collect::>(), - vec![(12, &VideoOrientation), (14, &TransportSequenceNumber)] - ); - } - - #[test] - fn audio_level_round_trip() { - // The V bit (voice activity) must survive serialization for every - // level on the scale, not just when it is set. - let mut exts = ExtensionMap::empty(); - exts.set(1, Extension::AudioLevel); - - for level in -127..=0 { - for voice_activity in [false, true] { - let ev = ExtensionValues { - audio_level: Some(level), - voice_activity: Some(voice_activity), - ..Default::default() - }; - - let mut buf = vec![0_u8; 8]; - exts.write_to(&mut buf[..], &ev, ExtensionsForm::OneByte); - - let mut ev2 = ExtensionValues::default(); - exts.parse(&buf, ExtensionsForm::OneByte, &mut ev2); - - assert_eq!(ev2.audio_level, Some(level)); - assert_eq!(ev2.voice_activity, Some(voice_activity)); - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/header.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/header.rs deleted file mode 100644 index fa917f11d1c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/header.rs +++ /dev/null @@ -1,823 +0,0 @@ -#![allow(clippy::unusual_byte_groupings)] - -use super::ext::{ExtensionMap, ExtensionValues, ExtensionsForm}; -use super::{Pt, SeqNo, Ssrc}; -use tracing::{trace, warn}; - -/// Parsed header from an RTP packet. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RtpHeader { - /// Always 2 - pub version: u8, - /// Whether the RTP packet has padding to be an equal of 4 bytes. - pub has_padding: bool, - /// RTP packet has "RTP header extensions". - pub has_extension: bool, - /// Number of contributing source identifiers. - pub csrc_count: usize, - /// For video, this marker signifies the end of a series of packets that - /// together form a single video frame. - /// For audio, it marks the beginning of a talkspurt, which is a burst of - /// audio packets. - pub marker: bool, - /// Type of payload being carried. What this correlates to is sent in the SDP. - pub payload_type: Pt, - /// Sequence number increasing by 1 for each RTP packet. - pub sequence_number: u16, - /// Timestamp in media time for the RTP packet. What the media time base is depends - /// on the codec. - pub timestamp: u32, - /// Sender source identifier. - pub ssrc: Ssrc, - /// Contributing source identifiers (CSRC). Up to 15 values per RFC 3550. - pub csrc: [u32; 15], - /// The extension values parsed using the mapping via SDP. - pub ext_vals: ExtensionValues, - /// Length of header. - pub header_len: usize, -} - -impl RtpHeader { - pub(crate) fn write_to(&self, buf: &mut [u8], exts: &ExtensionMap) -> usize { - assert!(self.csrc_count <= 15, "CSRC count must be <= 15"); - buf[0] = 0b10_0_0_0000 - | if self.has_padding { 1 << 5 } else { 0 } - | if self.has_extension { 1 << 4 } else { 0 } - | (self.csrc_count as u8); - - assert!(*self.payload_type <= 127); - buf[1] = *self.payload_type & 0b0111_1111 | if self.marker { 1 << 7 } else { 0 }; - - buf[2..4].copy_from_slice(&self.sequence_number.to_be_bytes()); - buf[4..8].copy_from_slice(&self.timestamp.to_be_bytes()); - buf[8..12].copy_from_slice(&self.ssrc.to_be_bytes()); - - let csrc_len = self.csrc_count * 4; - for i in 0..self.csrc_count { - let offset = 12 + i * 4; - buf[offset..offset + 4].copy_from_slice(&self.csrc[i].to_be_bytes()); - } - - let ext_start = 12 + csrc_len; - let exts_form = exts.form(&self.ext_vals); - buf[ext_start..ext_start + 2].copy_from_slice(&exts_form.serialize()); - - let ext_buf = &mut buf[ext_start + 4..]; - let mut ext_len = exts.write_to(ext_buf, &self.ext_vals, exts_form); - - let pad = 4 - ext_len % 4; - if pad < 4 { - ext_len += pad; - for i in 0..pad { - ext_buf[ext_len - i - 1] = 0; - } - } - - let bede_len = (ext_len / 4) as u16; - buf[ext_start + 2..ext_start + 4].copy_from_slice(&bede_len.to_be_bytes()); - - ext_start + 4 + ext_len - } - - /// Returns `buf` with any trailing SRTP padding removed, or `None` if the - /// trailing padding length is invalid. - pub(crate) fn unpad_payload(buf: &[u8]) -> Option<&[u8]> { - if buf.is_empty() { - return Some(buf); - } - let pad_len = buf[buf.len() - 1] as usize; - let unpadded_len = buf.len().checked_sub(pad_len)?; - Some(&buf[..unpadded_len]) - } - - pub(crate) fn parse(buf: &[u8], exts: &ExtensionMap) -> Option { - let orig_len = buf.len(); - if buf.len() < 12 { - trace!("RTP header too short < 12: {}", buf.len()); - return None; - } - - let version = (buf[0] & 0b1100_0000) >> 6; - if version != 2 { - trace!("RTP version is not 2"); - return None; - } - let has_padding = buf[0] & 0b0010_0000 > 0; - let has_extension = buf[0] & 0b0001_0000 > 0; - let csrc_count = (buf[0] & 0b0000_1111) as usize; - let marker = buf[1] & 0b1000_0000 > 0; - let payload_type = (buf[1] & 0b0111_1111).into(); - let sequence_number = u16::from_be_bytes([buf[2], buf[3]]); - - let timestamp = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - - let ssrc = u32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]); - - let buf: &[u8] = &buf[12..]; - - let csrc_len = 4 * csrc_count; - if buf.len() < csrc_len { - trace!("RTP header invalid, not enough csrc"); - return None; - } - - let mut csrc = [0_u32; 15]; - for (i, item) in csrc.iter_mut().enumerate().take(csrc_count) { - let offset = i * 4; - *item = u32::from_be_bytes([buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3]]); - } - - let buf: &[u8] = &buf[csrc_len..]; - - let mut ext = ExtensionValues { ..Default::default() }; - - let rest = if !has_extension { - buf - } else { - if buf.len() < 4 { - trace!("RTP bad header extension"); - return None; - } - - let Some(exts_form) = ExtensionsForm::parse([buf[0], buf[1]]) else { - trace!( - "Ignoring unknown RTP header extensions form: {:?}", - u16::from_be_bytes([buf[0], buf[1]]) - ); - return None; - }; - let ext_words = u16::from_be_bytes([buf[2], buf[3]]); - let ext_len = ext_words as usize * 4; - - let buf: &[u8] = &buf[4..]; - - if buf.len() < ext_len { - trace!("RTP ext len larger than header {} > {}", buf.len(), ext_len); - return None; - } - - exts.parse(&buf[..ext_len], exts_form, &mut ext); - &buf[ext_len..] - }; - - let header_len = orig_len - rest.len(); - - let ret = RtpHeader { - version, - has_padding, - has_extension, - csrc_count, - marker, - payload_type, - sequence_number, - timestamp, - ssrc: ssrc.into(), - csrc, - ext_vals: ext, - header_len, - }; - - Some(ret) - } - - /// For RTX the original sequence number is inserted before the RTP payload. - pub fn read_original_sequence_number(buf: &[u8], seq_no: &mut u16) -> usize { - if buf.len() < 2 { - // This is not an RTX packet, probably a padding packet - return 0; - } - *seq_no = u16::from_be_bytes([buf[0], buf[1]]); - 2 - } - - /// For RTX the original sequence number is inserted before the RTP payload. - pub fn write_original_sequence_number(buf: &mut [u8], seq_no: SeqNo) -> usize { - let seq_u16 = (*seq_no) as u16; - buf[0..2].copy_from_slice(&seq_u16.to_be_bytes()); - 2 - } - - /// Sequencer number of this RTP header given the previous number. - /// - /// The logic detects wrap-arounds of the 16-bit RTP sequence number. - pub fn sequence_number(&self, previous: Option) -> SeqNo { - let e_seq = extend_u16(previous.map(|v| *v), self.sequence_number); - e_seq.into() - } -} - -macro_rules! mk_extend { - ($id:ident, $t:ty, $bits:expr) => { - /// "extend" a less than 64 bit sequence number into a 64 bit by - /// using the knowledge of the previous such sequence number. - pub fn $id(prev_ext_seq: Option, seq: $t) -> u64 { - const MAX: u64 = 2_u64.pow($bits); // u16: 65_536; - const HALF: u64 = MAX / 2; // u16: 32_768 - const BITS: usize = $bits; - const VAL_MASK: u64 = ((1 << BITS) - 1); - const ROC_MASK: i64 = (u64::MAX >> BITS) as i64; - - // We define the index of the SRTP packet corresponding to a given - // ROC and RTP sequence number to be the 48-bit quantity - // i = 2^16 * ROC + SEQ. - // - // https://tools.ietf.org/html/rfc3711#appendix-A - // - - // Mask seq to the N bits we are considering. - // As an example, this allows us to handle the wrap-around of 7 bit - // values while storing them in u8 - let seq = seq as u64 & VAL_MASK; - - if prev_ext_seq.is_none() { - // No wrap-around so far. - return seq; - } - - let prev_index = prev_ext_seq.unwrap(); - let roc = (prev_index >> BITS) as i64; // how many wrap-arounds. - let prev_seq = prev_index & (MAX - 1); // u16: 0xffff - - let v = if prev_seq < HALF { - if seq > HALF + prev_seq { - (roc - 1) & ROC_MASK - } else { - roc - } - } else if prev_seq > seq + HALF { - (roc + 1) & ROC_MASK - } else { - roc - }; - - if v < 0 { - return 0; - } - - (v as u64) * MAX + seq - } - }; -} - -mk_extend!(extend_u8, u8, 8); -mk_extend!(extend_u16, u16, 16); -mk_extend!(extend_u32, u32, 32); - -// we 'host' 7 bits in u8 but we ignore the most significant one -mk_extend!(extend_u7, u8, 7); -mk_extend!(extend_u15, u16, 15); - -impl Default for RtpHeader { - fn default() -> Self { - Self { - version: 2, - has_padding: false, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 1.into(), - sequence_number: 0, - timestamp: 0, - ssrc: 0.into(), - csrc: [0; 15], - ext_vals: ExtensionValues::default(), - header_len: 16, - } - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::util::already_happened; - use crate::vendor::str0m::{io::DATAGRAM_MAX_PACKET_SIZE, rtp_::Extension}; - use std::time::Duration; - - use super::*; - - #[test] - fn extend_u16_wrap_around() { - assert_eq!(extend_u16(None, 0), 0); - assert_eq!(extend_u16(Some(0), 1), 1); - assert_eq!(extend_u16(Some(65_535), 0), 65_536); - assert_eq!(extend_u16(Some(65_500), 2), 65_538); - assert_eq!(extend_u16(Some(2), 1), 1); - assert_eq!(extend_u16(Some(65_538), 1), 65_537); - assert_eq!(extend_u16(Some(3), 3), 3); - assert_eq!(extend_u16(Some(65_500), 65_500), 65_500); - } - - #[test] - fn extend_u16_with_0_prev() { - // This tests going backwards from previous 0. This should wrap - // around "backwards" making a ridiculous number. - let seq = u16::MAX / 2 + 2; - let expected = u64::MAX - (u16::MAX - seq) as u64; - assert_eq!(extend_u16(Some(0), seq), expected); - } - - #[test] - fn extend_u32_wrap_around() { - const U32MAX: u64 = u32::MAX as u64 + 1; - assert_eq!(extend_u32(None, 0), 0); - assert_eq!(extend_u32(Some(0), 1), 1); - assert_eq!(extend_u32(Some(U32MAX - 1), 0), U32MAX); - assert_eq!(extend_u32(Some(U32MAX - 32), 2), U32MAX + 2); - assert_eq!(extend_u32(Some(2), 1), 1); - assert_eq!(extend_u32(Some(U32MAX + 2), 1), U32MAX + 1); - assert_eq!(extend_u32(Some(3), 3), 3); - assert_eq!(extend_u32(Some(U32MAX - 32), (U32MAX - 32) as u32), U32MAX - 32); - } - - #[test] - fn extend_u32_with_0_prev() { - // This tests going backwards from previous 0. This should wrap - // around "backwards" making a ridiculous number. - let seq = u32::MAX / 2 + 2; - let expected = u64::MAX - (u32::MAX - seq) as u64; - assert_eq!(extend_u32(Some(0), seq), expected); - } - - #[test] - fn extend_u7_wrap_around() { - let max = 2_u64.pow(7) - 1; - let half = max / 2; - assert_eq!(extend_u7(None, 0), 0); - assert_eq!(extend_u7(None, 1), 1); - - // most significant bit gets ignored - assert_eq!(extend_u7(None, max as u8), max); - assert_eq!(extend_u7(None, (max + 1) as u8), 0); - - assert_eq!(extend_u7(Some(0), half as u8), half); - assert_eq!(extend_u7(Some(0), (half + 1) as u8), half + 1); - - let seq = max / 2 + 2; - let expected = u64::MAX - (max - seq); - assert_eq!(extend_u7(Some(0), seq as u8), expected); - } - - #[test] - fn extend_u15_wrap_around() { - let max = 2_u64.pow(15) - 1; - let half = max / 2; - assert_eq!(extend_u15(None, 0), 0); - assert_eq!(extend_u15(None, 1), 1); - - assert_eq!(extend_u15(None, max as u16), max); - assert_eq!(extend_u15(None, (max + 1) as u16), 0); - - assert_eq!(extend_u15(Some(0), half as u16), half); - assert_eq!(extend_u15(Some(0), (half + 1) as u16), half + 1); - - let seq = max / 2 + 2; - let expected = u64::MAX - (max - seq); - assert_eq!(extend_u15(Some(0), seq as u16), expected); - } - - #[test] - fn test_write_rtp_headers() { - fn mk_header(seq: u16, ts: u32, level: i8, marker: bool, exts: &ExtensionMap) -> Vec { - let header = RtpHeader { - payload_type: 33.into(), - sequence_number: seq, - timestamp: ts, - ssrc: 44.into(), - marker, - ext_vals: ExtensionValues { - audio_level: Some(level), - voice_activity: Some(false), - ..Default::default() - }, - ..Default::default() - }; - let mut buf = vec![0; DATAGRAM_MAX_PACKET_SIZE]; - let n = header.write_to(&mut buf[..], exts); - buf.truncate(n); - - buf - } - - let mut exts = ExtensionMap::empty(); - // The expected bytes below carry the level with the V bit CLEAR, which - // is what `voice_activity: Some(false)` above asks for. They used to - // have bit 7 set (170 = 0xAA rather than 42 = 0x2A) because the - // serializer let the sign of the negative level spill into that bit. - exts.set(3, Extension::AudioLevel); - - let buf1 = mk_header(47_000, 10_000, -42, false, &exts); - let buf2 = mk_header(47_001, 12_000, -43, true, &exts); - let buf3 = mk_header(47_002, 14_000, -44, false, &exts); - - let p1 = &[ - 144, 33, 183, 152, 0, 0, 39, 16, 0, 0, 0, 44, 0xBE, 0xDE, 0, 1, 48, 42, 0, 0, - ]; - let p2 = &[ - 144, 161, 183, 153, 0, 0, 46, 224, 0, 0, 0, 44, 0xBE, 0xDE, 0, 1, 48, 43, 0, 0, - ]; - let p3 = &[ - 144, 33, 183, 154, 0, 0, 54, 176, 0, 0, 0, 44, 0xBE, 0xDE, 0, 1, 48, 44, 0, 0, - ]; - - assert_eq!(&buf1, p1); - assert_eq!(&buf2, p2); - assert_eq!(&buf3, p3); - } - - #[test] - fn test_write_rtp_headers_two_byte_form() { - fn mk_header(seq: u16, ts: u32, level: i8, marker: bool, exts: &ExtensionMap) -> Vec { - let header = RtpHeader { - payload_type: 33.into(), - sequence_number: seq, - timestamp: ts, - ssrc: 44.into(), - marker, - ext_vals: ExtensionValues { - audio_level: Some(level), - voice_activity: Some(false), - ..Default::default() - }, - ..Default::default() - }; - let mut buf = vec![0; DATAGRAM_MAX_PACKET_SIZE]; - let n = header.write_to(&mut buf[..], exts); - buf.truncate(n); - - buf - } - - let mut exts = ExtensionMap::empty(); - // Same correction as above: the V bit is clear because the header - // asks for `voice_activity: Some(false)`. - // An ID larger than 14 forces the 2-byte header extension form - exts.set(15, Extension::AudioLevel); - - let buf1 = mk_header(47_000, 10_000, -42, false, &exts); - let buf2 = mk_header(47_001, 12_000, -43, true, &exts); - let buf3 = mk_header(47_002, 14_000, -44, false, &exts); - - let p1 = &[ - 144, 33, 183, 152, 0, 0, 39, 16, 0, 0, 0, 44, 0x10, 0x00, 0, 1, 15, 1, 42, 0, - ]; - let p2 = &[ - 144, 161, 183, 153, 0, 0, 46, 224, 0, 0, 0, 44, 0x10, 0x00, 0, 1, 15, 1, 43, 0, - ]; - let p3 = &[ - 144, 33, 183, 154, 0, 0, 54, 176, 0, 0, 0, 44, 0x10, 0x00, 0, 1, 15, 1, 44, 0, - ]; - - assert_eq!(&buf1, p1); - assert_eq!(&buf2, p2); - assert_eq!(&buf3, p3); - } - - #[test] - fn test_parse_rtp_headers() { - let exts = ExtensionMap::standard(); - - let hb1 = [ - 176, 111, 183, 152, 0, 0, 39, 16, 46, 87, 21, 249, 0xBE, 0xDE, 0, 4, 16, 170, 34, 254, 32, 106, 49, 0, 0, - 66, 120, 89, 106, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, - ]; - - let hb2 = [ - 176, 111, 183, 153, 0, 0, 46, 224, 46, 87, 21, 249, 0xBE, 0xDE, 0, 4, 16, 171, 34, 254, 134, 208, 49, 0, 2, - 66, 120, 89, 106, 0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, - ]; - let hb3 = [ - 176, 111, 183, 154, 0, 0, 54, 176, 46, 87, 21, 249, 0xBE, 0xDE, 0, 4, 16, 172, 34, 254, 32, 106, 49, 0, 1, - 66, 120, 89, 106, 0, 0, 0, 9, 10, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, - ]; - - let h1 = RtpHeader::parse(&hb1, &exts).unwrap(); - let abs1 = already_happened() + Duration::from_micros(63531654); - - assert_eq!( - h1, - RtpHeader { - version: 2, - has_padding: true, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 111.into(), - sequence_number: 47000, - timestamp: 10000, - ssrc: 777459193.into(), - csrc: [0; 15], - ext_vals: ExtensionValues { - mid: Some("xYj".into()), - abs_send_time: Some(abs1), - voice_activity: Some(true), - audio_level: Some(-42), - transport_cc: Some(0), - ..Default::default() - }, - header_len: 32 - } - ); - - let h2 = RtpHeader::parse(&hb2, &exts).unwrap(); - let abs2 = already_happened() + Duration::from_micros(63631652); - - assert_eq!( - h2, - RtpHeader { - version: 2, - has_padding: true, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 111.into(), - sequence_number: 47001, - timestamp: 12000, - ssrc: 777459193.into(), - csrc: [0; 15], - ext_vals: ExtensionValues { - mid: Some("xYj".into()), - abs_send_time: Some(abs2), - voice_activity: Some(true), - audio_level: Some(-43), - transport_cc: Some(2), - ..Default::default() - }, - header_len: 32 - } - ); - - let h3 = RtpHeader::parse(&hb3, &exts).unwrap(); - let abs3 = already_happened() + Duration::from_micros(63531654); - - assert_eq!( - h3, - RtpHeader { - version: 2, - has_padding: true, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 111.into(), - sequence_number: 47002, - timestamp: 14000, - ssrc: 777459193.into(), - csrc: [0; 15], - ext_vals: ExtensionValues { - mid: Some("xYj".into()), - abs_send_time: Some(abs3), - voice_activity: Some(true), - audio_level: Some(-44), - transport_cc: Some(1), - ..Default::default() - }, - header_len: 32 - } - ); - } - - #[test] - fn test_parse_rtp_headers_two_byte_form() { - let exts = ExtensionMap::standard(); - - let hb1 = [ - 176, 111, 183, 152, 0, 0, 39, 16, 46, 87, 21, 249, 0x10, 0x01, 0, 5, 1, 1, 170, 2, 3, 254, 32, 106, 3, 2, - 0, 0, 4, 3, 120, 89, 106, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, - ]; - - let hb2 = [ - 176, 111, 183, 153, 0, 0, 46, 224, 46, 87, 21, 249, 0x10, 0x02, 0, 5, 1, 1, 171, 2, 3, 254, 134, 208, 3, 2, - 0, 2, 4, 3, 120, 89, 106, 0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, - ]; - let hb3 = [ - 176, 111, 183, 154, 0, 0, 54, 176, 46, 87, 21, 249, 0x10, 0x03, 0, 5, 1, 1, 172, 2, 3, 254, 32, 106, 3, 2, - 0, 1, 4, 3, 120, 89, 106, 0, 0, 0, 9, 10, 11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, - ]; - - let h1 = RtpHeader::parse(&hb1, &exts).unwrap(); - let abs1 = already_happened() + Duration::from_micros(63531654); - - assert_eq!( - h1, - RtpHeader { - version: 2, - has_padding: true, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 111.into(), - sequence_number: 47000, - timestamp: 10000, - ssrc: 777459193.into(), - csrc: [0; 15], - ext_vals: ExtensionValues { - mid: Some("xYj".into()), - abs_send_time: Some(abs1), - voice_activity: Some(true), - audio_level: Some(-42), - transport_cc: Some(0), - ..Default::default() - }, - header_len: 36 - } - ); - - let h2 = RtpHeader::parse(&hb2, &exts).unwrap(); - let abs2 = already_happened() + Duration::from_micros(63631652); - - assert_eq!( - h2, - RtpHeader { - version: 2, - has_padding: true, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 111.into(), - sequence_number: 47001, - timestamp: 12000, - ssrc: 777459193.into(), - csrc: [0; 15], - ext_vals: ExtensionValues { - mid: Some("xYj".into()), - abs_send_time: Some(abs2), - voice_activity: Some(true), - audio_level: Some(-43), - transport_cc: Some(2), - ..Default::default() - }, - header_len: 36 - } - ); - - let h3 = RtpHeader::parse(&hb3, &exts).unwrap(); - let abs3 = already_happened() + Duration::from_micros(63531654); - - assert_eq!( - h3, - RtpHeader { - version: 2, - has_padding: true, - has_extension: true, - csrc_count: 0, - marker: false, - payload_type: 111.into(), - sequence_number: 47002, - timestamp: 14000, - ssrc: 777459193.into(), - csrc: [0; 15], - ext_vals: ExtensionValues { - mid: Some("xYj".into()), - abs_send_time: Some(abs3), - voice_activity: Some(true), - audio_level: Some(-44), - transport_cc: Some(1), - ..Default::default() - }, - header_len: 36 - } - ); - } - - #[test] - fn test_write_rtp_headers_with_csrc() { - fn mk_header(csrc_count: usize, csrc: [u32; 15], exts: &ExtensionMap) -> Vec { - let header = RtpHeader { - csrc_count, - payload_type: 33.into(), - sequence_number: 47_000, - timestamp: 10_000, - ssrc: 44.into(), - csrc, - ext_vals: ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(true), - ..Default::default() - }, - ..Default::default() - }; - let mut buf = vec![0; DATAGRAM_MAX_PACKET_SIZE]; - let n = header.write_to(&mut buf[..], exts); - buf.truncate(n); - buf - } - - let mut exts = ExtensionMap::empty(); - exts.set(3, Extension::AudioLevel); - - // 3 CSRC entries, one-byte extension form - let buf1 = mk_header( - 3, - [100, 0x12_34_56_78, 0xFFFF_FFFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - &exts, - ); - let p1 = &[ - 147, 33, 183, 152, 0, 0, 39, 16, 0, 0, 0, 44, // fixed header (CC=3) - 0, 0, 0, 100, 0x12, 0x34, 0x56, 0x78, 0xFF, 0xFF, 0xFF, 0xFF, // CSRC values - 0xBE, 0xDE, 0, 1, 48, 170, 0, 0, // extension - ]; - assert_eq!(&buf1, p1); - - // 15 CSRC entries (maximum) - let buf2 = mk_header(15, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], &exts); - let p2 = &[ - 159, 33, 183, 152, 0, 0, 39, 16, 0, 0, 0, 44, // fixed header (CC=15) - 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, // CSRC 1-4 - 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 8, // CSRC 5-8 - 0, 0, 0, 9, 0, 0, 0, 10, 0, 0, 0, 11, 0, 0, 0, 12, // CSRC 9-12 - 0, 0, 0, 13, 0, 0, 0, 14, 0, 0, 0, 15, // CSRC 13-15 - 0xBE, 0xDE, 0, 1, 48, 170, 0, 0, // extension - ]; - assert_eq!(&buf2, p2); - } - - #[test] - fn test_parse_rtp_headers_with_csrc() { - let mut exts = ExtensionMap::empty(); - exts.set(3, Extension::AudioLevel); - - // 3 CSRC entries with one-byte extension form (produced by test_write_rtp_headers_with_csrc) - let buf1 = [ - 147, 33, 183, 152, 0, 0, 39, 16, 0, 0, 0, 44, 0, 0, 0, 100, 0x12, 0x34, 0x56, 0x78, 0xFF, 0xFF, 0xFF, 0xFF, - 0xBE, 0xDE, 0, 1, 48, 170, 0, 0, - ]; - - let h1 = RtpHeader::parse(&buf1, &exts).unwrap(); - - assert_eq!( - h1, - RtpHeader { - version: 2, - has_padding: false, - has_extension: true, - csrc_count: 3, - marker: false, - payload_type: 33.into(), - sequence_number: 47_000, - timestamp: 10_000, - ssrc: 44.into(), - csrc: [100, 0x12_34_56_78, 0xFFFF_FFFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ext_vals: ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(true), - ..Default::default() - }, - header_len: 32, - } - ); - - // 15 CSRC entries (maximum) - let buf2 = [ - 159, 33, 183, 152, 0, 0, 39, 16, 0, 0, 0, 44, // fixed header (CC=15) - 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, // CSRC 1-4 - 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0, 8, // CSRC 5-8 - 0, 0, 0, 9, 0, 0, 0, 10, 0, 0, 0, 11, 0, 0, 0, 12, // CSRC 9-12 - 0, 0, 0, 13, 0, 0, 0, 14, 0, 0, 0, 15, // CSRC 13-15 - 0xBE, 0xDE, 0, 1, 48, 170, 0, 0, // extension - ]; - - let h2 = RtpHeader::parse(&buf2, &exts).unwrap(); - - assert_eq!( - h2, - RtpHeader { - version: 2, - has_padding: false, - has_extension: true, - csrc_count: 15, - marker: false, - payload_type: 33.into(), - sequence_number: 47_000, - timestamp: 10_000, - ssrc: 44.into(), - csrc: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], - ext_vals: ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(true), - ..Default::default() - }, - header_len: 80, - } - ); - } - - #[test] - fn truncate_off_srtp_padding() { - let truncate = |payload: Vec| -> Result, ()> { - match RtpHeader::unpad_payload(&payload) { - Some(unpadded) => Ok(unpadded.to_vec()), - None => Err(()), - } - }; - - assert_eq!(Ok(vec![1, 2, 3, 4, 0]), truncate(vec![1, 2, 3, 4, 0])); - assert_eq!(Ok(vec![1, 2, 3, 4]), truncate(vec![1, 2, 3, 4, 1])); - assert_eq!(Ok(vec![1, 2, 3]), truncate(vec![1, 2, 3, 4, 2])); - assert_eq!(Ok(vec![1, 2]), truncate(vec![1, 2, 3, 4, 3])); - assert_eq!(Ok(vec![1]), truncate(vec![1, 2, 3, 4, 4])); - assert_eq!(Ok(vec![]), truncate(vec![1, 2, 3, 4, 5])); - assert_eq!(Err(()), truncate(vec![1, 2, 3, 4, 6])); - assert_eq!(Err(()), truncate(vec![1, 2, 3, 4, 255])); - assert_eq!(Ok(vec![0]), truncate(vec![0])); - assert_eq!(Ok(vec![]), truncate(vec![1])); - assert_eq!(Ok(vec![]), truncate(vec![])); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/id.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/id.rs deleted file mode 100644 index 650a542be01..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/id.rs +++ /dev/null @@ -1,349 +0,0 @@ -use std::fmt; -use std::ops::Deref; -use std::str::from_utf8; - -use serde::{Deserialize, Serialize}; - -use crate::vendor::str0m_proto::Id; -use crate::vendor::str0m_proto::NonCryptographicRng; - -macro_rules! str_id { - ($id:ident, $name:literal, $num:tt, $new_len:tt) => { - impl $id { - /// Creates a new random id. - pub fn new() -> $id { - let mut arr = Id::<$num>::random().into_array(); - for i in $new_len..$num { - arr[i] = b' '; - } - $id(arr) - } - - /// Converts an array of bytes to an id. - pub const fn from_array(a: [u8; $num]) -> $id { - $id(a) - } - } - - impl fmt::Display for $id { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s: &str = self; - write!(f, "{}", s) - } - } - - impl fmt::Debug for $id { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s: &str = self; - write!(f, "{}({})", $name, s) - } - } - - impl Deref for $id { - type Target = str; - - fn deref(&self) -> &Self::Target { - from_utf8(&self.0).expect("ascii id").trim() - } - } - - impl<'a> From<&'a str> for $id { - fn from(v: &'a str) -> Self { - let v = v - .chars() - .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) - .collect::(); - - let bytes = v.as_bytes(); - let bytes = &bytes[0..$num.min(bytes.len())]; - - // pad with space. - let mut array = [b' '; $num]; - - let max = bytes.len().min(array.len()); - (&mut array[0..max]).copy_from_slice(bytes); - - $id(array) - } - } - - impl Default for $id { - fn default() -> Self { - $id::new() - } - } - }; -} - -macro_rules! num_id { - ($id:ident, $t:tt) => { - impl $id { - /// Creates a new random id. - pub fn new() -> Self { - loop { - let v = NonCryptographicRng::$t(); - // At least Ssrc assigns special meaning to 0, - // but it's fine to avoid for the other numeric - // ids as well. - if v != 0 { - return $id(v); - } - } - } - } - - impl Deref for $id { - type Target = $t; - - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - impl From<$t> for $id { - fn from(v: $t) -> Self { - $id(v) - } - } - - impl fmt::Display for $id { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } - } - }; -} - -/// Media identifier. -/// -/// In SDP this is found per m-line with the attribute `a=mid:`. -/// -/// When using Direct API we still need `Mid`, since they group individual -/// encoded streams. For example a simulcast of 3 layers would have -/// 3 incoming StreamRx, but since they belong to the same media, -/// the have the same `Mid`. -#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Mid([u8; 16]); -str_id!(Mid, "Mid", 16, 3); - -/// Identifier of a simulcast layer for an encoded stream. -/// -/// The abbreviation means "RTP Stream Id", which is a very confusing name, because -/// everything in RTP is a stream. People tend to just call it "rid". -/// -/// In SDP this is an optional value that will be seen in [`MediaData`][crate::vendor::str0m::media::MediaData] -/// if the remote peer is configured for simulcast. -#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct Rid([u8; 8]); -str_id!(Rid, "Rid", 8, 3); - -/// Synchronization source. -/// -/// Uniquely identifies a sending source of data. Each video/audio stream would be associated -/// with at least one synchronization source. Multiple sources for the same stream happens -/// for RTX (resend) and simulcast. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Ssrc(u32); -num_id!(Ssrc, u32); - -impl Ssrc { - /// Returns true if this is the probe SSRC (0). - /// - /// libwebrtc uses SSRC 0 for bandwidth estimation probes sent before - /// video media starts. These probes require special handling. - pub fn is_probe(&self) -> bool { - self.0 == 0 - } -} - -/// Payload type. -/// -/// The payload type identifies which codec and format parameters a stream is sent with. -/// The mappings of Pt-Codec + parameters is negotiated in SDP OFFER/ANSWER. -/// -/// PTs in RTP headers are 7 bits. Values >=128 are not valid. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct Pt(u8); -num_id!(Pt, u8); - -/// Identifier of an SDP session. -/// -/// This value is rarely interesting, but is part of the SDP OFFER and ANSWER. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct SessionId(u64); -num_id!(SessionId, u64); - -/// Sequence number of an RTP packet. -/// -/// An RTP packet is identified by: SSRC + SeqNo. However in the RTP header the sequence number -/// is a `u16`, meaning the value quite quickly "rolls over". To uniquely identify a packet, -/// str0m keeps track of the roll overs and converts the `u16` to `u64` in this `SeqNo`. -/// -/// To get the RTP u16 value from a `SeqNo`, use `as_u16()` or cast it to u16. -/// -/// ```ignore -/// # use crate::vendor::str0m::rtp::SeqNo; -/// let seq_no: SeqNo = 65_537.into(); -/// -/// // Use `as_u16()`. -/// let a = seq_no.as_u16(); -/// // Discard upper 48 bits to get RTP u16. -/// let b = *seq_no as u16; -/// -/// assert_eq!(a, 1); -/// assert_eq!(b, 1); -/// ``` -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct SeqNo(u64); -num_id!(SeqNo, u64); - -/// TWCC-specific sequence number. -/// -/// Transport-Wide Congestion Control uses its own sequence number space, -/// separate from RTP sequence numbers. This type ensures TWCC sequences -/// cannot be confused with RTP SeqNo values. -/// -/// TWCC sequences are also u64 internally (tracking rollovers), though the -/// wire format uses u16. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)] -pub struct TwccSeq(u64); -num_id!(TwccSeq, u64); - -impl SeqNo { - pub(crate) const MAX: SeqNo = SeqNo(u64::MAX); - - /// Check if the `other` sequence number is directly following this. - #[inline(always)] - pub fn is_next(&self, other: SeqNo) -> bool { - if **self >= *other { - return false; - } - *other - **self == 1 - } - - /// Increase (mutate) this sequence number and return the previous value. - #[inline(always)] - pub fn inc(&mut self) -> SeqNo { - let n = SeqNo(self.0); - self.0 += 1; - n - } - - #[inline(always)] - pub(crate) fn is_max(&self) -> bool { - self.0 == Self::MAX.0 - } - - /// The RTP header value (discarding the ROC). - /// - /// This is the same as discarding the top 48 bits by casting to a u16. - /// - /// ```ignore - /// # use crate::vendor::str0m::rtp::SeqNo; - /// let seq_no: SeqNo = 65_537.into(); - /// - /// // Use `as_u16()`. - /// let a = seq_no.as_u16(); - /// - /// assert_eq!(a, 1); - /// ``` - #[inline(always)] - pub fn as_u16(&self) -> u16 { - self.0 as u16 - } - - /// Get the rollover counter (ROC) value. - /// - /// ```ignore - /// # use crate::vendor::str0m::rtp::SeqNo; - /// // More than 2^16, thus rolled over. - /// let seq_no: SeqNo = 95_000.into(); - /// - /// assert_eq!(seq_no.roc(), 1); - /// - /// // Is the same as shifting 16 bits. - /// assert_eq!(seq_no.roc(), 95_000 >> 16); - /// ``` - #[inline(always)] - pub fn roc(&self) -> u64 { - self.0 >> 16 - } -} - -impl TwccSeq { - /// Check if the `other` sequence number is directly following this. - #[inline(always)] - pub fn is_next(&self, other: TwccSeq) -> bool { - if **self >= *other { - return false; - } - *other - **self == 1 - } - - /// Increase (mutate) this sequence number and return the previous value. - #[inline(always)] - pub fn inc(&mut self) -> TwccSeq { - let n = TwccSeq(self.0); - self.0 += 1; - n - } - - /// The TWCC wire format value (discarding the ROC). - /// - /// This is the same as discarding the top 48 bits by casting to a u16. - #[inline(always)] - pub fn as_u16(&self) -> u16 { - self.0 as u16 - } - - /// Get the rollover counter (ROC) value. - #[inline(always)] - pub fn roc(&self) -> u64 { - self.0 >> 16 - } -} - -impl Default for SeqNo { - fn default() -> Self { - // https://www.rfc-editor.org/rfc/rfc3550#page-13 - // The initial value of the sequence number SHOULD be random (unpredictable) - // to make known-plaintext attacks on encryption more difficult - // Upper half of range is avoided in order to prevent SRTP wraparound issues - // during startup. - // Sequence number 0 is avoided for historical reasons, presumably to avoid - // debugability or test usage conflicts. - // i.e the range is (1, 2^15-1) - Self((NonCryptographicRng::u16() % 32767 + 1) as u64) - } -} - -impl Pt { - /// Create a PT with a specific value. - /// - /// PTs are 7 bit. Values with 8 bits are not valid in RTP headers. - pub const fn new_with_value(v: u8) -> Pt { - Pt(v) - } -} - -/// A combination of Mid/Rid -/// -/// In many cases they go hand-in-hand. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub(crate) struct MidRid(pub Mid, pub Option); - -impl MidRid { - #[inline(always)] - pub fn mid(&self) -> Mid { - self.0 - } - - #[inline(always)] - pub fn rid(&self) -> Option { - self.1 - } - - pub fn special_equals(&self, other: &MidRid) -> bool { - self.0 == other.0 && (self.1.is_none() || self.1 == other.1) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/mod.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/mod.rs deleted file mode 100644 index 18f0023db55..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -mod id; -pub(crate) use id::MidRid; -pub use id::{Mid, Pt, Rid, SeqNo, SessionId, Ssrc, TwccSeq}; - -mod seq_no_window; -pub(crate) use seq_no_window::SeqNoWindow; - -mod ext; -pub use ext::{AbsCaptureTime, UserExtensionValues, VideoOrientation}; -pub use ext::{Extension, ExtensionMap, ExtensionSerializer, ExtensionValues}; - -mod dir; -pub use dir::Direction; - -mod mtime; -pub use mtime::Frequency; -pub use mtime::MediaTime; - -mod header; -pub use header::RtpHeader; -pub(crate) use header::{extend_u7, extend_u8, extend_u15, extend_u16, extend_u32}; - -mod srtp; -pub(crate) use srtp::SrtpContext; -pub(crate) use srtp::{SRTCP_OVERHEAD, SRTP_BLOCK_SIZE, SRTP_OVERHEAD}; - -mod rtcp; -pub use rtcp::*; - -pub use crate::vendor::str0m_proto::{Bitrate, DataSize}; - -/// Errors that can arise in RTP. -mod error; -pub use error::RtpError; diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/mtime.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/mtime.rs deleted file mode 100644 index 6b427b197ce..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/mtime.rs +++ /dev/null @@ -1,444 +0,0 @@ -use std::cmp::Ordering; -use std::fmt::Display; -use std::num::NonZeroU32; -use std::ops::{Add, AddAssign, Sub, SubAssign}; -use std::str::FromStr; -use std::time::Duration; -use std::time::Instant; - -use serde::{Deserialize, Serialize}; - -/// Media timeline frequency as represented by a non-zero unsigned integer. -/// -/// The frequency can be found in the negotiated payload parameters for a -/// media writer. -/// -/// ```ignore -/// # use crate::vendor::str0m::Rtc; -/// # use crate::vendor::str0m::media::{Mid, MediaTime}; -/// # let rtc: Rtc = todo!(); -/// # -/// // Obtain mid from Event::MediaAdded -/// let mid: Mid = todo!(); -/// -/// // Create a media writer for the mid. -/// let writer = rtc.writer(mid).unwrap(); -/// -/// // Get the payload type (pt) for the wanted codec. -/// let params = writer.payload_params().nth(0).unwrap(); -/// -/// // Obtain the frequency for the selected codec. -/// let freq = params.spec().clock_rate; -/// -/// let mtime = MediaTime::new(2000, freq); -/// ``` -#[derive(Debug, Clone, Copy, Serialize)] -pub struct Frequency(NonZeroU32); - -impl Frequency { - /// Microseconds in a second. - pub const MICROS: Self = Self::make(1_000_000); - - /// 1 / 2 ^ 18 seconds in a second. - pub const FIXED_POINT_6_18: Frequency = Self::make(2u32.pow(18)); // 262_144 - - /// Cycles in a second of a 90 kHz signal. - pub const NINETY_KHZ: Frequency = Self::make(90_000); - - /// Cycles in a second of a 48 kHz signal. - pub const FORTY_EIGHT_KHZ: Frequency = Self::make(48_000); - - /// Cycles in a second of a 16 kHz signal. - /// - /// This is the RTP clock rate for AMR-WB. - pub const SIXTEEN_KHZ: Frequency = Self::make(16_000); - - /// Cycles in a second of a 8000 Hz signal. - pub const EIGHT_KHZ: Frequency = Self::make(8_000); - - /// Milliseconds in a second. - pub const MILLIS: Frequency = Self::make(1_000); - - /// Hundredths in a second. - pub const HUNDREDTHS: Frequency = Self::make(100); - - /// Seconds in a second. - pub const SECONDS: Frequency = Self::make(1); - - /// Private unconditional non-zero constructor for use with constants. - const fn make(v: u32) -> Frequency { - match NonZeroU32::new(v) { - Some(v) => Self(v), - None => panic!("assured non-zero value is zero"), - } - } - - /// Any non-zero u32 is a valid media timeline frequency. - pub const fn from_nonzero(v: NonZeroU32) -> Self { - Self(v) - } - - /// Every u32 is a valid media timeline frequency except zero. - pub fn new(v: u32) -> Option { - NonZeroU32::new(v).map(Self) - } - - /// The frequency as a u32. - pub const fn get(&self) -> u32 { - self.0.get() - } - - /// The frequency as a [`std::num::NonZeroU32`] i.e. including a positivity proof. - pub const fn nonzero(&self) -> NonZeroU32 { - self.0 - } -} - -impl PartialEq for Frequency { - fn eq(&self, other: &Self) -> bool { - self.0 == other.0 - } -} -impl Eq for Frequency {} - -impl From for NonZeroU32 { - fn from(value: Frequency) -> Self { - value.0 - } -} - -impl From for Frequency { - fn from(value: NonZeroU32) -> Self { - Self(value) - } -} - -impl FromStr for Frequency { - type Err = ::Err; - - fn from_str(s: &str) -> Result { - NonZeroU32::from_str(s).map(Self) - } -} - -impl Display for Frequency { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} - -impl<'de> Deserialize<'de> for Frequency { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - NonZeroU32::deserialize(deserializer).map(Self) - } -} - -/// Media timeline offset represented by a count (numerator) / frequency (denominator) in seconds. -/// -/// The numerator is typically the packet time of an Rtp header. The denominator is the clock -/// frequency of the media source (typically 90kHz for video and 48kHz for audio). The denominator -/// is guaranteed to be a positive integer while the numerator could be positive, negative, or zero. -/// -/// The frequency can be found in the negotiated payload parameters for a media writer. -/// -/// ```ignore -/// # use crate::vendor::str0m::Rtc; -/// # use crate::vendor::str0m::media::{Mid, MediaTime}; -/// # let rtc: Rtc = todo!(); -/// # -/// // Obtain mid from Event::MediaAdded -/// let mid: Mid = todo!(); -/// -/// // Create a media writer for the mid. -/// let writer = rtc.writer(mid).unwrap(); -/// -/// // Get the payload type (pt) for the wanted codec. -/// let params = writer.payload_params().nth(0).unwrap(); -/// -/// // Obtain the frequency for the selected codec. -/// let freq = params.spec().clock_rate; -/// -/// let mtime = MediaTime::new(2000, freq); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct MediaTime(u64, Frequency); - -impl MediaTime { - /// The additive identity: 0/1. - pub const ZERO: MediaTime = MediaTime::from_secs(0); - - /// Construct a [`MediaTime`] from a guaranteed non-zero [`Frequency`]. - pub const fn new(numer: u64, denom: Frequency) -> Self { - Self(numer, denom) - } - - /// The numerator of the offset time. - #[inline(always)] - pub const fn numer(&self) -> u64 { - self.0 - } - - /// The denominator of the offset time. - #[inline(always)] - pub const fn denom(&self) -> u32 { - self.1.get() - } - - /// The [`Frequency`] of the offset time. - #[inline(always)] - pub const fn frequency(&self) -> Frequency { - self.1 - } - - /// Convenience constructor for numbers of microseconds (v/1_000_000). - #[inline(always)] - pub const fn from_micros(v: u64) -> MediaTime { - MediaTime(v, Frequency::MICROS) - } - - /// Convenience constructor for numbers of 24-bit 6.18 fixed point units (v/2^18). - #[inline(always)] - pub const fn from_fixed_point_6_18(v: u64) -> MediaTime { - MediaTime(v, Frequency::FIXED_POINT_6_18) - } - - /// Convenience constructor for numbers of 90kHz units (v/90_000). - #[inline(always)] - pub const fn from_90khz(v: u64) -> MediaTime { - MediaTime(v, Frequency::NINETY_KHZ) - } - - /// Convenience constructor for numbers of milliseconds (v/1000). - #[inline(always)] - pub const fn from_millis(v: u64) -> MediaTime { - MediaTime(v, Frequency::MILLIS) - } - - /// Convenience constructor for numbers of hundredths of seconds (v/100). - #[inline(always)] - pub const fn from_hundredths(v: u64) -> MediaTime { - MediaTime(v, Frequency::HUNDREDTHS) - } - - /// Convenience constructor for numbers of seconds (v/1). - #[inline(always)] - pub const fn from_secs(v: u64) -> MediaTime { - MediaTime(v, Frequency::SECONDS) - } - - /// Convenience constructor for floating point fractions of seconds as microsecond units. - #[inline(always)] - pub fn from_seconds(v: impl Into) -> MediaTime { - Self::from_micros((v.into() * 1_000_000.0_f64) as u64) - } - - /// A floating point fraction second representation. - #[inline(always)] - pub fn as_seconds(&self) -> f64 { - let denom: f64 = self.1.get().into(); - self.0 as f64 / denom - } - - /// A microsecond representation. - pub const fn as_micros(&self) -> u64 { - self.rebase(Frequency::MICROS).numer() - } - - /// Predicate for checking that the numerator is 0. - #[inline(always)] - pub const fn is_zero(&self) -> bool { - self.0 == 0 - } - - /// Convert this offset time to have a different denominator - /// (frequency). This conversion may lose precision and, after - /// arithmetic operations with other times of higher frequencies, - /// may have a higher frequency. - #[inline(always)] - pub const fn rebase(self, denom: Frequency) -> MediaTime { - if denom.get() == self.1.get() { - self - } else { - let numer = self.0 as i128 * denom.get() as i128 / self.1.get() as i128; - MediaTime::new(numer as u64, denom) - } - } - - #[inline(always)] - fn same_base(t0: MediaTime, t1: MediaTime) -> (MediaTime, MediaTime) { - let max = Frequency(t0.1.0.max(t1.1.0)); - (t0.rebase(max), t1.rebase(max)) - } - - /// Checked `MediaTime` subtraction. Returns [`None`] if the result - /// would be negative. - /// - /// # Examples - /// - /// Basic usage: - /// ```ignore - /// use crate::vendor::str0m::media::MediaTime; - /// - /// assert_eq!( - /// MediaTime::from_micros(10).checked_sub(MediaTime::from_micros(5)), - /// Some(MediaTime::from_micros(5)) - /// ); - /// assert_eq!( - /// MediaTime::from_micros(5).checked_sub(MediaTime::from_micros(10)), - /// None - /// ); - /// ``` - #[inline] - pub fn checked_sub(self, rhs: MediaTime) -> Option { - let (lhs, rhs) = MediaTime::same_base(self, rhs); - if lhs.0 < rhs.0 { - None - } else { - Some(MediaTime::new(lhs.0 - rhs.0, lhs.1)) - } - } - - /// Saturating `MediaTime` subtraction. Returns [`MediaTime::ZERO`] if the result - /// would be negative. - /// - /// # Examples - /// - /// Basic usage: - /// ```ignore - /// use crate::vendor::str0m::media::MediaTime; - /// - /// assert_eq!( - /// MediaTime::from_micros(10).saturating_sub(MediaTime::from_micros(5)), - /// MediaTime::from_micros(5) - /// ); - /// assert_eq!( - /// MediaTime::from_micros(5).saturating_sub(MediaTime::from_micros(10)), - /// MediaTime::ZERO - /// ); - /// ``` - #[inline] - pub fn saturating_sub(self, rhs: MediaTime) -> MediaTime { - match self.checked_sub(rhs) { - Some(v) => v, - None => MediaTime::ZERO, - } - } -} - -impl PartialEq for MediaTime { - #[inline(always)] - fn eq(&self, other: &Self) -> bool { - let (t0, t1) = MediaTime::same_base(*self, *other); - t0.0 == t1.0 - } -} -impl Eq for MediaTime {} - -impl PartialOrd for MediaTime { - #[inline(always)] - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for MediaTime { - #[inline(always)] - fn cmp(&self, other: &Self) -> Ordering { - let (t0, t1) = MediaTime::same_base(*self, *other); - if t0 == t1 { - Ordering::Equal - } else if t0.0 < t1.0 { - Ordering::Less - } else { - Ordering::Greater - } - } -} - -impl Add for MediaTime { - type Output = MediaTime; - - #[inline(always)] - fn add(self, rhs: Self) -> Self::Output { - let (t0, t1) = MediaTime::same_base(self, rhs); - MediaTime::new(t0.0 + t1.0, t0.1) - } -} - -impl Sub for MediaTime { - type Output = MediaTime; - - fn sub(self, rhs: Self) -> Self::Output { - self.checked_sub(rhs).expect("overflow when subtracting MediaTime") - } -} - -impl SubAssign for MediaTime { - fn sub_assign(&mut self, rhs: Self) { - *self = *self - rhs; - } -} - -impl Sub for Instant { - type Output = Instant; - - fn sub(self, rhs: MediaTime) -> Self::Output { - self - Duration::from(rhs) - } -} - -impl SubAssign for Instant { - fn sub_assign(&mut self, rhs: MediaTime) { - *self = *self - rhs; - } -} - -impl AddAssign for MediaTime { - fn add_assign(&mut self, rhs: Self) { - *self = *self + rhs; - } -} - -impl Add for Instant { - type Output = Instant; - - fn add(self, rhs: MediaTime) -> Self::Output { - self + Duration::from(rhs) - } -} - -impl AddAssign for Instant { - fn add_assign(&mut self, rhs: MediaTime) { - *self = *self + rhs; - } -} - -impl From for Duration { - fn from(value: MediaTime) -> Self { - Duration::from_micros(value.rebase(Frequency::MICROS).numer()) - } -} - -impl From for MediaTime { - fn from(v: Duration) -> Self { - MediaTime::new(v.as_micros() as u64, Frequency::MICROS) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn ts_rebase() { - let t1 = MediaTime::from_seconds(10.0); - let t2 = t1.rebase(Frequency::NINETY_KHZ); - assert_eq!(t2.numer(), 90_000 * 10); - assert_eq!(t2.denom(), 90_000); - - println!("{}", (10.0234_f64).fract()); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/bb.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/bb.rs deleted file mode 100644 index 633664fa41a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/bb.rs +++ /dev/null @@ -1,62 +0,0 @@ -use super::{FeedbackMessageType, ReportList, RtcpHeader, RtcpPacket, RtcpType, Ssrc}; - -/// RTCP packet BY -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Goodbye { - /// The SSRC that are no longer in use. - pub reports: ReportList, -} - -impl RtcpPacket for Goodbye { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::Goodbye, - feedback_message_type: FeedbackMessageType::SourceCount(self.reports.len() as u8), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // each ssrc is one word - 1 + self.reports.len() - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(&mut buf[..4]); - let buf = &mut buf[4..]; - for (i, s) in self.reports.iter().enumerate() { - buf[i * 4..(i + 1) * 4].copy_from_slice(&s.to_be_bytes()); - } - - self.length_words() * 4 - } -} - -impl<'a> TryFrom<(usize, &'a [u8])> for Goodbye { - type Error = &'static str; - - fn try_from((count, buf): (usize, &'a [u8])) -> Result { - if buf.len() < 4 { - return Err("Less than 4 bytes for Goodbye"); - } - - let mut reports = ReportList::new(); - let mut buf = buf; - - if buf.len() < count * 4 { - return Err("Less than count * 4 bytes for Goodbye"); - } - - let max = count.min(31); - - for _ in 0..max { - let ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - reports.push(ssrc); - buf = &buf[4..]; - } - - // TODO parse the optional reason string here. - - Ok(Goodbye { reports }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/fir.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/fir.rs deleted file mode 100644 index c2508b646ad..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/fir.rs +++ /dev/null @@ -1,89 +0,0 @@ -use super::list::private::WordSized; -use super::{FeedbackMessageType, PayloadType, ReportList, RtcpHeader, RtcpPacket, RtcpType, Ssrc}; - -/// Full Intra Request (FIR). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Fir { - /// Sender of this feedback. Mostly irrelevant, but part of RTCP packets. - pub sender_ssrc: Ssrc, - /// The SSRC needing a full codec restart. - pub reports: ReportList, -} - -/// Entry reported needing a codec restart. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct FirEntry { - /// The SSRC needing a full codec restart. - pub ssrc: Ssrc, - /// Counter keeping track of which restart request this is. - pub seq_no: u8, -} - -impl RtcpPacket for Fir { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::PayloadSpecificFeedback, - feedback_message_type: FeedbackMessageType::PayloadFeedback(PayloadType::FullIntraRequest), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // header - // sender SSRC - // media SSRC (set to 0) - // reports * FirEntry: SSRC + seqNo - 1 + 1 + 1 + self.reports.len() * 2 - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(&mut buf[..4]); - - buf[4..8].copy_from_slice(&self.sender_ssrc.to_be_bytes()); - - let media_ssrc = self.reports.iter().next().map(|s| *s.ssrc).unwrap_or(0); - buf[8..12].copy_from_slice(&media_ssrc.to_be_bytes()); - - let mut buf = &mut buf[12..]; - for r in &self.reports { - buf[0..4].copy_from_slice(&r.ssrc.to_be_bytes()); - buf[4..8].copy_from_slice(&[r.seq_no, 0, 0, 0]); - buf = &mut buf[8..]; - } - - 4 + 4 + 4 + self.reports.len() * 8 - } -} - -impl WordSized for FirEntry { - fn word_size(&self) -> usize { - 2 - } -} - -impl<'a> TryFrom<&'a [u8]> for Fir { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 16 { - return Err("Fir less than 16 bytes"); - } - - let sender_ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - - let mut reports = ReportList::new(); - - let mut buf = &buf[8..]; - let count = buf.len() / 8; - let max = count.min(31); - - for _ in 0..max { - let ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let seq_no = buf[4]; - reports.push(FirEntry { ssrc, seq_no }); - buf = &buf[8..]; - } - - Ok(Fir { sender_ssrc, reports }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/fmt.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/fmt.rs deleted file mode 100644 index 6d8c3a8cc97..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/fmt.rs +++ /dev/null @@ -1,133 +0,0 @@ -/// Number of _something_ in the RTCP packet. -/// -/// PacketType determines how to interpret the count field. -use tracing::trace; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FeedbackMessageType { - /// When packet type SenderReport or ReceiverReport. - /// - /// The contained u8 is number of receiver reports. - ReceptionReport(u8), - - /// When packet type SourceDescription (SDES) or Goodbye - /// - /// The contained u8 is number of contained SDES or Goodbyes. - SourceCount(u8), - - /// When packet type ApplicationDefined - /// - /// The contained u8 is a subtype which is upp to the application. - Subtype(u8), - - /// When packet type is TransportLayerFeedback. - TransportFeedback(TransportType), - - /// When packet type is PayloadSpecificFeedback. - PayloadFeedback(PayloadType), - - /// When the packet type is ExtendedReport - NotUsed, -} - -impl FeedbackMessageType { - pub fn count(&self) -> u8 { - match self { - FeedbackMessageType::ReceptionReport(v) => *v, - FeedbackMessageType::SourceCount(v) => *v, - _ => panic!("Not a count"), - } - } -} - -impl From for u8 { - fn from(val: FeedbackMessageType) -> Self { - use FeedbackMessageType::*; - match val { - ReceptionReport(v) | SourceCount(v) | Subtype(v) => { - assert!(v <= 31, "rtcp fmt when count must be <= 31"); - v - } - TransportFeedback(v) => v as u8, - PayloadFeedback(v) => v as u8, - NotUsed => 0, - } - } -} - -/// Subtypes of [`FeedbackMessageType::TransportFeedback`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TransportType { - /// Nack RTCP packet. - /// - /// Definition: - Nack = 1, - - /// Transportwide congestion control packet. - /// - /// Definition: - TransportWide = 15, -} - -impl TryFrom for TransportType { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - use TransportType::*; - match v { - 1 => Ok(Nack), - 15 => Ok(TransportWide), - _ => { - trace!("Uknown TransportType: {}", v); - Err("Uknown TransportType") - } - } - } -} - -/// Subtypes of [`FeedbackMessageType::PayloadFeedback`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PayloadType { - /// PLI packet type. - /// - /// Definition: - PictureLossIndication = 1, - - /// SLI packet type. - /// - /// Definition: - SliceLossIndication = 2, - - /// RPSI packet type. - /// - /// Definition: - ReferencePictureSelectionIndication = 3, - - /// FIR packet type. - /// - /// Definition: - FullIntraRequest = 4, - - /// Application specific type. - /// - /// Definition: - ApplicationLayer = 15, -} - -impl TryFrom for PayloadType { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - use PayloadType::*; - match v { - 1 => Ok(PictureLossIndication), - 2 => Ok(SliceLossIndication), - 3 => Ok(ReferencePictureSelectionIndication), - 4 => Ok(FullIntraRequest), - 15 => Ok(ApplicationLayer), - _ => { - trace!("Uknown PayloadType: {}", v); - Err("Uknown PayloadType") - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/header.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/header.rs deleted file mode 100644 index 1e4501e33f4..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/header.rs +++ /dev/null @@ -1,198 +0,0 @@ -#![allow(clippy::unusual_byte_groupings)] - -use super::{FeedbackMessageType, PayloadType, TransportType}; -use tracing::trace; - -pub(crate) const LEN_HEADER: usize = 4; - -#[derive(Debug, PartialEq, Eq)] -pub struct RtcpHeader { - pub(crate) rtcp_type: RtcpType, - pub(crate) feedback_message_type: FeedbackMessageType, - pub(crate) words_less_one: u16, -} - -impl RtcpHeader { - /// Type of RTCP packet. This is further divided into subtypes by - /// `feedback_message_type`. - pub fn rtcp_type(&self) -> RtcpType { - self.rtcp_type - } - - /// Subtype of RTCP message. - pub fn feedback_message_type(&self) -> FeedbackMessageType { - self.feedback_message_type - } - - /// Number of reports stacked in this message. - /// - /// Depending `rtcp_type` and `feedback_message_type` multiple reports of the same type can be - /// stacked into one RTCP packet under the same header. - pub fn count(&self) -> usize { - match self.rtcp_type { - RtcpType::SenderReport | RtcpType::ReceiverReport | RtcpType::SourceDescription | RtcpType::Goodbye => { - self.feedback_message_type.count() as usize - } - RtcpType::ApplicationDefined => 1, - RtcpType::TransportLayerFeedback => { - let transport_type = match self.feedback_message_type { - FeedbackMessageType::TransportFeedback(v) => v, - _ => unreachable!(), - }; - - match transport_type { - TransportType::Nack => { - // [ssrc_sender, ssrc_media_source, fci, fci, ...] - let fci_length = self.length_words() * 4 - LEN_HEADER - 2 * 4; - - // each fci is one word: [pid, blp] - fci_length / 4 - } - TransportType::TransportWide => { - // TODO - 0 - } - } - } - RtcpType::PayloadSpecificFeedback => { - let payload_type = match self.feedback_message_type { - FeedbackMessageType::PayloadFeedback(v) => v, - _ => unreachable!(), - }; - - match payload_type { - PayloadType::PictureLossIndication => { - // PLI does not require parameters. Therefore, the length field MUST be - // 2, and there MUST NOT be any Feedback Control Information. - 1 - } - - PayloadType::FullIntraRequest => { - // [ssrc_sender, ssrc_media_source, fci, fci, ...] - let fci_length = self.length_words() * 4 - LEN_HEADER - 2 * 4; - - // each fci is two words: [ssrc, [seq_no, reserved]] - fci_length / 8 - } - - _ => { - // PayloadType::SliceLossIndication => {}, - // PayloadType::ReferencePictureSelectionIndication => {}, - // PayloadType::ApplicationLayer => {}, - 0 - } - } - } - RtcpType::ExtendedReport => 0, - } - } - - /// Length of entire RTCP packet (including header) in words (4 bytes). - pub fn length_words(&self) -> usize { - self.words_less_one as usize + 1 - } - - /// Write header to buffer. - pub(crate) fn write_to(&self, buf: &mut [u8]) -> usize { - let fmt: u8 = self.feedback_message_type.into(); - - buf[0] = 0b10_0_00000 | fmt; - buf[1] = self.rtcp_type as u8; - - buf[2..4].copy_from_slice(&self.words_less_one.to_be_bytes()); - - 4 - } -} - -/// Kind of RTCP packet. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RtcpType { - /// RTCP_PT_SR - SenderReport = 200, - - /// RTCP_PT_RR - ReceiverReport = 201, - - /// RTCP_PT_SDES - SourceDescription = 202, - - /// RTCP_PT_BYE - Goodbye = 203, - - /// RTCP_PT_APP - ApplicationDefined = 204, - - /// RTCP_PT_RTPFB - // https://tools.ietf.org/html/rfc4585 - TransportLayerFeedback = 205, - - /// RTCP_PT_PSFB - // https://tools.ietf.org/html/rfc4585 - PayloadSpecificFeedback = 206, - - /// RTCP_PT_XR - ExtendedReport = 207, -} - -impl TryFrom for RtcpType { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - use RtcpType::*; - match v { - 200 => Ok(SenderReport), // sr - 201 => Ok(ReceiverReport), // rr - 202 => Ok(SourceDescription), - 203 => Ok(Goodbye), - 204 => Ok(ApplicationDefined), - 205 => Ok(TransportLayerFeedback), - 206 => Ok(PayloadSpecificFeedback), - 207 => Ok(ExtendedReport), - _ => { - trace!("Unknown RtcpType: {}", v); - Err("Unknown RtcpType") - } - } - } -} - -impl<'a> TryFrom<&'a [u8]> for RtcpHeader { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 4 { - return Err("Need 4 bytes for RTCP header"); - } - - let version = (buf[0] & 0b11_0_00000) >> 6; - if version != 2 { - return Err("RTCP header version should be 2"); - } - - let fmt = buf[0] & 0b00_0_11111; - let rtcp_type: RtcpType = buf[1].try_into()?; - - let feedback_message_type = { - use FeedbackMessageType::*; - match rtcp_type { - RtcpType::SenderReport => ReceptionReport(fmt), - RtcpType::ReceiverReport => ReceptionReport(fmt), - RtcpType::SourceDescription => SourceCount(fmt), - RtcpType::Goodbye => SourceCount(fmt), - RtcpType::ApplicationDefined => Subtype(fmt), - RtcpType::TransportLayerFeedback => TransportFeedback(fmt.try_into()?), - RtcpType::PayloadSpecificFeedback => PayloadFeedback(fmt.try_into()?), - RtcpType::ExtendedReport => NotUsed, - } - }; - - let words_less_one = u16::from_be_bytes([buf[2], buf[3]]); - - Ok(RtcpHeader { - rtcp_type, - feedback_message_type, - words_less_one, - }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/list.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/list.rs deleted file mode 100644 index 52318a78a1a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/list.rs +++ /dev/null @@ -1,251 +0,0 @@ -use std::fmt; -use std::ops::Index; - -/// List containing max 31 items. -#[derive(Clone, PartialEq, Eq)] -pub struct ReportList([Option; 31]); - -impl ReportList { - pub(crate) fn new() -> Self { - ReportList::default() - } - - /// Number of elements in the list. - pub fn len(&self) -> usize { - self.0.iter().position(|i| i.is_none()).unwrap_or(31) - } - - pub(crate) fn push(&mut self, v: T) { - let pos = self.len(); - self.0[pos] = Some(v); - } - - /// Get element at position. - pub fn get(&self, i: usize) -> Option<&T> { - self.0[i].as_ref() - } - - /// Iterator over the elements in the list. - pub fn iter(&self) -> impl Iterator { - self.into_iter() - } - - /// Tells if the list contains zero elements. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub(crate) fn lists_from_iter(iterator: impl IntoIterator) -> Vec { - let mut result = vec![]; - let mut current = Self::default(); - - for (i, item) in iterator.into_iter().enumerate() { - if i % 31 == 0 && i != 0 { - result.push(current); - current = Self::default(); - } - - current.push(item); - } - - if !current.is_empty() { - result.push(current); - } - - result - } - - pub(crate) fn is_full(&self) -> bool { - self.len() == 31 - } -} - -impl ReportList { - pub(crate) fn append_all_possible(&mut self, other: &mut Self, mut words_left: usize) -> usize { - // Position where we start inserting in self. - let pos = self.len(); - - // Max number we can move. - let max = (31 - pos).min(other.len()); - - // after this loop ends, i will hold the number of items moved. - let mut i = 0; - loop { - if i == max { - break; - } - - // first borrow item from other, to check the item size will fit. - let item = other.0[i].as_ref().unwrap(); - let item_size = item.word_size(); - - // can we fit one more item? - if words_left < item_size { - break; - } - - // it fits, move it. - self.0[pos + i] = other.0[i].take(); - - // reduce space left. - words_left -= item_size; - - i += 1; - } - - // shift down remaining in other - for j in i..31 { - other.0[j - i] = other.0[j].take(); - } - - // return number of appended items. - i - } -} - -pub(crate) mod private { - pub trait WordSized { - fn word_size(&self) -> usize; - } -} - -impl Index for ReportList { - type Output = T; - - fn index(&self, index: usize) -> &Self::Output { - self.0[index].as_ref().unwrap() - } -} - -impl Default for ReportList { - fn default() -> Self { - // We don't want to require T: Copy. - ReportList([ - None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, - None, None, None, None, None, None, None, None, None, None, None, None, None, - ]) - } -} - -impl<'a, T> IntoIterator for &'a ReportList { - type Item = &'a T; - type IntoIter = Iter<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - Iter(self, 0) - } -} - -impl IntoIterator for ReportList { - type Item = T; - type IntoIter = IterOwned; - - fn into_iter(self) -> Self::IntoIter { - IterOwned(self, 0) - } -} - -pub struct Iter<'a, T>(&'a ReportList, usize); - -pub struct IterOwned(ReportList, usize); - -impl<'a, T> Iterator for Iter<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option { - if self.1 > 30 { - return None; - } - - let n = self.0.0[self.1].as_ref(); - if n.is_some() { - self.1 += 1; - } - - n - } -} - -impl Iterator for IterOwned { - type Item = T; - - fn next(&mut self) -> Option { - if self.1 > 30 { - return None; - } - - let n = self.0.0[self.1].take(); - if n.is_some() { - self.1 += 1; - } - n - } -} - -impl From for ReportList { - fn from(t: T) -> Self { - let mut l = ReportList::default(); - l.push(t); - l - } -} - -impl fmt::Debug for ReportList { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "[")?; - let len = self.len(); - for (i, s) in self.0.iter().filter_map(|f| f.as_ref()).enumerate() { - if i == len - 1 { - write!(f, "{s:?}")?; - } else { - write!(f, "{s:?},")?; - } - } - write!(f, "]") - } -} - -#[cfg(test)] -mod test { - use super::ReportList; - - #[test] - fn test_lists_from_iter() { - let lists = ReportList::lists_from_iter(0..66); - - assert_eq!(lists.len(), 3); - assert_eq!(lists[0].len(), 31); - assert_eq!(lists[1].len(), 31); - assert_eq!(lists[2].len(), 4); - } - - #[test] - fn test_max_length_iter() { - let list = { - let mut list = ReportList::new(); - for i in 1..=31 { - list.push(i); - } - - list - }; - let sum: u64 = list.iter().sum(); - - assert_eq!(sum, 496); - } - - #[test] - fn test_max_length_into_iter() { - let list = { - let mut list = ReportList::new(); - for i in 1..=31 { - list.push(i); - } - - list - }; - let sum: u64 = list.into_iter().sum(); - - assert_eq!(sum, 496); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/mod.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/mod.rs deleted file mode 100644 index ff2cb682504..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/mod.rs +++ /dev/null @@ -1,701 +0,0 @@ -#![allow(clippy::unusual_byte_groupings)] - -use tracing::debug; -mod header; -use std::collections::VecDeque; - -pub use header::{RtcpHeader, RtcpType}; - -mod list; -pub use list::ReportList; -use list::private::WordSized; - -mod fmt; -pub use fmt::{FeedbackMessageType, PayloadType, TransportType}; - -mod sr; -pub use sr::{SenderInfo, SenderReport}; - -mod rr; -pub use rr::{ReceiverReport, ReceptionReport}; - -mod xr; -pub use xr::{Dlrr, DlrrItem, ExtendedReport, ReportBlock, Rrtr}; - -mod sdes; -pub use sdes::{Descriptions, Sdes, SdesType}; - -mod bb; -pub use bb::Goodbye; - -mod nack; -pub use nack::{Nack, NackEntry}; - -mod pli; -pub use pli::Pli; - -mod fir; -pub use fir::{Fir, FirEntry}; - -mod twcc; -pub use twcc::{Twcc, TwccRecvRegister}; - -mod rtcpfb; -pub use rtcpfb::RtcpFb; - -mod remb; -pub use remb::Remb; - -use super::SeqNo; -use super::Ssrc; -use super::extend_u16; - -pub trait RtcpPacket { - /// The... - fn header(&self) -> RtcpHeader; - - /// Length of entire RTCP packet (including header) in words (4 bytes). - fn length_words(&self) -> usize; - - /// Write this packet to the buffer. - /// - /// Panics if the buffer doesn't have capacity to hold length_words * 4 bytes. - fn write_to(&self, buf: &mut [u8]) -> usize; -} - -/// RTCP reports handled by str0m. -#[allow(clippy::large_enum_variant)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Rtcp { - /// Sender report. Also known as SR. - SenderReport(SenderReport), - /// Receiver report. Also known as RR. - ReceiverReport(ReceiverReport), - /// Extended receiver report. Sometimes called XR. - /// - /// Always sent together with a receiver report. - ExtendedReport(ExtendedReport), - /// Description of Synchronization Sources (senders). - SourceDescription(Descriptions), - /// BYE. When a stream is over. - Goodbye(Goodbye), - /// Reports missing packets. - Nack(Nack), - /// Picture Loss Indiciation. When decoding a picture is not possible. - Pli(Pli), - /// Full Intra Request. Complete restart of a video decoder. - Fir(Fir), - /// Transport Wide Congestion Control. Feedback for every received RTP packet. - Twcc(Twcc), - /// Receiver Estimated Maximum Bitrate. Feedback to the sender about the maximum bitrate. - Remb(Remb), -} - -impl Rtcp { - pub(crate) fn read_packet(buf: &[u8], feedback: &mut VecDeque) { - let mut buf = buf; - loop { - if buf.is_empty() { - break; - } - - let header: RtcpHeader = match buf.try_into() { - Ok(v) => v, - Err(e) => { - debug!("{}", e); - break; - } - }; - let has_padding = buf[0] & 0b00_1_00000 > 0; - let full_length = header.length_words() * 4; - - if full_length > buf.len() { - // this length is incorrect. - break; - } - - let unpadded_length = if has_padding { - let pad = buf[full_length - 1] as usize; - if full_length < pad { - debug!("buf.len() is less than padding: {} < {}", full_length, pad); - break; - } - full_length - pad - } else { - full_length - }; - - match (&buf[..unpadded_length]).try_into() { - Ok(v) => feedback.push_back(v), - Err(e) => debug!("{}", e), - } - - buf = &buf[full_length..]; - } - } - - pub(crate) fn write_packet(feedback: &mut VecDeque, buf: &mut [u8], mut output: impl FnMut(Rtcp)) -> usize { - if feedback.is_empty() { - return 0; - } - - // Total length, in bytes, shrunk to be on the pad_to boundary. - let total_len = buf.len(); - - // Capacity in words - let word_capacity = total_len / 4; - - // Pack RTCP feedback packets. Merge together ones of the same type. - Rtcp::pack(feedback, word_capacity); - - let mut offset = 0; - while let Some(fb) = feedback.front() { - // Length of next item. - let item_len = fb.length_words() * 4; - - // Capacity left in the buffer. - let capacity = total_len - offset; - if capacity < item_len { - break; - } - - // We definitely can fit the next RTCP item. - let fb = feedback.pop_front().unwrap(); - let written = fb.write_to(&mut buf[offset..]); - - assert_eq!(written, item_len, "length_words equals write_to length: {fb:?}"); - - // When debugging we can pass an output to get the serialized packets. - output(fb); - - // Move offsets for the amount written. - offset += item_len; - } - - offset - } - - fn merge(&mut self, other: &mut Rtcp, words_left: usize) -> bool { - match (self, other) { - // Stack receiver reports into sender reports. - (Rtcp::SenderReport(sr), Rtcp::ReceiverReport(rr)) => { - let n = sr.reports.append_all_possible(&mut rr.reports, words_left); - n > 0 - } - - // Stack receiver reports. - (Rtcp::ReceiverReport(r1), Rtcp::ReceiverReport(r2)) => { - let n = r1.reports.append_all_possible(&mut r2.reports, words_left); - n > 0 - } - - // Stack source descriptions. - (Rtcp::SourceDescription(s1), Rtcp::SourceDescription(s2)) => { - let n = s1.reports.append_all_possible(&mut s2.reports, words_left); - n > 0 - } - - // Stack source descriptions. - (Rtcp::Goodbye(g1), Rtcp::Goodbye(g2)) => { - let n = g1.reports.append_all_possible(&mut g2.reports, words_left); - n > 0 - } - - // Stack Nack - (Rtcp::Nack(n1), Rtcp::Nack(n2)) if n1.ssrc == n2.ssrc => { - let n = n1.reports.append_all_possible(&mut n2.reports, words_left); - n > 0 - } - - // Stack source descriptions. - (Rtcp::Fir(f1), Rtcp::Fir(f2)) => { - let n = f1.reports.append_all_possible(&mut f2.reports, words_left); - n > 0 - } - - // No merge possible - _ => false, - } - } - - fn is_full(&self) -> bool { - match self { - Rtcp::SenderReport(v) => v.reports.is_full(), - Rtcp::ReceiverReport(v) => v.reports.is_full(), - Rtcp::ExtendedReport(_) => true, - Rtcp::SourceDescription(v) => v.reports.is_full(), - Rtcp::Goodbye(v) => v.reports.is_full(), - Rtcp::Nack(v) => v.reports.is_full(), - Rtcp::Pli(_) => true, - Rtcp::Fir(v) => v.reports.is_full(), - Rtcp::Twcc(_) => true, - Rtcp::Remb(_) => true, - } - } - - /// If this RtcpFb contains no reports (anymore). This can happen after - /// merging reports together. - fn is_empty(&self) -> bool { - match self { - // A SenderReport always has, at least, the SenderInfo part. - Rtcp::SenderReport(_) => false, - // ReceiverReport can become empty. - Rtcp::ReceiverReport(v) => v.reports.is_empty(), - // ExtendedReport can become empty. - Rtcp::ExtendedReport(v) => v.blocks.is_empty(), - // SourceDescription can become empty. - Rtcp::SourceDescription(v) => v.reports.is_empty(), - // Goodbye can become empty, - Rtcp::Goodbye(v) => v.reports.is_empty(), - // Nack can become empty - Rtcp::Nack(v) => v.reports.is_empty(), - // Nack is never empty - Rtcp::Pli(_) => false, - // Fir can be merged to empty. - Rtcp::Fir(v) => v.reports.is_empty(), - // A twcc report is never empty. - Rtcp::Twcc(_) => false, - // A REMB report is never empty. - Rtcp::Remb(_) => false, - } - } - - fn pack(feedback: &mut VecDeque, mut word_capacity: usize) { - // Index into feedback of item we are to pack into. - let mut i = 0; - let len = feedback.len(); - - // Need at least on feedback to pack into, and one to take from. - if len < 2 { - return; - } - - // SenderReport/ReceiveReport first for SRTCP. - feedback.make_contiguous().sort_by_key(Self::order_no); - - 'outer: loop { - // If we reach last element, there is no more packing to do. - if i == len - 1 { - break; - } - - let (pack_into, pack_from) = feedback.make_contiguous().split_at_mut(i + 1); - let fb_a = pack_into.last_mut().unwrap(); - - // abort if fb_a won't fit in the spare capacity. - if word_capacity < fb_a.length_words() { - break 'outer; - } - - // if we manage to merge anything into fb_a. - let mut any_change = false; - - // fb_b goes from the item _after_ i - for fb_b in pack_from { - // if fb_a is full (or empty), we don't want to move any more elements into fb_a. - if fb_a.is_full() || fb_a.is_empty() { - break; - } - - // abort if fb_a won't fit in the spare capacity. - if word_capacity < fb_a.length_words() { - break 'outer; - } - - // amount of capacity (in words) left to fill. - let capacity = word_capacity - fb_a.length_words(); - - // attempt to merge some elements into fb_a from fb_b. - let did_merge = fb_a.merge(fb_b, capacity); - any_change |= did_merge; - } - - if !any_change { - word_capacity -= fb_a.length_words(); - i += 1; - } - } - - // Prune empty. - feedback.retain(|f| !f.is_empty()); - } - - fn order_no(&self) -> u8 { - use Rtcp::*; - match self { - // SenderReport/ReceiverReport first since they possibly contain - // the SSRC for the SRTCP encryption. - SenderReport(_) => 0, - ReceiverReport(_) => 1, - - SourceDescription(_) => 2, - Nack(_) => 3, - Pli(_) => 4, - Fir(_) => 5, - Twcc(_) => 6, - Remb(_) => 7, - ExtendedReport(_) => 10, - - // Goodbye last since they remove stuff. - Goodbye(_) => 11, - } - } -} - -impl RtcpPacket for Rtcp { - fn header(&self) -> RtcpHeader { - match self { - Rtcp::SenderReport(v) => v.header(), - Rtcp::ReceiverReport(v) => v.header(), - Rtcp::ExtendedReport(v) => v.header(), - Rtcp::SourceDescription(v) => v.header(), - Rtcp::Goodbye(v) => v.header(), - Rtcp::Nack(v) => v.header(), - Rtcp::Pli(v) => v.header(), - Rtcp::Fir(v) => v.header(), - Rtcp::Twcc(v) => v.header(), - Rtcp::Remb(v) => v.header(), - } - } - - fn length_words(&self) -> usize { - match self { - Rtcp::SenderReport(v) => v.length_words(), - Rtcp::ReceiverReport(v) => v.length_words(), - Rtcp::ExtendedReport(v) => v.length_words(), - Rtcp::SourceDescription(v) => v.length_words(), - Rtcp::Goodbye(v) => v.length_words(), - Rtcp::Nack(v) => v.length_words(), - Rtcp::Pli(v) => v.length_words(), - Rtcp::Fir(v) => v.length_words(), - Rtcp::Twcc(v) => v.length_words(), - Rtcp::Remb(v) => v.length_words(), - } - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - match self { - Rtcp::SenderReport(v) => v.write_to(buf), - Rtcp::ReceiverReport(v) => v.write_to(buf), - Rtcp::ExtendedReport(v) => v.write_to(buf), - Rtcp::SourceDescription(v) => v.write_to(buf), - Rtcp::Goodbye(v) => v.write_to(buf), - Rtcp::Nack(v) => v.write_to(buf), - Rtcp::Pli(v) => v.write_to(buf), - Rtcp::Fir(v) => v.write_to(buf), - Rtcp::Twcc(v) => v.write_to(buf), - Rtcp::Remb(v) => v.write_to(buf), - } - } -} - -impl<'a> TryFrom<&'a [u8]> for Rtcp { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - let header: RtcpHeader = buf.try_into()?; - - // By constraining the length, all subparsing can go - // until they exhaust the buffer length. This presupposes - // padding is removed from the input. - let buf = &buf[4..]; - - Ok(match header.rtcp_type() { - RtcpType::SenderReport => Rtcp::SenderReport(buf.try_into()?), - RtcpType::ReceiverReport => Rtcp::ReceiverReport(buf.try_into()?), - RtcpType::SourceDescription => Rtcp::SourceDescription(buf.try_into()?), - RtcpType::Goodbye => Rtcp::Goodbye((header.count(), buf).try_into()?), - RtcpType::ApplicationDefined => return Err("Ignore RTCP type: ApplicationDefined"), - RtcpType::TransportLayerFeedback => { - let tlfb = match header.feedback_message_type() { - FeedbackMessageType::TransportFeedback(v) => v, - _ => return Err("Expected TransportFeedback in FeedbackMessageType"), - }; - - match tlfb { - TransportType::Nack => Rtcp::Nack(buf.try_into()?), - TransportType::TransportWide => Rtcp::Twcc(buf.try_into()?), - } - } - RtcpType::PayloadSpecificFeedback => { - let plfb = match header.feedback_message_type() { - FeedbackMessageType::PayloadFeedback(v) => v, - _ => return Err("Expected PayloadFeedback in FeedbackMessageType"), - }; - - match plfb { - PayloadType::PictureLossIndication => Rtcp::Pli(buf.try_into()?), - PayloadType::SliceLossIndication => return Err("Ignore PayloadType type: SLI"), - PayloadType::ReferencePictureSelectionIndication => { - return Err("Ignore PayloadType type: RPSI"); - } - PayloadType::FullIntraRequest => Rtcp::Fir(buf.try_into()?), - PayloadType::ApplicationLayer => { - if header.rtcp_type() == RtcpType::PayloadSpecificFeedback { - if let Ok(remb) = Remb::try_from(buf) { - return Ok(Rtcp::Remb(remb)); - } - } - return Err("Ignore PayloadType: ApplicationLayer"); - } - } - } - RtcpType::ExtendedReport => Rtcp::ExtendedReport(buf.try_into()?), - }) - } -} - -impl WordSized for Ssrc { - fn word_size(&self) -> usize { - 1 - } -} - -/// Pad up to the next word (4 byte) boundary. -fn pad_bytes_to_word(n: usize) -> usize { - let pad = 4 - n % 4; - if pad == 4 { n } else { n + pad } -} - -#[cfg(test)] -mod test { - use std::time::{Duration, SystemTime}; - - use crate::vendor::str0m::rtp_::MediaTime; - - use super::twcc::{Delta, PacketChunk, PacketStatus}; - use super::*; - - #[test] - fn padding_of_rtcp() { - let mut queue = VecDeque::new(); - let mut twcc = Twcc { - sender_ssrc: 1.into(), - ssrc: 0.into(), - base_seq: 82, - status_count: 3, - reference_time: 25, - feedback_count: 17, - chunks: VecDeque::new(), - delta: VecDeque::new(), - }; - twcc.chunks - .push_back(PacketChunk::Run(PacketStatus::ReceivedSmallDelta, 3)); - twcc.delta.push_back(Delta::Small(0x7c)); - twcc.delta.push_back(Delta::Small(0x93)); - twcc.delta.push_back(Delta::Small(0x84)); - queue.push_back(Rtcp::Twcc(twcc)); - let mut buf = vec![0; 1500]; - let n = Rtcp::write_packet(&mut queue, &mut buf, |_| {}); - buf.truncate(n); - println!("{buf:02x?}"); - assert_eq!( - &buf, - &[ - // TWCC 0xaf got padding bit set - 0xaf, 0xcd, 0x00, 0x06, // - 0x00, 0x00, 0x00, 0x01, // sender SSRC - 0x00, 0x00, 0x00, 0x00, // media SSRC - 0x00, 0x52, // base seq - 0x00, 0x03, // status count - 0x00, 0x00, 0x19, // reference time - 0x11, // feedback count - 0x20, 0x03, // run of 3 - 0x7c, 0x93, 0x84, // three small delta - 0x00, 0x00, 0x03 // padding - ] - ); - } - - #[test] - fn pack_sr_4_rr() { - let now = SystemTime::now(); - let mut queue = VecDeque::new(); - queue.push_back(rr(3)); - queue.push_back(rr(4)); - queue.push_back(rr(5)); - queue.push_back(sr(1, now)); // should be sorted to front - - Rtcp::pack(&mut queue, 350); - - assert_eq!(queue.len(), 1); - - let sr = match queue.pop_front().unwrap() { - Rtcp::SenderReport(v) => v, - _ => unreachable!(), - }; - - assert_eq!(sr.reports.len(), 4); - let mut iter = sr.reports.iter(); - assert_eq!(iter.next().unwrap(), &report(2)); - assert_eq!(iter.next().unwrap(), &report(3)); - assert_eq!(iter.next().unwrap(), &report(4)); - assert_eq!(iter.next().unwrap(), &report(5)); - } - - #[test] - fn pack_4_rr() { - let mut queue = VecDeque::new(); - queue.push_back(rr(1)); - queue.push_back(rr(2)); - queue.push_back(rr(3)); - queue.push_back(rr(4)); - - Rtcp::pack(&mut queue, 350); - - assert_eq!(queue.len(), 1); - - let sr = match queue.pop_front().unwrap() { - Rtcp::ReceiverReport(v) => v, - _ => unreachable!(), - }; - - assert_eq!(sr.reports.len(), 4); - let mut iter = sr.reports.iter(); - assert_eq!(iter.next().unwrap(), &report(1)); - assert_eq!(iter.next().unwrap(), &report(2)); - assert_eq!(iter.next().unwrap(), &report(3)); - assert_eq!(iter.next().unwrap(), &report(4)); - } - - #[test] - fn roundtrip_sr_rr() { - let now = SystemTime::now(); - let mut feedback = VecDeque::new(); - feedback.push_back(sr(1, now)); - feedback.push_back(rr(3)); - feedback.push_back(rr(4)); - feedback.push_back(rr(5)); - - let mut buf = vec![0_u8; 1360]; - let n = Rtcp::write_packet(&mut feedback, &mut buf, |_| {}); - buf.truncate(n); - - let mut parsed = VecDeque::new(); - Rtcp::read_packet(&buf, &mut parsed); - - let Rtcp::SenderReport(s) = parsed.get(0).unwrap() else { - panic!("Not a SenderReport in Rtcp"); - }; - let now2 = s.sender_info.ntp_time; - - let mut compare = VecDeque::new(); - compare.push_back(sr(1, now2)); - compare.push_back(rr(3)); - compare.push_back(rr(4)); - compare.push_back(rr(5)); - Rtcp::pack(&mut compare, 1400); - - assert_eq!(parsed, compare); - - // Ensure ntp_time is not too far off. - let abs = abs_time_delta(now, now2); - assert!(abs < Duration::from_millis(1)); - } - - fn abs_time_delta(st1: SystemTime, st2: SystemTime) -> Duration { - let delta = if st1 > st2 { - st1.duration_since(st2) - } else { - st2.duration_since(st1) - }; - delta.expect("delta should be absolute") - } - - fn sr(ssrc: u32, ntp_time: SystemTime) -> Rtcp { - Rtcp::SenderReport(SenderReport { - sender_info: SenderInfo { - ssrc: ssrc.into(), - ntp_time, - rtp_time: MediaTime::from_secs(4), - sender_packet_count: 5, - sender_octet_count: 6, - }, - reports: report(2).into(), - }) - } - - fn rr(ssrc: u32) -> Rtcp { - Rtcp::ReceiverReport(ReceiverReport { - sender_ssrc: 42.into(), - reports: report(ssrc).into(), - }) - } - - fn report(ssrc: u32) -> ReceptionReport { - ReceptionReport { - ssrc: ssrc.into(), - fraction_lost: 3, - packets_lost: 1234, - max_seq: 4000, - jitter: 5, - last_sr_time: 12, - last_sr_delay: 1, - } - } - - // fn sdes(ssrc: u32) -> RtcpFb { - // RtcpFb::Sdes(Sdes { - // ssrc: ssrc.into(), - // values: vec![ - // (SdesType::NAME, "Martin".into()), - // (SdesType::TOOL, "str0m".into()), - // (SdesType::NOTE, "Writing things right here".into()), - // ], - // }) - // } - - // fn nack(ssrc: u32, pid: u16) -> RtcpFb { - // RtcpFb::Nack(Nack { - // ssrc: ssrc.into(), - // pid, - // blp: 0b1010_0101, - // }) - // } - - // fn gb(ssrc: u32) -> RtcpFb { - // RtcpFb::Goodbye(ssrc.into()) - // } - - #[test] - fn fuzz_failures() { - const TESTS: &[&[u8]] = &[ - // - &[133, 201, 0, 0], - &[191, 202, 54, 74], - &[166, 202, 0, 2, 218, 54, 214, 222, 160, 2, 146, 0, 251], - &[ - 151, 203, 0, 40, 88, 236, 217, 19, 82, 62, 73, 84, 112, 252, 69, 78, 38, 72, 43, 4, 21, 136, 90, 29, - 89, 70, 90, 196, 149, 168, 54, 1, 57, 16, 128, 8, 53, 172, 192, 248, 175, 7, 92, 54, 82, 153, 179, 204, - 181, 64, 94, 211, 67, 77, 110, 252, 181, 18, 53, 48, 180, 179, 205, 234, 139, 61, 179, 54, 19, 120, 79, - 119, 232, 208, 210, 73, 78, 28, 242, 156, 242, 239, 19, 246, 183, 10, 49, 114, 216, 64, 105, 161, 50, - 99, 156, 113, 153, 90, 207, 53, 145, 96, 158, 198, 224, 114, 9, 20, 30, 156, 220, 56, 151, 216, 164, - 129, 156, 40, 85, 70, 189, 210, 146, 242, 242, 55, 70, 144, 113, 9, 44, 74, 22, 123, 180, 153, 18, 88, - 1, 185, 85, 227, 200, 62, 53, 142, 89, 28, 37, 128, 223, 36, 248, 117, 26, 182, 173, 112, 42, 1, 2, - 117, 203, 114, 179, - ], - &[ - 150, 202, 0, 54, 0, 149, 201, 0, 0, 138, 201, 0, 0, 152, 201, 0, 0, 151, 201, 0, 0, 150, 201, 0, 0, - 141, 201, 0, 0, 159, 201, 0, 0, 150, 201, 0, 0, 159, 201, 0, 0, 134, 201, 0, 0, 143, 201, 0, 0, 162, - 201, 0, 0, 166, 201, 0, 0, 177, 201, 0, 0, 182, 201, 0, 0, 131, 201, 0, 0, 164, 201, 0, 0, 133, 201, 0, - 0, 143, 201, 0, 0, 174, 201, 0, 0, 186, 201, 0, 0, 165, 201, 0, 0, 173, 201, 0, 0, 186, 201, 0, 0, 166, - 201, 0, 0, 159, 201, 0, 0, 158, 201, 0, 0, 190, 201, 0, 0, 156, 201, 0, 0, 147, 201, 0, 0, 169, 201, 0, - 0, 135, 201, 0, 0, 148, 201, 0, 0, 132, 201, 0, 0, 138, 201, 0, 0, 162, 201, 0, 0, 185, 201, 0, 0, 157, - 201, 0, 0, 183, 201, 0, 0, 145, 201, 0, 0, 130, 201, 0, 0, 183, 201, 0, 0, 152, 201, 0, 0, 153, 201, 0, - 0, 154, 201, 0, 0, 138, 201, 0, 0, 148, 201, 0, 0, 158, 201, 0, 0, 156, 201, 0, 0, 181, 201, 0, 0, 173, - 201, 0, 0, 171, 201, 0, 0, 169, 201, 0, 0, 167, 201, 41, 216, - ], - &[ - 143, 205, 0, 8, 143, 93, 208, 93, 201, 4, 131, 131, 131, 3, 0, 143, 1, 143, 0, 143, 0, 80, 143, 231, - 231, 0, 143, 181, 202, 0, 143, 236, 242, 0, 238, 21, - ], - ]; - - let mut parsed = VecDeque::new(); - - for t in TESTS { - parsed.clear(); - Rtcp::read_packet(t, &mut parsed); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/nack.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/nack.rs deleted file mode 100644 index 12f228b0644..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/nack.rs +++ /dev/null @@ -1,153 +0,0 @@ -use super::extend_u16; -use super::{FeedbackMessageType, ReportList, RtcpHeader, RtcpPacket, SeqNo}; -use super::{RtcpType, Ssrc, TransportType}; - -use super::list::private::WordSized; - -/// A NACK entry indiciating packets missing. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Nack { - /// Sender of this feedback. Mostly irrelevant, but part of RTCP packets. - pub sender_ssrc: Ssrc, - /// The SSRC this nack reports missing packets for. - pub ssrc: Ssrc, - /// The missing nack. This can be multiple segments. - pub reports: ReportList, -} - -/// A range of sequence numbers missing. -#[allow(missing_docs)] -#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)] -pub struct NackEntry { - pub pid: u16, - pub blp: u16, -} - -impl RtcpPacket for Nack { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::TransportLayerFeedback, - feedback_message_type: FeedbackMessageType::TransportFeedback(TransportType::Nack), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // header - // sender SSRC - // media SSRC - // 1 word per NackPair - 1 + 2 + self.reports.len() - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(&mut buf[..4]); - buf[4..8].copy_from_slice(&self.sender_ssrc.to_be_bytes()); - buf[8..12].copy_from_slice(&self.ssrc.to_be_bytes()); - let mut buf = &mut buf[12..]; - for r in &self.reports { - buf[0..2].copy_from_slice(&r.pid.to_be_bytes()); - buf[2..4].copy_from_slice(&r.blp.to_be_bytes()); - buf = &mut buf[4..]; - } - self.length_words() * 4 - } -} - -impl WordSized for NackEntry { - fn word_size(&self) -> usize { - 1 - } -} - -impl<'a> TryFrom<&'a [u8]> for Nack { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 12 { - return Err("Nack less than 12 bytes"); - } - - let sender_ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]).into(); - - let mut reports = ReportList::new(); - - let mut buf = &buf[8..]; - let count = buf.len() / 4; - let max = count.min(31); - - for _ in 0..max { - let pid = u16::from_be_bytes([buf[0], buf[1]]); - let blp = u16::from_be_bytes([buf[2], buf[3]]); - reports.push(NackEntry { pid, blp }); - buf = &buf[4..]; - } - - Ok(Nack { - sender_ssrc, - ssrc, - reports, - }) - } -} - -impl NackEntry { - /// Iterator over sequence numbers missing. - /// - /// The given sequence number is used to interpret ROC. - pub fn into_iter(self, seq_no: SeqNo) -> impl Iterator { - NackEntryIterator(self, 0, seq_no) - } -} - -pub struct NackEntryIterator(NackEntry, u16, SeqNo); - -impl Iterator for NackEntryIterator { - type Item = SeqNo; - - fn next(&mut self) -> Option { - let seq_16 = if self.1 == 0 { - self.1 += 1; - self.0.pid - } else { - loop { - if self.1 >= 17 { - return None; - } - let i = self.1 - 1; - self.1 += 1; - if 1 << i & self.0.blp > 0 { - break self.0.pid.wrapping_add(self.1 - 1); - } - } - }; - let l = extend_u16(Some(*self.2), seq_16); - Some(l.into()) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn nack_entry_iter() { - // 196_618 - let seq_no: SeqNo = (65_536_u64 * 3 + 10).into(); - - // 196_508 - let pid = (65_536_u32 - 100) as u16; - - println!("{seq_no:?} {pid:?}"); - - // 196_509, 196_512, 196_524 - let blp = 0b1000_0000_0000_1001; - - let entry = NackEntry { pid, blp }; - - let nacks: Vec<_> = entry.into_iter(seq_no).collect(); - - assert_eq!(nacks, vec![196508.into(), 196509.into(), 196512.into(), 196524.into()]); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/pli.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/pli.rs deleted file mode 100644 index e8e7008a531..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/pli.rs +++ /dev/null @@ -1,50 +0,0 @@ -use super::{FeedbackMessageType, PayloadType, RtcpHeader, RtcpPacket}; -use super::{RtcpType, Ssrc}; - -/// Picture loss indicator. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Pli { - /// Sender of this feedback. Mostly irrelevant, but part of RTCP packets. - pub sender_ssrc: Ssrc, - /// The SSRC this picture loss indication is for. - pub ssrc: Ssrc, -} - -impl RtcpPacket for Pli { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::PayloadSpecificFeedback, - feedback_message_type: FeedbackMessageType::PayloadFeedback(PayloadType::PictureLossIndication), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // header - // sender SSRC - // media SSRC - 3 - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(&mut buf[..4]); - buf[4..8].copy_from_slice(&self.sender_ssrc.to_be_bytes()); - buf[8..12].copy_from_slice(&self.ssrc.to_be_bytes()); - 12 - } -} - -impl<'a> TryFrom<&'a [u8]> for Pli { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 8 { - return Err("Pli less than 8 bytes"); - } - - let sender_ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]).into(); - - Ok(Pli { sender_ssrc, ssrc }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/remb.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/remb.rs deleted file mode 100644 index 65da13ab392..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/remb.rs +++ /dev/null @@ -1,300 +0,0 @@ -use crate::vendor::str0m::rtp::Ssrc; - -use super::RtcpType; -use super::{FeedbackMessageType, PayloadType, RtcpHeader, RtcpPacket}; - -const BITRATE_MAX: f32 = 2.417_842_4e24; //0x3FFFFp+63; -const MANTISSA_MAX: u32 = 0x7FFFFF; -const REMB_OFFSET: usize = 16; - -const UNIQUE_IDENTIFIER: [u8; 4] = *b"REMB"; - -/* - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |V=2|P| FMT=15 | PT=206 | length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | SSRC of packet sender | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | SSRC of media source | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Unique identifier 'R' 'E' 'M' 'B' | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Num SSRC | BR Exp | BR Mantissa | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | SSRC feedback | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | ... | -*/ - -#[derive(Debug, Clone)] -pub struct Remb { - /// SSRC of sender - pub sender_ssrc: Ssrc, - - /// SSRC of source, in Remb is default 0 - pub ssrc: Ssrc, - - /// Estimated maximum bitrate - pub bitrate: f32, - - /// SSRC entries which this packet applies to - pub ssrcs: Vec, -} - -impl Eq for Remb {} -impl PartialEq for Remb { - fn eq(&self, other: &Self) -> bool { - self.sender_ssrc == other.sender_ssrc - && (self.bitrate as u64) == (other.bitrate as u64) - && self.ssrcs == other.ssrcs - } -} - -impl RtcpPacket for Remb { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::PayloadSpecificFeedback, - feedback_message_type: FeedbackMessageType::PayloadFeedback(PayloadType::ApplicationLayer), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // header - // remb - // ssrcs - 1 + REMB_OFFSET / 4 + self.ssrcs.len() - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - let mut exp = 0; - let mut bitrate = self.bitrate.clamp(0.0, BITRATE_MAX); - - while bitrate >= (1 << 18) as f32 { - bitrate /= 2.0; - exp += 1; - } - - let mantissa = bitrate.floor() as u32; - - self.header().write_to(&mut buf[..4]); - buf[4..8].copy_from_slice(&self.sender_ssrc.to_be_bytes()); - buf[8..12].copy_from_slice(&[0; 4]); - buf[12..16].copy_from_slice(&UNIQUE_IDENTIFIER); - buf[16] = self.ssrcs.len() as u8; - // We can't quite use the binary package because - // a) it's a uint24 and b) the exponent is only 6-bits - // Just trust me; this is big-endian encoding. - buf[17] = (exp << 2) as u8 | (mantissa >> 16) as u8; - buf[18] = (mantissa >> 8) as u8; - buf[19] = mantissa as u8; - - // Write the SSRCs at the very end. - for (index, ssrc) in self.ssrcs.iter().enumerate() { - let begin = 4 + REMB_OFFSET + index * 4; - let end = begin + 4; - buf[begin..end].copy_from_slice(&ssrc.to_be_bytes()); - } - - 4 + REMB_OFFSET + self.ssrcs.len() * 4 - } -} - -impl<'a> TryFrom<&'a [u8]> for Remb { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 16 { - return Err("Remb less than 16 bytes"); - } - - let sender_ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let media_ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - if media_ssrc != 0 { - return Err("Ssrc must be zero"); - } - - if buf[8] != UNIQUE_IDENTIFIER[0] - || buf[9] != UNIQUE_IDENTIFIER[1] - || buf[10] != UNIQUE_IDENTIFIER[2] - || buf[11] != UNIQUE_IDENTIFIER[3] - { - return Err("Missing remb identifier"); - } - - // The next byte is the number of SSRC entries at the end. - let ssrcs_len = buf[12] as usize; - - // Get the 6-bit exponent value. - let b17 = buf[13]; - let mut exp = (b17 as u64) >> 2; - exp += 127; // bias for IEEE754 - exp += 23; // IEEE754 biases the decimal to the left, abs-send-time biases it to the right - - // The remaining 2-bits plus the next 16-bits are the mantissa. - let b18 = buf[14]; - let b19 = buf[15]; - let mut mantissa = ((b17 & 3) as u32) << 16 | (b18 as u32) << 8 | b19 as u32; - - if mantissa != 0 { - // ieee754 requires an implicit leading bit - while (mantissa & (MANTISSA_MAX + 1)) == 0 { - exp -= 1; - mantissa *= 2; - } - } - - // bitrate = mantissa * 2^exp - let bitrate = f32::from_bits(((exp as u32) << 23) | (mantissa & MANTISSA_MAX)); - - // `ssrcs_len` is attacker-controlled byte (buf[12], 0..=255) - // reject packets too short to hold that many trailing SSRC bytes. - if buf.len() < REMB_OFFSET + ssrcs_len * 4 { - return Err("Remb ssrcs length exceeds buffer"); - } - - let mut ssrcs = vec![]; - for i in 0..ssrcs_len { - let b_index = 16 + i * 4; - ssrcs.push(u32::from_be_bytes([ - buf[b_index], - buf[b_index + 1], - buf[b_index + 2], - buf[b_index + 3], - ])); - } - - Ok(Remb { - sender_ssrc, - ssrc: 0.into(), - ssrcs, - bitrate, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_receiver_estimated_maximum_bitrate_marshal() { - let input = Remb { - sender_ssrc: 1.into(), - ssrc: 0.into(), - bitrate: 8927168.0, - ssrcs: vec![1215622422], - }; - - let expected = [ - 143, 206, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 82, 69, 77, 66, 1, 26, 32, 223, 72, 116, 237, 22, - ]; - - let mut output = [0; 1500]; - let len = input.write_to(&mut output); - assert_eq!(expected, output[0..len]); - } - - #[test] - fn test_receiver_estimated_maximum_bitrate_unmarshal() { - // Real data sent by Chrome while watching a 6Mb/s stream - let input = [ - 143, 206, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 82, 69, 77, 66, 1, 26, 32, 223, 72, 116, 237, 22, - ]; - - // mantissa = []byte{26 & 3, 32, 223} = []byte{2, 32, 223} = 139487 - // exp = 26 >> 2 = 6 - // bitrate = 139487 * 2^6 = 139487 * 64 = 8927168 = 8.9 Mb/s - let expected = Remb { - sender_ssrc: 1.into(), - ssrc: 0.into(), - bitrate: 8927168.0, - ssrcs: vec![1215622422], - }; - - let packet = Remb::try_from(&input[4..]).unwrap(); - assert_eq!(expected, packet); - } - - #[test] - fn test_receiver_estimated_maximum_bitrate_truncate() { - let input = [ - 143, 206, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 82, 69, 77, 66, 1, 26, 32, 223, 72, 116, 237, 22, - ]; - - // Make sure that we're interpreting the bitrate correctly. - // For the above example, we have: - - // mantissa = 139487 - // exp = 6 - // bitrate = 8927168 - - let mut packet = Remb::try_from(&input[4..]).unwrap(); - assert_eq!(8927168.0, packet.bitrate); - - // Just verify marshal produces the same input. - let mut output = [0; 1500]; - let output_len = packet.write_to(&mut output); - assert_eq!(input, output[0..output_len]); - - // If we subtract the bitrate by 1, we'll round down a lower mantissa - packet.bitrate -= 1.0; - - // bitrate = 8927167 - // mantissa = 139486 - // exp = 6 - - let output_len = packet.write_to(&mut output); - assert_ne!(input, output[0..output_len]); - let expected = [ - 143, 206, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 82, 69, 77, 66, 1, 26, 32, 222, 72, 116, 237, 22, - ]; - assert_eq!(expected, output[0..output_len]); - - // Which if we actually unmarshal again, we'll find that it's actually decreased by 63 (which is exp) - // mantissa = 139486 - // exp = 6 - // bitrate = 8927104 - - let packet = Remb::try_from(&output[4..]).unwrap(); - assert_eq!(8927104.0, packet.bitrate); - } - - #[test] - fn test_receiver_estimated_maximum_bitrate_overflow() { - // Marshal a packet with the maximum possible bitrate. - let packet = Remb { - sender_ssrc: 0.into(), - ssrc: 0.into(), - bitrate: f32::MAX, - ssrcs: vec![], - }; - - // mantissa = 262143 = 0x3FFFF - // exp = 63 - - let expected = [143, 206, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 82, 69, 77, 66, 0, 255, 255, 255]; - - let mut output = [0; 1500]; - let output_len = packet.write_to(&mut output); - assert_eq!(expected, output[0..output_len]); - - // mantissa = 262143 - // exp = 63 - // bitrate = 0xFFFFC00000000000 - - let packet = Remb::try_from(&output[4..output_len]).unwrap(); - assert_eq!(f32::from_bits(0x67FFFFC0), packet.bitrate); - - // Make sure we marshal to the same result again. - let output_len = packet.write_to(&mut output); - assert_eq!(expected, output[0..output_len]); - - // Finally, try unmarshalling one number higher than we used to be able to handle. - let input = [143, 206, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 82, 69, 77, 66, 0, 188, 0, 0]; - let packet = Remb::try_from(&input[4..]).unwrap(); - assert_eq!(f32::from_bits(0x62800000), packet.bitrate); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/rr.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/rr.rs deleted file mode 100644 index dcaed2b3877..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/rr.rs +++ /dev/null @@ -1,130 +0,0 @@ -use super::Ssrc; -use super::list::private::WordSized; -use super::{FeedbackMessageType, ReportList, RtcpHeader, RtcpPacket, RtcpType}; - -/// A receiver report. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ReceiverReport { - /// Sender of this feedback. Mostly irrelevant, but part of RTCP packets. - pub sender_ssrc: Ssrc, - /// The individual reports for received SSRC. - pub reports: ReportList, -} - -/// An individual report of reception. -#[allow(missing_docs)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ReceptionReport { - pub ssrc: Ssrc, - pub fraction_lost: u8, - pub packets_lost: u32, // 24 bit - pub max_seq: u32, - pub jitter: u32, - pub last_sr_time: u32, - pub last_sr_delay: u32, -} - -impl RtcpPacket for ReceiverReport { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::ReceiverReport, - feedback_message_type: FeedbackMessageType::ReceptionReport(self.reports.len() as u8), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // * header: 1 - // * sender SSRC - // * reports: x 6 - 1 + 1 + 6 * self.reports.len() - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(buf); - - buf[4..8].copy_from_slice(&self.sender_ssrc.to_be_bytes()); - - for (i, r) in self.reports.iter().enumerate() { - r.write_to(&mut buf[8 + i * 24..]); - } - - self.length_words() * 4 - } -} - -impl WordSized for ReceptionReport { - fn word_size(&self) -> usize { - 6 - } -} - -impl ReceptionReport { - pub(crate) fn write_to(&self, buf: &mut [u8]) { - buf[0..4].copy_from_slice(&self.ssrc.to_be_bytes()); - buf[4..8].copy_from_slice(&self.packets_lost.to_be_bytes()); - buf[4] = self.fraction_lost; - buf[8..12].copy_from_slice(&self.max_seq.to_be_bytes()); - buf[12..16].copy_from_slice(&self.jitter.to_be_bytes()); - buf[16..20].copy_from_slice(&self.last_sr_time.to_be_bytes()); - buf[20..24].copy_from_slice(&self.last_sr_delay.to_be_bytes()); - } -} - -impl<'a> TryFrom<&'a [u8]> for ReceiverReport { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 4 { - return Err("Less than 4 bytes for ReceiverReport"); - } - - let sender_ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - - let mut reports = ReportList::new(); - let mut buf = &buf[4..]; - - let count = buf.len() / 24; - - let max = count.min(31); - - for _ in 0..max { - let report = buf.try_into()?; - reports.push(report); - buf = &buf[24..]; - } - - Ok(ReceiverReport { sender_ssrc, reports }) - } -} - -impl<'a> TryFrom<&'a [u8]> for ReceptionReport { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 24 { - return Err("Less than 24 bytes for ReceptionReport"); - } - - // Receiver report shape is here - // https://www.rfc-editor.org/rfc/rfc3550#section-6.4.2 - - let ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let fraction_lost = buf[4]; - let packets_lost = u32::from_be_bytes([0, buf[5], buf[6], buf[7]]); - let max_seq = u32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]); - let jitter = u32::from_be_bytes([buf[12], buf[13], buf[14], buf[15]]); - let last_sr_time = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]); - let last_sr_delay = u32::from_be_bytes([buf[20], buf[21], buf[22], buf[23]]); - - Ok(ReceptionReport { - ssrc, - fraction_lost, - packets_lost, - max_seq, - jitter, - last_sr_time, - last_sr_delay, - }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/rtcpfb.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/rtcpfb.rs deleted file mode 100644 index 4644b6ee47c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/rtcpfb.rs +++ /dev/null @@ -1,90 +0,0 @@ -use super::{DlrrItem, FirEntry, NackEntry, ReceptionReport, Remb}; -use super::{ReportBlock, ReportList, Rrtr, Rtcp, Sdes, SenderInfo, Ssrc, Twcc}; - -/// Normalization of [`Rtcp`] so we can deal with one SSRC at a time. -#[allow(clippy::large_enum_variant)] -#[derive(Debug)] -pub enum RtcpFb { - SenderInfo(SenderInfo), // tx -> rx - ReceptionReport(ReceptionReport), // rx -> tx - DlrrItem(DlrrItem), // rx <- tx - Rrtr((Rrtr, Ssrc)), // rx -> tx - SourceDescription(Sdes), // tx -> rx - Goodbye(Ssrc), // tx -> rx - Nack(Ssrc, ReportList), // rx -> tx - Pli(Ssrc), // rx -> tx - Fir(FirEntry), // rx -> tx - Twcc(Twcc), // rx -> tx - Remb(Remb), // rx -> tx -} - -impl RtcpFb { - pub fn is_for_rx(&self) -> bool { - matches!( - self, - RtcpFb::SenderInfo(_) | RtcpFb::SourceDescription(_) | RtcpFb::Goodbye(_) | RtcpFb::DlrrItem(_) - ) - } - - pub fn from_rtcp>(t: T) -> impl Iterator { - let mut q = Vec::new(); - let iter = t.into_iter(); - for pkt in iter { - match pkt { - Rtcp::SenderReport(v) => { - q.push(RtcpFb::SenderInfo(v.sender_info)); - q.extend(v.reports.into_iter().map(RtcpFb::ReceptionReport)); - } - Rtcp::ReceiverReport(v) => { - q.extend(v.reports.into_iter().map(RtcpFb::ReceptionReport)); - } - Rtcp::ExtendedReport(v) => { - for block in v.blocks { - match block { - ReportBlock::Rrtr(b) => q.push(RtcpFb::Rrtr((b, v.ssrc))), - ReportBlock::Dlrr(v) => q.extend(v.items.iter().map(|i| RtcpFb::DlrrItem(*i))), - } - } - } - Rtcp::SourceDescription(v) => { - q.extend(v.reports.into_iter().map(RtcpFb::SourceDescription)); - } - Rtcp::Goodbye(v) => { - q.extend(v.reports.into_iter().map(RtcpFb::Goodbye)); - } - Rtcp::Nack(v) => { - q.push(RtcpFb::Nack(v.ssrc, v.reports)); - } - Rtcp::Pli(v) => { - q.push(RtcpFb::Pli(v.ssrc)); - } - Rtcp::Fir(v) => { - q.extend(v.reports.into_iter().map(RtcpFb::Fir)); - } - Rtcp::Twcc(v) => { - q.push(RtcpFb::Twcc(v)); - } - Rtcp::Remb(v) => { - q.push(RtcpFb::Remb(v)); - } - } - } - q.into_iter() - } - - pub fn ssrc(&self) -> Ssrc { - match self { - RtcpFb::SenderInfo(v) => v.ssrc, - RtcpFb::ReceptionReport(v) => v.ssrc, - RtcpFb::DlrrItem(v) => v.ssrc, - RtcpFb::Rrtr((_, ssrc)) => *ssrc, - RtcpFb::SourceDescription(v) => v.ssrc, - RtcpFb::Goodbye(v) => *v, - RtcpFb::Nack(v, _) => *v, - RtcpFb::Pli(v) => *v, - RtcpFb::Fir(v) => v.ssrc, - RtcpFb::Twcc(v) => v.ssrc, - RtcpFb::Remb(v) => v.ssrcs.first().map(|ssrc| (*ssrc).into()).unwrap_or(v.ssrc), - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/sdes.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/sdes.rs deleted file mode 100644 index 415b6834202..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/sdes.rs +++ /dev/null @@ -1,322 +0,0 @@ -use std::str::from_utf8; - -use super::list::private::WordSized; -use super::{FeedbackMessageType, RtcpType, Ssrc}; -use super::{ReportList, RtcpHeader, RtcpPacket, pad_bytes_to_word}; - -/// Multiple source descriptions (SDES). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Descriptions { - /// The descriptions. - pub reports: Box>, -} - -/// A single source description (SDES). -#[allow(missing_docs)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Sdes { - pub ssrc: Ssrc, - pub values: ReportList<(SdesType, String)>, -} - -/// Types of SDES values. -#[allow(clippy::upper_case_acronyms)] -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -#[allow(missing_docs)] -pub enum SdesType { - /// End of SDES list - END = 0, - /// Canonical name. - CNAME = 1, - /// User name - NAME = 2, - /// User's electronic mail address - EMAIL = 3, - /// User's phone number - PHONE = 4, - /// Geographic user location - LOC = 5, - /// Name of application or tool - TOOL = 6, - /// Notice about the source - NOTE = 7, - /// Private extensions - PRIV = 8, - /// Rtp stream ID. - RtpStreamId = 12, - /// Repaired rtp stream ID. - RepairedRtpStreamId = 13, - /// Who knows - Unknown, -} - -impl RtcpPacket for Descriptions { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::SourceDescription, - feedback_message_type: FeedbackMessageType::SourceCount(self.reports.len() as u8), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // * header: 1 - // * size-per-item * items - 1 + self.reports.iter().map(|r| r.word_size()).sum::() - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(buf); - - let mut buf = &mut buf[4..]; - let mut tot = 4; - - for r in &*self.reports { - let n = r.write_to(buf); - buf = &mut buf[n..]; - tot += n; - } - - tot - } -} - -impl Sdes { - fn write_to(&self, buf: &mut [u8]) -> usize { - buf[..4].copy_from_slice(&self.ssrc.to_be_bytes()); - let mut tot = 4; - - let mut buf = &mut buf[4..]; - for (t, v) in &self.values { - let bytes = v.as_bytes(); - let len = bytes.len(); - - buf[0] = *t as u8; - buf[1] = len as u8; - - buf = &mut buf[2..]; - buf[..len].copy_from_slice(bytes); - - buf = &mut buf[len..]; - tot += 2 + len; - } - - buf[0] = SdesType::END as u8; - buf = &mut buf[1..]; - tot += 1; - - let pad = 4 - tot % 4; - if pad < 4 { - #[allow(clippy::needless_range_loop)] - for i in 0..pad { - buf[i] = SdesType::END as u8; - } - tot += pad; - } - - assert!(tot % 4 == 0, "Sdes is padded to word boundary"); - - tot - } -} - -impl WordSized for Sdes { - fn word_size(&self) -> usize { - let byte_size = 4 - + self - .values - .iter() - // 2 here for 2 byte encoding of type + length - .map(|(_, s)| 2 + s.len()) - .sum::() - + 1; // 1 here for the end byte - - let padded = pad_bytes_to_word(byte_size); - - padded / 4 - } -} - -impl From for SdesType { - fn from(v: u8) -> Self { - use SdesType::*; - match v { - 0 => END, - 1 => CNAME, - 2 => NAME, - 3 => EMAIL, - 4 => PHONE, - 5 => LOC, - 6 => TOOL, - 7 => NOTE, - 8 => PRIV, - 12 => RtpStreamId, - 13 => RepairedRtpStreamId, - _ => Unknown, - } - } -} - -impl<'a> TryFrom<&'a [u8]> for Descriptions { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - let mut reports = ReportList::new(); - - let mut buf = buf; - - loop { - if reports.len() == 31 { - break; - } - // For some reason FF sends us a full SDES and then [0,0,0,0] at the end. - // This can't be interpreted as SDES, so we just ignore it. - if buf.len() < 8 { - break; - } - let report: Sdes = buf.try_into()?; - - let len = report.word_size() * 4; - - reports.push(report); - - // word_size() pads up to a 32-bit boundary and may report more bytes - // than remain for a trailing or truncated chunk. Guard against slicing - // past the end (which would panic) and against a zero len that would - // otherwise spin forever. - if len == 0 || len >= buf.len() { - break; - } - - buf = &buf[len..]; - } - - Ok(Descriptions { - reports: Box::new(reports), - }) - } -} - -impl<'a> TryFrom<&'a [u8]> for Sdes { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 8 { - return Err("Less than 8 bytes for Sdes"); - } - - let ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let mut values = ReportList::new(); - - let mut buf = &buf[4..]; - let mut abs = 0; - - loop { - // SDES items are END-terminated rather than count-bounded, so a - // malformed chunk could contain more than the ReportList capacity. - // Stop at the cap rather than panicking on the 32nd push. - if values.is_full() { - break; - } - - // Per RFC 3550 Section 6.5: - // "The list of items in each chunk MUST be terminated by one or more null octets, - // the first of which is interpreted as an item type of end of list. - // No length octet follows the null item type octet, but additional null octets - // MUST be included if needed to pad until the next 32-bit boundary." - // - // This means we need a special case when there's only a single END byte (0x00) - // at the end of the buffer - it's a valid terminator despite not having a length byte. - if buf.len() == 1 && buf[0] == SdesType::END as u8 { - break; - } - - if buf.len() < 2 { - return Err("Less than 2 bytes for next Sdes value"); - } - - let stype: SdesType = buf[0].into(); - - if matches!(stype, SdesType::END) { - // The end of SDES. - - // Each chunk consists of an SSRC/CSRC identifier followed by a list of - // zero or more items, which carry information about the SSRC/CSRC. - // Each chunk starts on a 32-bit boundary. - // - // Items are contiguous, i.e., items are not individually padded to a - // 32-bit boundary. Text is not null terminated because some multi- - // octet encodings include null octets. - // - // No length octet follows the null item type octet, but additional null - // octets MUST be included if needed to pad until the next 32-bit - // boundary. - - let pad = 4 - abs % 4; - if pad < 4 && buf.len() < pad { - return Err("Not enough buf.len() for Sdes padding"); - } - - break; - } - - let len = buf[1] as usize; - - if buf.len() < 2 + len { - return Err("Not enough buf.len() for Sdes value"); - } - buf = &buf[2..]; - abs += 2; - - if let Ok(value) = from_utf8(&buf[..len]) { - values.push((stype, value.to_string())); - } else { - // failed to read as utf-8. skip. - } - - buf = &buf[len..]; - abs += len; - } - - Ok(Sdes { ssrc, values }) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn computed_and_write_to_equal() { - let mut buf = vec![0; 1500]; - - for i in 1usize..=255 { - let mut r = ReportList::new(); - r.push((SdesType::CNAME, String::from_utf8_lossy(&vec![b'a'; i][..]).to_string())); - let sdes = Sdes { - ssrc: 1.into(), - values: r, - }; - assert_eq!(sdes.write_to(&mut buf), sdes.word_size() * 4); - } - } - - #[test] - fn cname_serialize_deserialize() { - let mut s1 = Sdes { - ssrc: 1.into(), - values: ReportList::new(), - }; - s1.values.push((SdesType::CNAME, "abc123".into())); - - let mut buf = vec![0; 50]; - let n = s1.write_to(&mut buf); - buf.truncate(n); - - println!("{buf:02x?}"); - - let s2: Sdes = buf.as_slice().try_into().unwrap(); - - assert_eq!(s1, s2); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/sr.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/sr.rs deleted file mode 100644 index 995a6a32540..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/sr.rs +++ /dev/null @@ -1,145 +0,0 @@ -use std::time::SystemTime; - -use crate::vendor::str0m::rtp_::MediaTime; -use crate::vendor::str0m::util::SystemTimeExt; - -use super::{FeedbackMessageType, RtcpType, Ssrc}; -use super::{ReceptionReport, ReportList, RtcpHeader, RtcpPacket}; - -/// A report of packets sent. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SenderReport { - /// Information about the sender of this report. - pub sender_info: SenderInfo, - /// A sender report is implicitly also a receiver report. This - /// might hold data that would otherwise come in a separate RR. - pub reports: ReportList, -} - -/// Information about a stream being sent. -/// -/// A subset of the information contained in Sender Reports(SR). -/// -/// See [RFC 3550 6.4.1](https://www.rfc-editor.org/rfc/rfc3550#section-6.4.1) -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct SenderInfo { - /// The SSRC of the SR originator. - pub ssrc: Ssrc, - /// The 64 bit NTP timestamp converted to a [`SystemTime`]. - pub ntp_time: SystemTime, - /// The RTP timestamp that corresponds to the same point in time as the NTP timestamp above. - pub rtp_time: MediaTime, - /// The total number of packets the sender had sent when this information was generated. - pub sender_packet_count: u32, - /// The total number of octets the sender had sent when this information was generated. - pub sender_octet_count: u32, -} - -impl RtcpPacket for SenderReport { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::SenderReport, - feedback_message_type: FeedbackMessageType::ReceptionReport(self.reports.len() as u8), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // * header: 1 - // * sender info: 6 - // * reports: x 6 - 1 + 6 + 6 * self.reports.len() - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - self.header().write_to(buf); - - self.sender_info.write_to(&mut buf[4..]); - - for (i, r) in self.reports.iter().enumerate() { - r.write_to(&mut buf[28 + i * 24..]); - } - - self.length_words() * 4 - } -} -impl SenderInfo { - fn write_to(&self, buf: &mut [u8]) { - // pub ssrc: Ssrc, - // pub ntp_time: MediaTime, - // pub rtp_time: u32, - // pub sender_packet_count: u32, - // pub sender_octet_count: u32, - buf[..4].copy_from_slice(&self.ssrc.to_be_bytes()); - - let mt = self.ntp_time.as_ntp_64(); - buf[4..12].copy_from_slice(&mt.to_be_bytes()); - - buf[12..16].copy_from_slice(&(self.rtp_time.numer() as u32).to_be_bytes()); - buf[16..20].copy_from_slice(&self.sender_packet_count.to_be_bytes()); - buf[20..24].copy_from_slice(&self.sender_octet_count.to_be_bytes()); - } -} - -impl<'a> TryFrom<&'a [u8]> for SenderReport { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - let sender_info = buf.try_into()?; - - let mut reports = ReportList::new(); - let mut buf = &buf[24..]; - - let count = buf.len() / 24; - - let max = count.min(31); - - for _ in 0..max { - let report = buf.try_into()?; - reports.push(report); - buf = &buf[24..]; - } - - Ok(SenderReport { sender_info, reports }) - } -} - -impl<'a> TryFrom<&'a [u8]> for SenderInfo { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 24 { - return Err("Less than 24 bytes for SenderInfo"); - } - - // Sender report shape is here - // https://www.rfc-editor.org/rfc/rfc3550#section-6.4.1 - - let ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - - let ntp_time = u64::from_be_bytes([buf[4], buf[5], buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]]); - let ntp_time = SystemTime::from_ntp_64(ntp_time); - - // https://www.cs.columbia.edu/~hgs/rtp/faq.html#timestamp-computed - // For video, time clock rate is fixed at 90 kHz. The timestamps generated - // depend on whether the application can determine the frame number or not. - // If it can or it can be sure that it is transmitting every frame with a - // fixed frame rate, the timestamp is governed by the nominal frame rate. - // Thus, for a 30 f/s video, timestamps would increase by 3,000 for each - // frame, for a 25 f/s video by 3,600 for each frame. - let rtp_time = u32::from_be_bytes([buf[12], buf[13], buf[14], buf[15]]); - // The base (90kHz etc) is set higher up the stack (in StreamRx to be precise). - let rtp_time = MediaTime::from_secs(rtp_time as u64); - - let sender_packet_count = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]); - let sender_octet_count = u32::from_be_bytes([buf[20], buf[21], buf[22], buf[23]]); - - Ok(SenderInfo { - ssrc, - ntp_time, - rtp_time, - sender_packet_count, - sender_octet_count, - }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/twcc.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/twcc.rs deleted file mode 100644 index 974549a1499..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/twcc.rs +++ /dev/null @@ -1,1838 +0,0 @@ -use std::collections::VecDeque; -use std::collections::vec_deque; -use std::fmt; -use std::ops::RangeInclusive; -use std::time::{Duration, Instant}; -use tracing::warn; - -use super::{FeedbackMessageType, RtcpHeader, RtcpPacket, extend_u16}; -use super::{RtcpType, Ssrc, TransportType}; - -use crate::vendor::str0m::rtp_::TwccSeq; - -/// Transport Wide Congestion Control. -/// -/// Sent in response to every RTP packet, but does ranges of packets to respond to. -#[derive(Clone, PartialEq, Eq)] -pub struct Twcc { - /// Sender of this feedback. Mostly irrelevant, but part of RTCP packets. - pub sender_ssrc: Ssrc, - /// The SSRC this report is for. - pub ssrc: Ssrc, - /// Start sequence number. - pub base_seq: u16, - /// Number of reported statuses. - pub status_count: u16, - /// Clock time this report was produced. Used for RTT measurement. - pub reference_time: u32, // 24 bit - /// Increasing counter for each TWCC. For deduping. - pub feedback_count: u8, // counter for each Twcc - /// Ranges received. - pub chunks: VecDeque, - /// Delta times for the ranges received. - pub delta: VecDeque, -} - -impl Twcc { - fn chunks_byte_len(&self) -> usize { - self.chunks.len() * 2 - } - - fn delta_byte_len(&self) -> usize { - self.delta.iter().map(|d| d.byte_len()).sum() - } - - /// Iterate over the reported sequences. - pub fn into_iter(self, time_zero: Instant, extend_from: TwccSeq) -> TwccIter { - let millis = self.reference_time as u64 * 64; - let time_base = time_zero + Duration::from_millis(millis); - let base_seq = extend_u16(Some(*extend_from), self.base_seq); - let last_seq = base_seq + self.status_count as u64; - - TwccIter { - base_seq, - last_seq, - time_base, - index: 0, - twcc: self, - } - } -} - -pub struct TwccIter { - base_seq: u64, - last_seq: u64, - time_base: Instant, - index: usize, - twcc: Twcc, -} - -impl Iterator for TwccIter { - type Item = (TwccSeq, PacketStatus, Option); - - fn next(&mut self) -> Option { - let seq: TwccSeq = (self.base_seq + self.index as u64).into(); - - if *seq == self.last_seq { - return None; - } - - let head = self.twcc.chunks.front()?; - - let (status, amount) = match head { - PacketChunk::Run(s, n) => { - use PacketStatus::*; - let status = match s { - NotReceived | Unknown => NotReceived, - ReceivedSmallDelta => ReceivedSmallDelta, - PacketStatus::ReceivedLargeOrNegativeDelta => ReceivedLargeOrNegativeDelta, - }; - (status, *n) - } - PacketChunk::VectorSingle(v, n) => { - let status = if 1 << (13 - self.index) & v > 0 { - PacketStatus::ReceivedSmallDelta - } else { - PacketStatus::NotReceived - }; - (status, *n) - } - PacketChunk::VectorDouble(v, n) => { - let e = ((v >> (12 - self.index * 2)) & 0b11) as u8; - let status = PacketStatus::from(e); - (status, *n) - } - }; - - let instant = match status { - PacketStatus::NotReceived => None, - PacketStatus::ReceivedSmallDelta => match self.twcc.delta.pop_front()? { - Delta::Small(v) => Some(self.time_base + Duration::from_micros(250 * v as u64)), - Delta::Large(_) => panic!("Incorrect large delta size"), - }, - PacketStatus::ReceivedLargeOrNegativeDelta => match self.twcc.delta.pop_front()? { - Delta::Small(_) => panic!("Incorrect small delta size"), - Delta::Large(v) => { - let dur = Duration::from_micros(250 * v.unsigned_abs() as u64); - Some(if v < 0 { - self.time_base.checked_sub(dur).unwrap_or(self.time_base) - } else { - self.time_base + dur - }) - } - }, - // A VectorDouble chunk can carry 0b11 for any of its statuses. The - // parser maps that to Unknown and consumes no delta, so there is nothing - // to report for it either. - PacketStatus::Unknown => None, - }; - - if let Some(new_timebase) = instant { - self.time_base = new_timebase; - } - - self.index += 1; - if self.index == amount as usize { - self.twcc.chunks.pop_front(); - self.base_seq = *seq + 1; - self.index = 0; - } - - Some((seq, status, instant)) - } -} - -impl RtcpPacket for Twcc { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::TransportLayerFeedback, - feedback_message_type: FeedbackMessageType::TransportFeedback(TransportType::TransportWide), - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - // header: 1 - // sender ssrc: 1 - // ssrc: 1 - // base seq + packet status: 1 - // ref time + feedback count: 1 - // chunks byte len + delta byte len + padding - - let mut total = self.chunks_byte_len() + self.delta_byte_len(); - - let pad = 4 - total % 4; - if pad < 4 { - total += pad; - } - - assert!(total.is_multiple_of(4)); - - let total_words = total / 4; - - 5 + total_words - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - let len_start = buf.len(); - - let mut total = { - let buf = &mut buf[..]; - - self.header().write_to(buf); - buf[4..8].copy_from_slice(&self.sender_ssrc.to_be_bytes()); - buf[8..12].copy_from_slice(&self.ssrc.to_be_bytes()); - - buf[12..14].copy_from_slice(&self.base_seq.to_be_bytes()); - buf[14..16].copy_from_slice(&self.status_count.to_be_bytes()); - - let ref_time = self.reference_time.to_be_bytes(); - buf[16..19].copy_from_slice(&ref_time[1..4]); - buf[19] = self.feedback_count; - - let mut buf = &mut buf[20..]; - for p in &self.chunks { - p.write_to(buf); - buf = &mut buf[2..]; - } - - for d in &self.delta { - let n = d.write_to(buf); - buf = &mut buf[n..]; - } - - len_start - buf.len() - }; - - let pad = 4 - total % 4; - if pad < 4 { - for i in 0..pad { - buf[total + i] = 0; - } - buf[total + pad - 1] = pad as u8; - - total += pad; - // Toggle padding bit - buf[0] |= 0b00_1_00000; - } - - total - } -} - -#[derive(Debug)] -pub struct TwccRecvRegister { - // How many packets to keep when they are reported. This is to handle packets arriving out - // of order and where two consecutive calls to `build_report` needs to go "backwards" in - // base_seq. - keep_reported: usize, - - /// Queue of packets to form Twcc reports of. - /// - /// Once the queue has some content, we will always keep at least one entry to "remember" for the - /// next report. - queue: VecDeque, - - /// Index into queue from where we start reporting on next build_report(). - report_from: usize, - - /// Interims built in this for every build_report. - interims: VecDeque, - - /// The point in time we consider 0. All reported values are offset from this. Set to first - /// unreported packet in first `build_reported`. - /// - // https://datatracker.ietf.org/doc/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5 - // reference time: 24 bits Signed integer indicating an absolute - // reference time in some (unknown) time base chosen by the - // sender of the feedback packets. - time_start: Option, - - /// Counter that increases by one for each report generated. - generated_reports: u64, - - /// Data to calculate received loss. - receive_window: ReceiveWindow, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct Receipt { - seq: TwccSeq, - time: Instant, -} - -impl TwccRecvRegister { - pub fn new(keep_reported: usize) -> Self { - TwccRecvRegister { - keep_reported, - queue: VecDeque::new(), - report_from: 0, - interims: VecDeque::new(), - time_start: None, - generated_reports: 0, - receive_window: ReceiveWindow::default(), - } - } - - /// Find the last sequence number, or `None` if the queue is empty. - pub fn max_seq(&self) -> Option { - // The highest seq must be the last since update_seq inserts values - // using a binary search. - self.queue.back().map(|r| r.seq) - } - - pub fn update_seq(&mut self, seq: TwccSeq, time: Instant) { - self.receive_window.record_seq(seq); - - match self.queue.binary_search_by_key(&seq, |r| r.seq) { - Ok(_) => { - // Exact same SeqNo found. This is an error where the sender potentially - // used the same twcc sequence number for two packets. Let's ignore it. - } - Err(idx) => { - if let Some(time_start) = self.time_start { - // If time goes back more than 8192 millis from the time point we've - // chosen as our 0, we can't represent that in the report. Let's just - // forget about it and hope for the best. - if time_start - time >= Duration::from_millis(8192) { - return; - } - } - - self.queue.insert(idx, Receipt { seq, time }); - - if idx < self.report_from { - self.report_from = idx; - } - } - } - } - - pub fn build_report(&mut self, max_byte_size: usize) -> Option { - if max_byte_size > 10_000 { - warn!("Refuse to build too large Twcc report"); - return None; - } - - // First unreported is the self.time_start relative offset of the next Twcc. - let first = self.queue.get(self.report_from); - let first = first?; - - // Set once on first ever built report. - if self.time_start.is_none() { - self.time_start = Some(first.time); - } - - let (base_seq, first_time) = (first.seq, first.time); - let time_start = self.time_start.expect("a start time"); - - // The difference between our Twcc reference time and the first ever report start time. - let first_time_rel = first_time - time_start; - - // The value is to be interpreted in multiples of 64ms. - let reference_time = (first_time_rel.as_micros() as u64 / 64_000) as u32; - - let mut twcc = Twcc { - sender_ssrc: 0.into(), - ssrc: 0.into(), - feedback_count: self.generated_reports as u8, - base_seq: *base_seq as u16, - reference_time, - status_count: 0, - chunks: VecDeque::new(), - delta: VecDeque::new(), - }; - - // Because reference time is in steps of 64ms, the first reported packet might have an - // offset (packet time resolution is 250us). This base_time is calculated backwards from - // reference time so that we can offset all packets from the "truncated" 64ms steps. - // The RFC says: - // The first recv delta in this packet is relative to the reference time. - let base_time = time_start + Duration::from_micros(reference_time as u64 * 64_000); - - // The ChunkInterim are helpers structures that hold the deltas between - // the registered receptions. - build_interims(&self.queue, self.report_from, base_seq, base_time, &mut self.interims); - let interims = &mut self.interims; - - // 20 bytes is the size of the fixed fields in Twcc. - let mut bytes_left = max_byte_size - 20; - - while !interims.is_empty() { - // 2 chunk + 2 large delta + 3 padding - const MIN_RUN_SIZE: usize = 2 + 2 + 3; - - if bytes_left < MIN_RUN_SIZE { - break; - } - - // Chose the packet chunk type that can fit the most interims. - let (mut chunk, max) = { - let first_status = interims.front().expect("at least one interim").status(); - - let c_run = PacketChunk::Run(first_status, 0); - let c_single = PacketChunk::VectorSingle(0, 0); - let c_double = PacketChunk::VectorDouble(0, 0); - - let max_run = c_run.append_max(interims.iter()); - let max_single = c_single.append_max(interims.iter()); - let max_double = c_double.append_max(interims.iter()); - - let max = max_run.max(max_single).max(max_double); - - // 2 chunk + 14 small delta + 3 padding - const MAX_SINGLE_SIZE: usize = 2 + 14 + 3; - // 2 chunk + 7 large delta + 3 padding - const MAX_DOUBLE_SIZE: usize = 2 + 14 + 3; - - if max == max_run { - (c_run, max_run) - } else if max == max_single && bytes_left >= MAX_SINGLE_SIZE { - (c_single, max_single) - } else if max == max_double && bytes_left >= MAX_DOUBLE_SIZE { - (c_double, max_double) - } else { - // fallback, since we can always do runs. - (c_run, max_run) - } - }; - - // we should _definitely_ be able to fit this many reported. - let mut todo = max; - - loop { - if bytes_left < MIN_RUN_SIZE { - break; - } - - if todo == 0 { - break; - } - - let i = match interims.front_mut() { - Some(v) => v, - None => break, - }; - - let appended = chunk.append(i); - assert!(appended > 0); - todo -= appended; - twcc.status_count += appended; - - if i.consume(appended) { - // it was fully consumed. - if matches!(i, ChunkInterim::Received(_, _)) { - self.report_from += 1; - } - - if let Some(delta) = i.delta() { - twcc.delta.push_back(delta); - bytes_left -= delta.byte_len(); - } - - // move on to next interim - interims.pop_front(); - } else { - // not fully consumed, then we must have run out of space in the chunk. - assert!(todo == 0); - } - } - - let free = chunk.free(); - if chunk.must_be_full() && free > 0 { - // this must be at the end where we can shift in missing - assert!(interims.is_empty()); - chunk.append(&ChunkInterim::Missing(free)); - } - - twcc.chunks.push_back(chunk); - bytes_left -= 2; - } - - // libWebRTC demands at least one chunk, or it will warn with - // "Buffer too small (16 bytes) to fit a FeedbackPacket. Minimum size = 18" - // (18 bytes here is not including the RTCP header). - if twcc.chunks.is_empty() { - return None; - } - - self.generated_reports += 1; - - // clean up - if self.report_from > self.keep_reported { - let to_remove = self.report_from - self.keep_reported; - self.queue.drain(..to_remove); - self.report_from -= to_remove; - } - - Some(twcc) - } - - pub fn has_unreported(&self) -> bool { - self.queue.len() > self.report_from - } - - /// Calculate the fraction of lost packets since the last call. - /// - /// To get periodic stats call this method at fixed intervals. - pub fn loss(&mut self) -> Option { - // Based on the algorithm described in - // [RFC 3550 Appendix A](https://www.rfc-editor.org/rfc/rfc3550#appendix-A.3), but instead - // of applying it to an individual RTP stream it's applied to the whole session using TWCC - // sequence numbers rather than RTP sequence numbers. - let max_seq = self.receive_window.max_seq?; - let base_seq = self.receive_window.base_seq?; - let expected = *max_seq - *base_seq + 1_u64; - - let expected_interval = expected - self.receive_window.expected_prior; - self.receive_window.expected_prior = expected; - - let received_interval = self.receive_window.received - self.receive_window.received_prior; - self.receive_window.received_prior = self.receive_window.received; - - let lost_interval = expected_interval.saturating_sub(received_interval); - - (expected_interval != 0).then_some(lost_interval as f32 / expected_interval as f32) - } -} - -/// Interims are deltas between `Receiption` which is an intermediary format before -/// we populate the Twcc report. -fn build_interims( - queue: &VecDeque, - report_from: usize, - base_seq: TwccSeq, - base_time: Instant, - interims: &mut VecDeque, -) { - interims.clear(); - let report_from = queue.iter().skip(report_from); - - let mut prev = (base_seq, base_time); - - for r in report_from { - let diff_seq = *r.seq - *prev.0; - - if diff_seq > 1 { - let mut todo = diff_seq - 1; - while todo > 0 { - // max 2^13 run length in each missing chunk - let n = todo.min(8192); - interims.push_back(ChunkInterim::Missing(n as u16)); - todo -= n; - } - } - - let diff_time = if r.time < prev.1 { - // negative - let dur = prev.1 - r.time; - -(dur.as_micros() as i64) - } else { - let dur = r.time - prev.1; - dur.as_micros() as i64 - }; - - let (status, time) = if diff_time < -8_192_000 || diff_time > 8_191_750 { - // This is too large to be representable in deltas. - // Abort, make a report of what we got, and start anew. - break; - } else if diff_time < 0 || diff_time > 63_750 { - let t = diff_time / 250; - assert!(t >= -32_768 && t <= 32_767); - (PacketStatus::ReceivedLargeOrNegativeDelta, t as i16) - } else { - let t = diff_time / 250; - assert!(t >= 0 && t <= 255); - (PacketStatus::ReceivedSmallDelta, t as i16) - }; - - interims.push_back(ChunkInterim::Received(status, time)); - - // The next delta is relative to the time this delta REPORTS, not the - // true receive time: the receiver of the report sums the deltas, so - // carrying r.time would let each delta's truncation (up to 250us) - // accumulate across the report. - let reported = Duration::from_micros(250 * time.unsigned_abs() as u64); - let reported_time = if time < 0 { - prev.1.checked_sub(reported).unwrap_or(prev.1) - } else { - prev.1 + reported - }; - prev = (r.seq, reported_time); - } -} - -#[derive(Debug, Clone, Copy)] -enum ChunkInterim { - Missing(u16), // max 2^13 (one run length) - Received(PacketStatus, i16), -} - -#[derive(Debug, Default)] -struct ReceiveWindow { - /// The base seq num, set on the first receive. - base_seq: Option, - - /// The large seq num received. - max_seq: Option, - - /// The previous number of packets expected, used to calculate a delta for loss. - expected_prior: u64, - - /// The total number of packets received - received: u64, - - /// The previous number of packets received, used to calculate a delta for loss. - received_prior: u64, -} - -impl ReceiveWindow { - fn record_seq(&mut self, seq: TwccSeq) { - if self.base_seq.is_none() { - self.base_seq = Some(seq); - } - - self.received += 1; - self.max_seq = self.max_seq.max(Some(seq)); - } -} - -impl ChunkInterim { - fn status(&self) -> PacketStatus { - match self { - ChunkInterim::Missing(_) => PacketStatus::NotReceived, - ChunkInterim::Received(s, _) => *s, - } - } - - fn delta(&self) -> Option { - match self { - ChunkInterim::Missing(_) => None, - ChunkInterim::Received(s, d) => match *s { - PacketStatus::ReceivedSmallDelta => Some(Delta::Small(*d as u8)), - PacketStatus::ReceivedLargeOrNegativeDelta => Some(Delta::Large(*d)), - _ => unreachable!(), - }, - } - } - - fn consume(&mut self, n: u16) -> bool { - match self { - ChunkInterim::Missing(c) => { - *c -= n; - *c == 0 - } - ChunkInterim::Received(_, _) => { - assert!(n <= 1); - n == 1 - } - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PacketChunk { - Run(PacketStatus, u16), // 13 bit repeat - VectorSingle(u16, u16), - VectorDouble(u16, u16), -} - -impl PacketChunk { - fn append_max<'a>(&self, iter: impl Iterator) -> u16 { - let mut to_fill = *self; - - let mut reached_end = true; - - for i in iter { - if to_fill.free() == 0 { - reached_end = false; - break; - } - - // The status is not possible to add in this chunk. This could be - // a large delta in a single, or a mismatching run. - if !to_fill.can_append_status(i.status()) { - reached_end = false; - break; - } - - to_fill.append(i); - } - - // As a special case, single/double must be completely filled. However if - // we reached the end of the interims, we can shift in "missing" to make - // them full. - if to_fill.must_be_full() && to_fill.free() > 0 && !reached_end { - return 0; - } - - self.free() - to_fill.free() - } - - fn append(&mut self, i: &ChunkInterim) -> u16 { - use ChunkInterim::*; - use PacketChunk::*; - let free = self.free(); - match (self, i) { - (Run(s, n), Missing(c)) => { - if *s != PacketStatus::NotReceived { - return 0; - } - let max = free.min(*c); - *n += max; - max - } - (Run(s, n), Received(s2, _)) => { - if *s != *s2 { - return 0; - } - let max = free.min(1); - *n += max; - max - } - (VectorSingle(n, f), Missing(c)) => { - let max = free.min(*c); - *n <<= max; - *f += max; - max - } - (VectorSingle(n, f), Received(s2, _)) => { - if *s2 == PacketStatus::ReceivedLargeOrNegativeDelta { - return 0; - } - let max = free.min(1); - if max == 1 { - *n <<= 1; - *n |= 1; - *f += 1; - } - max - } - (VectorDouble(n, f), Missing(c)) => { - let max = free.min(*c); - *n <<= max * 2; - *f += max; - max - } - (VectorDouble(n, f), Received(s2, _)) => { - let max = free.min(1); - if max == 1 { - *n <<= 2; - *n |= *s2 as u16; - *f += 1; - } - max - } - } - } - - fn must_be_full(&self) -> bool { - match self { - PacketChunk::Run(_, _) => false, - PacketChunk::VectorSingle(_, _) => true, - PacketChunk::VectorDouble(_, _) => true, - } - } - - fn free(&self) -> u16 { - match self { - PacketChunk::Run(_, n) => 8192 - *n, - PacketChunk::VectorSingle(_, filled) => 14 - *filled, - PacketChunk::VectorDouble(_, filled) => 7 - *filled, - } - } - - fn write_to(&self, buf: &mut [u8]) { - let x = match self { - // 0 1 - // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - // |T| S | Run Length | - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - // chunk type (T): 1 bit A zero identifies this as a run length chunk. - // packet status symbol (S): 2 bits The symbol repeated in this run. - // See above. - // run length (L): 13 bits An unsigned integer denoting the run length. - PacketChunk::Run(s, n) => { - let mut x = 0_u16; - x |= (*s as u16) << 13; - assert!(*n <= 8192); - x |= n; - x - } - - // Corrected according to email exchange at the bottom.. - // - // 0 1 - // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - // |T|S| symbol list | - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - // chunk type (T): 1 bit A one identifies this as a status vector - // chunk. - // symbol size (S): 1 bit A zero means this vector contains only - // "packet received" (1) and "packet not received" (0) - // symbols. This means we can compress each symbol to just - // one bit, 14 in total. A one means this vector contains - // the normal 2-bit symbols, 7 in total. - // symbol list: 14 bits A list of packet status symbols, 7 or 14 in - // total. - PacketChunk::VectorSingle(n, fill) => { - assert!(*fill == 14); - let mut x: u16 = 1 << 15; - assert!(*n <= 16384); - x |= *n; - x - } - PacketChunk::VectorDouble(n, fill) => { - assert!(*fill == 7); - let mut x: u16 = 1 << 15; - assert!(*n <= 16384); - x |= 1 << 14; - x |= *n; - x - } - }; - buf[..2].copy_from_slice(&x.to_be_bytes()); - } - - fn max_possible_status_count(&self) -> usize { - match self { - PacketChunk::Run(_, n) => *n as usize, - PacketChunk::VectorSingle(_, _) => 14, - PacketChunk::VectorDouble(_, _) => 7, - } - } - - fn can_append_status(&self, status: PacketStatus) -> bool { - match self { - PacketChunk::Run(s, _) => *s == status, - PacketChunk::VectorSingle(_, _) => status != PacketStatus::ReceivedLargeOrNegativeDelta, - PacketChunk::VectorDouble(_, _) => true, - } - } -} - -impl Delta { - fn write_to(&self, buf: &mut [u8]) -> usize { - match self { - Delta::Small(v) => { - buf[0] = *v; - 1 - } - Delta::Large(v) => { - buf[..2].copy_from_slice(&v.to_be_bytes()); - 2 - } - } - } - - fn byte_len(&self) -> usize { - match self { - Delta::Small(_) => 1, - Delta::Large(_) => 2, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PacketStatus { - NotReceived = 0b00, - ReceivedSmallDelta = 0b01, - ReceivedLargeOrNegativeDelta = 0b10, - Unknown = 0b11, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Delta { - Small(u8), - Large(i16), -} - -impl From for u8 { - fn from(val: PacketStatus) -> Self { - val as usize as u8 - } -} - -impl From for PacketStatus { - fn from(v: u8) -> Self { - match v { - 0b00 => Self::NotReceived, - 0b01 => Self::ReceivedSmallDelta, - 0b10 => Self::ReceivedLargeOrNegativeDelta, - _ => Self::Unknown, - } - } -} - -impl<'a> TryFrom<&'a [u8]> for Twcc { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 16 { - return Err("Less than 16 bytes for start of Twcc"); - } - - let sender_ssrc = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]).into(); - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]).into(); - let base_seq = u16::from_be_bytes([buf[8], buf[9]]); - let status_count = u16::from_be_bytes([buf[10], buf[11]]); - let reference_time = u32::from_be_bytes([0, buf[12], buf[13], buf[14]]); - let feedback_count = buf[15]; - - let mut twcc = Twcc { - sender_ssrc, - ssrc, - base_seq, - status_count, - reference_time, - feedback_count, - chunks: VecDeque::new(), - delta: VecDeque::new(), - }; - - let mut todo = status_count as isize; - let mut buf = &buf[16..]; - loop { - if todo <= 0 { - break; - } - - let chunk: PacketChunk = buf.try_into()?; - - todo -= chunk.max_possible_status_count() as isize; - - twcc.chunks.push_back(chunk); - buf = &buf[2..]; - } - - if twcc.chunks.is_empty() { - return Ok(twcc); - } - - fn read_delta_small(buf: &[u8], n: usize) -> Result + '_, &'static str> { - if buf.len() < n { - return Err("Not enough buf for small deltas"); - } - Ok((0..n).map(|i| Delta::Small(buf[i]))) - } - - fn read_delta_large(buf: &[u8], n: usize) -> Result + '_, &'static str> { - if buf.len() < n * 2 { - return Err("Not enough buf for large deltas"); - } - Ok((0..(n * 2)) - .step_by(2) - .map(|i| Delta::Large(i16::from_be_bytes([buf[i], buf[i + 1]])))) - } - - for c in &twcc.chunks { - match c { - PacketChunk::Run(PacketStatus::ReceivedSmallDelta, n) => { - let n = *n as usize; - twcc.delta.extend(read_delta_small(buf, n)?); - buf = &buf[n..]; - } - PacketChunk::Run(PacketStatus::ReceivedLargeOrNegativeDelta, n) => { - let n = *n as usize; - twcc.delta.extend(read_delta_large(buf, n)?); - buf = &buf[n..]; - } - PacketChunk::VectorSingle(v, _) => { - let n = v.count_ones() as usize; - twcc.delta.extend(read_delta_small(buf, n)?); - buf = &buf[n..]; - } - PacketChunk::VectorDouble(v, _) => { - for n in (0..=12).step_by(2) { - let x = (*v >> (12 - n)) & 0b11; - match PacketStatus::from(x as u8) { - PacketStatus::ReceivedSmallDelta => { - twcc.delta.extend(read_delta_small(buf, 1)?); - buf = &buf[1..]; - } - PacketStatus::ReceivedLargeOrNegativeDelta => { - twcc.delta.extend(read_delta_large(buf, 1)?); - buf = &buf[2..]; - } - _ => {} - } - } - } - _ => {} - } - } - - Ok(twcc) - } -} - -impl<'a> TryFrom<&'a [u8]> for PacketChunk { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 2 { - return Err("Less than 2 bytes for PacketChunk"); - } - - let x = u16::from_be_bytes([buf[0], buf[1]]); - - let is_vec = (x & 0b1000_0000_0000_0000) > 0; - - let p = if is_vec { - let is_double = (x & 0b0100_0000_0000_0000) > 0; - let n = x & 0b0011_1111_1111_1111; - if is_double { - PacketChunk::VectorDouble(n, 7) - } else { - PacketChunk::VectorSingle(n, 14) - } - } else { - let s: PacketStatus = ((x >> 13) as u8).into(); - let n = x & 0b0001_1111_1111_1111; - PacketChunk::Run(s, n) - }; - - Ok(p) - } -} - -// Below is a clarification of the RFC draft from an email exchange with Erik Språng (one of the authors). -// -// > I'm trying to implement the draft spec -// > https://datatracker.ietf.org/doc/html/draft-holmer-rmcat-transport-wide-cc-extensions-01 -// > I found a number of errors/inconsistencies in the RFC, and wonder who I should address this to. -// > I think the RFC could benefit from another revision. -// > -// > There are three problems listed below. -// > -// > 1. There's a contradiction between section 3.1.1 and the example in 3.1.3. First the RFC tells -// > me 11 is Reserved, later it shows an example using 11 saying it is a run of packets received w/o -// > recv delta. Which one is right? -// > -// > Section 3.1.1 -// > ... -// > The status of a packet is described using a 2-bit symbol: -// > ... -// > 11 [Reserved] -// > -// > Section 3.1.3 -// > ... -// > Example 2: -// > -// > 0 1 -// > 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 -// > +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// > |0|1 1|0 0 0 0 0 0 0 0 1 1 0 0 0| -// > +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// > -// > -// > This is a run of the "packet received, w/o recv delta" status of -// > length 24. -// -// I believe this example is in error. Packets without receive deltas was a proposal for the v1 -// protocol but was dropped iirc. Note that there is a newer header extension available, which -// when negotiated allows send-side control over when feedback is generated - and that provides -// the option to omit all receive deltas from the feedback. -// -// > 2. In section 3.1.4 when using a 1-bit vector to indicate packet received or not received, -// > there's a contradiction between the the definition and the example. The definition says -// > "packet received" (0) and "packet not received" (1), while the example is the opposite way -// > around: 0 is packet not received. Which way around is it? -// > -// > symbol size (S): 1 bit A zero means this vector contains only -// > "packet received" (0) and "packet not received" (1) -// > symbols. This means we can compress each symbol to just -// > one bit, 14 in total. A one means this vector contains -// > the normal 2-bit symbols, 7 in total. -// > ... -// > Example 1: -// > -// > 0 1 -// > 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 -// > +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// > |1|0|0 1 1 1 1 1 0 0 0 1 1 1 0 0| -// > +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// > -// > This chunk contains, in order: -// > -// > 1x "packet not received" -// > -// > 5x "packet received" -// -// I believe the definition is wrong in this case. The intent is to just truncate the 2-bit values: -// -// 3.1.1. Packet Status Symbols -// -// The status of a packet is described using a 2-bit symbol: -// -// 00 Packet not received -// -// 01 Packet received, small delta -// -// So (0) for not received and (1) for received, small delta. -// This also matches what the libwebrtc source code does. -// -// > 3. In section 3.1.4 when using a 1-bit vector, the RFC doesn't say what a "packet received" in that -// > vector should be accompanied by in receive delta size. Is it an 8 bit delta or 16 bit -// > delta per "packet received"? -// -// Same as the question above, this is a truncation to (0) for not received and (1) for -// received, small delta. - -impl fmt::Debug for Twcc { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Twcc") - .field("sender_ssrc", &self.sender_ssrc) - .field("ssrc", &self.ssrc) - .field("base_seq", &self.base_seq) - .field("status_count", &self.status_count) - .field("reference_time", &self.reference_time) - .field("feedback_count", &self.feedback_count) - .field("chunks", &self.chunks) - .field("delta", &self.delta.len()) - .finish() - } -} - -#[allow(clippy::assign_op_pattern)] -#[cfg(test)] -mod test { - use std::time::Duration; - - use super::*; - - use Delta::*; - use PacketChunk::*; - use PacketStatus::*; - - #[test] - fn register_write_parse_small_delta() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(11.into(), now + Duration::from_millis(12)); - reg.update_seq(12.into(), now + Duration::from_millis(23)); - reg.update_seq(13.into(), now + Duration::from_millis(43)); - - let report = reg.build_report(1000).unwrap(); - let mut buf = vec![0_u8; 1500]; - let n = report.write_to(&mut buf[..]); - buf.truncate(n); - - let header: RtcpHeader = (&buf[..]).try_into().unwrap(); - let parsed: Twcc = (&buf[4..]).try_into().unwrap(); - - assert_eq!(header, report.header()); - assert_eq!(parsed, report); - } - - #[test] - fn register_write_parse_small_delta_missing() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(11.into(), now + Duration::from_millis(12)); - reg.update_seq(12.into(), now + Duration::from_millis(23)); - // 13 is not there - reg.update_seq(14.into(), now + Duration::from_millis(43)); - - let report = reg.build_report(1000).unwrap(); - let mut buf = vec![0_u8; 1500]; - let n = report.write_to(&mut buf[..]); - buf.truncate(n); - - let header: RtcpHeader = (&buf[..]).try_into().unwrap(); - let parsed: Twcc = (&buf[4..]).try_into().unwrap(); - - assert_eq!(header, report.header()); - assert_eq!(parsed, report); - } - - #[test] - fn register_write_parse_large_delta() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(11.into(), now + Duration::from_millis(70)); - reg.update_seq(12.into(), now + Duration::from_millis(140)); - reg.update_seq(13.into(), now + Duration::from_millis(210)); - - let report = reg.build_report(1000).unwrap(); - let mut buf = vec![0_u8; 1500]; - let n = report.write_to(&mut buf[..]); - buf.truncate(n); - - let header: RtcpHeader = (&buf[..]).try_into().unwrap(); - let parsed: Twcc = (&buf[4..]).try_into().unwrap(); - - assert_eq!(header, report.header()); - assert_eq!(parsed, report); - } - - #[test] - fn register_write_parse_mixed_delta() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(11.into(), now + Duration::from_millis(12)); - reg.update_seq(12.into(), now + Duration::from_millis(140)); - reg.update_seq(13.into(), now + Duration::from_millis(152)); - - let report = reg.build_report(1000).unwrap(); - let mut buf = vec![0_u8; 1500]; - let n = report.write_to(&mut buf[..]); - buf.truncate(n); - - let header: RtcpHeader = (&buf[..]).try_into().unwrap(); - let parsed: Twcc = (&buf[4..]).try_into().unwrap(); - - assert_eq!(header, report.header()); - assert_eq!(parsed, report); - } - - #[test] - fn too_big_time_gap_requires_two_reports() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(11.into(), now + Duration::from_millis(12)); - reg.update_seq(12.into(), now + Duration::from_millis(9000)); - - let _ = reg.build_report(1000).unwrap(); - let report2 = reg.build_report(1000).unwrap(); - - // 9000 milliseconds is not possible to set as exact reference time which - // is in multiples of 64ms. 9000/64 = 140.625. - assert_eq!(report2.reference_time, 140); - - // 140 * 64 = 8960 - // So the first offset must be 40ms, i.e. 40_000us / 250us = 160 - assert_eq!(report2.delta[0], Small(160)); - } - - /// Reconstructs every receive time of a report the way its receiver does. - fn reported_times(report: Twcc, time_zero: Instant) -> Vec { - report - .into_iter(time_zero, 0.into()) - .filter_map(|(_, _, instant)| instant) - .collect() - } - - #[test] - fn report_deltas_do_not_accumulate_truncation() { - let mut reg = TwccRecvRegister::new(200); - let now = Instant::now(); - - // 20.1 ms apart: every delta has a 100us remainder below the 250us - // resolution. Carried from the true time, 70 truncations would - // report the last packet ~7 ms early. - let truth: Vec = (0..70_u64).map(|i| now + Duration::from_micros(i * 20_100)).collect(); - for (i, t) in truth.iter().enumerate() { - reg.update_seq((i as u64).into(), *t); - } - - let report = reg.build_report(1500).unwrap(); - assert_eq!(report.status_count, 70, "one report covers all packets"); - let reported = reported_times(report, now); - assert_eq!(reported.len(), truth.len()); - for (t, r) in truth.iter().zip(&reported) { - assert!(*r <= *t, "never reported later than received"); - assert!(*t - *r < Duration::from_micros(250), "off by {:?}", *t - *r); - } - } - - #[test] - fn report_deltas_do_not_accumulate_across_reordering() { - let mut reg = TwccRecvRegister::new(200); - let now = Instant::now(); - - // A reordered arrival makes a negative (large) delta; the error must - // stay within one tick on both sides of it. - let offsets_us = [0, 20_130, 40_270, 35_090, 60_410, 80_550, 100_690]; - for (i, us) in offsets_us.iter().enumerate() { - reg.update_seq((i as u64).into(), now + Duration::from_micros(*us)); - } - - let reported = reported_times(reg.build_report(1500).unwrap(), now); - assert_eq!(reported.len(), offsets_us.len()); - for (us, r) in offsets_us.iter().zip(&reported) { - let t = now + Duration::from_micros(*us); - let err = if *r > t { *r - t } else { t - *r }; - assert!(err < Duration::from_micros(250), "off by {err:?} at {us}us"); - } - } - - /// Two interleaved 20 ms streams, every tenth adjacent pair swapped on - /// the wire, 249 packets before the first report: every reconstructed - /// time must stay within one tick of the truth. - #[test] - fn report_reconstructs_long_reordered_first_report() { - let mut reg = TwccRecvRegister::new(100); - let now = Instant::now(); - let mut truth: Vec<(u64, Instant)> = Vec::new(); - let mut seq = 0u64; - for i in 0..125u64 { - let a = now + Duration::from_micros(i * 20_000 + (i % 7) * 130); - let b = a + Duration::from_micros(6_840 + (i % 3) * 110); - truth.push((seq, a)); - truth.push((seq + 1, b)); - seq += 2; - } - truth.truncate(249); - // wire order: swap every tenth adjacent pair (the later seq arrives first) - let mut wire = truth.clone(); - let mut k = 1; - while k + 1 < wire.len() { - wire.swap(k, k + 1); - // the swapped packets keep their arrival instants: the one with - // the higher seq now arrives earlier - let (s0, t0) = wire[k]; - let (s1, t1) = wire[k + 1]; - wire[k] = (s0, t1.min(t0)); - wire[k + 1] = (s1, t1.max(t0)); - k += 10; - } - let mut arrivals: Vec<(u64, Instant)> = wire.clone(); - arrivals.sort_by_key(|(_, t)| *t); - for (s, t) in &arrivals { - reg.update_seq((*s).into(), *t); - } - let report = reg.build_report(1100).unwrap(); - assert_eq!(report.status_count as usize, 249); - let mut expected: Vec<(u64, Instant)> = wire.clone(); - expected.sort_by_key(|(s, _)| *s); - let reported: Vec<(u64, Instant)> = report - .into_iter(now, 0.into()) - .filter_map(|(s, _, t)| t.map(|t| (*s, t))) - .collect(); - assert_eq!(reported.len(), expected.len()); - for ((s, t), (rs, r)) in expected.iter().zip(&reported) { - assert_eq!(s, rs); - let err = if *r > *t { *r - *t } else { *t - *r }; - assert!(err < Duration::from_micros(250), "seq {s} off by {err:?}"); - } - } - - #[test] - fn report_padded_to_even_word() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - - let report = reg.build_report(1000).unwrap(); - let mut buf = vec![0_u8; 1500]; - let n = report.write_to(&mut buf[..]); - - assert!(n % 4 == 0); - } - - #[test] - fn report_truncated_to_max_byte_size() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(11.into(), now + Duration::from_millis(12)); - reg.update_seq(12.into(), now + Duration::from_millis(140)); - reg.update_seq(13.into(), now + Duration::from_millis(152)); - - let report = reg.build_report(28).unwrap(); - - assert_eq!(report.status_count, 2); - assert_eq!(report.chunks, vec![Run(ReceivedSmallDelta, 2)]); - assert_eq!(report.delta, vec![Small(0), Small(48)]); - - let report = reg.build_report(28).unwrap(); - - assert_eq!(report.status_count, 2); - assert_eq!(report.chunks, vec![Run(ReceivedSmallDelta, 2)]); - assert_eq!(report.delta, vec![Small(48), Small(48)]); - } - - #[test] - fn truncated_counts_gaps_correctly() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - // gap - reg.update_seq(13.into(), now + Duration::from_millis(12)); - reg.update_seq(14.into(), now + Duration::from_millis(140)); - reg.update_seq(15.into(), now + Duration::from_millis(152)); - - let report = reg.build_report(32).unwrap(); - - assert_eq!(report.status_count, 4); - assert_eq!( - report.chunks, - vec![ - Run(ReceivedSmallDelta, 1), - Run(NotReceived, 2), - Run(ReceivedSmallDelta, 1) - ] - ); - assert_eq!(report.delta, vec![Small(0), Small(48)]); - } - - #[test] - fn run_max_is_8192() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(0.into(), now + Duration::from_millis(0)); - reg.update_seq(8194.into(), now + Duration::from_millis(10)); - - let report = reg.build_report(1000).unwrap(); - - assert_eq!(report.status_count, 8195); - assert_eq!( - report.chunks, - vec![ - VectorSingle(8192, 14), - Run(NotReceived, 8180), - Run(ReceivedSmallDelta, 1) - ] - ); - } - - #[test] - fn single_followed_by_missing() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(0)); - reg.update_seq(12.into(), now + Duration::from_millis(10)); - reg.update_seq(100.into(), now + Duration::from_millis(20)); - - let report = reg.build_report(2016).unwrap(); - - assert_eq!(report.status_count, 91); - assert_eq!( - report.chunks, - vec![ - VectorSingle(10240, 14), - Run(NotReceived, 76), - Run(ReceivedSmallDelta, 1) - ] - ); - assert_eq!(report.delta, vec![Small(0), Small(40), Small(40)]); - } - - #[test] - fn time_jump_small_back_for_second_report() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(8000)); - let _ = reg.build_report(2016).unwrap(); - - reg.update_seq(9.into(), now + Duration::from_millis(0)); - let report = reg.build_report(2016).unwrap(); - - assert_eq!(report.status_count, 2); - assert_eq!(report.chunks, vec![Run(ReceivedLargeOrNegativeDelta, 2)]); - assert_eq!(report.delta, vec![Large(-32000), Large(32000)]); - } - - #[test] - fn time_jump_large_back_for_second_report() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(9000)); - let _ = reg.build_report(2016).unwrap(); - - reg.update_seq(9.into(), now + Duration::from_millis(0)); - assert!(reg.build_report(2016).is_none()); - - assert_eq!(reg.queue.len(), 1); - } - - #[test] - fn empty_twcc() { - let twcc = Twcc { - sender_ssrc: 0.into(), - ssrc: 0.into(), - base_seq: 0, - status_count: 0, - reference_time: 0, - feedback_count: 0, - chunks: VecDeque::new(), - delta: VecDeque::new(), - }; - - let mut buf = vec![0_u8; 1500]; - let n = twcc.write_to(&mut buf[..]); - buf.truncate(n); - - let header: RtcpHeader = (&buf[..]).try_into().unwrap(); - let parsed: Twcc = (&buf[4..]).try_into().unwrap(); - - assert_eq!(header, twcc.header()); - assert_eq!(parsed, twcc); - } - - #[test] - fn negative_deltas() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - reg.update_seq(10.into(), now + Duration::from_millis(12)); - reg.update_seq(11.into(), now + Duration::from_millis(0)); - reg.update_seq(12.into(), now + Duration::from_millis(23)); - - let report = reg.build_report(1000).unwrap(); - - assert_eq!(report.status_count, 3); - assert_eq!(report.base_seq, 10); - assert_eq!(report.reference_time, 0); - assert_eq!(report.chunks, vec![VectorDouble(6400, 7)]); - assert_eq!(report.delta, vec![Small(0), Large(-48), Small(92)]); - - let base = reg.time_start.unwrap(); - - let mut iter = report.into_iter(base, 10.into()); - assert_eq!( - iter.next(), - Some(( - 10.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_millis(0)) - )) - ); - assert_eq!( - iter.next(), - Some(( - 11.into(), - PacketStatus::ReceivedLargeOrNegativeDelta, - Some(base.checked_sub(Duration::from_millis(12)).unwrap()) - )) - ); - assert_eq!( - iter.next(), - Some(( - 12.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_millis(11)) - )) - ); - } - - #[test] - fn twcc_fuzz_fail() { - let mut reg = TwccRecvRegister::new(100); - - let now = Instant::now(); - - // [Register(, ), Register(, ), Register(, ), BuildReport(43)] - - reg.update_seq(4542.into(), now + Duration::from_millis(2373281424)); - reg.update_seq(15918.into(), now + Duration::from_millis(2373862820)); - reg.update_seq(8405.into(), now + Duration::from_millis(2379074367)); - - let report = reg.build_report(43).unwrap(); - - let mut buf = vec![0_u8; 1500]; - let n = report.write_to(&mut buf[..]); - buf.truncate(n); - - let header: RtcpHeader = match (&buf[..]).try_into() { - Ok(v) => v, - Err(_) => return, - }; - let parsed: Twcc = match (&buf[4..]).try_into() { - Ok(v) => v, - Err(_) => return, - }; - - assert_eq!(header, report.header()); - assert_eq!(parsed, report); - } - - #[test] - fn twcc_large_time_delta_edges() { - let mut reg = TwccRecvRegister::new(100); - - // Stretch the boundaries of the i16 type used for deltas - let now = Instant::now(); - reg.update_seq(0.into(), now + Duration::from_micros(8_192_000)); - reg.update_seq(1.into(), now + Duration::from_micros(0)); - reg.update_seq(2.into(), now + Duration::from_micros(8_191_750)); - - let report = reg.build_report(1000).unwrap(); - - assert_eq!(report.status_count, 3); - assert_eq!(report.delta, vec![Small(0), Large(-32768), Large(32767)]); - } - - #[test] - fn twcc_crazy_negative_time_delta() { - let mut reg = TwccRecvRegister::new(100); - - // Deltas so big they wrap around the bounds of an i32 to become small again. - // These constants are chosen carefully to look normal when wrapped - let now = Instant::now(); - reg.update_seq(0.into(), now + Duration::from_micros(4_294_967_547)); // Wraps to -251 - reg.update_seq(1.into(), now + Duration::from_micros(0)); - - // The bogus value should be ignored - let report = reg.build_report(1000).unwrap(); - assert_eq!(report.status_count, 1); - assert_eq!(report.delta, vec![Small(0)]); - } - - #[test] - fn twcc_crazy_positive_time_delta() { - let mut reg = TwccRecvRegister::new(100); - - // Deltas so big they wrap around the bounds of an i32 to become small again. - // These constants are chosen carefully to look normal when wrapped - let now = Instant::now(); - reg.update_seq(0.into(), now + Duration::from_micros(0)); - reg.update_seq(1.into(), now + Duration::from_micros(4_294_967_547)); // Wraps to 251 - - // The bogus value should be ignored - let report = reg.build_report(1000).unwrap(); - assert_eq!(report.status_count, 1); - assert_eq!(report.delta, vec![Small(0)]); - } - - #[test] - fn test_twcc_iter_correct_deltas() { - let twcc = Twcc { - sender_ssrc: 0.into(), - ssrc: 0.into(), - base_seq: 1, - status_count: 12, - reference_time: 1337, - feedback_count: 0, - chunks: [ - PacketChunk::Run(PacketStatus::ReceivedSmallDelta, 2), - PacketChunk::VectorDouble(0b1101_0010_0101_0000, 7), - PacketChunk::Run(PacketStatus::ReceivedLargeOrNegativeDelta, 3), - ] - .into(), - delta: [ - // Run of length 2 - Delta::Small(10), - Delta::Small(15), - // Double status vector with 4 deltas - Delta::Small(7), - Delta::Large(280), - Delta::Small(3), - Delta::Small(13), - // Run of length 3 - Delta::Large(-37), - Delta::Large(32), - Delta::Large(89), - ] - .into(), - }; - - let now = Instant::now(); - let base = now + Duration::from_millis(1337 * 64); - let expected = vec![ - ( - 1.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_micros(10 * 250)), - ), - ( - 2.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_micros(25 * 250)), - ), - ( - 3.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_micros(32 * 250)), - ), - (4.into(), PacketStatus::NotReceived, None), - ( - 5.into(), - PacketStatus::ReceivedLargeOrNegativeDelta, - Some(base + Duration::from_micros(312 * 250)), - ), - ( - 6.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_micros(315 * 250)), - ), - ( - 7.into(), - PacketStatus::ReceivedSmallDelta, - Some(base + Duration::from_micros(328 * 250)), - ), - (8.into(), PacketStatus::NotReceived, None), - (9.into(), PacketStatus::NotReceived, None), - ( - 10.into(), - PacketStatus::ReceivedLargeOrNegativeDelta, - Some(base + Duration::from_micros(291 * 250)), - ), - ( - 11.into(), - PacketStatus::ReceivedLargeOrNegativeDelta, - Some(base + Duration::from_micros(323 * 250)), - ), - ( - 12.into(), - PacketStatus::ReceivedLargeOrNegativeDelta, - Some(base + Duration::from_micros(412 * 250)), - ), - ]; - - let result: Vec<_> = twcc.into_iter(now, 1.into()).collect(); - - assert_eq!(result, expected); - } - - #[test] - fn test_twcc_iter_limited_with_status_count() { - let status_count = 3; - - // [(1, NotReceived), (2, ReceivedSmallDelta), (3, ReceivedSmallDelta)] - let twcc_iter_count = Twcc { - sender_ssrc: 1.into(), - ssrc: 2.into(), - base_seq: 1, - status_count, - reference_time: 406753, - feedback_count: 1, - chunks: VecDeque::from(vec![VectorDouble(0b00_00_01_01_00_00_00_00, 7)]), - delta: VecDeque::from(vec![Small(236), Small(1)]), - } - .into_iter(Instant::now(), 1.into()) - .count(); - - assert_eq!(twcc_iter_count, status_count as usize); - } - - fn received(base_seq: u16, status_count: u16) -> Twcc { - Twcc { - sender_ssrc: Ssrc::new(), - ssrc: Ssrc::new(), - base_seq, - status_count, - reference_time: 35, - feedback_count: 0, - chunks: [PacketChunk::Run(PacketStatus::ReceivedSmallDelta, status_count)].into(), - delta: (0..status_count).map(|_| Delta::Small(10)).collect(), - } - } - - #[test] - fn test_twcc_recv_register_loss() { - let mut reg = TwccRecvRegister::new(25); - let mut now = Instant::now(); - - for i in 0..10 { - if i == 3 || i == 7 { - // simulate loss - continue; - } - reg.update_seq(i.into(), now); - now = now + Duration::from_millis(50); - } - - assert_eq!(reg.loss(), Some(2.0 / 10.0)); - - for i in 10..20 { - if i == 11 || i == 13 || i == 15 || i == 17 { - // simulate loss - continue; - } - reg.update_seq(i.into(), now); - now = now + Duration::from_millis(50); - } - - assert_eq!(reg.loss(), Some(4.0 / 10.0)); - } - - #[test] - fn test_twcc_recv_register_high_initial_sequence() { - // Test TWCC sequence numbers starting at high values (>= 32768) - let test_cases = vec![ - (32767, "just below half"), - (32768, "exactly half"), - (65434, "just below u16"), - (65535, "maximum u16"), - ]; - - for (transport_cc, description) in test_cases { - let mut twcc_rx_register = TwccRecvRegister::new(100); - let now = Instant::now(); - - // Empty register should return `None` - assert_eq!( - twcc_rx_register.max_seq(), - None, - "Empty register should return None for {}", - description - ); - - // This is what `session.rs` does: - let prev = twcc_rx_register.max_seq(); - let extended = extend_u16(prev.map(|s| *s), transport_cc); - twcc_rx_register.update_seq(extended.into(), now); - - assert_eq!( - twcc_rx_register.max_seq(), - Some(extended.into()), - "First packet for {}", - description - ); - - // Add a few more packets, simulating production code path - for i in 1..5 { - let raw_seq = ((transport_cc as u32 + i) % 65536) as u16; - let prev = twcc_rx_register.max_seq(); - let extended = extend_u16(prev.map(|s| *s), raw_seq); - twcc_rx_register.update_seq(extended.into(), now + Duration::from_millis(i as u64 * 10)); - } - - // Verify wrap-around handling if we crossed the boundary - if transport_cc >= 65533 { - // Should have wrapped to extended values > 65536 - let max = twcc_rx_register.max_seq().unwrap(); - assert!(*max > 65536, "Should wrap correctly for {}: got {}", description, *max); - } - - // build_report should NOT panic or allocate huge memory (leading to OOM) - let report = twcc_rx_register.build_report(1000); - assert!(report.is_some(), "Should build report for {}", description); - - let report = report.unwrap(); - assert!(report.status_count > 0, "Should have packets for {}", description); - assert!(!report.chunks.is_empty(), "Should have chunks for {}", description); - - // Sanity check: should never have an absurdly large number of chunks - assert!( - report.chunks.len() < 10, - "Should not create excessive chunks for {}", - description - ); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/xr.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/xr.rs deleted file mode 100644 index 56a5471d9a1..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/rtcp/xr.rs +++ /dev/null @@ -1,285 +0,0 @@ -use std::time::SystemTime; - -use crate::vendor::str0m::util::SystemTimeExt; - -use super::{FeedbackMessageType, RtcpType, Ssrc}; -use super::{RtcpHeader, RtcpPacket}; - -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |V=2|P|reserved | PT=XR=207 | length | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | SSRC | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// : report blocks : -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - -/// Extended receiver report (XR). -/// -/// RFC 3611: -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ExtendedReport { - /// The SSRC this report is for. - pub ssrc: Ssrc, - /// The blocks reported. - pub blocks: Vec, -} - -/// Parts of an extended report XR. -#[derive(Debug, Clone, PartialEq, Eq)] -#[allow(missing_docs)] -pub enum ReportBlock { - Rrtr(Rrtr), - Dlrr(Dlrr), -} - -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | BT=4 | reserved | block length = 2 | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | NTP timestamp, most significant word | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | NTP timestamp, least significant word | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - -/// Receiver Reference Time Report Block. -/// -/// -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[allow(missing_docs)] -pub struct Rrtr { - pub ntp_time: SystemTime, -} - -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | BT=5 | reserved | block length | -// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// | SSRC_1 (SSRC of first receiver) | sub- -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ block -// | last RR (LRR) | 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | delay since last RR (DLRR) | -// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// | SSRC_2 (SSRC of second receiver) | sub- -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ block -// : ... : 2 -// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ - -/// DLRR Report Block -/// -/// -#[derive(Debug, Clone, PartialEq, Eq)] -#[allow(missing_docs)] -pub struct Dlrr { - pub items: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct DlrrItem { - pub ssrc: Ssrc, - pub last_rr_time: u32, - pub last_rr_delay: u32, -} - -impl RtcpPacket for ExtendedReport { - fn header(&self) -> RtcpHeader { - RtcpHeader { - rtcp_type: RtcpType::ExtendedReport, - feedback_message_type: FeedbackMessageType::NotUsed, - words_less_one: (self.length_words() - 1) as u16, - } - } - - fn length_words(&self) -> usize { - let header = 1; - let ssrc = 1; - let blocks: usize = self.blocks.iter().map(|b| b.len() / 4).sum(); - header + ssrc + blocks - } - - fn write_to(&self, buf: &mut [u8]) -> usize { - let mut len = self.header().write_to(buf); - - buf[4..8].copy_from_slice(&self.ssrc.to_be_bytes()); - len += 4; - - for block in self.blocks.iter() { - len += match block { - ReportBlock::Rrtr(b) => b.write_to(&mut buf[len..]), - ReportBlock::Dlrr(b) => b.write_to(&mut buf[len..]), - }; - } - - len - } -} - -impl ReportBlock { - pub(crate) fn len(&self) -> usize { - match self { - Self::Rrtr(_) => Rrtr::len(), - Self::Dlrr(v) => v.len(), - } - } -} - -impl Rrtr { - fn write_to(&self, buf: &mut [u8]) -> usize { - // block type - buf[0] = 4_u8; - // reserved; - buf[1] = 0_u8; - // block length - buf[2..4].copy_from_slice(&2_u16.to_be_bytes()); - - // NTP timestamp - let mt = self.ntp_time.as_ntp_64(); - buf[4..12].copy_from_slice(&mt.to_be_bytes()); - - 12 - } - - fn len() -> usize { - 12 - } -} - -impl Dlrr { - fn write_to(&self, buf: &mut [u8]) -> usize { - // block type - buf[0] = 5_u8; - // reserved; - buf[1] = 0_u8; - // block length, in 32-bit words (RFC 3611 §3): each DLRR sub-block is 3 words - // (ssrc + last_rr + delay = 12 bytes). Must match the parser, which divides this - // field by 3 to recover the item count. - let len: u16 = self.items.len() as u16 * 3_u16; - buf[2..4].copy_from_slice(&len.to_be_bytes()); - - let mut buf = &mut buf[4..]; - - for item in self.items.iter() { - buf[0..4].copy_from_slice(&item.ssrc.to_be_bytes()); - buf[4..8].copy_from_slice(&item.last_rr_time.to_be_bytes()); - buf[8..12].copy_from_slice(&item.last_rr_delay.to_be_bytes()); - // advance past the full 12-byte sub-block - buf = &mut buf[12..]; - } - - self.len() - } - - fn len(&self) -> usize { - 4 + (self.items.len() * 4 * 3) - } -} - -impl<'a> TryFrom<&'a [u8]> for ExtendedReport { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 4 { - return Err("Less than 4 bytes for ExtendedReport"); - } - - let ssrc = u32::from_be_bytes(buf[..4].try_into().unwrap()).into(); - - let mut blocks: Vec = Vec::new(); - let mut buf = &buf[4..]; - - while let Ok(block) = buf.try_into() { - let block: ReportBlock = block; - let len = block.len(); - blocks.push(block); - // A block's reported len may exceed the remaining bytes for a - // truncated/malformed packet. Guard against slicing past the end - // (panic) and against a zero len that would spin forever. - if len == 0 || len >= buf.len() { - break; - } - buf = &buf[len..]; - } - - Ok(ExtendedReport { ssrc, blocks }) - } -} - -impl<'a> TryFrom<&'a [u8]> for ReportBlock { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.is_empty() { - return Err("not enough data"); - } - - let block_type: u8 = buf[0]; - match block_type { - 4 => { - let block = Rrtr::try_from(buf)?; - Ok(Self::Rrtr(block)) - } - 5 => { - let block = Dlrr::try_from(buf)?; - Ok(Self::Dlrr(block)) - } - _ => Err("unknown block type"), - } - } -} - -impl<'a> TryFrom<&'a [u8]> for Rrtr { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 12 { - return Err("Less than 12 bytes for Rrtr"); - } - - let ntp_time = u64::from_be_bytes(buf[4..4 + 8].try_into().unwrap()); - let ntp_time = SystemTime::from_ntp_64(ntp_time); - - Ok(Rrtr { ntp_time }) - } -} - -impl<'a> TryFrom<&'a [u8]> for Dlrr { - type Error = &'static str; - - fn try_from(buf: &'a [u8]) -> Result { - if buf.len() < 4 { - return Err("Less than 4 bytes for Dlrr"); - } - - let words_per_block = 3; - let blocks = u16::from_be_bytes(buf[2..4].try_into().unwrap()) / words_per_block; - - let mut items: Vec = Vec::with_capacity(blocks as usize); - - // move on after the header - let mut buf = &buf[4..]; - - for _ in 0..blocks { - // Each DLRR item is 12 bytes. The block count comes from the - // (attacker-controlled) length field, so stop if there aren't - // enough bytes left for another item. - if buf.len() < 12 { - break; - } - let ssrc = u32::from_be_bytes(buf[0..4].try_into().unwrap()).into(); - let last_rr_time = u32::from_be_bytes(buf[4..8].try_into().unwrap()); - let last_rr_delay = u32::from_be_bytes(buf[8..12].try_into().unwrap()); - items.push(DlrrItem { - ssrc, - last_rr_time, - last_rr_delay, - }); - buf = &buf[12..]; - } - - Ok(Dlrr { items }) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/seq_no_window.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/seq_no_window.rs deleted file mode 100644 index 316d9c58c91..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/seq_no_window.rs +++ /dev/null @@ -1,191 +0,0 @@ -use super::SeqNo; - -/// Tracks receipts in a fixed window of 128 sequence numbers without allocating. -/// -/// The window covers the highest recorded sequence number and the preceding 127. -/// Unseen numbers within that window, including numbers before the initial receipt, -/// are accepted. Numbers ahead of the window are accepted; older numbers and duplicates -/// are rejected. [`Self::new_after`] additionally blocks all numbers at or below a -/// restored maximum. -/// -/// Callers supply extended [`SeqNo`] values: this type does not extend wire sequence -/// numbers or calculate rollover counters. For authenticated traffic, check [`Self::accepts`] -/// before authentication and call [`Self::update`] only after authentication succeeds. -#[derive(Debug)] -pub(crate) struct SeqNoWindow { - max: SeqNo, - // Bit n records receipt of max - n. - seen: u128, -} - -impl SeqNoWindow { - /// Starts a window with `seq` already recorded as received. - pub fn new(seq: SeqNo) -> Self { - Self { max: seq, seen: 1 } - } - - /// Starts a window accepting only sequence numbers greater than `seq`. - /// - /// Use this when restoring a remembered maximum without its receipt bitmap. - /// All positions at or below that maximum are blocked to prevent accepting replays - /// after their individual receipt history has been discarded. - pub fn new_after(seq: SeqNo) -> Self { - Self { - max: seq, - seen: u128::MAX, - } - } - - /// Returns the highest recorded sequence number. - pub fn max_seq(&self) -> SeqNo { - self.max - } - - /// Returns whether a packet with `seq` may be processed as a new receipt. - /// - /// - Above the highest recorded number: `true`, even if there is a gap. - /// - Within the last 128 positions: `true` if that number has not been recorded - /// or blocked by [`Self::new_after`]; otherwise `false`. - /// - Below those 128 positions: `false`. Receipt history has been discarded there, - /// so a delayed packet can no longer be distinguished from a replay. - /// - /// For example, a window created with `new(200.into())` accepts 201 and 199, - /// rejects the recorded 200, and rejects 72 because it is too old. - /// - /// This is only a check: it does not mark `seq` as received or move the window. - /// A `true` result also says nothing about the packet's authenticity. After the - /// packet passes authentication, call [`Self::update`] to record its receipt. - /// Subsequent checks for that sequence number will then return `false`. - pub fn accepts(&self, seq: SeqNo) -> bool { - seq > self.max || (*self.max - *seq < 128 && self.seen & (1u128 << (*self.max - *seq)) == 0) - } - - /// Records a receipt, advancing the window when necessary. - /// - /// Duplicates and numbers older than the window leave it unchanged. - pub fn update(&mut self, seq: SeqNo) { - if seq > self.max { - self.seen = self.seen.checked_shl((*seq - *self.max).min(128) as u32).unwrap_or(0); - self.max = seq; - } - if let Some(bit) = 1u128.checked_shl((*self.max - *seq).min(128) as u32) { - self.seen |= bit; - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn initial_receipt_is_seen_but_earlier_numbers_are_not() { - let window = SeqNoWindow::new(100.into()); - assert_eq!(window.max_seq(), 100.into()); - assert!(!window.accepts(100.into())); - assert!(window.accepts(99.into())); - assert!(window.accepts(0.into())); - assert!(window.accepts(101.into())); - - let window = SeqNoWindow::new(0.into()); - assert!(!window.accepts(0.into())); - assert!(window.accepts(1.into())); - } - - #[test] - fn reordered_receipts_are_recorded_without_moving_the_maximum() { - let mut window = SeqNoWindow::new(65535.into()); - window.update(65537.into()); - assert!(window.accepts(65536.into())); - // Checking eligibility must not record a packet before it is authenticated. - assert!(window.accepts(65536.into())); - window.update(65536.into()); - window.update(65536.into()); - assert_eq!(window.max_seq(), 65537.into()); - for seq in 65535..=65537 { - assert!(!window.accepts(seq.into())); - } - } - - #[test] - fn oldest_position_is_retained_until_it_leaves_the_window() { - let mut window = SeqNoWindow::new(10.into()); - window.update(137.into()); - assert!(!window.accepts(10.into())); - assert!(window.accepts(11.into())); - window.update(138.into()); - assert!(!window.accepts(10.into())); - assert!(window.accepts(11.into())); - window.update(11.into()); - assert!(!window.accepts(11.into())); - - window.update(10.into()); - assert_eq!(window.max_seq(), 138.into()); - assert!(window.accepts(12.into())); - assert!(!window.accepts(138.into())); - } - - #[test] - fn large_jumps_clear_the_previous_bitmap() { - for gap in [128, 129, 1u64 << 32] { - let mut window = SeqNoWindow::new(138.into()); - window.update(137.into()); - let next = 138 + gap; - window.update(next.into()); - assert_eq!(window.max_seq(), next.into()); - assert!(!window.accepts(138.into())); - assert!(!window.accepts(next.into())); - assert!(window.accepts((next - 1).into())); - assert!(window.accepts((next - 127).into())); - assert!(!window.accepts((next - 128).into())); - } - } - - #[test] - fn mixed_receipts_match_a_set_of_received_numbers() { - use std::collections::BTreeSet; - - for start in [0u64, 65500, u64::MAX - 10000] { - let mut window = SeqNoWindow::new(start.into()); - let mut received = BTreeSet::from([start]); - let mut max = start; - // Advance across word and window boundaries, fill gaps, repeat receipts, - // and submit packets too old to retain. Near u64::MAX, advances saturate. - let deltas = [1, 63, -1, 64, -64, 65, -127, -128, 127, 128, 129, 0]; - for delta in deltas.into_iter().cycle().take(240) { - let seq = max.saturating_add_signed(delta); - window.update(seq.into()); - received.insert(seq); - max = max.max(seq); - assert_eq!(window.max_seq(), max.into()); - - // The reference keeps every receipt and applies only the age cutoff. - for candidate in max.saturating_sub(130)..=max.saturating_add(2) { - let expected = candidate >= max.saturating_sub(127) && !received.contains(&candidate); - assert_eq!( - window.accepts(candidate.into()), - expected, - "start={start}, receipt={seq}, max={max}, candidate={candidate}" - ); - } - } - } - } - - #[test] - fn restored_maximum_blocks_old_receipts_but_allows_new_gaps() { - let mut window = SeqNoWindow::new_after(200.into()); - for seq in 0..=200 { - assert!(!window.accepts(seq.into())); - } - assert!(window.accepts(201.into())); - window.update(203.into()); - assert!(!window.accepts(200.into())); - assert!(window.accepts(201.into())); - assert!(window.accepts(202.into())); - assert!(!window.accepts(203.into())); - window.update(201.into()); - assert!(!window.accepts(201.into())); - assert!(window.accepts(202.into())); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs b/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs deleted file mode 100644 index 2f6c7ff224a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/rtp/srtp.rs +++ /dev/null @@ -1,1606 +0,0 @@ -use std::fmt; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use tracing::{trace, warn}; - -use crate::vendor::str0m::crypto::Aes128CmSha1_80Cipher; -use crate::vendor::str0m::crypto::dtls::{KeyingMaterial, SrtpProfile}; -use crate::vendor::str0m::crypto::{AeadAes128Gcm, AeadAes256Gcm, Aes128CmSha1_80}; -use crate::vendor::str0m::crypto::{AeadAes128GcmCipher, AeadAes256GcmCipher}; -use crate::vendor::str0m::crypto::{CryptoProvider, Sha1HmacProvider, SrtpProvider}; -use crate::vendor::str0m::io::DATAGRAM_MAX_PACKET_SIZE; - -use super::header::RtpHeader; - -// Common among various profiles(defined in RFC3711 Section 4.3) -const LABEL_RTP_AES: u8 = 0; -const LABEL_RTP_AUTHENTICATION_KEY: u8 = 1; -const LABEL_RTP_SALT: u8 = 2; - -const LABEL_RTCP_AES: u8 = 3; -const LABEL_RTCP_AUTHENTICATION_KEY: u8 = 4; -const LABEL_RTCP_SALT: u8 = 5; - -// header = 4 bytes -// ssrc = 4 bytes -// ssrtcp_index = 4 bytes -// tag = bytes -// TOTAL overhead for SRTCP = 12 + T bytes. -// However, each RTCP packet must be on a 4 byte boundary since length is -// given in number of 4 bytes - 1 (making 0 valid). - -pub const SRTP_BLOCK_SIZE: usize = 16; -const SRTCP_INDEX_LEN: usize = 4; -const SRTCP_HEADER_LEN: usize = 8; -const MAX_TAG_LEN: usize = AeadAes256Gcm::TAG_LEN; -pub const SRTCP_OVERHEAD: usize = MAX_TAG_LEN + SRTCP_INDEX_LEN; -pub const SRTP_OVERHEAD: usize = MAX_TAG_LEN; - -/// Initial capacity for the RTP decryption scratch buffer. Sized to fit the -/// largest possible received datagram, so `unprotect_rtp` never has to grow -/// the buffer in practice. -const RX_SCRATCH_CAPACITY: usize = DATAGRAM_MAX_PACKET_SIZE; - -/// Start repeated warnings here, then double the failure count between reports. -const DECRYPT_WARN_INITIAL_COUNT: u64 = 4_096; - -impl SrtpContext { - /// Create an SRTP context for the relevant profile using the provided keying material. - pub fn new(crypto: &CryptoProvider, profile: SrtpProfile, mat: &KeyingMaterial, left: bool) -> Self { - let sha1_hmac_provider = crypto.sha1_hmac_provider; - - match profile { - SrtpProfile::AES128_CM_SHA1_80 => { - let key = SrtpKey::<{ Aes128CmSha1_80::KEY_LEN }, { Aes128CmSha1_80::SALT_LEN }>::new(mat, left); - - let (rtp, rtcp) = Derived::aes_128_cm_sha1_80(crypto.srtp_provider, &key); - - SrtpContext { - rtp, - rtcp, - srtcp_index: 0, - sha1_hmac_provider, - rx_scratch: Vec::with_capacity(RX_SCRATCH_CAPACITY), - decrypt_warnings: DecryptWarnings::default(), - } - } - SrtpProfile::AEAD_AES_128_GCM => { - let key = SrtpKey::<{ AeadAes128Gcm::KEY_LEN }, { AeadAes128Gcm::SALT_LEN }>::new(mat, left); - - let (rtp, rtcp) = Derived::aead_aes_128_gcm(crypto.srtp_provider, &key); - - SrtpContext { - rtp, - rtcp, - srtcp_index: 0, - sha1_hmac_provider, - rx_scratch: Vec::with_capacity(RX_SCRATCH_CAPACITY), - decrypt_warnings: DecryptWarnings::default(), - } - } - SrtpProfile::AEAD_AES_256_GCM => { - let key = SrtpKey::<{ AeadAes256Gcm::KEY_LEN }, { AeadAes256Gcm::SALT_LEN }>::new(mat, left); - - let (rtp, rtcp) = Derived::aead_aes_256_gcm(crypto.srtp_provider, &key); - - SrtpContext { - rtp, - rtcp, - srtcp_index: 0, - sha1_hmac_provider, - rx_scratch: Vec::with_capacity(RX_SCRATCH_CAPACITY), - decrypt_warnings: DecryptWarnings::default(), - } - } - _ => panic!("Unexpected SRTP profile: {profile:?}"), - } - } - - #[cfg(test)] - fn new_aead_aes_128_gcm( - rtp_key: [u8; AeadAes128Gcm::KEY_LEN], - rtp_salt: [u8; AeadAes128Gcm::SALT_LEN], - rtcp_key: [u8; AeadAes128Gcm::KEY_LEN], - rtcp_salt: [u8; AeadAes128Gcm::SALT_LEN], - srtcp_index: u32, - ) -> Self { - let provider = crate::vendor::str0m::crypto::test_default_provider(); - - Self { - rtp: Derived::AeadAes128Gcm { - salt: rtp_salt, - enc: provider.srtp_provider.aead_aes_128_gcm().create_cipher(rtp_key, true), - dec: provider.srtp_provider.aead_aes_128_gcm().create_cipher(rtp_key, false), - }, - rtcp: Derived::AeadAes128Gcm { - salt: rtcp_salt, - enc: provider.srtp_provider.aead_aes_128_gcm().create_cipher(rtcp_key, true), - dec: provider.srtp_provider.aead_aes_128_gcm().create_cipher(rtcp_key, false), - }, - srtcp_index, - sha1_hmac_provider: provider.sha1_hmac_provider, - rx_scratch: Vec::with_capacity(RX_SCRATCH_CAPACITY), - decrypt_warnings: DecryptWarnings::default(), - } - } - - #[cfg(test)] - fn new_aead_aes_256_gcm( - rtp_key: [u8; AeadAes256Gcm::KEY_LEN], - rtp_salt: [u8; AeadAes256Gcm::SALT_LEN], - rtcp_key: [u8; AeadAes256Gcm::KEY_LEN], - rtcp_salt: [u8; AeadAes256Gcm::SALT_LEN], - srtcp_index: u32, - ) -> Self { - let provider = crate::vendor::str0m::crypto::test_default_provider(); - - Self { - rtp: Derived::AeadAes256Gcm { - salt: rtp_salt, - enc: provider.srtp_provider.aead_aes_256_gcm().create_cipher(rtp_key, true), - dec: provider.srtp_provider.aead_aes_256_gcm().create_cipher(rtp_key, false), - }, - rtcp: Derived::AeadAes256Gcm { - salt: rtcp_salt, - enc: provider.srtp_provider.aead_aes_256_gcm().create_cipher(rtcp_key, true), - dec: provider.srtp_provider.aead_aes_256_gcm().create_cipher(rtcp_key, false), - }, - srtcp_index, - sha1_hmac_provider: provider.sha1_hmac_provider, - rx_scratch: Vec::with_capacity(RX_SCRATCH_CAPACITY), - decrypt_warnings: DecryptWarnings::default(), - } - } -} - -#[derive(Debug)] -pub struct SrtpContext { - /// Encryption/decryption derived from srtp_key for RTP. - rtp: Derived, - /// Encryption/decryption derived from srtp_key for RTCP. - rtcp: Derived, - /// Counter for outgoing SRTCP packets. - srtcp_index: u32, - /// SHA1-HMAC provider for AES_128_CM_SHA1_80 profile. - sha1_hmac_provider: &'static dyn Sha1HmacProvider, - /// Reusable scratch buffer for RTP decryption output. Reused across calls - /// to `unprotect_rtp` so we don't allocate a fresh `Vec` per packet. - rx_scratch: Vec, - decrypt_warnings: DecryptWarnings, -} - -/// SrtpContext contains cipher contexts that can't observe broken invariants after a panic. -impl UnwindSafe for SrtpContext {} -impl RefUnwindSafe for SrtpContext {} - -/// Shares one warning budget across all SRTP and SRTCP streams in a receive context. -/// Reports the first failure immediately, then at exponentially increasing counts. -#[derive(Debug, Default)] -struct DecryptWarnings { - failures: u64, - suppressed_srtp: u64, - suppressed_srtcp: u64, -} - -impl DecryptWarnings { - fn warn(&mut self, profile: SrtpProfile, is_rtcp: bool) { - self.failures = self.failures.saturating_add(1); - let should_warn = - self.failures == 1 || (self.failures >= DECRYPT_WARN_INITIAL_COUNT && self.failures.is_power_of_two()); - if !should_warn { - let count = if is_rtcp { - &mut self.suppressed_srtcp - } else { - &mut self.suppressed_srtp - }; - *count = count.saturating_add(1); - return; - } - - let protocol = if is_rtcp { "SRTCP" } else { "SRTP" }; - warn!( - failures = self.failures, - suppressed_srtp = self.suppressed_srtp, - suppressed_srtcp = self.suppressed_srtcp, - "Failed to decrypt {protocol} {profile}" - ); - self.suppressed_srtp = 0; - self.suppressed_srtcp = 0; - } -} - -impl SrtpContext { - pub fn protect_rtp( - &mut self, - buf: &[u8], - header: &RtpHeader, - srtp_index: u64, // same as ext_seq - ) -> Vec { - // SRTP layout - // [header, [rtp, (padding + pad_count)], tag] - - // 0 1 2 3 - // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<+ - // |V=2|P|X| CC |M| PT | sequence number | | - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | - // | timestamp | | - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | - // | synchronization source (SSRC) identifier | | - // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ | - // | contributing source (CSRC) identifiers | | - // | .... | | - // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | - // | RTP extension (OPTIONAL) | | - // +>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | - // | | payload ... | | - // | | +-------------------------------+ | - // | | | RTP padding | RTP pad count | | - // +>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<+ - // | ~ SRTP MKI (OPTIONAL) ~ | - // | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | - // | : authentication tag (RECOMMENDED) : | - // | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | - // | | - // +- Encrypted Portion* Authenticated Portion ---+ - let hlen = header.header_len; - let input = &buf[hlen..]; - - match &mut self.rtp { - Derived::Aes128CmSha1_80 { key, salt, enc, .. } => { - // Counter mode takes arbitrary body lengths, so no 16-byte alignment is required. - let iv = Aes128CmSha1_80::rtp_iv(*salt, *header.ssrc, srtp_index); - - let mut output = vec![0_u8; buf.len() + Aes128CmSha1_80::HMAC_TAG_LEN]; - - enc.encrypt(&iv, input, &mut output[hlen..]).expect("rtp encrypt"); - - output[..hlen].copy_from_slice(&buf[..hlen]); - - let hmac_start = buf.len(); - let sha1_hmac = |k: &[u8], p: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(k, p); - Aes128CmSha1_80::rtp_hmac(sha1_hmac, key, &mut output, srtp_index, hmac_start); - - output - } - Derived::AeadAes128Gcm { salt, enc, .. } => { - let roc = (srtp_index >> 16) as u32; - - let iv = AeadAes128Gcm::rtp_iv(*salt, *header.ssrc, roc, header.sequence_number); - let aad = &buf[..hlen]; - - // Input and output lengths for encryption: - // https://www.rfc-editor.org/rfc/rfc7714#section-5.2.1 - let mut output = vec![0_u8; buf.len() + AeadAes128Gcm::TAG_LEN]; - enc.encrypt(&iv, aad, input, &mut output[hlen..]).expect("rtp encrypt"); - - output[..hlen].copy_from_slice(aad); - - output - } - Derived::AeadAes256Gcm { salt, enc, .. } => { - let roc = (srtp_index >> 16) as u32; - - let iv = AeadAes256Gcm::rtp_iv(*salt, *header.ssrc, roc, header.sequence_number); - let aad = &buf[..hlen]; - - // Input and output lengths for encryption: - // https://www.rfc-editor.org/rfc/rfc7714#section-5.2.1 - let mut output = vec![0_u8; buf.len() + AeadAes256Gcm::TAG_LEN]; - enc.encrypt(&iv, aad, input, &mut output[hlen..]).expect("rtp encrypt"); - - output[..hlen].copy_from_slice(aad); - - output - } - } - } - - /// Decrypts an SRTP packet into the internal reusable scratch buffer and - /// returns a slice of the plaintext bytes. The returned slice borrows from - /// `self` until the next mutable use; the scratch buffer is reused across - /// calls to avoid per-packet allocation. - pub fn unprotect_rtp( - &mut self, - buf: &[u8], - header: &RtpHeader, - srtp_index: u64, // same as ext_seq - ) -> Option<&[u8]> { - match &mut self.rtp { - Derived::Aes128CmSha1_80 { key, salt, dec, .. } => { - if buf.len() < header.header_len + Aes128CmSha1_80::HMAC_TAG_LEN { - return None; - } - - let hmac_start = buf.len() - Aes128CmSha1_80::HMAC_TAG_LEN; - - let sha1_hmac = |k: &[u8], p: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(k, p); - if !Aes128CmSha1_80::rtp_verify(sha1_hmac, key, &buf[..hmac_start], srtp_index, &buf[hmac_start..]) { - trace!("unprotect_rtp hmac verify fail"); - return None; - } - - let iv = Aes128CmSha1_80::rtp_iv(*salt, *header.ssrc, srtp_index); - - let input = &buf[header.header_len..hmac_start]; - self.rx_scratch.resize(input.len(), 0); - - if let Err(e) = dec.decrypt(&iv, input, &mut self.rx_scratch) { - trace!( - "Failed to decrypt SRTP {} ({}): {}", - self.rtp.profile(), - error_details(header, srtp_index), - e - ); - self.decrypt_warnings.warn(self.rtp.profile(), false); - return None; - }; - - Some(&self.rx_scratch[..input.len()]) - } - Derived::AeadAes128Gcm { salt, dec, .. } => { - if buf.len() < header.header_len + AeadAes128Gcm::TAG_LEN { - return None; - } - - let roc: u32 = (srtp_index >> 16) as u32; - let seq = header.sequence_number; - - let iv = AeadAes128Gcm::rtp_iv(*salt, *header.ssrc, roc, seq); - - let (aad, input) = buf.split_at(header.header_len); - // Input and output lengths for decryption: - // https://www.rfc-editor.org/rfc/rfc7714#section-5.2.2 - let out_len = input.len() - AeadAes128Gcm::TAG_LEN; - self.rx_scratch.resize(out_len, 0); - - match dec.decrypt(&iv, &[aad], input, &mut self.rx_scratch) { - Ok(v) => v, - Err(e) => { - trace!( - "Failed to decrypt SRTP {} ({}): {}", - self.rtp.profile(), - error_details(header, srtp_index), - e - ); - self.decrypt_warnings.warn(self.rtp.profile(), false); - return None; - } - }; - - Some(&self.rx_scratch[..out_len]) - } - Derived::AeadAes256Gcm { salt, dec, .. } => { - if buf.len() < header.header_len + AeadAes256Gcm::TAG_LEN { - return None; - } - - let roc: u32 = (srtp_index >> 16) as u32; - let seq = header.sequence_number; - - let iv = AeadAes256Gcm::rtp_iv(*salt, *header.ssrc, roc, seq); - - let (aad, input) = buf.split_at(header.header_len); - // Input and output lengths for decryption: - // https://www.rfc-editor.org/rfc/rfc7714#section-5.2.2 - let out_len = input.len() - AeadAes256Gcm::TAG_LEN; - self.rx_scratch.resize(out_len, 0); - - match dec.decrypt(&iv, &[aad], input, &mut self.rx_scratch) { - Ok(v) => v, - Err(e) => { - trace!( - "Failed to decrypt SRTP {} ({}): {}", - self.rtp.profile(), - error_details(header, srtp_index), - e - ); - self.decrypt_warnings.warn(self.rtp.profile(), false); - return None; - } - }; - - Some(&self.rx_scratch[..out_len]) - } - } - } - - pub fn protect_rtcp(&mut self, buf: &[u8]) -> Vec { - let srtcp_index = self.srtcp_index; - - // https://tools.ietf.org/html/rfc3711#page-15 - // The SRTCP index MUST be set to zero before the first SRTCP - // packet is sent, and MUST be incremented by one, - // modulo 2^31, after each SRTCP packet is sent. - self.srtcp_index = (self.srtcp_index + 1) % 2_u32.pow(31); - - // e is always encrypted, rest is 31 byte index. - let e_and_si = 0x8000_0000 | srtcp_index; - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - - if ssrc == 0 { - warn!("SSRC 0 does not make a good SRTCP IV"); - } - - match &mut self.rtcp { - Derived::Aes128CmSha1_80 { key, salt, enc, .. } => { - let iv = Aes128CmSha1_80::rtp_iv(*salt, ssrc, srtcp_index as u64); - - let final_size = buf.len() + SRTCP_INDEX_LEN + Aes128CmSha1_80::HMAC_TAG_LEN; - let mut output = vec![0_u8; final_size]; - - output[0..8].copy_from_slice(&buf[0..8]); - let input = &buf[8..]; - enc.encrypt(&iv, input, &mut output[8..]).expect("rtcp encrypt"); - - let to = &mut output[buf.len()..]; - to[0..4].copy_from_slice(&e_and_si.to_be_bytes()); - - let hmac_index = final_size - Aes128CmSha1_80::HMAC_TAG_LEN; - let sha1_hmac = |k: &[u8], p: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(k, p); - Aes128CmSha1_80::rtcp_hmac(sha1_hmac, key, &mut output, hmac_index); - - output - } - Derived::AeadAes128Gcm { salt, enc, .. } => { - let iv = AeadAes128Gcm::rtcp_iv(*salt, ssrc, srtcp_index); - - let mut aad = [0; AeadAes128Gcm::RTCP_AAD_LEN]; - aad[..8].copy_from_slice(&buf[..8]); - aad[8..12].copy_from_slice(&e_and_si.to_be_bytes()); - - let mut output = vec![0_u8; buf.len() + SRTCP_INDEX_LEN + AeadAes128Gcm::TAG_LEN]; - output[0..8].copy_from_slice(&buf[0..8]); - let input = &buf[8..]; - - let enc_start = 8; - let enc_end = input.len() + 8 + AeadAes128Gcm::TAG_LEN; - let encout = &mut output[enc_start..enc_end]; - - enc.encrypt(&iv, &aad, input, encout).expect("rtcp encrypt"); - - let to = &mut output[enc_end..]; - to[0..4].copy_from_slice(&e_and_si.to_be_bytes()); - - output - } - Derived::AeadAes256Gcm { salt, enc, .. } => { - let iv = AeadAes256Gcm::rtcp_iv(*salt, ssrc, srtcp_index); - - let mut aad = [0; AeadAes256Gcm::RTCP_AAD_LEN]; - aad[..8].copy_from_slice(&buf[..8]); - aad[8..12].copy_from_slice(&e_and_si.to_be_bytes()); - - let mut output = vec![0_u8; buf.len() + SRTCP_INDEX_LEN + AeadAes256Gcm::TAG_LEN]; - output[0..8].copy_from_slice(&buf[0..8]); - let input = &buf[8..]; - - let enc_start = 8; - let enc_end = input.len() + 8 + AeadAes256Gcm::TAG_LEN; - let encout = &mut output[enc_start..enc_end]; - - enc.encrypt(&iv, &aad, input, encout).expect("rtcp encrypt"); - - let to = &mut output[enc_end..]; - to[0..4].copy_from_slice(&e_and_si.to_be_bytes()); - - output - } - } - } - - // SRTCP layout - // ["header", ssrc, payload, ["header", ssrc, payload], ...], ssrtcp_index, tag] - // - // |----------------------------------------------------------------------| - // authenticated - // - // |--------------------------------------| - // encrypted (aes) - pub fn unprotect_rtcp(&mut self, buf: &[u8]) -> Option> { - match &mut self.rtcp { - Derived::Aes128CmSha1_80 { key, salt, dec, .. } => { - if buf.len() < SRTCP_HEADER_LEN + SRTCP_INDEX_LEN + Aes128CmSha1_80::HMAC_TAG_LEN { - return None; - } - - let hmac_start = buf.len() - Aes128CmSha1_80::HMAC_TAG_LEN; - - let sha1_hmac = |k: &[u8], p: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(k, p); - if !Aes128CmSha1_80::rtcp_verify(sha1_hmac, key, &buf[..hmac_start], &buf[hmac_start..]) { - trace!("unprotect_rtcp hmac verify fail"); - return None; - } - - let idx_start = hmac_start - SRTCP_INDEX_LEN; - - let srtcp_index_be = [ - buf[idx_start], - buf[idx_start + 1], - buf[idx_start + 2], - buf[idx_start + 3], - ]; - - // E-flag and SRTCP index. - let e_and_si = u32::from_be_bytes(srtcp_index_be); - - let is_encrypted = e_and_si & 0x8000_0000 > 0; - - if !is_encrypted { - // Non-encrypted we can just return - return Some(buf[0..idx_start].to_vec()); - } - - // The SRTCP index is a 31-bit counter for the SRTCP packet. - let srtcp_index = e_and_si & 0x7fff_ffff; - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - - let iv = Aes128CmSha1_80::rtp_iv(*salt, ssrc, srtcp_index as u64); - - // The Encrypted Portion of an SRTCP packet consists of the encryption - // of the RTCP payload of the equivalent compound RTCP packet, from the - // first RTCP packet, i.e., from the ninth (9) octet to the end of the - // compound packet. - let input = &buf[8..idx_start]; - let mut output = vec![0_u8; input.len() + 8]; - output[0..8].copy_from_slice(&buf[0..8]); - - if let Err(e) = dec.decrypt(&iv, input, &mut output[8..]) { - trace!("Failed to decrypt SRTCP {}: {}", self.rtcp.profile(), e); - self.decrypt_warnings.warn(self.rtcp.profile(), true); - return None; - } - - Some(output) - } - Derived::AeadAes128Gcm { salt, dec, .. } => { - if buf.len() < SRTCP_HEADER_LEN + SRTCP_INDEX_LEN + AeadAes128Gcm::TAG_LEN { - // Too short - return None; - } - - let idx_start = buf.len() - SRTCP_INDEX_LEN; - - // Assume no MKI - let e_and_si = u32::from_be_bytes( - buf[idx_start..buf.len()] - .try_into() - // This is ok because SRTCP_INDEX_LEN is 4 bytes and the buffer is at least - // that long. - .expect("SRTCP_INDEX_LEN to be 4"), - ); - let is_encrypted = e_and_si & 0x8000_0000 > 0; - - // The Encrypted Portion of an SRTCP packet consists of the encryption - // of the RTCP payload of the equivalent compound RTCP packet, from the - // first RTCP packet, i.e., from the ninth (9) octet to the end of the - // compound packet. - let input = if is_encrypted { - &buf[8..idx_start] - } else { - // No, encryption but we still pass the tag down to decrypt so it can verify - // it. - &buf[idx_start - AeadAes128Gcm::TAG_LEN..idx_start] - }; - - // The SRTCP index is a 31-bit counter for the SRTCP packet. - let srtcp_index = e_and_si & 0x7fff_ffff; - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - - let iv = AeadAes128Gcm::rtcp_iv(*salt, ssrc, srtcp_index); - // Declared out here for lifetime purposes, only used in the first branch of the if. - let mut encrypted_aad = [0; AeadAes128Gcm::RTCP_AAD_LEN]; - let mut aads: [&[u8]; 2] = [&[], &[]]; - - if is_encrypted { - encrypted_aad[0..8].copy_from_slice(&buf[0..8]); - encrypted_aad[8..12].copy_from_slice(&e_and_si.to_be_bytes()); - - aads[0] = encrypted_aad.as_slice(); - } else { - // The whole packet is AAD - aads[0] = &buf[0..idx_start - AeadAes128Gcm::TAG_LEN]; - aads[1] = &buf[idx_start..]; - }; - - let mut output = vec![0_u8; buf.len() - AeadAes128Gcm::TAG_LEN - SRTCP_INDEX_LEN]; - output[0..8].copy_from_slice(&buf[0..8]); - - let count = match dec.decrypt(&iv, &aads, input, &mut output[8..]) { - Ok(c) => c, - Err(e) => { - trace!("Failed to decrypt SRTCP {}: {}", self.rtcp.profile(), e); - self.decrypt_warnings.warn(self.rtcp.profile(), true); - return None; - } - }; - - if is_encrypted { - output.truncate(8 + count); - } else { - // decrypt didn't error, the data is authenticated. - output.copy_from_slice(&buf[0..buf.len() - SRTCP_INDEX_LEN - AeadAes128Gcm::TAG_LEN]) - } - - Some(output) - } - Derived::AeadAes256Gcm { salt, dec, .. } => { - if buf.len() < SRTCP_HEADER_LEN + SRTCP_INDEX_LEN + AeadAes256Gcm::TAG_LEN { - // Too short - return None; - } - - let idx_start = buf.len() - SRTCP_INDEX_LEN; - - // Assume no MKI - let e_and_si = u32::from_be_bytes( - buf[idx_start..buf.len()] - .try_into() - // This is ok because SRTCP_INDEX_LEN is 4 bytes and the buffer is at least - // that long. - .expect("SRTCP_INDEX_LEN to be 4"), - ); - let is_encrypted = e_and_si & 0x8000_0000 > 0; - - // The Encrypted Portion of an SRTCP packet consists of the encryption - // of the RTCP payload of the equivalent compound RTCP packet, from the - // first RTCP packet, i.e., from the ninth (9) octet to the end of the - // compound packet. - let input = if is_encrypted { - &buf[8..idx_start] - } else { - // No, encryption but we still pass the tag down to decrypt so it can verify - // it. - &buf[idx_start - AeadAes256Gcm::TAG_LEN..idx_start] - }; - - // The SRTCP index is a 31-bit counter for the SRTCP packet. - let srtcp_index = e_and_si & 0x7fff_ffff; - let ssrc = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - - let iv = AeadAes256Gcm::rtcp_iv(*salt, ssrc, srtcp_index); - // Declared out here for lifetime purposes, only used in the first branch of the if. - let mut encrypted_aad = [0; AeadAes256Gcm::RTCP_AAD_LEN]; - let mut aads: [&[u8]; 2] = [&[], &[]]; - - if is_encrypted { - encrypted_aad[0..8].copy_from_slice(&buf[0..8]); - encrypted_aad[8..12].copy_from_slice(&e_and_si.to_be_bytes()); - - aads[0] = encrypted_aad.as_slice(); - } else { - // The whole packet is AAD - aads[0] = &buf[0..idx_start - AeadAes256Gcm::TAG_LEN]; - aads[1] = &buf[idx_start..]; - }; - - let mut output = vec![0_u8; buf.len() - AeadAes256Gcm::TAG_LEN - SRTCP_INDEX_LEN]; - output[0..8].copy_from_slice(&buf[0..8]); - - let count = match dec.decrypt(&iv, &aads, input, &mut output[8..]) { - Ok(c) => c, - Err(e) => { - trace!("Failed to decrypt SRTCP {}: {}", self.rtcp.profile(), e); - self.decrypt_warnings.warn(self.rtcp.profile(), true); - return None; - } - }; - - if is_encrypted { - output.truncate(8 + count); - } else { - // decrypt didn't error, the data is authenticated. - output.copy_from_slice(&buf[0..buf.len() - SRTCP_INDEX_LEN - AeadAes256Gcm::TAG_LEN]) - } - - Some(output) - } - } - } -} - -/// SrtpKeys created from DTLS SrtpKeyMaterial. -#[derive(Debug)] -struct SrtpKey { - master: [u8; ML], - salt: [u8; SL], -} - -impl SrtpKey { - pub fn new(mat: &KeyingMaterial, left: bool) -> Self { - // layout in SrtpKeyMaterial is [key_input, key_output, salt_input, salt_output] - - // Invariant - assert!( - mat.len() == ML * 2 + SL * 2, - "The KeyingMaterial provided to SrtpKey::new must be ML * 2 + SL * 2 in length" - ); - - // offset 0, offset 1 - let (o0, o1) = if left { (0, 0) } else { (ML, SL) }; - - let mut master = [0; ML]; - let mut salt = [0; SL]; - - master[0..ML].copy_from_slice(&mat[o0..(o0 + ML)]); - salt[0..SL].copy_from_slice(&mat[(ML + ML + o1)..(ML + ML + o1 + SL)]); - - SrtpKey { master, salt } - } - - fn derive(&self, crypto: &dyn SrtpProvider, label: u8, out: &mut [u8]) { - // AES-CM (128 or 256 bits) defined in RFC3711 - assert!(ML == 16 || ML == 32, "Only valid for 128 bit master keys"); - assert!(SL <= 14, "Only valid for 128 bit master keys"); - let mut i = 0; // index in out - - // input layout: [salt[SL] || label, round[2]] (|| is xor 7th byte) - let mut input = [0; 16]; - - input[0..SL].copy_from_slice(&self.salt[..]); - input[7] ^= label; - - let mut buf = [0; 16 + 16]; // output from each AES - let mut round: u16 = 0; // counter for each AES round - - // loop each AES round - loop { - if i == out.len() { - break; - } - - // splice in round at bottom of input - input[14..].copy_from_slice(&round.to_be_bytes()[..]); - - // default key derivation function, which uses AES-128 in Counter Mode - match ML { - 16 => crypto.srtp_aes_128_ecb_round(&self.master, &input[..], &mut buf[..]), - 32 => crypto.srtp_aes_256_ecb_round(&self.master, &input[..], &mut buf[..]), - _ => panic!("Only valid for 128 or 256 bit master keys"), - } - - // Copy to output. Even if we get 32 bytes of output with AES 128 ECB, we - // only use the first 16. That matches the tests in the RFC. - for j in buf.iter().take(16) { - if i == out.len() { - break; - } - out[i] = *j; - i += 1; - } - - round += 1; - } - } -} - -/// Encryption/decryption derived from the SrtpKey. -enum Derived { - Aes128CmSha1_80 { - key: [u8; 20], - salt: [u8; 14], - enc: Box, - dec: Box, - }, - AeadAes128Gcm { - salt: [u8; 12], - enc: Box, - dec: Box, - }, - AeadAes256Gcm { - salt: [u8; 12], - enc: Box, - dec: Box, - }, -} - -impl Derived { - fn aes_128_cm_sha1_80( - crypto: &dyn SrtpProvider, - srtp_key: &SrtpKey<{ Aes128CmSha1_80::KEY_LEN }, { Aes128CmSha1_80::SALT_LEN }>, - ) -> (Self, Self) { - // RTP AES Counter - let mut rtp_aes = [0; Aes128CmSha1_80::KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTP_AES, &mut rtp_aes[..]); - - // RTP SHA1 HMAC - let rtp_hmac = { - let mut hmac = [0; Aes128CmSha1_80::HMAC_KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTP_AUTHENTICATION_KEY, &mut hmac[..]); - hmac - }; - - // RTP IV SALT - let mut rtp_salt = [0; Aes128CmSha1_80::SALT_LEN]; - srtp_key.derive(crypto, LABEL_RTP_SALT, &mut rtp_salt[..]); - - // RTCP AES Counter - let mut rtcp_aes = [0; Aes128CmSha1_80::KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_AES, &mut rtcp_aes[..]); - - // RTCP SHA1 HMAC - let rtcp_hmac = { - let mut hmac = [0; Aes128CmSha1_80::HMAC_KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_AUTHENTICATION_KEY, &mut hmac[..]); - hmac - }; - - // RTCP IV SALT - let mut rtcp_salt = [0; Aes128CmSha1_80::SALT_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_SALT, &mut rtcp_salt[..]); - - let rtp = Derived::Aes128CmSha1_80 { - key: rtp_hmac, - salt: rtp_salt, - enc: crypto.aes_128_cm_sha1_80().create_cipher(rtp_aes, true), - dec: crypto.aes_128_cm_sha1_80().create_cipher(rtp_aes, false), - }; - - let rtcp = Derived::Aes128CmSha1_80 { - key: rtcp_hmac, - salt: rtcp_salt, - enc: crypto.aes_128_cm_sha1_80().create_cipher(rtcp_aes, true), - dec: crypto.aes_128_cm_sha1_80().create_cipher(rtcp_aes, false), - }; - - (rtp, rtcp) - } - - fn aead_aes_128_gcm( - crypto: &dyn SrtpProvider, - srtp_key: &SrtpKey<{ AeadAes128Gcm::KEY_LEN }, { AeadAes128Gcm::SALT_LEN }>, - ) -> (Derived, Derived) { - // RTP session key - let mut rtp_aes = [0; AeadAes128Gcm::KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTP_AES, &mut rtp_aes[..]); - - // RTP session salt - let mut rtp_salt = [0; AeadAes128Gcm::SALT_LEN]; - srtp_key.derive(crypto, LABEL_RTP_SALT, &mut rtp_salt[..]); - - // RTCP session key - let mut rtcp_aes = [0; AeadAes128Gcm::KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_AES, &mut rtcp_aes[..]); - - // RTCP session salt - let mut rtcp_salt = [0; AeadAes128Gcm::SALT_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_SALT, &mut rtcp_salt[..]); - - let rtp = Derived::AeadAes128Gcm { - salt: rtp_salt, - enc: crypto.aead_aes_128_gcm().create_cipher(rtp_aes, true), - dec: crypto.aead_aes_128_gcm().create_cipher(rtp_aes, false), - }; - - let rtcp = Derived::AeadAes128Gcm { - salt: rtcp_salt, - enc: crypto.aead_aes_128_gcm().create_cipher(rtcp_aes, true), - dec: crypto.aead_aes_128_gcm().create_cipher(rtcp_aes, false), - }; - - (rtp, rtcp) - } - - fn aead_aes_256_gcm( - crypto: &dyn SrtpProvider, - srtp_key: &SrtpKey<{ AeadAes256Gcm::KEY_LEN }, { AeadAes256Gcm::SALT_LEN }>, - ) -> (Derived, Derived) { - // RTP session key - let mut rtp_aes = [0; AeadAes256Gcm::KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTP_AES, &mut rtp_aes[..]); - - // RTP session salt - let mut rtp_salt = [0; AeadAes256Gcm::SALT_LEN]; - srtp_key.derive(crypto, LABEL_RTP_SALT, &mut rtp_salt[..]); - - // RTCP session key - let mut rtcp_aes = [0; AeadAes256Gcm::KEY_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_AES, &mut rtcp_aes[..]); - - // RTCP session salt - let mut rtcp_salt = [0; AeadAes256Gcm::SALT_LEN]; - srtp_key.derive(crypto, LABEL_RTCP_SALT, &mut rtcp_salt[..]); - - let rtp = Derived::AeadAes256Gcm { - salt: rtp_salt, - enc: crypto.aead_aes_256_gcm().create_cipher(rtp_aes, true), - dec: crypto.aead_aes_256_gcm().create_cipher(rtp_aes, false), - }; - - let rtcp = Derived::AeadAes256Gcm { - salt: rtcp_salt, - enc: crypto.aead_aes_256_gcm().create_cipher(rtcp_aes, true), - dec: crypto.aead_aes_256_gcm().create_cipher(rtcp_aes, false), - }; - - (rtp, rtcp) - } - - fn profile(&self) -> SrtpProfile { - match self { - Derived::Aes128CmSha1_80 { .. } => SrtpProfile::AES128_CM_SHA1_80, - Derived::AeadAes128Gcm { .. } => SrtpProfile::AEAD_AES_128_GCM, - Derived::AeadAes256Gcm { .. } => SrtpProfile::AEAD_AES_256_GCM, - } - } -} - -impl fmt::Debug for Derived { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Derived") - } -} - -fn error_details(header: &RtpHeader, srtp_index: u64) -> String { - format!( - "SSRC: {} seq_no: {} pt: {} mid: {:?} rid: {:?} rid_repair: {:?} srtp_index: {}", - header.ssrc, - header.sequence_number, - header.payload_type, - header.ext_vals.mid, - header.ext_vals.rid, - header.ext_vals.rid_repair, - srtp_index - ) -} - -#[cfg(test)] -mod test { - use std::io::Write; - use std::sync::{Arc, Mutex}; - - use super::*; - - #[derive(Clone, Default)] - struct CapturedLogs(Arc>>); - - impl Write for CapturedLogs { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().unwrap().write(buf) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - - impl CapturedLogs { - fn lines(&self) -> Vec { - String::from_utf8(self.0.lock().unwrap().clone()) - .unwrap() - .lines() - .map(str::to_owned) - .collect() - } - } - - #[test] - fn aead_128_decryption_warnings_are_rate_limited() { - for rtcp_first in [false, true] { - check_decryption_warning_rate_limit(SrtpProfile::AEAD_AES_128_GCM, rtcp_first); - } - } - - #[test] - fn aead_256_decryption_warnings_are_rate_limited() { - for rtcp_first in [false, true] { - check_decryption_warning_rate_limit(SrtpProfile::AEAD_AES_256_GCM, rtcp_first); - } - } - - fn check_decryption_warning_rate_limit(profile: SrtpProfile, rtcp_first: bool) { - let logs = CapturedLogs::default(); - let writer = logs.clone(); - let subscriber = tracing_subscriber::fmt() - .without_time() - .with_ansi(false) - .with_max_level(tracing::Level::WARN) - .with_writer(move || writer.clone()) - .finish(); - - tracing::subscriber::with_default(subscriber, || { - let crypto = crate::vendor::str0m::crypto::test_default_provider(); - let mat = KeyingMaterial::new(&vec![0; profile.keying_material_len()]); - let mut context = SrtpContext::new(crypto, profile, &mat, true); - let plaintext_rtp = [0x80, 111, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 42]; - let header = RtpHeader::parse(&plaintext_rtp, &crate::vendor::str0m::rtp_::ExtensionMap::empty()).unwrap(); - let valid_rtp = context.protect_rtp(&plaintext_rtp, &header, 1); - let plaintext_rtcp = [0x80, 201, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0]; - let valid_rtcp = context.protect_rtcp(&plaintext_rtcp); - - assert_eq!(context.unprotect_rtp(&valid_rtp, &header, 1).unwrap(), &[42]); - assert_eq!(context.unprotect_rtcp(&valid_rtcp).unwrap(), plaintext_rtcp); - assert!(logs.lines().is_empty()); - - // Corrupt both authentication tags. - let mut rtp = valid_rtp.clone(); - let mut rtcp = valid_rtcp.clone(); - *rtp.last_mut().unwrap() ^= 1; - let rtcp_tag_end = rtcp.len() - SRTCP_INDEX_LEN - 1; - rtcp[rtcp_tag_end] ^= 1; - if rtcp_first { - assert!(context.unprotect_rtcp(&rtcp).is_none()); - } else { - assert!(context.unprotect_rtp(&rtp, &header, 1).is_none()); - } - assert_eq!(logs.lines().len(), 1, "the first failure warns immediately"); - assert!(logs.lines()[0].contains("suppressed_srtp=0 suppressed_srtcp=0")); - - for ssrc in 1u32..=2_046 { - // Changing SSRCs must not create additional warning budgets. - rtp[8..12].copy_from_slice(&ssrc.to_be_bytes()); - rtcp[4..8].copy_from_slice(&ssrc.to_be_bytes()); - let header = RtpHeader::parse(&rtp, &crate::vendor::str0m::rtp_::ExtensionMap::empty()).unwrap(); - assert!(context.unprotect_rtp(&rtp, &header, 1).is_none()); - assert!(context.unprotect_rtcp(&rtcp).is_none()); - } - rtp[8..12].copy_from_slice(&plaintext_rtp[8..12]); - rtcp[4..8].copy_from_slice(&plaintext_rtcp[4..8]); - - // Successful packets do not reset the warning budget or failure counts. - assert!(context.unprotect_rtp(&valid_rtp, &header, 1).is_some()); - assert!(context.unprotect_rtcp(&valid_rtcp).is_some()); - assert!(context.unprotect_rtp(&rtp, &header, 1).is_none()); - assert!(context.unprotect_rtcp(&rtcp).is_none()); - assert_eq!(logs.lines().len(), 1, "4,095 failures still yield one warning"); - - // Either protocol can trigger the next report at failure 4,096. - if rtcp_first { - assert!(context.unprotect_rtp(&rtp, &header, 1).is_none()); - } else { - assert!(context.unprotect_rtcp(&rtcp).is_none()); - } - let lines = logs.lines(); - assert_eq!(lines.len(), 2); - assert!(lines[1].contains("suppressed_srtp=2047 suppressed_srtcp=2047")); - - for failure in 0..4_095 { - if failure % 2 == 0 { - assert!(context.unprotect_rtp(&rtp, &header, 1).is_none()); - } else { - assert!(context.unprotect_rtcp(&rtcp).is_none()); - } - } - assert_eq!(logs.lines().len(), 2, "the next report waits until failure 8,192"); - assert!(context.unprotect_rtcp(&rtcp).is_none()); - let lines = logs.lines(); - assert_eq!(lines.len(), 3); - assert!(lines[2].contains("suppressed_srtp=2048 suppressed_srtcp=2047")); - - for failure in 0..8_191 { - if failure % 2 == 0 { - assert!(context.unprotect_rtp(&rtp, &header, 1).is_none()); - } else { - assert!(context.unprotect_rtcp(&rtcp).is_none()); - } - if failure == 4_095 { - assert_eq!(logs.lines().len(), 3, "the reporting gap doubles"); - } - } - assert_eq!(logs.lines().len(), 3, "16,383 failures yield three warnings"); - assert!(context.unprotect_rtcp(&rtcp).is_none()); - let lines = logs.lines(); - assert_eq!(lines.len(), 4); - assert!(lines[3].contains("suppressed_srtp=4096 suppressed_srtcp=4095")); - - let mut independent = SrtpContext::new(crypto, profile, &mat, true); - assert!(independent.unprotect_rtcp(&rtcp).is_none()); - let lines = logs.lines(); - assert_eq!(lines.len(), 5, "independent contexts warn immediately"); - assert!(lines[4].contains("suppressed_srtp=0 suppressed_srtcp=0")); - for (line, count) in lines.iter().zip([1, 4_096, 8_192, 16_384, 1]) { - assert_eq!(line.split_whitespace().next(), Some("WARN")); - assert!(line.contains(&format!("failures={count} "))); - } - }); - } - - #[test] - fn derive_key() { - crate::vendor::str0m::init_crypto_default(); - let provider = crate::vendor::str0m::crypto::from_feature_flags(); - let crypto = provider.srtp_provider; - - // https://tools.ietf.org/html/rfc3711#appendix-B.3 - // - // Key Derivation Test Vectors. - - let master = [ - 0xE1, 0xF9, 0x7A, 0x0D, 0x3E, 0x01, 0x8B, 0xE0, // - 0xD6, 0x4F, 0xA3, 0x2C, 0x06, 0xDE, 0x41, 0x39, - ]; - - let salt = [ - 0x0E, 0xC6, 0x75, 0xAD, 0x49, 0x8A, 0xFE, // - 0xEB, 0xB6, 0x96, 0x0B, 0x3A, 0xAB, 0xE6, - ]; - - let sk = SrtpKey { master, salt }; - - // aes crypto key - let mut out = [0_u8; 16]; - sk.derive(crypto, 0, &mut out[..]); - - assert_eq!( - out, - [ - 0xC6, 0x1E, 0x7A, 0x93, 0x74, 0x4F, 0x39, 0xEE, // - 0x10, 0x73, 0x4A, 0xFE, 0x3F, 0xF7, 0xA0, 0x87 - ] - ); - - // hmac - let mut out = [0_u8; 20]; - sk.derive(crypto, 1, &mut out[..]); - - assert_eq!( - out, - [ - 0xCE, 0xBE, 0x32, 0x1F, 0x6F, 0xF7, 0x71, 0x6B, // - 0x6F, 0xD4, 0xAB, 0x49, 0xAF, 0x25, 0x6A, 0x15, // - 0x6D, 0x38, 0xBA, 0xA4 - ] - ); - - // salt - let mut out = [0_u8; 14]; - sk.derive(crypto, 2, &mut out[..]); - - assert_eq!( - out, - [ - 0x30, 0xCB, 0xBC, 0x08, 0x86, 0x3D, 0x8C, // - 0x85, 0xD4, 0x9D, 0xB3, 0x4A, 0x9A, 0xE1 - ] - ); - } - - mod test_aes128_cm_sha1_80 { - use super::*; - - const MAT: [u8; 60] = [ - 0x2C, 0xB0, 0x23, 0x46, 0xB4, 0x22, 0x76, 0xA6, 0x72, 0xCF, 0xD1, 0x43, 0xAE, 0xC2, 0xD5, 0xEE, 0xDD, 0xDE, - 0x55, 0xF0, 0xAD, 0x7B, 0xCA, 0xC2, 0x26, 0x66, 0xF1, 0xC6, 0x38, 0x61, 0x73, 0xED, 0x6E, 0xB2, 0x5C, 0xB7, - 0xD2, 0x6A, 0x61, 0xA1, 0xEE, 0x2C, 0x21, 0x0A, 0xDA, 0xE7, 0x60, 0xAA, 0xA2, 0xFD, 0x67, 0xB6, 0x72, 0xC4, - 0x1A, 0xED, 0x10, 0x5F, 0x9D, 0x36, - ]; - - const SRTCP: &[u8] = &[ - // header - 0x80, 0xC8, 0x00, 0x06, // - // ssrc - 0x3C, 0xD7, 0xCC, 0x13, // - // encrypted payload - 0xB7, 0xC8, 0x31, 0xDC, 0xB7, 0x76, 0xCD, 0x8D, 0xC2, 0x6F, 0xDA, 0x1D, 0x9B, 0xFC, 0x8E, 0xE6, 0x58, 0x9A, - 0x1A, 0x8A, 0x49, 0x28, 0x9C, 0xAE, 0xB2, 0x64, 0x20, 0x0C, 0x37, 0xD2, 0xD0, 0xA4, 0xAF, 0xAC, 0x63, 0x85, - 0xFF, 0xC6, 0x0D, 0xEC, 0x7D, 0x06, 0xD4, 0x87, 0x3D, 0xD3, 0xA8, 0xCC, // - // E flag and srtcp index (1) - 0x80, 0x00, 0x00, 0x01, // - // hmac - 0xB7, 0xBB, 0x52, 0x65, 0x21, 0xD1, 0xE7, 0x3C, 0x0F, 0xC0, - ]; - - const DECRYPTED_PAYLOAD: &[u8] = &[ - 0x80, 0xc8, 0x00, 0x06, 0x3c, 0xd7, 0xcc, 0x13, 0xe2, 0xee, 0x35, 0xc8, 0x60, 0x4e, 0x61, 0x8c, 0x26, 0xf3, - 0x27, 0x34, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x14, 0x07, 0x81, 0xca, 0x00, 0x06, 0x3c, 0xd7, 0xcc, 0x13, - 0x01, 0x10, 0x38, 0x6e, 0x46, 0x75, 0x32, 0x68, 0x57, 0x66, 0x72, 0x4d, 0x44, 0x72, 0x47, 0x66, 0x34, 0x6f, - 0x00, 0x00, - ]; - - #[test] - fn unprotect_rtcp() { - let key_mat = KeyingMaterial::new(&MAT); - let crypto = crate::vendor::str0m::crypto::test_default_provider(); - let mut ctx_rx = SrtpContext::new(crypto, SrtpProfile::AES128_CM_SHA1_80, &key_mat, true); - ctx_rx.srtcp_index = 1; - - let decrypted = ctx_rx.unprotect_rtcp(SRTCP).unwrap(); - - assert_eq!(ctx_rx.srtcp_index, 1); - // check srtcp_index in incoming was indeed 1 - let srtcp_index = SRTCP.len() - Aes128CmSha1_80::HMAC_TAG_LEN - SRTCP_INDEX_LEN; - let e_and_i = &SRTCP[srtcp_index..(srtcp_index + 4)]; - assert_eq!(e_and_i, &0x8000_0001_u32.to_be_bytes()); - assert_eq!(decrypted, DECRYPTED_PAYLOAD); - - // Take us back to where we started. - let encrypted = ctx_rx.protect_rtcp(&decrypted); - assert_eq!(encrypted, SRTCP); - } - } - - mod test_aead_aes_128_gcm { - use crate::vendor::str0m::crypto::AeadAes128Gcm; - use crate::vendor::str0m::rtp_::ExtensionMap; - - use super::*; - - const TAG_LEN: usize = AeadAes128Gcm::TAG_LEN; - - mod rfc7714 { - // Test vectors from RFC7714 - - // Session Key (RTP and RTCP) - pub(super) const KEY: [u8; 16] = [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - ]; - - // Session Salt (RTP and RTCP) - pub(super) const SALT: [u8; 12] = [0x51, 0x75, 0x69, 0x64, 0x20, 0x70, 0x72, 0x6f, 0x20, 0x71, 0x75, 0x6f]; - - /// Full plaintext RTP packet. First 12 octets is the header - pub(super) const PLAINTEXT_RTP_PACKET: &[u8] = &[ - 0x80, 0x40, 0xf1, 0x7b, 0x80, 0x41, 0xf8, 0xd3, 0x55, 0x01, 0xa0, 0xb2, 0x47, 0x61, 0x6c, 0x6c, 0x69, - 0x61, 0x20, 0x65, 0x73, 0x74, 0x20, 0x6f, 0x6d, 0x6e, 0x69, 0x73, 0x20, 0x64, 0x69, 0x76, 0x69, 0x73, - 0x61, 0x20, 0x69, 0x6e, 0x20, 0x70, 0x61, 0x72, 0x74, 0x65, 0x73, 0x20, 0x74, 0x72, 0x65, 0x73, - ]; - - /// Full encrypted RTP packet. First 12 octets is the header. - pub(super) const PROTECTED_RTP_PACKET: &[u8] = &[ - 0x80, 0x40, 0xf1, 0x7b, 0x80, 0x41, 0xf8, 0xd3, 0x55, 0x01, 0xa0, 0xb2, 0xf2, 0x4d, 0xe3, 0xa3, 0xfb, - 0x34, 0xde, 0x6c, 0xac, 0xba, 0x86, 0x1c, 0x9d, 0x7e, 0x4b, 0xca, 0xbe, 0x63, 0x3b, 0xd5, 0x0d, 0x29, - 0x4e, 0x6f, 0x42, 0xa5, 0xf4, 0x7a, 0x51, 0xc7, 0xd1, 0x9b, 0x36, 0xde, 0x3a, 0xdf, 0x88, 0x33, 0x89, - 0x9d, 0x7f, 0x27, 0xbe, 0xb1, 0x6a, 0x91, 0x52, 0xcf, 0x76, 0x5e, 0xe4, 0x39, 0x0c, 0xce, - ]; - - // Full plaintext RTCP packet - pub(super) const PLAINTEXT_RTCP_PACKET: &[u8] = &[ - 0x81, 0xc8, 0x00, 0x0d, 0x4d, 0x61, 0x72, 0x73, 0x4e, 0x54, 0x50, 0x31, 0x4e, 0x54, 0x50, 0x32, 0x52, - 0x54, 0x50, 0x20, 0x00, 0x00, 0x04, 0x2a, 0x00, 0x00, 0xe9, 0x30, 0x4c, 0x75, 0x6e, 0x61, 0xde, 0xad, - 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, - 0xef, - ]; - - /// Full encrypted RTCP packet - pub(super) const PROTECTED_RTCP_PACKET: &[u8] = &[ - 0x81, 0xc8, 0x00, 0x0d, 0x4d, 0x61, 0x72, 0x73, 0x63, 0xe9, 0x48, 0x85, 0xdc, 0xda, 0xb6, 0x7c, 0xa7, - 0x27, 0xd7, 0x66, 0x2f, 0x6b, 0x7e, 0x99, 0x7f, 0xf5, 0xc0, 0xf7, 0x6c, 0x06, 0xf3, 0x2d, 0xc6, 0x76, - 0xa5, 0xf1, 0x73, 0x0d, 0x6f, 0xda, 0x4c, 0xe0, 0x9b, 0x46, 0x86, 0x30, 0x3d, 0xed, 0x0b, 0xb9, 0x27, - 0x5b, 0xc8, 0x4a, 0xa4, 0x58, 0x96, 0xcf, 0x4d, 0x2f, 0xc5, 0xab, 0xf8, 0x72, 0x45, 0xd9, 0xea, 0xde, - 0x80, 0x00, 0x05, 0xd4, - ]; - - // A RTCP packet that hasn't been encrypted, only authenticated. - pub(super) const TAGGED_RTCP_PACKET: &[u8] = &[ - // RTCP Packet - 0x81, 0xc8, 0x00, 0x0d, 0x4d, 0x61, 0x72, 0x73, 0x4e, 0x54, 0x50, 0x31, 0x4e, 0x54, 0x50, 0x32, 0x52, - 0x54, 0x50, 0x20, 0x00, 0x00, 0x04, 0x2a, 0x00, 0x00, 0xe9, 0x30, 0x4c, 0x75, 0x6e, 0x61, 0xde, 0xad, - 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, - 0xef, // - // Tag - 0x84, 0x1d, 0xd9, 0x68, 0x3d, 0xd7, 0x8e, 0xc9, 0x2a, 0xe5, 0x87, 0x90, 0x12, 0x5f, 0x62, 0xb3, // - // SRTCP Index - 0x00, 0x00, 0x05, 0xd4, - ]; - } - - #[test] - fn protect_rtp_rfc_7714_test() { - let mut context = make_rtp_context(); - - let header = RtpHeader::parse(&rfc7714::PLAINTEXT_RTP_PACKET[..12], &ExtensionMap::empty()) - .expect("header to parse"); - let out = context.protect_rtp(rfc7714::PLAINTEXT_RTP_PACKET, &header, 0); - - assert_eq!( - out, - rfc7714::PROTECTED_RTP_PACKET, - "failed to encrypted packet.\n{:02x?}\n{:02x?}", - out, - rfc7714::PLAINTEXT_RTP_PACKET - ); - } - - #[test] - fn unprotect_rtp_rfc_7714_test() { - let mut context = make_rtp_context(); - let header = RtpHeader::parse(&rfc7714::PROTECTED_RTP_PACKET[..12], &ExtensionMap::empty()) - .expect("header to parse"); - - let out = context - .unprotect_rtp(rfc7714::PROTECTED_RTP_PACKET, &header, 0) - .expect("decrypt rtp"); - - assert_eq!( - out, - &rfc7714::PLAINTEXT_RTP_PACKET[12..], - "failed to decrypt packet.\n{:02x?}\n{:02x?}", - out, - rfc7714::PLAINTEXT_RTP_PACKET - ); - } - - #[test] - fn symmetry_rtp_rfc_7714_test() { - let mut context = make_rtp_context(); - - // First we encrypt - let header = RtpHeader::parse(&rfc7714::PLAINTEXT_RTP_PACKET[..12], &ExtensionMap::empty()) - .expect("header to parse"); - let encrypted = context.protect_rtp(rfc7714::PLAINTEXT_RTP_PACKET, &header, 0); - - // Then we decrypt the resulting cipher text - let header = RtpHeader::parse(&encrypted[..12], &ExtensionMap::empty()).expect("header to parse"); - let decrypted = context.unprotect_rtp(&encrypted, &header, 0).expect("rtp unprotect"); - - // And verify we get the input back. - assert_eq!(decrypted, &rfc7714::PLAINTEXT_RTP_PACKET[12..]); - } - - #[test] - fn unprotect_rtp_should_fail_with_broken_tag_data() { - let mut context = make_rtp_context(); - - let header_buf = { - let mut buf = rfc7714::PROTECTED_RTP_PACKET[..12].to_vec(); - // Mess with part of the sequence number, since this makes up part of the - // authenticated additional data(AAD) the resulting authenticity tag should not - // match. - buf[3] ^= 0xFF; - - buf - }; - - let header = RtpHeader::parse(&header_buf, &ExtensionMap::empty()).expect("header to parse"); - - let result = context.unprotect_rtp(rfc7714::PROTECTED_RTP_PACKET, &header, 0); - assert!( - result.is_none(), - "Should fail to decrypt a SRTP packet that has mismatched \ - authenicated additional data" - ); - } - - #[test] - fn unprotect_rtp_should_fail_with_broken_null_tag() { - let mut context = make_rtp_context(); - - let input = { - let mut input = rfc7714::PROTECTED_RTP_PACKET.to_vec(); - let len = input.len(); - input[len - TAG_LEN..].copy_from_slice(&[0; TAG_LEN]); - - input - }; - - let header = RtpHeader::parse(&input[..12], &ExtensionMap::empty()).expect("header to parse"); - - let result = context.unprotect_rtp(&input, &header, 0); - assert!(result.is_none(), "Should fail to decrypt a SRTP packet with null tag"); - } - - #[test] - fn protect_rtcp_rfc_7714_test() { - let mut context = make_rtcp_context(); - - let out = context.protect_rtcp(rfc7714::PLAINTEXT_RTCP_PACKET); - - assert!( - out == rfc7714::PROTECTED_RTCP_PACKET, - "Expected encrypted and tagged RTCP packet:\n{:02x?}\nGot:\n{:02x?}", - rfc7714::PROTECTED_RTCP_PACKET, - out - ); - } - - #[test] - fn unprotect_rtcp_rfc_auth_only_7714_test() { - let mut context = make_rtcp_context(); - - let out = context - .unprotect_rtcp(rfc7714::TAGGED_RTCP_PACKET) - .expect("Unprotect RTCP"); - - assert_eq!(out, rfc7714::PLAINTEXT_RTCP_PACKET); - } - - fn make_rtp_context() -> SrtpContext { - crate::vendor::str0m::init_crypto_default(); - SrtpContext::new_aead_aes_128_gcm(rfc7714::KEY, rfc7714::SALT, rfc7714::KEY, rfc7714::SALT, 0) - } - - fn make_rtcp_context() -> SrtpContext { - crate::vendor::str0m::init_crypto_default(); - SrtpContext::new_aead_aes_128_gcm(rfc7714::KEY, rfc7714::SALT, rfc7714::KEY, rfc7714::SALT, 0x000005d4) - } - } - - mod test_aead_aes_256_gcm { - use crate::vendor::str0m::crypto::AeadAes256Gcm; - use crate::vendor::str0m::rtp_::ExtensionMap; - - use super::*; - - const TAG_LEN: usize = AeadAes256Gcm::TAG_LEN; - - mod rfc7714 { - // Test vectors from RFC7714 - - // Session Key (RTP and RTCP) - pub(super) const KEY: [u8; 32] = [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, // - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // - 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - ]; - - // Session Salt (RTP and RTCP) - pub(super) const SALT: [u8; 12] = [0x51, 0x75, 0x69, 0x64, 0x20, 0x70, 0x72, 0x6f, 0x20, 0x71, 0x75, 0x6f]; - - /// Full plaintext RTP packet. First 12 octets is the header - pub(super) const PLAINTEXT_RTP_PACKET: &[u8] = &[ - 0x80, 0x40, 0xf1, 0x7b, 0x80, 0x41, 0xf8, 0xd3, 0x55, 0x01, 0xa0, 0xb2, 0x47, 0x61, 0x6c, 0x6c, 0x69, - 0x61, 0x20, 0x65, 0x73, 0x74, 0x20, 0x6f, 0x6d, 0x6e, 0x69, 0x73, 0x20, 0x64, 0x69, 0x76, 0x69, 0x73, - 0x61, 0x20, 0x69, 0x6e, 0x20, 0x70, 0x61, 0x72, 0x74, 0x65, 0x73, 0x20, 0x74, 0x72, 0x65, 0x73, - ]; - - /// Full encrypted RTP packet. First 12 octets is the header. - pub(super) const PROTECTED_RTP_PACKET: &[u8] = &[ - 0x80, 0x40, 0xf1, 0x7b, 0x80, 0x41, 0xf8, 0xd3, 0x55, 0x01, 0xa0, 0xb2, 0x32, 0xb1, 0xde, 0x78, 0xa8, - 0x22, 0xfe, 0x12, 0xef, 0x9f, 0x78, 0xfa, 0x33, 0x2e, 0x33, 0xaa, 0xb1, 0x80, 0x12, 0x38, 0x9a, 0x58, - 0xe2, 0xf3, 0xb5, 0x0b, 0x2a, 0x02, 0x76, 0xff, 0xae, 0x0f, 0x1b, 0xa6, 0x37, 0x99, 0xb8, 0x7b, 0x7a, - 0xa3, 0xdb, 0x36, 0xdf, 0xff, 0xd6, 0xb0, 0xf9, 0xbb, 0x78, 0x78, 0xd7, 0xa7, 0x6c, 0x13, - ]; - - // Full plaintext RTCP packet - pub(super) const PLAINTEXT_RTCP_PACKET: &[u8] = &[ - 0x81, 0xc8, 0x00, 0x0d, 0x4d, 0x61, 0x72, 0x73, 0x4e, 0x54, 0x50, 0x31, 0x4e, 0x54, 0x50, 0x32, 0x52, - 0x54, 0x50, 0x20, 0x00, 0x00, 0x04, 0x2a, 0x00, 0x00, 0xe9, 0x30, 0x4c, 0x75, 0x6e, 0x61, 0xde, 0xad, - 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, - 0xef, - ]; - - /// Full encrypted RTCP packet - pub(super) const PROTECTED_RTCP_PACKET: &[u8] = &[ - 0x81, 0xc8, 0x00, 0x0d, 0x4d, 0x61, 0x72, 0x73, 0xd5, 0x0a, 0xe4, 0xd1, 0xf5, 0xce, 0x5d, 0x30, 0x4b, - 0xa2, 0x97, 0xe4, 0x7d, 0x47, 0x0c, 0x28, 0x2c, 0x3e, 0xce, 0x5d, 0xbf, 0xfe, 0x0a, 0x50, 0xa2, 0xea, - 0xa5, 0xc1, 0x11, 0x05, 0x55, 0xbe, 0x84, 0x15, 0xf6, 0x58, 0xc6, 0x1d, 0xe0, 0x47, 0x6f, 0x1b, 0x6f, - 0xad, 0x1d, 0x1e, 0xb3, 0x0c, 0x44, 0x46, 0x83, 0x9f, 0x57, 0xff, 0x6f, 0x6c, 0xb2, 0x6a, 0xc3, 0xbe, - 0x80, 0x00, 0x05, 0xd4, - ]; - - // A RTCP packet that hasn't been encrypted, only authenticated. - pub(super) const TAGGED_RTCP_PACKET: &[u8] = &[ - // RTCP Packet - 0x81, 0xc8, 0x00, 0x0d, 0x4d, 0x61, 0x72, 0x73, 0x4e, 0x54, 0x50, 0x31, 0x4e, 0x54, 0x50, 0x32, 0x52, - 0x54, 0x50, 0x20, 0x00, 0x00, 0x04, 0x2a, 0x00, 0x00, 0xe9, 0x30, 0x4c, 0x75, 0x6e, 0x61, 0xde, 0xad, - 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, - 0xef, // - // Tag - 0x91, 0xdb, 0x4a, 0xfb, 0xfe, 0xee, 0x5a, 0x97, 0x8f, 0xab, 0x43, 0x93, 0xed, 0x26, 0x15, 0xfe, // - // SRTCP Index - 0x00, 0x00, 0x05, 0xd4, - ]; - } - - #[test] - fn protect_rtp_rfc_7714_test() { - let mut context = make_rtp_context(); - - let header = RtpHeader::parse(&rfc7714::PLAINTEXT_RTP_PACKET[..12], &ExtensionMap::empty()) - .expect("header to parse"); - let out = context.protect_rtp(rfc7714::PLAINTEXT_RTP_PACKET, &header, 0); - - assert_eq!( - out, - rfc7714::PROTECTED_RTP_PACKET, - "failed to encrypted packet.\n{:02x?}\n{:02x?}", - out, - rfc7714::PLAINTEXT_RTP_PACKET - ); - } - - #[test] - fn unprotect_rtp_rfc_7714_test() { - let mut context = make_rtp_context(); - let header = RtpHeader::parse(&rfc7714::PROTECTED_RTP_PACKET[..12], &ExtensionMap::empty()) - .expect("header to parse"); - - let out = context - .unprotect_rtp(rfc7714::PROTECTED_RTP_PACKET, &header, 0) - .expect("decrypt rtp"); - - assert_eq!( - out, - &rfc7714::PLAINTEXT_RTP_PACKET[12..], - "failed to decrypt packet.\n{:02x?}\n{:02x?}", - out, - rfc7714::PLAINTEXT_RTP_PACKET - ); - } - - #[test] - fn symmetry_rtp_rfc_7714_test() { - let mut context = make_rtp_context(); - - // First we encrypt - let header = RtpHeader::parse(&rfc7714::PLAINTEXT_RTP_PACKET[..12], &ExtensionMap::empty()) - .expect("header to parse"); - let encrypted = context.protect_rtp(rfc7714::PLAINTEXT_RTP_PACKET, &header, 0); - - // Then we decrypt the resulting cipher text - let header = RtpHeader::parse(&encrypted[..12], &ExtensionMap::empty()).expect("header to parse"); - let decrypted = context.unprotect_rtp(&encrypted, &header, 0).expect("rtp unprotect"); - - // And verify we get the input back. - assert_eq!(decrypted, &rfc7714::PLAINTEXT_RTP_PACKET[12..]); - } - - #[test] - fn unprotect_rtp_should_fail_with_broken_tag_data() { - let mut context = make_rtp_context(); - - let header_buf = { - let mut buf = rfc7714::PROTECTED_RTP_PACKET[..12].to_vec(); - // Mess with part of the sequence number, since this makes up part of the - // authenticated additional data(AAD) the resulting authenticity tag should not - // match. - buf[3] ^= 0xFF; - - buf - }; - - let header = RtpHeader::parse(&header_buf, &ExtensionMap::empty()).expect("header to parse"); - - let result = context.unprotect_rtp(rfc7714::PROTECTED_RTP_PACKET, &header, 0); - assert!( - result.is_none(), - "Should fail to decrypt a SRTP packet that has mismatched \ - authenicated additional data" - ); - } - - #[test] - fn unprotect_rtp_should_fail_with_broken_null_tag() { - let mut context = make_rtp_context(); - - let input = { - let mut input = rfc7714::PROTECTED_RTP_PACKET.to_vec(); - let len = input.len(); - input[len - TAG_LEN..].copy_from_slice(&[0; TAG_LEN]); - - input - }; - - let header = RtpHeader::parse(&input[..12], &ExtensionMap::empty()).expect("header to parse"); - - let result = context.unprotect_rtp(&input, &header, 0); - assert!(result.is_none(), "Should fail to decrypt a SRTP packet with null tag"); - } - - #[test] - fn protect_rtcp_rfc_7714_test() { - let mut context = make_rtcp_context(); - - let out = context.protect_rtcp(rfc7714::PLAINTEXT_RTCP_PACKET); - - assert!( - out == rfc7714::PROTECTED_RTCP_PACKET, - "Expected encrypted and tagged RTCP packet:\n{:02x?}\nGot:\n{:02x?}", - rfc7714::PROTECTED_RTCP_PACKET, - out - ); - } - - #[test] - fn unprotect_rtcp_rfc_auth_only_7714_test() { - let mut context = make_rtcp_context(); - - let out = context - .unprotect_rtcp(rfc7714::TAGGED_RTCP_PACKET) - .expect("Unprotect RTCP"); - - assert_eq!(out, rfc7714::PLAINTEXT_RTCP_PACKET); - } - - fn make_rtp_context() -> SrtpContext { - crate::vendor::str0m::init_crypto_default(); - SrtpContext::new_aead_aes_256_gcm(rfc7714::KEY, rfc7714::SALT, rfc7714::KEY, rfc7714::SALT, 0) - } - - fn make_rtcp_context() -> SrtpContext { - crate::vendor::str0m::init_crypto_default(); - SrtpContext::new_aead_aes_256_gcm(rfc7714::KEY, rfc7714::SALT, rfc7714::KEY, rfc7714::SALT, 0x000005d4) - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs b/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs deleted file mode 100644 index 37cda0411c3..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs +++ /dev/null @@ -1,2981 +0,0 @@ -#![allow(clippy::single_match)] - -use combine::{EasyParser, Parser}; -use std::collections::HashMap; -use std::collections::HashSet; -use std::fmt::{self}; -use std::ops::Deref; -use tracing::{trace, warn}; - -use crate::vendor::str0m::crypto::Fingerprint; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::format::CodecSpec; -use crate::vendor::str0m::format::FormatParams; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::packet::H265ProfileTierLevel; -use crate::vendor::str0m::rtp_::{Direction, Extension, Frequency, Mid, Pt, Rid, SessionId, Ssrc}; -use crate::vendor::str0m::{Candidate, IceCreds, VERSION}; -use crate::vendor::str0m_proto::Id; - -use super::SdpError; -use super::parser::sdp_parser; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Sdp { - pub session: Session, - pub media_lines: Vec, -} - -impl Sdp { - pub(crate) fn parse(input: &str) -> Result { - // `easy_parse` builds (allocates, merges, dedups) an error for every alternative tried, - // which is most of the cost of parsing a valid SDP. Plain `&str` errors cost nothing; the - // detailed message is only needed when the input is invalid, so parse again for it then. - if let Ok((sdp, _)) = sdp_parser().parse(input) { - return Ok(sdp); - } - sdp_parser() - .easy_parse(input) - .map(|(sdp, _)| sdp) - .map_err(|e| SdpError::ParseError(e.to_string())) - } - - /// Get the MIDs listed in the BUNDLE group, if any. - pub(crate) fn bundle_mids(&self) -> Option<&[Mid]> { - self.session.attrs.iter().find_map(|a| { - if let SessionAttribute::Group { typ, mids } = a { - if typ == "BUNDLE" { - return Some(mids.as_slice()); - } - } - None - }) - } - - pub(crate) fn assert_consistency(&self) -> Result<(), SdpError> { - match self.do_assert_consistency() { - None => Ok(()), - Some(error) => Err(SdpError::Inconsistent(error)), - } - } - - pub(crate) fn fingerprint(&self) -> Option { - self.session - .fingerprint() - .or_else(|| self.media_lines.iter().find_map(|m| m.fingerprint())) - } - - pub(crate) fn ice_creds(&self) -> Option { - self.session - .ice_creds() - .or_else(|| self.media_lines.iter().find_map(|m| m.ice_creds())) - } - - pub(crate) fn ice_candidates(&self) -> impl Iterator { - let mut candidates: HashSet<&Candidate> = HashSet::new(); - - // Session level ice candidates. - candidates.extend(self.session.ice_candidates()); - - // Ice candidates. - for m in &self.media_lines { - candidates.extend(m.ice_candidates()); - } - - candidates.into_iter() - } - - pub(crate) fn setup(&self) -> Option { - self.session - .setup() - .or_else(|| self.media_lines.iter().find_map(|m| m.setup())) - } - - fn do_assert_consistency(&self) -> Option { - // TODO: SDP assertions we need to make: - // 1. Ensure that every m-line has the same PT configuration for a codec. I.e. if FIR is enabled - // for PT 96 in one m-line it must be in all m-lines. - // 2. Compare with previous m-lines that remote isn't narrowing/expanding PT and/or extmaps. - - for media in &self.media_lines { - if let Some(error) = media.check_consistent() { - return Some(error); - } - } - - // SDP typically has few m-lines, so a pairwise scan avoids allocation and hashing - // for a small number of comparisons (at most 45 for 10 m-lines). - for (i, media) in self.media_lines.iter().enumerate() { - let mid = media.mid(); - if self.media_lines.iter().skip(i + 1).any(|m| m.mid() == mid) { - return Some(format!("Mid {mid} is used by more than one m-line")); - } - } - - let group = self - .session - .attrs - .iter() - .find(|a| matches!(a, SessionAttribute::Group { .. })); - - if let Some(SessionAttribute::Group { mids, .. }) = group { - // For str0m's single BUNDLE transport, expect participating m-lines in - // media-section order, as libwebrtc generates offers and answers in - // pc/media_session.cc, omitting rejected sections from the group. - // This ordering is a deliberate interoperability constraint, stricter - // than RFC 9143 section 5, which permits BUNDLE MID order to differ - // from media-section order. Rejecting a section does not remove its - // m-line from the SDP or change the positions of the remaining m-lines. - // Port 0 outside BUNDLE means rejected; inside BUNDLE it can be bundle-only. - let media_lines = self - .media_lines - .iter() - .filter(|m| !m.disabled || mids.contains(&m.mid())); - // This clones only the iterator state: a slice cursor and a filter closure - // borrowing `mids`. It does not clone any MediaLine, its attributes, or the - // backing Vec, and it allocates nothing. Counting consumes the cloned - // iterator so the original remains available for the order check below. - let media_count = media_lines.clone().count(); - if mids.len() != media_count { - return Some(format!( - "a=group mid count doesn't match m-line count {} != {}", - mids.len(), - media_count - )); - } - for (media, mid) in media_lines.zip(mids.iter()) { - let m = media.mid(); - if m != *mid { - return Some(format!("Mid order not matching a=group {m} != {mid}")); - } - } - } else { - return Some("Session attribute a=group missing".into()); - } - - None - } -} - -/// Session info, before the first m= line -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Session { - pub id: SessionId, - pub bw: Option, - pub attrs: Vec, -} - -/// Bandwidth from b= line -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Bandwidth { - pub typ: String, - pub val: String, -} - -impl Session { - pub fn setup(&self) -> Option { - let setup = self.attrs.iter().find_map(|m| { - if let SessionAttribute::Setup(v) = m { - Some(v) - } else { - None - } - })?; - - Some(*setup) - } - - pub fn ice_creds(&self) -> Option { - let ufrag = self.attrs.iter().find_map(|m| { - if let SessionAttribute::IceUfrag(v) = m { - Some(v) - } else { - None - } - })?; - - let pass = self.attrs.iter().find_map(|m| { - if let SessionAttribute::IcePwd(v) = m { - Some(v) - } else { - None - } - })?; - - Some(IceCreds { - ufrag: ufrag.to_string(), - pass: pass.to_string(), - }) - } - - pub fn fingerprint(&self) -> Option { - self.attrs - .iter() - .filter_map(|a| match a { - SessionAttribute::Fingerprint(v) => Some(v), - _ => None, - }) - .min_by_key(|v| v.hash_preference()) - .cloned() - } - - pub fn ice_lite(&self) -> bool { - self.attrs.iter().any(|a| matches!(a, SessionAttribute::IceLite)) - } - - pub fn ice_candidates(&self) -> impl Iterator { - self.attrs.iter().filter_map(|a| { - if let SessionAttribute::Candidate(v) = a { - Some(v) - } else { - None - } - }) - } - - pub fn end_of_candidates(&self) -> bool { - self.attrs - .iter() - .any(|a| matches!(a, SessionAttribute::EndOfCandidates)) - } -} - -/// Attributes before the first m= line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum SessionAttribute { - Group { - typ: String, // BUNDLE, LS etc - mids: Vec, // 0 1 2 3 - }, - MsidSemantic { - semantic: String, // WMS - stream_ids: Vec, - }, - AllowMixedExts, - IceLite, - IceUfrag(String), - IcePwd(String), - IceOptions(String), - Fingerprint(Fingerprint), - Setup(Setup), // active, passive, actpass, holdconn - Candidate(Candidate), - EndOfCandidates, - Unused(String), -} - -fn is_dir(a: &MediaAttribute) -> bool { - use MediaAttribute::*; - matches!(a, SendRecv | SendOnly | RecvOnly | Inactive) -} - -/// An m-line -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub struct MediaLine { - pub typ: MediaType, - pub disabled: bool, - pub proto: Proto, - pub pts: Vec, // payload types 96 97 125 107 from the m= line - pub bw: Option, - pub attrs: Vec, -} - -impl MediaLine { - pub fn mid(&self) -> Mid { - self.attrs - .iter() - .find_map(|a| if let MediaAttribute::Mid(m) = a { Some(*m) } else { None }) - // We should only use `mid()` once we're certain there is - // a mid line. This is checked by `check_consistent`. - .expect("missing a=mid") - } - - pub fn msid(&self) -> Option { - self.attrs.iter().find_map(|a| { - if let MediaAttribute::Msid(m) = a { - Some(m.clone()) - } else { - None - } - }) - } - - pub fn direction(&self) -> Direction { - for a in &self.attrs { - match a { - MediaAttribute::SendRecv => return Direction::SendRecv, - MediaAttribute::SendOnly => return Direction::SendOnly, - MediaAttribute::RecvOnly => return Direction::RecvOnly, - MediaAttribute::Inactive => return Direction::Inactive, - _ => {} - } - } - // Should we error here? - Direction::Inactive - } - - pub fn set_direction(&mut self, dir: Direction) { - let idx = self.attrs.iter().position(is_dir).expect("m-line must have direction"); - self.attrs[idx] = dir.into(); - } - - pub fn rtp_params(&self) -> Vec { - let mut rtp_maps: Vec<_> = self - .attrs - .iter() - .filter_map(|a| { - if let MediaAttribute::RtpMap { pt, value: c } = a { - Some((*pt, *c)) - } else { - None - } - }) - .collect(); - - let fmtps: Vec<_> = self - .attrs - .iter() - .filter_map(|a| { - if let MediaAttribute::Fmtp { pt, values } = a { - Some((pt, values)) - } else { - None - } - }) - .collect(); - - let fbs: Vec<_> = self - .attrs - .iter() - .filter_map(|a| { - if let MediaAttribute::RtcpFb { pt, value } = a { - Some((pt, value)) - } else { - None - } - }) - .collect(); - - let mut params: Vec<_> = rtp_maps - .iter() - .filter(|(_, c)| c.codec.is_audio() || c.codec.is_video()) - .filter_map(|(pt, c)| { - let mut p = PayloadParams::new(*pt, None, (*c).into()); - p.spec.format = FormatParams::from_sdp_fmtp( - c.codec, - fmtps - .iter() - .filter(|(fmtp_pt, _)| **fmtp_pt == *pt) - .map(|(_, values)| values.as_slice()), - )?; - // Remote TWCC feedback is supported only when explicitly advertised. - p.set_fb_transport_cc(false); - Some(p) - }) - .collect(); - - for p in &mut params { - for (pt, values) in fmtps.iter() { - // find resend pt, if there is one. - for fp in values.iter() { - if let FormatParam::Apt(v) = fp { - if *v == p.pt { - // ensure this is a rtx - let is_rtx = rtp_maps.iter().any(|(cpt, c)| cpt == *pt && c.codec == Codec::Rtx); - if is_rtx { - p.resend = Some(**pt); - } - } - } - } - } - - // rtcp feedback mechanisms - for (pt, value) in fbs.iter() { - if **pt == p.pt { - match &value[..] { - "goog-remb" => { - p.fb_remb = true; - } - "transport-cc" => { - p.fb_transport_cc = true; - } - "ccm fir" => { - p.fb_fir = true; - } - "nack" => { - p.fb_nack = true; - } - "nack pli" => { - p.fb_pli = true; - } - _ => { - // - } - } - } - } - } - - params - } - - pub fn check_consistent(&self) -> Option { - use MediaAttribute::*; - - let mid_count = self.attrs.iter().filter(|a| matches!(a, Mid(_))).count(); - - if mid_count == 0 { - return Some(format!("Media is missing a=mid: {} {}", self.typ, self.proto)); - } - - if mid_count > 1 { - return Some(format!("Media has more than one a=mid: {} {}", self.typ, self.proto)); - } - - let setup = self.attrs.iter().filter(|a| matches!(a, Setup(_))).count(); - - if setup > 1 { - return Some(format!("Expected 0 or 1 a=setup: line for mid: {}", self.mid())); - } - - let dir_count = self.attrs.iter().filter(|a| is_dir(a)).count(); - - if self.proto == Proto::Srtp && dir_count != 1 { - return Some(format!( - "Expected exactly one of a=sendrecv, a=sendonly, a=recvonly, a=inactive for mid: {}", - self.mid() - )); - } - - if self.proto == Proto::Srtp && self.pts.is_empty() && !self.disabled { - return Some(format!("Expected at least one PT for mid: {}", self.mid())); - } - - for m in &self.pts { - let rtp_count = self - .attrs - .iter() - .filter(|a| { - if let MediaAttribute::RtpMap { pt, value: _ } = a { - pt == m - } else { - false - } - }) - .count(); - // Static payload types (RFC 3551) may omit their rtpmap. None is a codec str0m - // supports, so they are ignored rather than rejected. - if rtp_count == 0 && !matches!(**m, 0 | 8 | 9 | 13) { - return Some(format!("Missing a=rtp_map:{} for mid: {}", m, self.mid())); - } - if rtp_count > 1 { - return Some(format!("More than one a=rtp_map:{} for mid: {}", m, self.mid())); - } - } - - // An RTX PT must identify only one primary PT, including across multiple fmtp lines. - let mut rtx_apts = HashMap::new(); - for attr in &self.attrs { - let Fmtp { pt, values } = attr else { - continue; - }; - for value in values { - let FormatParam::Apt(apt) = value else { - continue; - }; - if let Some(previous) = rtx_apts.insert(*pt, *apt) { - if previous != *apt { - return Some(format!( - "PT {pt} has conflicting apt values {previous} and {apt} for mid: {}", - self.mid() - )); - } - } - } - } - None - } - - pub fn setup(&self) -> Option { - let setup = self.attrs.iter().find_map(|m| { - if let MediaAttribute::Setup(v) = m { - Some(v) - } else { - None - } - })?; - - Some(*setup) - } - - pub fn ice_creds(&self) -> Option { - let ufrag = self.attrs.iter().find_map(|m| { - if let MediaAttribute::IceUfrag(v) = m { - Some(v) - } else { - None - } - })?; - - let pass = self.attrs.iter().find_map(|m| { - if let MediaAttribute::IcePwd(v) = m { - Some(v) - } else { - None - } - })?; - - Some(IceCreds { - ufrag: ufrag.to_string(), - pass: pass.to_string(), - }) - } - pub fn fingerprint(&self) -> Option { - self.attrs - .iter() - .filter_map(|a| match a { - MediaAttribute::Fingerprint(v) => Some(v), - _ => None, - }) - .min_by_key(|v| v.hash_preference()) - .cloned() - } - - /// This hoovers the ice candidates from all m-lines, lots of dupes. - /// For WebRTC we don't expect different ice states per media line. - pub fn ice_candidates(&self) -> impl Iterator { - self.attrs.iter().filter_map(|a| { - if let MediaAttribute::Candidate(v) = a { - Some(v) - } else { - None - } - }) - } - - /// Any end-of-candidate in any m-line. - /// For WebRTC we don't expect different ice states per media line. - pub fn end_of_candidates(&self) -> bool { - self.attrs.iter().any(|a| matches!(a, MediaAttribute::EndOfCandidates)) - } - - pub fn extmaps(&self) -> Vec<(u8, &Extension)> { - let mut ret = vec![]; - - for a in &self.attrs { - if let MediaAttribute::ExtMap { id, ext } = a { - ret.push((*id, ext)); - } - } - - ret - } - - pub fn rids(&self) -> Vec { - let mut ret = vec![]; - for a in &self.attrs { - if let MediaAttribute::Rid { id, .. } = a { - ret.push(id.0.as_str().into()) - } - } - ret - } - - pub fn simulcast(&self) -> Option { - let mut found = None; - - for a in &self.attrs { - if let MediaAttribute::Simulcast(s) = a { - found = Some(s.clone()); - } - if let MediaAttribute::Rid { pt, restriction, .. } = a { - if !pt.is_empty() { - warn!("Not currently supporting PT via a=rid"); - } - if !restriction.is_empty() { - warn!("Not currently supporting restrictions via a=rid"); - } - } - } - - if found.is_some() { - return found; - } - - // Here we could handle munged SDPs and we used to, but we have dropped support for this. - - None - } - - pub fn ssrc_info(&self) -> Vec { - let mut v = vec![]; - - fn by_ssrc(v: &mut Vec, ssrc: Ssrc) -> &mut SsrcInfo { - if let Some(pos) = v.iter().position(|i| i.ssrc == ssrc) { - &mut v[pos] - } else { - v.push(SsrcInfo { - ssrc, - ..Default::default() - }); - v.last_mut().unwrap() - } - } - - for a in &self.attrs { - match a { - MediaAttribute::Ssrc { ssrc, attr, value } => { - let info = by_ssrc(&mut v, *ssrc); - - // a=ssrc:2147603131 cname:TbS1Ajv9obq6/63I - // a=ssrc:2147603131 msid:- 7a08dda6-518f-4027-b707-410a6d414176 - match attr.to_lowercase().as_str() { - "cname" => info.cname = Some(value.clone()), - "msid" => { - let mut iter = value.split(' '); - - fn trim_and_no_minus(s: &str) -> Option { - if is_no_stream(s) { None } else { Some(s.trim().into()) } - } - - if let Some(stream_id) = iter.next() { - info.stream_id = trim_and_no_minus(stream_id); - } - if let Some(track_id) = iter.next() { - info.track_id = trim_and_no_minus(track_id); - } - } - _ => {} - } - } - _ => {} - } - } - // Match this second to ensure we preserve order of a=ssrc. - for a in &self.attrs { - match a { - MediaAttribute::SsrcGroup { semantics, ssrcs } => { - if semantics.to_lowercase() != "fid" { - continue; - } - - // a=ssrc-group:FID 659652645 98148385 - // Should be two SSRC after FID. - if ssrcs.len() != 2 { - continue; - } - - let info = by_ssrc(&mut v, ssrcs[1]); - info.repairs = Some(ssrcs[0]); - } - _ => {} - } - } - - v - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SsrcInfo { - pub ssrc: Ssrc, - /// the other ssrc this ssrc is repairing - pub repairs: Option, - pub cname: Option, - pub stream_id: Option, - pub track_id: Option, -} - -impl Default for SsrcInfo { - fn default() -> Self { - Self { - ssrc: 0.into(), - repairs: None, - cname: None, - stream_id: None, - track_id: None, - } - } -} - -impl From for MediaAttribute { - fn from(v: Direction) -> Self { - match v { - Direction::SendOnly => MediaAttribute::SendOnly, - Direction::RecvOnly => MediaAttribute::RecvOnly, - Direction::SendRecv => MediaAttribute::SendRecv, - Direction::Inactive => MediaAttribute::Inactive, - } - } -} - -/// Identifier of an `a=rid` restriction. -/// -/// Defined in https://tools.ietf.org/html/draft-ietf-avtext-rid-09 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RestrictionId(pub String, pub bool); - -impl RestrictionId { - pub fn new(rid: String, active: bool) -> Self { - RestrictionId(rid, active) - } - - pub fn new_active(rid: String) -> Self { - RestrictionId(rid, true) - } - - pub fn to_sdp(&self) -> String { - format!("{}{}", if self.1 { "" } else { "~" }, self.0) - } -} - -impl Default for RestrictionId { - fn default() -> Self { - RestrictionId("".to_string(), true) - } -} - -/// "audio", "video", "application" -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub enum MediaType { - #[default] - Audio, - Video, - Application, - // If a parsed SDP has a value we don't recognize, we stick it - // in here. We could consider making that a parse exception instead. - Unknown(String), -} - -impl MediaType { - pub fn is_media(&self) -> bool { - matches!(self, MediaType::Audio | MediaType::Video) - } - - pub fn is_channel(&self) -> bool { - matches!(self, MediaType::Application) - } -} - -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub enum Proto { - #[default] - Srtp, - Sctp, -} - -impl Proto { - pub fn proto_line(&self) -> &str { - match self { - Proto::Srtp => "UDP/TLS/RTP/SAVPF", - Proto::Sctp => "UDP/DTLS/SCTP", - } - } -} - -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub enum Setup { - #[default] - ActPass, - Active, - Passive, -} - -impl fmt::Display for Setup { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match self { - Setup::ActPass => "actpass", - Setup::Active => "active", - Setup::Passive => "passive", - } - ) - } -} - -impl Setup { - pub fn setup_line(&self) -> &str { - match self { - Setup::ActPass => "actpass", - Setup::Active => "active", - Setup::Passive => "passive", - } - } - - pub fn compare_to_remote(&self, remote: Setup) -> Option { - use Setup::*; - match (self, remote) { - (ActPass, ActPass) => None, - (ActPass, Active) => Some(Passive), - (ActPass, Passive) => Some(Active), - (Active, ActPass) => Some(Active), - (Active, Active) => None, - (Active, Passive) => Some(Active), - (Passive, ActPass) => Some(Passive), - (Passive, Active) => Some(Passive), - (Passive, Passive) => None, - } - } - - pub fn invert(&self) -> Setup { - match self { - Setup::ActPass => Setup::ActPass, - Setup::Active => Setup::Passive, - Setup::Passive => Setup::Active, - } - } -} - -/// Attributes before the first m= line. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum MediaAttribute { - // The "a=rtcp" line MUST NOT be added if the most recent answer included an "a=rtcp-mux" line. - Rtcp(String), - IceUfrag(String), - IcePwd(String), - IceOptions(String), - Fingerprint(Fingerprint), - Setup(Setup), // active, passive, actpass, holdconn - Mid(Mid), // 0, 1, 2 - SctpPort(u16), - MaxMessageSize(usize), - /// a=sctp-init: - /// See draft-hancke-tsvwg-snap - SctpInit(String), - // a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level - // a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time - ExtMap { - id: u8, // 1-14 inclusive, - ext: Extension, - }, - RecvOnly, // a=recvonly - SendRecv, // a=sendrecv - SendOnly, // a=sendonly - Inactive, // a=inactive - // a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1 - // a=msid:- 78dde68-7055-4e20-bb37-433803dd1ed1 - Msid(Msid), - RtcpMux, // - RtcpMuxOnly, // only in offer, answer with a=rtcp-mux - // reduced size rtcp. remove this if not supported. - RtcpRsize, - Candidate(Candidate), - EndOfCandidates, - RtpMap { - pt: Pt, - value: RtpMap, - }, - // rtcp-fb RTCP feedback parameters, repeated - RtcpFb { - pt: Pt, // 111 - value: String, // nack, nack pli, ccm fir... - }, - // format parameters, seems to be one of these - Fmtp { - pt: Pt, // 111 - values: Vec, // minptime=10;useinbandfec=1 - }, - // a=rid: [pt=;]= - // a=rid:hi send pt=111,112;max-br=64000;max-height=360 - // https://tools.ietf.org/html/draft-ietf-mmusic-rid-15 - Rid { - id: RestrictionId, // - direction: &'static str, // send or recv - // No pt means the rid applies to all - pt: Vec, // 111, 112 (rtpmap no) - restriction: Vec<(String, String)>, - }, - // a=rid:hi send - // a=rid:lo send - // a=simulcast:send hi;lo - // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-14 - // a=simulcast: ;, [same] - Simulcast(Simulcast), - SsrcGroup { - semantics: String, // i.e. "FID" - ssrcs: Vec, // - }, - Ssrc { - ssrc: Ssrc, // synchronization source id - attr: String, - value: String, - }, - Unused(String), -} - -impl MediaAttribute { - pub fn is_direction(&self) -> bool { - use MediaAttribute::*; - matches!(self, RecvOnly | SendRecv | SendOnly | Inactive) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FormatParam { - /// The minimum duration of media represented by a packet. - /// - /// Default 3. Max 120. - MinPTime(u8), - - /// Decoder-side preference for stereo audio. Default is mono per - /// RFC 7587 Section 7.1: - Stereo(bool), - - /// Sender-side stereo hint for Opus. This is the symmetric m-line companion - /// to `stereo` and signals the sender's intention to transmit stereo. - SpropStereo(bool), - - /// Specifies that the decoder can do Opus in-band FEC - UseInbandFec(bool), - - /// Specifies that the decoder can do Opus DTX - UseDtx(bool), - - /// Whether h264 sending media encoded at a different level in the offerer-to-answerer - /// direction than the level in the answerer-to-offerer direction, is allowed. - LevelAsymmetryAllowed(bool), - - /// What h264 packetization mode is used. - /// - /// * 0 - single nal. - /// * 1 - STAP-A, FU-A is allowed. Non-interleaved. - PacketizationMode(u8), - - /// H264 profile level. - /// - /// * 42 00 1f - 4200=baseline (B) 1f=level 3.1 - /// * 42 e0 1f - 42e0=constrained baseline (CB) 1f=level 3.1 - /// * 4d 00 1f - 4d00=main (M) 1f=level 3.1 - /// * 64 00 1f - 6400=high (H) 1f=level 3.1 - ProfileLevelId(u32), - - /// VP9 profile id - ProfileId(u32), - - /// AV1 profile - Profile(u8), - - /// AV1 level-idx - LevelIdx(u8), - - /// AV1 tier - Tier(u8), - - /// H.265/HEVC profile, tier, and level. - H265ProfileTierLevel(crate::vendor::str0m::packet::H265ProfileTierLevel), - - /// H.265 sprop-max-don-diff parameter (RFC 7798 §7.1). - /// When > 0, DONL fields are included in RTP packets to support - /// out-of-order NAL unit decoding. Valid range: 0–32767. - SpropMaxDonDiff(u16), - - /// AMR-WB octet-aligned (`1`) or bandwidth-efficient (`0`, default) payloads. - OctetAlign(bool), - - /// AMR-WB allowed speech modes as a bitmask. - ModeSet(u16), - - /// An AMR-WB parameter that needs a feature str0m lacks, such as `crc=1`. - /// Declines the payload type. - AmrWbUnsupported, - - /// RTX (resend) codecs, which PT it concerns. - Apt(Pt), - - /// Unrecognized fmtp. - Unknown, -} - -fn parse_amr_wb_mode_set(value: &str) -> Option { - value.split(',').try_fold(0u16, |mask, mode| { - let mode: u8 = mode.trim().parse().ok()?; - (mode <= 8).then(|| mask | (1 << mode)) - }) -} - -impl FormatParam { - pub fn parse(k: &str, v: &str) -> Self { - use FormatParam::*; - match k.to_ascii_lowercase().as_str() { - "minptime" => v.parse().map(MinPTime).ok(), - "useinbandfec" => Some(UseInbandFec(v == "1")), - "usedtx" => Some(UseDtx(v == "1")), - "stereo" => Some(Stereo(v == "1")), - "sprop-stereo" => Some(SpropStereo(v == "1")), - "level-asymmetry-allowed" => Some(LevelAsymmetryAllowed(v == "1")), - "packetization-mode" => v.parse().map(PacketizationMode).ok(), - "profile-level-id" => u32::from_str_radix(v, 16) - .or_else(|_| v.parse()) - .map(ProfileLevelId) - .ok(), - "profile-id" => v.parse().map(ProfileId).ok(), - "profile" => v.parse().map(Profile).ok(), - "level-idx" => v.parse().map(LevelIdx).ok(), - "tier" => v.parse().map(Tier).ok(), - "sprop-max-don-diff" => v.parse::().ok().filter(|&v| v <= 32767).map(SpropMaxDonDiff), - "octet-align" => Some(OctetAlign(v == "1")), - "mode-set" => parse_amr_wb_mode_set(v).map(ModeSet), - "crc" | "robust-sorting" if v == "1" => Some(AmrWbUnsupported), - "mode-change-period" if v == "2" => Some(AmrWbUnsupported), - "interleaving" => Some(AmrWbUnsupported), - "apt" => v.parse::().map(|v| Apt(Pt::from(v))).ok(), - _ => None, - } - .unwrap_or_else(|| { - trace!("Failed to parse FormatParam: {k}={v}"); - Unknown - }) - } - - /// Parse multiple format parameters from key-value pairs. - /// Handles the H.265 special case where three params combine into - /// one composite ProfileTierLevel. - pub fn parse_pairs(mut pairs: Vec<(String, String)>) -> Vec { - // Parameter names are case-insensitive (RFC 4855 §3). - for (k, _) in &mut pairs { - k.make_ascii_lowercase(); - } - - // Check if this looks like H.265 by presence of tier-flag or level-id. - let is_ptl = pairs.iter().any(|(k, _)| k == "tier-flag" || k == "level-id"); - - if is_ptl { - // Build composite ProfileTierLevel. - let map: HashMap = pairs.into_iter().collect(); - - let mut result = vec![]; - if let Some(ptl) = H265ProfileTierLevel::from_fmtp(&map) { - result.push(FormatParam::H265ProfileTierLevel(ptl)); - } - - // Include non-PTL parameters. - for (k, v) in map.iter() { - if k != "profile-id" && k != "tier-flag" && k != "level-id" { - result.push(FormatParam::parse(k, v)); - } - } - - result - } else { - // Standard parsing for non-PTL codecs. - pairs.into_iter().map(|(k, v)| FormatParam::parse(&k, &v)).collect() - } - } -} - -impl fmt::Display for FormatParam { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use FormatParam::*; - match self { - MinPTime(v) => write!(f, "minptime={v}"), - UseInbandFec(v) => write!(f, "useinbandfec={}", i32::from(*v)), - UseDtx(v) => write!(f, "usedtx={}", i32::from(*v)), - Stereo(v) => write!(f, "stereo={}", i32::from(*v)), - SpropStereo(v) => write!(f, "sprop-stereo={}", i32::from(*v)), - LevelAsymmetryAllowed(v) => { - write!(f, "level-asymmetry-allowed={}", i32::from(*v)) - } - PacketizationMode(v) => write!(f, "packetization-mode={}", *v), - ProfileLevelId(v) => write!(f, "profile-level-id={:06x}", *v), - ProfileId(v) => write!(f, "profile-id={}", *v), - Profile(v) => write!(f, "profile={}", v), - LevelIdx(v) => write!(f, "level-idx={}", *v), - Tier(v) => write!(f, "tier={}", v), - H265ProfileTierLevel(ptl) => { - write!( - f, - "profile-id={};tier-flag={};level-id={}", - ptl.profile_id(), - ptl.tier_flag(), - ptl.level_id() - ) - } - SpropMaxDonDiff(v) => write!(f, "sprop-max-don-diff={}", *v), - OctetAlign(v) => write!(f, "octet-align={}", i32::from(*v)), - ModeSet(mask) => { - write!(f, "mode-set=")?; - let mut separator = ""; - for mode in (0..=8).filter(|mode| mask & (1 << mode) != 0) { - write!(f, "{separator}{mode}")?; - separator = ","; - } - Ok(()) - } - AmrWbUnsupported => Ok(()), - Apt(v) => write!(f, "apt={v}"), - Unknown => Ok(()), - } - } -} - -impl PayloadParams { - pub(crate) fn as_media_attrs(&self, attrs: &mut Vec) { - attrs.push(MediaAttribute::RtpMap { - pt: self.pt, - value: self.spec.into(), - }); - - if self.fb_transport_cc { - attrs.push(MediaAttribute::RtcpFb { - pt: self.pt, - value: "transport-cc".into(), - }); - } - if self.fb_remb { - attrs.push(MediaAttribute::RtcpFb { - pt: self.pt, - value: "goog-remb".into(), - }); - } - if self.fb_fir { - attrs.push(MediaAttribute::RtcpFb { - pt: self.pt, - value: "ccm fir".into(), - }); - } - if self.fb_nack { - attrs.push(MediaAttribute::RtcpFb { - pt: self.pt, - value: "nack".into(), - }); - } - if self.fb_pli { - attrs.push(MediaAttribute::RtcpFb { - pt: self.pt, - value: "nack pli".into(), - }); - } - - let fmtps = self.spec.format.to_format_param(); - if !fmtps.is_empty() { - attrs.push(MediaAttribute::Fmtp { - pt: self.pt, - values: fmtps, - }); - } - - if let Some(pt) = self.resend { - attrs.push(MediaAttribute::RtpMap { - pt, - value: RtpMap { - codec: Codec::Rtx, - clock_rate: self.spec.clock_rate, - channels: None, - }, - }); - attrs.push(MediaAttribute::Fmtp { - pt, - values: vec![FormatParam::Apt(self.pt)], - }); - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct RtpMap { - pub codec: Codec, - pub clock_rate: Frequency, - pub channels: Option, -} - -impl From for CodecSpec { - fn from(v: RtpMap) -> Self { - CodecSpec { - codec: v.codec, - clock_rate: v.clock_rate, - channels: v.channels, - format: FormatParams::default(), - } - } -} - -impl From for RtpMap { - fn from(v: CodecSpec) -> Self { - RtpMap { - codec: v.codec, - clock_rate: v.clock_rate, - channels: v.channels, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Simulcast { - pub send: SimulcastGroups, - pub recv: SimulcastGroups, - /// If this is created synthetically for a munged SDP. - pub is_munged: bool, -} - -impl Simulcast { - pub fn invert(self) -> Self { - Simulcast { - send: self.recv, - recv: self.send, - is_munged: self.is_munged, - } - } -} - -/// RID organization inside a=simulcast line. -/// -/// `a=simulcast send 2;3,4` would result in -/// `SimulcastGroups(vec![SimulcastLayer("2"), SimulcastLayer("3")])` -/// -/// The choice between 3 and 4 for the rid is currently ignored and the first option is always -/// selected. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SimulcastGroups(pub Vec); - -/// Represents a simulcast layer in a group -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SimulcastLayer { - /// The layer's rid - pub restriction_id: RestrictionId, - /// Optional attributes per RFC 8851 - pub attributes: Option>, -} - -impl Deref for SimulcastGroups { - type Target = [SimulcastLayer]; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Msid { - pub stream_id: String, - pub track_id: String, -} - -/// RFC 8830's "no MediaStream" sentinel: a stream or track id of `-` means the -/// media is not associated with a MediaStream. -pub(crate) fn is_no_stream(s: &str) -> bool { - s.trim() == "-" -} - -impl Msid { - pub fn random() -> Self { - Msid { - stream_id: Id::<30>::random().to_string(), - track_id: Id::<30>::random().to_string(), - } - } -} - -impl fmt::Display for SimulcastGroups { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - for (idx, layer) in self.0.iter().enumerate() { - if idx + 1 == self.0.len() { - write!(f, "{}", layer.restriction_id.to_sdp())?; - } else { - write!(f, "{};", layer.restriction_id.to_sdp())?; - } - } - Ok(()) - } -} - -impl fmt::Display for Sdp { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.session)?; - for m in &self.media_lines { - write!(f, "{m}")?; - } - Ok(()) - } -} - -impl fmt::Display for Session { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "v=0\r\n")?; - write!(f, "o=str0m-{} {} 2 IN IP4 0.0.0.0\r\n", VERSION, self.id)?; - write!(f, "s=-\r\n")?; - if let Some(bw) = &self.bw { - write!(f, "b={}:{}\r\n", bw.typ, bw.val)?; - } - write!(f, "t=0 0\r\n")?; - for a in &self.attrs { - write!(f, "{a}")?; - } - Ok(()) - } -} - -impl fmt::Display for SessionAttribute { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use SessionAttribute::*; - match self { - Group { typ, mids } => { - write!(f, "a=group:{typ}")?; - for mid in mids { - write!(f, " {mid}")?; - } - write!(f, "\r\n")?; - } - AllowMixedExts => write!(f, "a=extmap-allow-mixed\r\n")?, - MsidSemantic { semantic, stream_ids } => { - write!(f, "a=msid-semantic: {} {}\r\n", semantic, stream_ids.join(" "))?; - } - IceLite => write!(f, "a=ice-lite\r\n")?, - IceUfrag(v) => write!(f, "a=ice-ufrag:{v}\r\n")?, - IcePwd(v) => write!(f, "a=ice-pwd:{v}\r\n")?, - IceOptions(v) => write!(f, "a=ice-options:{v}\r\n")?, - Fingerprint(v) => { - write!(f, "a=fingerprint:{} {}\r\n", v.hash_func, FingerprintFmt(&v.bytes))?; - } - Setup(v) => write!(f, "a=setup:{}\r\n", v.setup_line())?, - Candidate(c) => write!(f, "a={}\r\n", c.to_sdp_string())?, - EndOfCandidates => write!(f, "a=end-of-candidates\r\n")?, - Unused(v) => write!(f, "a={v}\r\n")?, - } - Ok(()) - } -} - -impl fmt::Display for MediaLine { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let port = if self.disabled { 0 } else { 9 }; - write!(f, "m={} {} {} ", self.typ, port, self.proto)?; - let len = self.pts.len(); - if self.typ.is_channel() { - write!(f, "webrtc-datachannel\r\n")?; - } else if self.pts.is_empty() { - write!(f, "0\r\n")?; - } else { - for (idx, m) in self.pts.iter().enumerate() { - if idx + 1 < len { - write!(f, "{m} ")?; - } else { - write!(f, "{m}")?; - } - } - write!(f, "\r\n")?; - } - write!(f, "c=IN IP4 0.0.0.0\r\n")?; - if let Some(bw) = &self.bw { - write!(f, "b={}:{}\r\n", bw.typ, bw.val)?; - } - for a in &self.attrs { - write!(f, "{a}")?; - } - Ok(()) - } -} - -impl fmt::Display for MediaType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - MediaType::Audio => write!(f, "audio"), - MediaType::Video => write!(f, "video"), - MediaType::Application => write!(f, "application"), - MediaType::Unknown(v) => write!(f, "{v}"), - } - } -} - -impl fmt::Display for Proto { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.proto_line()) - } -} - -impl fmt::Display for MediaAttribute { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use MediaAttribute::*; - match self { - Rtcp(v) => write!(f, "a=rtcp:{v}\r\n")?, - IceUfrag(v) => write!(f, "a=ice-ufrag:{v}\r\n")?, - IcePwd(v) => write!(f, "a=ice-pwd:{v}\r\n")?, - IceOptions(v) => write!(f, "a=ice-options:{v}\r\n")?, - Fingerprint(v) => { - write!(f, "a=fingerprint:{} {}\r\n", v.hash_func, FingerprintFmt(&v.bytes))?; - } - Setup(v) => write!(f, "a=setup:{}\r\n", v.setup_line())?, - Mid(v) => write!(f, "a=mid:{v}\r\n")?, - SctpPort(v) => write!(f, "a=sctp-port:{v}\r\n")?, - MaxMessageSize(v) => write!(f, "a=max-message-size:{v}\r\n")?, - SctpInit(v) => write!(f, "a=sctp-init:{v}\r\n")?, - ExtMap { id, ext } => { - if !ext.is_serialized() { - return Ok(()); - } - write!(f, "a=extmap:{}", id)?; - // if let Some(d) = &e.direction { - // write!(f, "/{d}")?; - // } - write!(f, " {}", ext.as_uri())?; - // if let Some(e) = &e.ext { - // write!(f, " {}", e)?; - // } - write!(f, "\r\n")?; - } - RecvOnly => write!(f, "a=recvonly\r\n")?, - SendRecv => write!(f, "a=sendrecv\r\n")?, - SendOnly => write!(f, "a=sendonly\r\n")?, - Inactive => write!(f, "a=inactive\r\n")?, - // a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1 - // a=msid:- 78dde68-7055-4e20-bb37-433803dd1ed1 - Msid(v) => write!(f, "a=msid:{} {}\r\n", v.stream_id, v.track_id)?, - RtcpMux => write!(f, "a=rtcp-mux\r\n")?, - RtcpMuxOnly => write!(f, "a=rtcp-mux-only\r\n")?, - RtcpRsize => write!(f, "a=rtcp-rsize\r\n")?, - Candidate(c) => write!(f, "a={}\r\n", c.to_sdp_string())?, - EndOfCandidates => write!(f, "a=end-of-candidates\r\n")?, - RtpMap { pt, value: c } => { - write!(f, "a=rtpmap:{} {}/{}", pt, c.codec, c.clock_rate)?; - if let Some(e) = c.channels { - write!(f, "/{e}")?; - } - write!(f, "\r\n")?; - } - RtcpFb { pt, value } => write!(f, "a=rtcp-fb:{pt} {value}\r\n")?, - Fmtp { pt, values } => { - if values.is_empty() { - // Skip empty fmtp lines - they're invalid SDP - return Ok(()); - } - write!(f, "a=fmtp:{pt} ")?; - for (idx, v) in values.iter().enumerate() { - if idx + 1 < values.len() { - write!(f, "{v};")?; - } else { - write!(f, "{v}\r\n")?; - } - } - } - // a=rid:hi send pt=111,112;max-br=64000;max-height=360 - Rid { - id, - direction, - pt, - restriction, - } => { - write!(f, "a=rid:{} {}", id.0, direction)?; - for (idx, p) in pt.iter().enumerate() { - if idx == 0 { - write!(f, " pt=")?; - } - if idx + 1 == pt.len() { - write!(f, "{p}")?; - } else { - write!(f, "{p},")?; - } - } - for (idx, (k, v)) in restriction.iter().enumerate() { - if idx == 0 { - if pt.is_empty() { - write!(f, " ")?; - } else { - write!(f, ";")?; - } - } - if idx + 1 == restriction.len() { - write!(f, "{k}={v}")?; - } else { - write!(f, "{k}={v};")?; - } - } - write!(f, "\r\n")?; - } - // a=simulcast: ;, [same] - Simulcast(x) => { - let self::Simulcast { send, recv, is_munged } = x; - assert!(!(send.0.is_empty() && recv.0.is_empty()), "Empty a=simulcast"); - if *is_munged { - // don't write - return Ok(()); - } - write!(f, "a=simulcast:")?; - if !send.0.is_empty() { - write!(f, "send {send}")?; - } - if !recv.0.is_empty() { - if !send.0.is_empty() { - write!(f, " ")?; - } - write!(f, "recv {recv}")?; - } - write!(f, "\r\n")?; - } - SsrcGroup { semantics, ssrcs } => { - write!(f, "a=ssrc-group:{semantics} ")?; - for (idx, ssrc) in ssrcs.iter().enumerate() { - if idx + 1 < ssrcs.len() { - write!(f, "{} ", **ssrc)?; - } else { - write!(f, "{}\r\n", **ssrc)?; - } - } - } - Ssrc { ssrc, attr, value } => { - write!(f, "a=ssrc:{} {}:{}\r\n", **ssrc, attr, value)?; - } - Unused(v) => write!(f, "a={v}\r\n")?, - } - Ok(()) - } -} - -pub struct FingerprintFmt<'a>(pub &'a [u8]); - -impl<'a> std::fmt::Display for FingerprintFmt<'a> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let last = self.0.len() - 1; - for (idx, b) in self.0.iter().enumerate() { - if idx < last { - write!(f, "{b:02X}:")?; - } else { - write!(f, "{b:02X}")?; - } - } - Ok(()) - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::VERSION; - use crate::vendor::str0m::packet::H265ProfileTierLevel; - use crate::vendor::str0m::rtp_::{Extension, Frequency}; - - use super::*; - - /// The captured Chrome offer in `docs/chrome-sdp.json`, as an SDP string. - fn chrome_offer() -> String { - let json: serde_json::Value = serde_json::from_str(include_str!("../docs/chrome-sdp.json")).unwrap(); - let lines = json["sdp"].as_array().unwrap(); - let sdp: String = lines.iter().map(|l| format!("{}\r\n", l.as_str().unwrap())).collect(); - sdp - } - - #[test] - fn fast_and_easy_parse_agree() { - let input = chrome_offer(); - let fast = Sdp::parse(&input).unwrap(); - let (easy, _) = sdp_parser().easy_parse(input.as_str()).unwrap(); - assert_eq!(fast, easy); - assert!(fast.media_lines.len() >= 2); - } - - #[test] - fn invalid_sdp_keeps_the_detailed_error() { - let input = chrome_offer().replacen("v=0", "v=x", 1); - let Err(SdpError::ParseError(msg)) = Sdp::parse(&input) else { - panic!("a bad version line parses"); - }; - assert!(msg.contains("Parse error at"), "{msg}"); - } - - #[test] - fn fingerprint_hash_preference_at_session_and_media_level() { - for (hashes, expected) in [ - (vec!["sha-1", "SHA-256"], "SHA-256"), - (vec!["sha-256", "SHA-1"], "sha-256"), - (vec!["sha-512", "SHA-1"], "SHA-1"), - (vec!["sha-512", "sha-256"], "sha-256"), - (vec!["sha-512", "md5"], "sha-512"), - ] { - for session_level in [false, true] { - let fingerprints = hashes - .iter() - .map(|hash| format!("a=fingerprint:{hash} 00:01\r\n")) - .collect::(); - let header = "v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"; - let media = "m=audio 9 UDP/TLS/RTP/SAVPF 0\r\na=mid:0\r\na=sendrecv\r\n"; - let sdp = if session_level { - format!("{header}{fingerprints}{media}") - } else { - format!("{header}{media}{fingerprints}") - }; - let parsed = Sdp::parse(&sdp).unwrap(); - assert_eq!(parsed.fingerprint().unwrap().hash_func, expected); - } - } - } - - #[test] - fn remote_twcc_feedback_is_explicit_and_per_payload_type() { - let sdp = Sdp::parse(concat!( - "v=0\r\n", - "o=- 1 1 IN IP4 127.0.0.1\r\n", - "s=-\r\n", - "t=0 0\r\n", - "m=video 9 UDP/TLS/RTP/SAVPF 96 98\r\n", - "a=mid:0\r\n", - "a=sendrecv\r\n", - "a=setup:actpass\r\n", - "a=ice-ufrag:test\r\n", - "a=ice-pwd:testpassword\r\n", - "a=rtpmap:96 VP8/90000\r\n", - "a=rtpmap:98 VP9/90000\r\n", - "a=rtcp-fb:98 transport-cc\r\n", - )) - .unwrap(); - let params = sdp.media_lines[0].rtp_params(); - for (pt, expected) in [(96, false), (98, true)] { - let p = params.iter().find(|p| p.pt == pt.into()).unwrap(); - assert_eq!(p.fb_transport_cc(), expected); - } - } - - #[test] - fn a_group_is_written_without_a_trailing_space() { - let empty = SessionAttribute::Group { - typ: "BUNDLE".into(), - mids: vec![], - }; - assert_eq!(empty.to_string(), "a=group:BUNDLE\r\n"); - - let two = SessionAttribute::Group { - typ: "BUNDLE".into(), - mids: vec!["0".into(), "1".into()], - }; - assert_eq!(two.to_string(), "a=group:BUNDLE 0 1\r\n"); - } - - fn sdp_with_mids(group: &str, mids: &[&str]) -> Sdp { - let mut sdp = format!("v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE {group}\r\n"); - for mid in mids { - sdp.push_str("m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n"); - sdp.push_str(&format!("a=mid:{mid}\r\n")); - sdp.push_str("a=sendrecv\r\na=rtpmap:111 opus/48000/2\r\n"); - } - Sdp::parse(&sdp).unwrap() - } - - #[test] - fn an_invalid_m_line_after_a_valid_one_is_inconsistent() { - let mut missing_mid = sdp_with_mids("0 1", &["0", "1"]); - missing_mid.media_lines[1] - .attrs - .retain(|a| !matches!(a, MediaAttribute::Mid(_))); - - let mut two_directions = sdp_with_mids("0 1", &["0", "1"]); - two_directions.media_lines[1].attrs.push(MediaAttribute::RecvOnly); - - for sdp in [missing_mid, two_directions] { - let expected = sdp.media_lines[1].check_consistent().unwrap(); - let err = sdp.assert_consistency().unwrap_err(); - let SdpError::Inconsistent(message) = err else { - panic!("expected an inconsistent SDP error, got {err:?}"); - }; - assert_eq!(message, expected); - } - } - - #[test] - fn group_mids_match_participating_m_lines_in_order() { - for group in ["1 0", "0", "0 1 2", "0 2"] { - assert!(sdp_with_mids(group, &["0", "1"]).assert_consistency().is_err()); - } - sdp_with_mids("0 1", &["0", "1"]).assert_consistency().unwrap(); - - for (group, rejected_index) in [("1", 0), ("0", 1)] { - let mut rejected = sdp_with_mids(group, &["0", "1"]); - rejected.media_lines[rejected_index].disabled = true; - rejected.assert_consistency().unwrap(); - } - - let mut bundle_only = sdp_with_mids("0 1", &["0", "1"]); - bundle_only.media_lines[1].disabled = true; - bundle_only.assert_consistency().unwrap(); - } - - #[test] - fn a_rejected_m_line_without_formats_is_consistent() { - let mut built = sdp_with_mids("0", &["0", "1"]); - built.media_lines[1].disabled = true; - built.media_lines[1].pts.clear(); - built.assert_consistency().unwrap(); - - let parsed = Sdp::parse( - "v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\n\ - m=video 0 UDP/TLS/RTP/SAVPF \r\na=mid:1\r\na=inactive\r\n", - ) - .unwrap(); - assert!(parsed.media_lines[1].disabled); - assert!(parsed.media_lines[1].pts.is_empty()); - parsed.assert_consistency().unwrap(); - } - - #[test] - fn duplicate_mids_are_inconsistent() { - let cases: [(&str, &[&str]); 3] = [("0 0", &["0", "0"]), ("0", &["0", "0"]), ("1 0 0", &["1", "0", "0"])]; - for (group, mids) in cases { - let err = sdp_with_mids(group, mids).assert_consistency().unwrap_err(); - let SdpError::Inconsistent(message) = err else { - panic!("expected an inconsistent SDP error, got {err:?}"); - }; - assert_eq!(message, "Mid 0 is used by more than one m-line"); - } - } - - /// Tests for general format parameter serialization and parsing. - /// These tests verify that format parameters can be correctly converted to/from strings. - mod format_params { - use super::*; - - #[test] - fn fmtp_param_to_string() { - let f = FormatParams { - min_p_time: Some(10), - stereo: Some(true), - use_inband_fec: Some(true), - ..Default::default() - }; - assert_eq!(f.to_string(), "minptime=10;stereo=1;useinbandfec=1"); - } - - #[test] - fn fmtp_param_names_are_case_insensitive() { - let pairs = |pairs: &[(&str, &str)]| -> Vec<(String, String)> { - pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() - }; - - let opus = pairs(&[("MinPTime", "10"), ("UseInbandFEC", "1")]); - assert_eq!( - FormatParam::parse_pairs(opus), - [FormatParam::MinPTime(10), FormatParam::UseInbandFec(true)] - ); - - let h265 = pairs(&[("Profile-Id", "1"), ("TIER-FLAG", "0"), ("Level-Id", "93")]); - let ptl = H265ProfileTierLevel::new(1, 0, 93).unwrap(); - assert_eq!(FormatParam::parse_pairs(h265), [FormatParam::H265ProfileTierLevel(ptl)]); - } - } - - /// Tests for SDP parsing, structure validation, and serialization. - /// Covers error handling, SDP generation, BUNDLE groups, and media line configuration. - mod sdp_parsing { - use super::*; - - #[test] - fn parse_error() { - let input = "v=0\r\n\ - o=mozilla...THIS_IS_SDPARTA-99.0 7710052215259647220 2 IN IP4 0.0.0.0\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=fingerprint:sha-256 A6:64:23:37:94:7E:4B:40:F6:62:86:8C:DD:09:D5:08:\ -7E:D4:0E:68:58:93:45:EC:99:F2:91:F7:19:72:E7:BB\r\n\ - a=group:BUNDLE 0 hxI i1X mxk B3D kNI nbB xIZ bKm Hkn\r\n\ - a=ice-options:trickle\r\n\ - a=msid-semantic:WMS *\r\n\ - m=audio 0 UDP/TLS/RTP/SAVPF 0\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=setup:actpass\r\n\ - a=mid:1\r\n\ - a=rtpmap:0 PCMU/8000\r\n\ - "; - - let sdp = Sdp::parse(input); - - match sdp { - Err(SdpError::ParseError(out)) => { - assert!(out.starts_with(&"Parse error at ".to_string())); - assert!( - out.contains( - &"Expected exactly one of a=sendrecv, a=sendonly, a=recvonly, a=inactive for mid: 1" - .to_string() - ) - ); - } - _ => panic!(), - } - } - - #[test] - fn write_sdp() { - let sdp = Sdp { - session: Session { - id: 5_058_682_828_002_148_772.into(), - bw: None, - attrs: vec![ - SessionAttribute::Group { - typ: "BUNDLE".into(), - mids: vec!["0".into()], - }, - SessionAttribute::Unused("msid-semantic: WMS 5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK".into()), - ], - }, - media_lines: vec![ - MediaLine { - typ: MediaType::Audio, - disabled: false, - proto: Proto::Srtp, - pts: vec![111, 103, 104, 9, 0, 8, 106, 105, 13, 110, 112, 113, 126] - .into_iter() - .map(Pt::from) - .collect(), - bw: None, - attrs: vec![ - MediaAttribute::Rtcp("9 IN IP4 0.0.0.0".into()), - MediaAttribute::IceUfrag("S5hk".into()), - MediaAttribute::IcePwd("0zV/Yu3y8aDzbHgqWhnVQhqP".into()), - MediaAttribute::IceOptions("trickle".into()), - MediaAttribute::Fingerprint(Fingerprint { - hash_func: "sha-256".into(), - bytes: vec![ - 140, 100, 237, 3, 118, 208, 61, 180, 136, 8, 145, 100, 8, 128, 168, 198, 90, 191, - 139, 78, 56, 39, 150, 202, 8, 73, 37, 115, 70, 96, 32, 220, - ], - }), - MediaAttribute::Setup(Setup::ActPass), - MediaAttribute::Mid("0".into()), - MediaAttribute::ExtMap { - id: 1, - ext: Extension::AudioLevel, - }, - MediaAttribute::ExtMap { - id: 2, - ext: Extension::AbsoluteSendTime, - }, - MediaAttribute::ExtMap { - id: 3, - ext: Extension::TransportSequenceNumber, - }, - MediaAttribute::ExtMap { - id: 4, - ext: Extension::RtpMid, - }, - MediaAttribute::ExtMap { - id: 5, - ext: Extension::RtpStreamId, - }, - MediaAttribute::ExtMap { - id: 6, - ext: Extension::RepairedRtpStreamId, - }, - MediaAttribute::SendRecv, - MediaAttribute::Msid(Msid { - stream_id: "5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK".into(), - track_id: "f78dde68-7055-4e20-bb37-433803dd1ed1".into(), - }), - MediaAttribute::RtcpMux, - MediaAttribute::RtpMap { - pt: 111.into(), - value: RtpMap { - codec: "opus".into(), - clock_rate: Frequency::FORTY_EIGHT_KHZ, - channels: Some(2), - }, - }, - MediaAttribute::RtcpFb { - pt: 111.into(), - value: "transport-cc".into(), - }, - MediaAttribute::Fmtp { - pt: 111.into(), - values: vec![FormatParam::MinPTime(10), FormatParam::UseInbandFec(true)], - }, - MediaAttribute::Ssrc { - ssrc: 3_948_621_874.into(), - attr: "cname".into(), - value: "xeXs3aE9AOBn00yJ".into(), - }, - MediaAttribute::Ssrc { - ssrc: 3_948_621_874.into(), - attr: "msid".into(), - value: "5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1" - .into(), - }, - MediaAttribute::Ssrc { - ssrc: 3_948_621_874.into(), - attr: "mslabel".into(), - value: "5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK".into(), - }, - MediaAttribute::Ssrc { - ssrc: 3_948_621_874.into(), - attr: "label".into(), - value: "f78dde68-7055-4e20-bb37-433803dd1ed1".into(), - }, - ], - }, - MediaLine { - typ: MediaType::Video, - disabled: false, - proto: Proto::Srtp, - pts: vec![45.into(), 46.into()], - bw: None, - attrs: vec![ - MediaAttribute::Rtcp("9 IN IP4 0.0.0.0".into()), - MediaAttribute::IceUfrag("S5hk".into()), - MediaAttribute::IcePwd("0zV/Yu3y8aDzbHgqWhnVQhqP".into()), - MediaAttribute::IceOptions("trickle".into()), - MediaAttribute::Fingerprint(Fingerprint { - hash_func: "sha-256".into(), - bytes: vec![ - 140, 100, 237, 3, 118, 208, 61, 180, 136, 8, 145, 100, 8, 128, 168, 198, 90, 191, - 139, 78, 56, 39, 150, 202, 8, 73, 37, 115, 70, 96, 32, 220, - ], - }), - MediaAttribute::Setup(Setup::ActPass), - MediaAttribute::Mid("1".into()), - MediaAttribute::ExtMap { - id: 14, - ext: Extension::TransmissionTimeOffset, - }, - MediaAttribute::ExtMap { - id: 2, - ext: Extension::AbsoluteSendTime, - }, - MediaAttribute::ExtMap { - id: 13, - ext: Extension::VideoOrientation, - }, - MediaAttribute::ExtMap { - id: 3, - ext: Extension::TransportSequenceNumber, - }, - MediaAttribute::ExtMap { - id: 5, - ext: Extension::PlayoutDelay, - }, - MediaAttribute::ExtMap { - id: 6, - ext: Extension::VideoContentType, - }, - MediaAttribute::ExtMap { - id: 7, - ext: Extension::VideoTiming, - }, - MediaAttribute::ExtMap { - id: 8, - ext: Extension::ColorSpace, - }, - MediaAttribute::ExtMap { - id: 4, - ext: Extension::RtpMid, - }, - MediaAttribute::ExtMap { - id: 10, - ext: Extension::RtpStreamId, - }, - MediaAttribute::ExtMap { - id: 11, - ext: Extension::RepairedRtpStreamId, - }, - MediaAttribute::SendRecv, - MediaAttribute::Msid(Msid { - stream_id: "-".into(), - track_id: "4018fd65-ac50-4861-89a4-1f2cc35bbb5e".into(), - }), - MediaAttribute::RtcpMux, - MediaAttribute::RtcpRsize, - MediaAttribute::RtpMap { - pt: 45.into(), - value: RtpMap { - codec: Codec::Av1, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - }, - }, - MediaAttribute::RtcpFb { - pt: 45.into(), - value: "goog-remb".into(), - }, - MediaAttribute::RtcpFb { - pt: 45.into(), - value: "transport-cc".into(), - }, - MediaAttribute::RtcpFb { - pt: 45.into(), - value: "ccm fir".into(), - }, - MediaAttribute::RtcpFb { - pt: 45.into(), - value: "nack".into(), - }, - MediaAttribute::RtcpFb { - pt: 45.into(), - value: "nack pli".into(), - }, - MediaAttribute::Fmtp { - pt: 45.into(), - values: vec![FormatParam::LevelIdx(5), FormatParam::Profile(0), FormatParam::Tier(0)], - }, - MediaAttribute::RtpMap { - pt: 46.into(), - value: RtpMap { - codec: Codec::Rtx, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - }, - }, - MediaAttribute::Fmtp { - pt: 46.into(), - values: vec![FormatParam::Apt(45.into())], - }, - ], - }, - ], - }; - assert_eq!( - &format!("{sdp}"), - &format!( - "v=0\r\n\ - o=str0m-{VERSION} 5058682828002148772 2 IN IP4 0.0.0.0\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=msid-semantic: WMS 5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=rtcp:9 IN IP4 0.0.0.0\r\n\ - a=ice-ufrag:S5hk\r\n\ - a=ice-pwd:0zV/Yu3y8aDzbHgqWhnVQhqP\r\n\ - a=ice-options:trickle\r\n\ - a=fingerprint:sha-256 8C:64:ED:03:76:D0:3D:B4:88:08:91:64:08:80:A8:C6:\ -5A:BF:8B:4E:38:27:96:CA:08:49:25:73:46:60:20:DC\r\n\ - a=setup:actpass\r\n\ - a=mid:0\r\n\ - a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\n\ - a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n\ - a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\n\ - a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\n\ - a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\n\ - a=extmap:6 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n\ - a=sendrecv\r\n\ - a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:111 opus/48000/2\r\n\ - a=rtcp-fb:111 transport-cc\r\n\ - a=fmtp:111 minptime=10;useinbandfec=1\r\n\ - a=ssrc:3948621874 cname:xeXs3aE9AOBn00yJ\r\n\ - a=ssrc:3948621874 msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK \ -f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\ - a=ssrc:3948621874 mslabel:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK\r\n\ - a=ssrc:3948621874 label:f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 45 46\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=rtcp:9 IN IP4 0.0.0.0\r\n\ - a=ice-ufrag:S5hk\r\n\ - a=ice-pwd:0zV/Yu3y8aDzbHgqWhnVQhqP\r\n\ - a=ice-options:trickle\r\n\ - a=fingerprint:sha-256 8C:64:ED:03:76:D0:3D:B4:88:08:91:64:08:80:A8:C6:\ -5A:BF:8B:4E:38:27:96:CA:08:49:25:73:46:60:20:DC\r\n\ - a=setup:actpass\r\n\ - a=mid:1\r\n\ - a=extmap:14 urn:ietf:params:rtp-hdrext:toffset\r\n\ - a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n\ - a=extmap:13 urn:3gpp:video-orientation\r\n\ - a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\n\ - a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\r\n\ - a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type\r\n\ - a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing\r\n\ - a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space\r\n\ - a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\n\ - a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\n\ - a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n\ - a=sendrecv\r\n\ - a=msid:- 4018fd65-ac50-4861-89a4-1f2cc35bbb5e\r\n\ - a=rtcp-mux\r\n\ - a=rtcp-rsize\r\n\ - a=rtpmap:45 AV1/90000\r\n\ - a=rtcp-fb:45 goog-remb\r\n\ - a=rtcp-fb:45 transport-cc\r\n\ - a=rtcp-fb:45 ccm fir\r\n\ - a=rtcp-fb:45 nack\r\n\ - a=rtcp-fb:45 nack pli\r\n\ - a=fmtp:45 level-idx=5;profile=0;tier=0\r\n\ - a=rtpmap:46 rtx/90000\r\n\ - a=fmtp:46 apt=45\r\n\ - " - ) - ); - } - - #[test] - fn bundle_mids_returns_correct_mids() { - let input = "v=0\r\n\ - o=- 123456 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0 1 2\r\n\ - a=msid-semantic:WMS *\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtpmap:111 opus/48000/2\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword1234\r\n\ - m=video 0 UDP/TLS/RTP/SAVPF 96\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:1\r\n\ - a=sendrecv\r\n\ - a=rtpmap:96 VP8/90000\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword1234\r\n\ - m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:2\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword1234\r\n\ - a=sctp-port:5000\r\n\ - "; - - let sdp = Sdp::parse(input).expect("should parse"); - - // bundle_mids should return all MIDs from the BUNDLE group - let mids = sdp.bundle_mids().expect("should have BUNDLE group"); - assert_eq!(mids.len(), 3); - assert_eq!(mids[0], "0".into()); - assert_eq!(mids[1], "1".into()); - assert_eq!(mids[2], "2".into()); - - // The m-lines with port=0 should have disabled=true at parsing level - // (interpretation of whether this means "rejected" happens later) - assert!(!sdp.media_lines[0].disabled, "audio has port=9"); - assert!(sdp.media_lines[1].disabled, "video has port=0"); - assert!(sdp.media_lines[2].disabled, "application has port=0"); - } - } - - /// Opus codec-specific tests. - /// These tests are mainly verify SDP format params. - mod opus_codec { - use super::*; - - #[test] - fn opus_fmtp_round_trip() { - let f = FormatParams { - use_dtx: Some(true), - stereo: Some(true), - sprop_stereo: Some(true), - ..Default::default() - }; - - let fmtp_str = f.to_string(); - assert_eq!(fmtp_str, "stereo=1;sprop-stereo=1;usedtx=1"); - - let parsed = FormatParams::parse_line(&fmtp_str); - assert_eq!(parsed, f); - } - - #[test] - fn opus_default_to_mono() { - let f = FormatParams { ..Default::default() }; - let fmtp_str = f.to_string(); - assert_eq!(fmtp_str, ""); - - let parsed = FormatParams::parse_line(&fmtp_str); - assert!(parsed.stereo.is_none()); - assert!(!parsed.stereo.unwrap_or(false)); - assert!(!parsed.sprop_stereo.unwrap_or(false)); - } - } - - /// Core H.265 (HEVC) codec-specific tests. - /// Tests basic H.265 parameter handling including profile-tier-level parsing, - /// serialization, and format parameter combinations. - mod h265_codec { - use super::*; - - /// Test that H.265 format parameters can be serialized to a string and parsed back - /// without loss of information. Verifies the round-trip conversion works correctly. - #[test] - fn h265_fmtp_round_trip() { - // Test that H.265 fmtp params round-trip correctly - let ptl = H265ProfileTierLevel::new(1, 0, 93).unwrap(); // Main, Main tier, Level 3.1 - - let f = FormatParams { - h265_profile_tier_level: Some(ptl), - ..Default::default() - }; - - // Serialize to string - let fmtp_str = f.to_string(); - assert_eq!(fmtp_str, "profile-id=1;tier-flag=0;level-id=93"); - - // Parse back - let parsed = FormatParams::parse_line(&fmtp_str); - assert_eq!(parsed.h265_profile_tier_level, Some(ptl)); - } - - /// Test different combinations of H.265 profiles, tiers, and levels to ensure - /// they are all serialized correctly. Covers Main, Main 10, different tiers, and levels. - #[test] - fn h265_different_profiles() { - // Test Main profile (1) - let main = H265ProfileTierLevel::new(1, 0, 93).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(main), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=93"); - - // Test Main 10 profile (2) - let main10 = H265ProfileTierLevel::new(2, 0, 93).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(main10), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=2;tier-flag=0;level-id=93"); - - // Test different tier (High tier) - let high_tier = H265ProfileTierLevel::new(1, 1, 93).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(high_tier), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=1;tier-flag=1;level-id=93"); - - // Test different level (Level 5.1 = 153) - let level_5_1 = H265ProfileTierLevel::new(1, 0, 153).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(level_5_1), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=153"); - } - - /// Test parsing H.265 parameters from key-value pairs as they would appear in SDP. - /// Verifies that the three separate params (profile-id, tier-flag, level-id) are - /// correctly combined into a single H265ProfileTierLevel composite. - #[test] - fn h265_parse_from_pairs() { - // Test parsing from key-value pairs (as would come from SDP) - let pairs = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - - let params = FormatParam::parse_pairs(pairs); - - // Should have exactly one H265ProfileTierLevel param - let h265_params: Vec<_> = params - .iter() - .filter(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - .collect(); - assert_eq!(h265_params.len(), 1); - - if let FormatParam::H265ProfileTierLevel(ptl) = h265_params[0] { - assert_eq!(ptl.profile_id(), 1); - assert_eq!(ptl.tier_flag(), 0); - assert_eq!(ptl.level_id(), 93); - } else { - panic!("Expected H265ProfileTierLevel"); - } - } - - /// Test that H.265 profile-tier-level params can coexist with other H.265-specific - /// parameters like sprop-max-don-diff without interfering with each other. - #[test] - fn h265_mixed_with_other_params() { - // Test H.265 params mixed with other format params - let pairs = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "93".to_string()), - ("sprop-max-don-diff".to_string(), "0".to_string()), - ]; - - let params = FormatParam::parse_pairs(pairs); - - // Should have H265ProfileTierLevel and SpropMaxDonDiff - assert!(params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - assert!(params.iter().any(|p| matches!(p, FormatParam::SpropMaxDonDiff(0)))); - } - - /// Test sprop-max-don-diff parsing, display, and round-trip for various values. - #[test] - fn sprop_max_don_diff_parse_and_display() { - // Parse standalone sprop-max-don-diff - let param = FormatParam::parse("sprop-max-don-diff", "32"); - assert!(matches!(param, FormatParam::SpropMaxDonDiff(32))); - - // Display format - assert_eq!(param.to_string(), "sprop-max-don-diff=32"); - - // Parse value 0 (DONL disabled) - let param0 = FormatParam::parse("sprop-max-don-diff", "0"); - assert!(matches!(param0, FormatParam::SpropMaxDonDiff(0))); - - // Parse max valid value (RFC 7798 §7.1: 0..32767) - let param_max = FormatParam::parse("sprop-max-don-diff", "32767"); - assert!(matches!(param_max, FormatParam::SpropMaxDonDiff(32767))); - - // Out-of-range value (32768) rejected per RFC 7798 §7.1 - let param_over = FormatParam::parse("sprop-max-don-diff", "32768"); - assert!(matches!(param_over, FormatParam::Unknown)); - - // Invalid value falls back to Unknown - let param_bad = FormatParam::parse("sprop-max-don-diff", "notanumber"); - assert!(matches!(param_bad, FormatParam::Unknown)); - } - - /// Test that sprop-max-don-diff > 0 round-trips through H.265 fmtp with PTL params. - #[test] - fn h265_sprop_max_don_diff_nonzero_with_ptl() { - let pairs = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "93".to_string()), - ("sprop-max-don-diff".to_string(), "32".to_string()), - ]; - - let params = FormatParam::parse_pairs(pairs); - - // Should have both H265ProfileTierLevel and SpropMaxDonDiff(32) - assert!(params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - assert!(params.iter().any(|p| matches!(p, FormatParam::SpropMaxDonDiff(32)))); - - // Verify PTL values are correct - if let Some(FormatParam::H265ProfileTierLevel(ptl)) = params - .iter() - .find(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - { - assert_eq!(ptl.profile_id(), 1); - assert_eq!(ptl.tier_flag(), 0); - assert_eq!(ptl.level_id(), 93); - } - } - } - - /// Tests ensuring H.265 parameters are not confused with other codecs. - /// Verifies that H.265's three-parameter format (profile-id, tier-flag, level-id) - /// is correctly distinguished from H.264's profile-level-id, VP9's profile-id, - /// and AV1's profile/tier/level-idx parameters. - mod no_confusion { - use super::*; - - /// Test that H.264's profile-level-id parameter (single hex value) is not confused - /// with H.265's three separate parameters. H.264 uses a different format entirely. - #[test] - fn h265_no_confusion_with_h264() { - // H.264 uses profile-level-id (single param) - let h264_pairs = vec![ - ("profile-level-id".to_string(), "42e01f".to_string()), - ("packetization-mode".to_string(), "1".to_string()), - ]; - - let h264_params = FormatParam::parse_pairs(h264_pairs); - - // Should NOT have H265ProfileTierLevel - assert!( - !h264_params - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - ); - - // Should have ProfileLevelId (H.264) - assert!(h264_params.iter().any(|p| matches!(p, FormatParam::ProfileLevelId(_)))); - assert!( - h264_params - .iter() - .any(|p| matches!(p, FormatParam::PacketizationMode(1))) - ); - } - - /// Test that VP9's profile-id parameter (standalone) is not confused with H.265's - /// profile-id which must be combined with tier-flag and level-id. - #[test] - fn h265_no_confusion_with_vp9() { - // VP9 uses profile-id (single param, not combined) - let vp9_pairs = vec![("profile-id".to_string(), "0".to_string())]; - - let vp9_params = FormatParam::parse_pairs(vp9_pairs); - - // Should NOT have H265ProfileTierLevel (missing tier-flag and level-id) - assert!( - !vp9_params - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - ); - - // Should have ProfileId (VP9) - assert!(vp9_params.iter().any(|p| matches!(p, FormatParam::ProfileId(0)))); - } - - /// Test that AV1's parameters (profile, tier, level-idx) use different naming than - /// H.265 (profile-id, tier-flag, level-id) and are not confused during parsing. - #[test] - fn h265_no_confusion_with_av1() { - // AV1 uses profile, level-idx, tier (but should not be confused with H.265) - let av1_pairs = vec![ - ("profile".to_string(), "0".to_string()), - ("level-idx".to_string(), "5".to_string()), - ("tier".to_string(), "0".to_string()), - ]; - - let av1_params = FormatParam::parse_pairs(av1_pairs); - - // Should NOT have H265ProfileTierLevel - // (AV1 uses different param names: profile vs profile-id, - // tier vs tier-flag, level-idx vs level-id) - assert!( - !av1_params - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - ); - - // Should have AV1-specific params - assert!(av1_params.iter().any(|p| matches!(p, FormatParam::Profile(0)))); - assert!(av1_params.iter().any(|p| matches!(p, FormatParam::LevelIdx(5)))); - assert!(av1_params.iter().any(|p| matches!(p, FormatParam::Tier(0)))); - } - } - - /// Additional H.265 parsing and validation tests. - /// Covers incomplete parameter handling and complete SDP integration scenarios. - mod h265_additional { - use super::*; - - /// Test that incomplete H.265 parameter sets do not create a composite ProfileTierLevel. - /// All three parameters (profile-id, tier-flag, level-id) must be present. - #[test] - fn h265_partial_params_no_composite() { - // If only some H.265 params are present, should not create composite - let partial_pairs = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - // Missing level-id - ]; - - let params = FormatParam::parse_pairs(partial_pairs); - - // Should NOT have H265ProfileTierLevel (incomplete) - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - } - - /// Test H.265 parameters in a complete SDP offer/answer scenario. - /// Verifies that H.265 rtpmap and fmtp lines are correctly parsed along with RTX. - #[test] - fn h265_in_complete_sdp() { - let input = "v=0\r\n\ - o=- 123456 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 96 97\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtpmap:96 H265/90000\r\n\ - a=fmtp:96 profile-id=1;tier-flag=0;level-id=93\r\n\ - a=rtpmap:97 rtx/90000\r\n\ - a=fmtp:97 apt=96\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword\r\n\ - "; - - let sdp = Sdp::parse(input).expect("should parse"); - - // Get RTP params - let params = sdp.media_lines[0].rtp_params(); - - // Find H.265 payload - let h265_payload = params - .iter() - .find(|p| p.spec.codec == Codec::H265) - .expect("should have H.265"); - - assert_eq!(h265_payload.pt, 96.into()); - assert_eq!(h265_payload.spec.clock_rate, Frequency::NINETY_KHZ); - - // Check H.265 params - let ptl = h265_payload - .spec - .format - .h265_profile_tier_level - .expect("should have H.265 PTL"); - assert_eq!(ptl.profile_id(), 1); - assert_eq!(ptl.tier_flag(), 0); - assert_eq!(ptl.level_id(), 93); - - // Check RTX - assert_eq!(h265_payload.resend, Some(97.into())); - } - } - - /// Multi-codec integration tests. - /// Verifies that multiple video codecs (H.264, H.265, VP8, VP9) can coexist - /// in the same SDP without parameter conflicts or interference. - mod multi_codec { - use super::*; - - /// Test that H.264, H.265, and other video codecs can coexist in the same SDP - /// without their format parameters interfering with each other. - #[test] - fn h265_and_h264_coexist() { - let input = "v=0\r\n\ - o=- 123456 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 96 97 98\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtpmap:96 H264/90000\r\n\ - a=fmtp:96 profile-level-id=42e01f;packetization-mode=1\r\n\ - a=rtpmap:97 H265/90000\r\n\ - a=fmtp:97 profile-id=1;tier-flag=0;level-id=93\r\n\ - a=rtpmap:98 VP8/90000\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword\r\n\ - "; - - let sdp = Sdp::parse(input).expect("should parse"); - let params = sdp.media_lines[0].rtp_params(); - - // Check H.264 - let h264 = params - .iter() - .find(|p| p.spec.codec == Codec::H264) - .expect("should have H.264"); - assert_eq!(h264.pt, 96.into()); - assert_eq!(h264.spec.format.profile_level_id, Some(0x42e01f)); - assert_eq!(h264.spec.format.packetization_mode, Some(1)); - assert!(h264.spec.format.h265_profile_tier_level.is_none()); - - // Check H.265 - let h265 = params - .iter() - .find(|p| p.spec.codec == Codec::H265) - .expect("should have H.265"); - assert_eq!(h265.pt, 97.into()); - let ptl = h265.spec.format.h265_profile_tier_level.expect("should have H.265 PTL"); - assert_eq!(ptl.profile_id(), 1); - assert!(h265.spec.format.profile_level_id.is_none()); - - // Check VP8 - let vp8 = params - .iter() - .find(|p| p.spec.codec == Codec::Vp8) - .expect("should have VP8"); - assert_eq!(vp8.pt, 98.into()); - assert!(vp8.spec.format.h265_profile_tier_level.is_none()); - assert!(vp8.spec.format.profile_level_id.is_none()); - } - } - - /// H.265 serialization and edge case tests. - /// Tests media attribute generation, empty parameter handling, extreme values, - /// parameter ordering independence, DONL parameters, and invalid value handling. - mod h265_serialization { - use super::*; - - /// Test that H.265 parameters are correctly serialized as media attributes, - /// including rtpmap, fmtp with ProfileTierLevel, rtcp-fb, and RTX payload. - #[test] - fn h265_serialization_in_media_attrs() { - let ptl = H265ProfileTierLevel::new(2, 1, 153).unwrap(); // Main 10, High tier, Level 5.1 - - let mut payload = PayloadParams::new( - 100.into(), - Some(101.into()), - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - h265_profile_tier_level: Some(ptl), - ..Default::default() - }, - }, - ); - payload.fb_transport_cc = true; - payload.fb_nack = true; - payload.fb_pli = true; - - let mut attrs = vec![]; - payload.as_media_attrs(&mut attrs); - - // Should have rtpmap for H.265 - assert!(attrs.iter().any(|a| matches!(a, - MediaAttribute::RtpMap { pt, value } - if *pt == 100.into() && value.codec == Codec::H265 - ))); - - // Should have fmtp with H.265 params - let fmtp = attrs.iter().find(|a| { - matches!(a, - MediaAttribute::Fmtp { pt, .. } if *pt == 100.into() - ) - }); - assert!(fmtp.is_some()); - - if let Some(MediaAttribute::Fmtp { values, .. }) = fmtp { - assert!(values.iter().any(|v| matches!(v, FormatParam::H265ProfileTierLevel(p) - if p.profile_id() == 2 && p.tier_flag() == 1 && p.level_id() == 153 - ))); - } - - // Should have rtx mapping - assert!(attrs.iter().any(|a| matches!(a, - MediaAttribute::RtpMap { pt, value } - if *pt == 101.into() && value.codec == Codec::Rtx - ))); - } - - /// Test that empty format parameters do not generate an a=fmtp line in SDP, - /// avoiding invalid SDP syntax with empty fmtp attributes. - #[test] - fn h265_empty_fmtp_not_serialized() { - // Empty fmtp should not be written - let payload = PayloadParams::new( - 100.into(), - None, - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams::default(), - }, - ); - - let mut attrs = vec![]; - payload.as_media_attrs(&mut attrs); - - // Should NOT have fmtp line (it would be empty) - assert!(!attrs.iter().any(|a| matches!(a, MediaAttribute::Fmtp { .. }))); - } - - /// Test H.265 with extreme profile/tier/level values at boundaries. - /// Verifies parsing and serialization of edge case values. - #[test] - fn h265_extreme_values() { - // Test minimum level (Level 1.0 = 30) - let min_level = H265ProfileTierLevel::new(1, 0, 30).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(min_level), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=30"); - - // Test maximum level (Level 6.2 = 186) - let max_level = H265ProfileTierLevel::new(1, 0, 186).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(max_level), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=186"); - - // Test Main10 with High tier - let main10_high = H265ProfileTierLevel::new(2, 1, 93).unwrap(); - let f = FormatParams { - h265_profile_tier_level: Some(main10_high), - ..Default::default() - }; - assert_eq!(f.to_string(), "profile-id=2;tier-flag=1;level-id=93"); - } - - /// Test H.265 parameter ordering doesn't affect parsing. - /// SDP parameters can appear in any order. - #[test] - fn h265_parameter_order_independence() { - // Normal order - let normal_order = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - - // Reversed order - let reversed_order = vec![ - ("level-id".to_string(), "93".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("profile-id".to_string(), "1".to_string()), - ]; - - // Mixed order - let mixed_order = vec![ - ("tier-flag".to_string(), "0".to_string()), - ("profile-id".to_string(), "1".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - - let normal_params = FormatParam::parse_pairs(normal_order); - let reversed_params = FormatParam::parse_pairs(reversed_order); - let mixed_params = FormatParam::parse_pairs(mixed_order); - - // All should create H265ProfileTierLevel - assert!( - normal_params - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - ); - assert!( - reversed_params - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - ); - assert!( - mixed_params - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - ); - - // All should have the same values - for params in [&normal_params, &reversed_params, &mixed_params] { - if let Some(FormatParam::H265ProfileTierLevel(ptl)) = params - .iter() - .find(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - { - assert_eq!(ptl.profile_id(), 1); - assert_eq!(ptl.tier_flag(), 0); - assert_eq!(ptl.level_id(), 93); - } - } - } - - #[test] - fn h265_invalid_parameter_values() { - // Invalid profile-id - let invalid_profile = vec![ - ("profile-id".to_string(), "999".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - let params = FormatParam::parse_pairs(invalid_profile); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - - // Invalid tier-flag - let invalid_tier = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "5".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - let params = FormatParam::parse_pairs(invalid_tier); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - - // Invalid level-id - let invalid_level = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "999".to_string()), - ]; - let params = FormatParam::parse_pairs(invalid_level); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - } - } - - /// H.265 integration with RTCP feedback mechanisms. - /// Tests H.265 behavior with multiple codecs and various RTCP feedback types - /// including NACK, PLI, FIR, and transport-cc. - mod h265_integration { - use super::*; - - /// Test H.265 in SDP with multiple video codecs and feedback mechanisms. - /// Verifies proper parsing of complex multi-codec scenarios. - #[test] - fn h265_multi_codec_with_feedback() { - let input = "v=0\r\n\ - o=- 123456 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 96 97 98 99\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtpmap:96 H265/90000\r\n\ - a=fmtp:96 profile-id=1;tier-flag=0;level-id=93\r\n\ - a=rtcp-fb:96 nack\r\n\ - a=rtcp-fb:96 nack pli\r\n\ - a=rtcp-fb:96 ccm fir\r\n\ - a=rtcp-fb:96 transport-cc\r\n\ - a=rtpmap:97 rtx/90000\r\n\ - a=fmtp:97 apt=96\r\n\ - a=rtpmap:98 VP9/90000\r\n\ - a=fmtp:98 profile-id=0\r\n\ - a=rtpmap:99 rtx/90000\r\n\ - a=fmtp:99 apt=98\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword\r\n\ - "; - - let sdp = Sdp::parse(input).expect("should parse"); - let params = sdp.media_lines[0].rtp_params(); - - // Check H.265 with all feedback mechanisms - let h265 = params - .iter() - .find(|p| p.spec.codec == Codec::H265) - .expect("should have H.265"); - assert_eq!(h265.pt, 96.into()); - assert!(h265.fb_nack); - assert!(h265.fb_pli); - assert!(h265.fb_fir); - assert!(h265.fb_transport_cc); - assert_eq!(h265.resend, Some(97.into())); - - // Verify H.265 PTL is correct - let ptl = h265.spec.format.h265_profile_tier_level.expect("should have PTL"); - assert_eq!(ptl.profile_id(), 1); - - // Check VP9 is separate and correct - let vp9 = params - .iter() - .find(|p| p.spec.codec == Codec::Vp9) - .expect("should have VP9"); - assert_eq!(vp9.pt, 98.into()); - assert_eq!(vp9.spec.format.profile_id, Some(0)); - assert!(vp9.spec.format.h265_profile_tier_level.is_none()); - } - } - - /// Advanced H.265 functionality tests. - /// Covers SDP round-trip serialization, incomplete parameter permutations, - /// browser compatibility (Chrome profile-only mode), and validation of all - /// standard H.265 level values (1.0 through 6.2). - mod h265_advanced { - use super::*; - - /// Test H.265 SDP serialization maintains parameter integrity. - /// Ensures that serialized SDP can be parsed back with identical values. - #[test] - fn h265_sdp_serialization_round_trip() { - let ptl = H265ProfileTierLevel::new(2, 0, 153).unwrap(); - - let payload = PayloadParams::new( - 100.into(), - Some(101.into()), - CodecSpec { - codec: Codec::H265, - clock_rate: Frequency::NINETY_KHZ, - channels: None, - format: FormatParams { - h265_profile_tier_level: Some(ptl), - ..Default::default() - }, - }, - ); - - let mut attrs = vec![]; - payload.as_media_attrs(&mut attrs); - - // Find the fmtp line - let fmtp = attrs - .iter() - .find_map(|a| match a { - MediaAttribute::Fmtp { pt, values } if *pt == 100.into() => Some(values), - _ => None, - }) - .expect("should have fmtp"); - - // Should contain H265ProfileTierLevel - assert!( - fmtp.iter() - .any(|v| matches!(v, FormatParam::H265ProfileTierLevel(p) if p.profile_id() == 2)) - ); - } - - /// Test that only two of three H.265 params doesn't create PTL. - /// Each permutation of missing parameter should fail. - #[test] - fn h265_incomplete_params_all_permutations() { - // Missing level-id - let missing_level = vec![ - ("profile-id".to_string(), "1".to_string()), - ("tier-flag".to_string(), "0".to_string()), - ]; - let params = FormatParam::parse_pairs(missing_level); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - - // Missing tier-flag - let missing_tier = vec![ - ("profile-id".to_string(), "1".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - let params = FormatParam::parse_pairs(missing_tier); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - - // Missing profile-id - let missing_profile = vec![ - ("tier-flag".to_string(), "0".to_string()), - ("level-id".to_string(), "93".to_string()), - ]; - let params = FormatParam::parse_pairs(missing_profile); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - - // Only one parameter - let only_profile = vec![("profile-id".to_string(), "1".to_string())]; - let params = FormatParam::parse_pairs(only_profile); - assert!(!params.iter().any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))); - } - - /// Test H.265 with Chrome-style profile-only in complete SDP. - /// Verifies that browser compatibility mode works in real SDP. - #[test] - fn h265_chrome_profile_only_sdp() { - let input = "v=0\r\n\ - o=- 123456 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtpmap:96 H265/90000\r\n\ - a=fmtp:96 profile-id=1\r\n\ - a=setup:actpass\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword\r\n\ - "; - - let sdp = Sdp::parse(input).expect("should parse"); - let params = sdp.media_lines[0].rtp_params(); - - let h265 = params - .iter() - .find(|p| p.spec.codec == Codec::H265) - .expect("should have H.265"); - - // Should NOT have full PTL - assert!(h265.spec.format.h265_profile_tier_level.is_none()); - - // Should have profile_id field instead - assert_eq!(h265.spec.format.profile_id, Some(1)); - } - - /// Test H.265 different level values in valid range. - /// Ensures all valid level IDs are properly handled. - #[test] - fn h265_all_valid_levels() { - let valid_levels = vec![ - 30, // Level 1.0 - 60, // Level 2.0 - 63, // Level 2.1 - 90, // Level 3.0 - 93, // Level 3.1 - 120, // Level 4.0 - 123, // Level 4.1 - 150, // Level 5.0 - 153, // Level 5.1 - 156, // Level 5.2 - 180, // Level 6.0 - 183, // Level 6.1 - 186, // Level 6.2 - ]; - - for level_id in valid_levels { - let ptl = H265ProfileTierLevel::new(1, 0, level_id); - assert!(ptl.is_some(), "Level ID {} should be valid", level_id); - - let f = FormatParams { - h265_profile_tier_level: ptl, - ..Default::default() - }; - - let serialized = f.to_string(); - assert!(serialized.contains(&format!("level-id={}", level_id))); - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sdp/error.rs b/rs/moq-webrtc/src/vendor/str0m/sdp/error.rs deleted file mode 100644 index 7955b00277c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sdp/error.rs +++ /dev/null @@ -1,21 +0,0 @@ -use std::error::Error; -use std::fmt; - -/// Errors from parsing and serializing SDP. -#[derive(Debug)] -#[allow(missing_docs)] -pub enum SdpError { - ParseError(String), - Inconsistent(String), -} - -impl fmt::Display for SdpError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - SdpError::ParseError(msg) => write!(f, "SDP parse: {}", msg), - SdpError::Inconsistent(msg) => write!(f, "SDP inconsistent: {}", msg), - } - } -} - -impl Error for SdpError {} diff --git a/rs/moq-webrtc/src/vendor/str0m/sdp/mod.rs b/rs/moq-webrtc/src/vendor/str0m/sdp/mod.rs deleted file mode 100644 index 7aa8f5e639d..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sdp/mod.rs +++ /dev/null @@ -1,202 +0,0 @@ -use std::fmt; -use std::ops::Deref; - -use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; - -mod data; -#[cfg(test)] -pub(crate) use data::RtpMap; -pub(crate) use data::is_no_stream; -pub(crate) use data::{FormatParam, Sdp, Session, SessionAttribute, Setup}; -pub(crate) use data::{MediaAttribute, MediaLine, MediaType, Msid, Proto}; -pub(crate) use data::{RestrictionId, Simulcast, SimulcastGroups, SimulcastLayer}; - -mod parser; - -mod error; -pub use error::SdpError; - -#[derive(Debug, PartialEq, Eq)] -/// SDP offer. Offers can be serialized via serde. -pub struct SdpOffer(Sdp); - -impl SdpOffer { - /// Takes the SDP string without any JSON wrapping and makes an `Offer`. - pub fn from_sdp_string(input: &str) -> Result { - let sdp = Sdp::parse(input)?; - Ok(SdpOffer(sdp)) - } - - /// Turns this offer into an SDP string, without any JSON wrapping. - pub fn to_sdp_string(&self) -> String { - self.0.to_string() - } - - #[cfg(test)] - pub(crate) fn into_inner(self) -> Sdp { - self.0 - } -} - -#[derive(Debug, PartialEq, Eq)] -/// SDP answer. Answers can be serialized via serde. -pub struct SdpAnswer(Sdp); - -impl SdpAnswer { - /// Takes the SDP string without any JSON wrapping and makes an `Answer`. - pub fn from_sdp_string(input: &str) -> Result { - let sdp = Sdp::parse(input)?; - Ok(SdpAnswer(sdp)) - } - - /// Turns this answer into an SDP string, without any JSON wrapping. - pub fn to_sdp_string(&self) -> String { - self.0.to_string() - } -} - -impl Deref for SdpOffer { - type Target = Sdp; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Deref for SdpAnswer { - type Target = Sdp; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl From for SdpOffer { - fn from(v: Sdp) -> Self { - SdpOffer(v) - } -} - -impl From for SdpAnswer { - fn from(v: Sdp) -> Self { - SdpAnswer(v) - } -} - -impl fmt::Display for SdpOffer { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", **self) - } -} - -impl fmt::Display for SdpAnswer { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", **self) - } -} - -macro_rules! sdp_ser { - ($Struct:tt, $Name:literal, $LCName:literal) => { - impl Serialize for $Struct { - fn serialize(&self, s: S) -> Result - where - S: Serializer, - { - #[derive(Serialize)] - struct Data { - r#type: &'static str, - sdp: String, - } - - Data { - r#type: $LCName, - sdp: self.0.to_string(), - } - .serialize(s) - } - } - - impl<'de> Deserialize<'de> for $Struct { - fn deserialize(d: D) -> Result - where - D: Deserializer<'de>, - { - #[derive(Deserialize)] - struct Data { - r#type: String, - sdp: String, - } - - let data = Data::deserialize(d)?; - - if data.r#type != $LCName { - return Err(de::Error::custom(format!( - "Expected SDP type '{}', got '{}'", - $LCName, data.r#type - ))); - } - - let sdp = Sdp::parse(&data.sdp) - .map_err(|err| de::Error::custom(format!("Failed to parse SDP: {:?}", err)))?; - - Ok(Self(sdp)) - } - } - }; -} - -sdp_ser!(SdpOffer, "Offer", "offer"); -sdp_ser!(SdpAnswer, "Answer", "answer"); - -#[cfg(test)] -mod test { - use crate::vendor::str0m::VERSION; - use crate::vendor::str0m::rtp_::SessionId; - - use super::*; - - fn sdp() -> Sdp { - Sdp { - session: Session { - id: SessionId::from(123_u64), - attrs: vec![], - bw: None, - }, - media_lines: vec![], - } - } - - #[test] - fn serialize_deserialize_offer() { - let offer = SdpOffer(sdp()); - let json = serde_json::to_string(&offer).unwrap(); - - let expected = format!( - "{{\"type\":\"offer\",\"sdp\":\ - \"v=0\\r\\no=str0m-{VERSION} 123 2 \ - IN IP4 0.0.0.0\\r\\ns=-\\r\\nt=0 0\\r\\n\"}}" - ); - assert_eq!(json, expected); - - let offer2: SdpOffer = serde_json::from_str(&json).unwrap(); - - assert_eq!(offer, offer2); - } - - #[test] - fn serialize_deserialize_answer() { - let answer = SdpAnswer(sdp()); - let json = serde_json::to_string(&answer).unwrap(); - - let expected = format!( - "{{\"type\":\"answer\",\"sdp\":\ - \"v=0\\r\\no=str0m-{VERSION} 123 2 \ - IN IP4 0.0.0.0\\r\\ns=-\\r\\nt=0 0\\r\\n\"}}" - ); - assert_eq!(json, expected); - - let answer2: SdpAnswer = serde_json::from_str(&json).unwrap(); - - assert_eq!(answer, answer2); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sdp/parser.rs b/rs/moq-webrtc/src/vendor/str0m/sdp/parser.rs deleted file mode 100644 index 016ed8b5665..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sdp/parser.rs +++ /dev/null @@ -1,1835 +0,0 @@ -use std::net::{IpAddr, SocketAddr}; -use std::str::FromStr; -use tracing::warn; - -use crate::vendor::str0m::crypto::Fingerprint; -use crate::vendor::str0m::io::TcpType; -use crate::vendor::str0m::rtp_::{Direction, Extension, Frequency, Mid, Pt, SessionId, Ssrc}; -use crate::vendor::str0m::{Candidate, CandidateKind}; -use combine::error::*; -use combine::parser::char::*; -use combine::parser::combinator::*; -use combine::stream::StreamErrorFor; -use combine::*; -use combine::{ParseError, Parser, Stream}; - -use super::data::*; - -/// Creates a parser of SDP -pub fn sdp_parser() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - (session_parser(), many::, _, _>(media_parser())).map(|(session, media)| Sdp { - session, - media_lines: media, - }) -} - -// /////////////////////////////////////////////////// Session description - -/// 1. First line must be v=0 -/// 2. The second SDP line MUST be an "o=" line The sess-id MUST be representable by a 64-bit signed -/// integer, and the initial value MUST be less than (2**62)-1 -/// 3. Third line is the session name. The "s=" field MUST NOT be empty and SHOULD contain -/// ISO 10646 characters (RFC 8866 section 5.3). -/// -/// Session is over when we find a "t=" line MUST be added, both and -/// SHOULD be set to zero, e.g. "t=0 0". -pub fn session_parser() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - ( - typed_line('v', token('0')), // v=0 - originator_line(), // o=- 6564425948916445306 2 IN IP4 127.0.0.1 - // The "s=" field MUST NOT be empty (RFC 8866 section 5.3) - typed_line('s', any_value()), - many::, _, _>(ignored_session_line()), - optional(bandwidth_line()), // b=CT:1234 - typed_line('t', string("0 0")), // t=0 0 - many::, _, _>(typed_line('r', any_value())), // r should never appear - // - many::, _, _>(session_attribute_line()), - ) - .map(|(_, id, _, _, bw, _, _, attrs)| Session { id, bw, attrs }) -} - -/// `o= ` -fn originator_line() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - let session_string = typed_line( - 'o', - // o=- 6564425948916445306 2 IN IP4 127.0.0.1 - ( - not_sp(), - token(' '), - many1::(digit()), - token(' '), - any_value(), - ) - .map(|(_, _, sess, _, _)| sess), - ); - from_str(session_string).map(|x: u64| -> SessionId { SessionId::from(x) }) -} - -/// `b=:` -fn bandwidth_line() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - typed_line('b', (many1(satisfy(|c| c != ':')), token(':'), any_value())).map(|(typ, _, val)| Bandwidth { typ, val }) -} - -/// An a= line that with value like: `a=:`. -fn attribute_line(attribute: &'static str, val: Pval) -> impl Parser -where - Input: Stream, - Pval: Parser, - Input::Error: ParseError, -{ - typed_line('a', (string(attribute), token(':'), val)).map(|(_, _, val)| val) -} - -/// An a= line that has no value like: `a=ice-lite`. -fn attribute_line_flag(attribute: &'static str) -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - typed_line('a', (string(attribute)).map(|_| ())) -} - -/// a=foo:bar lines belonging before the first m= line -fn session_attribute_line() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - // a=group:BUNDLE 1 2 - // a=group:LS 1 2 - let group = attribute_line( - "group", - ( - not_sp(), - many::, _, _>(attempt((token(' '), not_sp()).map(|(_, m)| Mid::from(m.as_str())))), - optional(token(' ')), - ), - ) - .map(|(typ, mids, _)| SessionAttribute::Group { typ, mids }); - - // a=msid-semantic: WMS 9ce81ef6-c7cb-4da5-8f5f-3e7cc9b5f9b0 - let msid_semantic = attribute_line( - "msid-semantic", - ( - optional(token(' ')), - not_sp(), - token(' '), - sep_by1(not_sp(), token(' ')), - ), - ) - .map(|(_, semantic, _, stream_ids)| SessionAttribute::MsidSemantic { semantic, stream_ids }); - - // a=ice-lite - let ice_lite = attribute_line_flag("ice-lite").map(|_| SessionAttribute::IceLite); - - // a=ice-ufrag:IdNYTNL1fjvjyEzL - let ice_ufrag = attribute_line("ice-ufrag", any_value()).map(SessionAttribute::IceUfrag); - - // a=ice-pwd:4d64pT3T1xfwbZvi9fQKjoPb - let ice_pwd = attribute_line("ice-pwd", any_value()).map(SessionAttribute::IcePwd); - - // a=ice-options:trickle - let ice_opt = attribute_line("ice-options", any_value()).map(SessionAttribute::IceOptions); - - // a=fingerprint:sha-256 45:AD:5C:82:F8:BE:B5:2A:D1:74:A6:16:D0:50:CD:86:9C:97:9D:BD:06:\ - // 8C:C9:85:C9:CD:AB:2B:A8:56:03:CD - // "sha-1" / "sha-224" / "sha-256" / - // "sha-384" / "sha-512" / - // "md5" / "md2" - let hex_byte = count_min_max(2, 2, hex_digit()) - .and_then(|x: String| u8::from_str_radix(&x, 16).map_err(StreamErrorFor::::message_format)); - let finger = attribute_line("fingerprint", (not_sp(), token(' '), sep_by1(hex_byte, token(':')))) - .map(|(hash_func, _, bytes)| SessionAttribute::Fingerprint(Fingerprint { hash_func, bytes })); - - let setup_val = choice(( - attempt(string("actpass").map(|_| Setup::ActPass)), - attempt(string("active").map(|_| Setup::Active)), - attempt(string("passive").map(|_| Setup::Passive)), - )); - - // a=setup:actpass - let setup = attribute_line("setup", setup_val).map(SessionAttribute::Setup); - - // a=candidate - let cand = candidate_attribute().map(SessionAttribute::Candidate); - - // a=end-of-candidates - let endof = attribute_line_flag("end-of-candidates").map(|_| SessionAttribute::EndOfCandidates); - - // tls-id - // identity - // extmap - let unused = typed_line('a', any_value()).map(SessionAttribute::Unused); - - choice(( - attempt(group), - attempt(msid_semantic), - attempt(ice_lite), - attempt(ice_ufrag), - attempt(ice_pwd), - attempt(ice_opt), - attempt(finger), - attempt(setup), - attempt(cand), - attempt(endof), - unused, - )) -} - -/// Parser for candidate, without attribute prefix (a=). -fn candidate() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - // Reference: https://datatracker.ietf.org/doc/html/rfc5245#section-15.1 - let port = || not_sp::().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)); - - let ip_addr = || not_sp().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)); - - let kind = choice(( - string("host").map(|_| CandidateKind::Host), - string("prflx").map(|_| CandidateKind::PeerReflexive), - string("srflx").map(|_| CandidateKind::ServerReflexive), - string("relay").map(|_| CandidateKind::Relayed), - )); - - ( - string("candidate:").and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - not_sp(), - token(' '), - not_sp().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - token(' '), - not_sp().and_then(|s| { - s.as_str() - .try_into() - .map_err(|_| StreamErrorFor::::message_format(format!("invalid protocol: {}", s))) - }), - token(' '), - not_sp().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - token(' '), - ip_addr(), - token(' '), - port(), - string(" typ "), - kind, - optional((attempt(string(" raddr ")), ip_addr(), string(" rport "), port())), - optional(( - attempt(string(" tcptype ")), - not_sp().and_then(|s| TcpType::from_str(s.as_str()).map_err(StreamErrorFor::::message_format)), - )), - optional((attempt(string(" generation ")), not_sp())), - optional((attempt(string(" network-id ")), not_sp())), - optional((attempt(string(" ufrag ")), not_sp())), - optional((attempt(string(" network-cost ")), not_sp())), - ) - .map( - |( - _, - found, - _, - comp_id, - _, - proto, - _, - prio, - _, - addr, - _, - port, - _, - kind, - raddr, // (" raddr ", addr, " rport ", port) - tcptype, // (" tcptype ", tcptype) - _, // (" generation ", generation) - _, // (" network-id ", network_id) - ufrag, // (" ufrag ", ufrag) - _, // ("network-cost", network_cost) - )| { - Candidate::from_parts( - found, - comp_id, - proto, - prio, // remote candidates calculate prio on their side - SocketAddr::from((addr, port)), - kind, - raddr.map(|(_, addr, _, port)| SocketAddr::from((addr, port))), - tcptype.map(|(_, tcptype)| tcptype), - ufrag.map(|(_, u)| u), - ) - }, - ) -} - -/// Parser for a=candidate lines. -pub(crate) fn candidate_attribute() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - (string("a="), candidate(), line_end()).map(|(_, c, _)| c) -} - -/// Session line with a key we ignore (spec says we should validate them, but meh). -fn ignored_session_line() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - // TODO: there must be a better way - let ignored = choice(( - token('i'), - token('u'), - token('e'), - token('p'), - token('c'), - token('z'), - token('k'), - )); - line(ignored, any_value()).map(|_| ()) -} - -// /////////////////////////////////////////////////// Media description - -/// A m= section with attributes, until next m= or EOF -fn media_parser() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - ( - media_line(), - optional(typed_line('c', any_value())), // c=IN IP4 0.0.0.0 - optional(bandwidth_line()), // b=AS:2500 - many::, _, _>(media_attribute_line()), - ) - .and_then(|((typ, port, proto, pts), _, bw, attrs)| { - let m = MediaLine { - typ, - disabled: port == "0", - proto, - pts, - bw, - attrs, - }; - if let Some(err) = m.check_consistent() { - warn!("{:?}", err); - return Err(StreamErrorFor::::message_format(err)); - } - Ok(m) - }) -} - -/// The m= line -// dormammu: -// m=audio 9 UDP/TLS/RTP/SAVPF 111 -// m=video 9 UDP/TLS/RTP/SAVPF 96 97 125 107 100 101 -// m=application 9 DTLS/SCTP 5000 -// chrome: -// m=audio 64205 UDP/TLS/RTP/SAVPF 111 -// m=video 53151 UDP/TLS/RTP/SAVPF 96 97 125 107 100 101 -// m=application 54055 DTLS/SCTP 5000 -// -// newer chrome: -// m=application 9 UDP/DTLS/SCTP webrtc-datachannel -fn media_line() -> impl Parser)> -where - Input: Stream, - Input::Error: ParseError, -{ - let media_type = choice(( - attempt(string("audio").map(|_| MediaType::Audio)), - attempt(string("video").map(|_| MediaType::Video)), - attempt(string("application").map(|_| MediaType::Application)), - not_sp().map(MediaType::Unknown), - )); - - let proto_line = choice(( - attempt(string("UDP/TLS/RTP/SAVPF").map(|_| Proto::Srtp)), - attempt(string("DTLS/SCTP").map(|_| Proto::Sctp)), - attempt(string("UDP/DTLS/SCTP").map(|_| Proto::Sctp)), - )); - - let parse_pt = not_sp().and_then(|s| { - s.parse::() - .map(Pt::from) - .map_err(StreamErrorFor::::message_format) - }); - - // m= ... - // is: - // where either matches a=rtpmap: or a=sctpmap: - typed_line( - 'm', - ( - media_type, // type: audio, video etc. - token(' '), - not_sp(), // port: just set to 9 or something - token(' '), - proto_line, // proto: or - token(' '), - choice(( - attempt(sep_by(parse_pt, token(' '))), // - any_value().map(|_| vec![]), - )), - ), - ) - .map(|(typ, _, port, _, proto, _, pts)| (typ, port, proto, pts)) -} - -/// a=foo:bar lines belonging before the first m= line -fn media_attribute_line() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - // a=rtcp:9 IN IP4 0.0.0.0 - let rtcp = attribute_line("rtcp", any_value()).map(MediaAttribute::Rtcp); - - // a=ice-ufrag:IdNYTNL1fjvjyEzL - let ice_ufrag = attribute_line("ice-ufrag", any_value()).map(MediaAttribute::IceUfrag); - - // a=ice-pwd:4d64pT3T1xfwbZvi9fQKjoPb - let ice_pwd = attribute_line("ice-pwd", any_value()).map(MediaAttribute::IcePwd); - - // a=ice-options:trickle - let ice_opt = attribute_line("ice-options", any_value()).map(MediaAttribute::IceOptions); - - // a=fingerprint:sha-256 45:AD:5C:82:F8:BE:B5:2A:D1:74:A6:16:D0:50:CD:86:9C:97:9D:BD:06:\ - // 8C:C9:85:C9:CD:AB:2B:A8:56:03:CD - // "sha-1" / "sha-224" / "sha-256" / - // "sha-384" / "sha-512" / - // "md5" / "md2" - let hex_byte = count_min_max(2, 2, hex_digit()) - .and_then(|x: String| u8::from_str_radix(&x, 16).map_err(StreamErrorFor::::message_format)); - let finger = attribute_line("fingerprint", (not_sp(), token(' '), sep_by1(hex_byte, token(':')))) - .map(|(hash_func, _, bytes)| MediaAttribute::Fingerprint(Fingerprint { hash_func, bytes })); - - let setup_val = choice(( - attempt(string("actpass").map(|_| Setup::ActPass)), - attempt(string("active").map(|_| Setup::Active)), - attempt(string("passive").map(|_| Setup::Passive)), - )); - - // a=setup:actpass - let setup = attribute_line("setup", setup_val).map(MediaAttribute::Setup); - - // a=mid:0 - let mid = attribute_line("mid", any_value()) - .map(|m| Mid::from(m.as_str())) - .map(MediaAttribute::Mid); - - let sctp_port = attribute_line( - "sctp-port", - not_sp::().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - ) - .map(MediaAttribute::SctpPort); - - let max_message_size = attribute_line( - "max-message-size", - not_sp::().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - ) - .map(MediaAttribute::MaxMessageSize); - - // a=sctp-init: - // See draft-hancke-tsvwg-snap (§4.2: base64 defined in RFC 4566, i.e. standard with padding) - // - // The base64 value is stored as-is; decoding happens when consumed. - let sctp_init = attribute_line("sctp-init", any_value()).map(MediaAttribute::SctpInit); - - // a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level - // a=extmap:["/"] - let extmap = attribute_line( - "extmap", - ( - many1::(satisfy(|c| c != '/' && c != ' ')) - .and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - optional((token('/'), not_sp().map(|d| Direction::from(&d[..])))), - token(' '), - not_sp().map(|uri| Extension::from_sdp_uri(&uri)), - optional((token(' '), any_value())), - ), - ) - .map(|(id, _dir_opt, _, ext, _ext_opt)| MediaAttribute::ExtMap { id, ext }); - - let direction = choice(( - attempt(attribute_line_flag("recvonly").map(|_| MediaAttribute::RecvOnly)), - attempt(attribute_line_flag("sendrecv").map(|_| MediaAttribute::SendRecv)), - attempt(attribute_line_flag("sendonly").map(|_| MediaAttribute::SendOnly)), - attempt(attribute_line_flag("inactive").map(|_| MediaAttribute::Inactive)), - )); - - // // a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1 - // // a=msid:- f78dde68-7055-4e20-bb37-433803dd1ed1 - let msid = attribute_line("msid", (not_sp(), token(' '), any_value())) - .map(|(stream_id, _, track_id)| MediaAttribute::Msid(Msid { stream_id, track_id })); - - let rtcpmux = attribute_line_flag("rtcp-mux").map(|_| MediaAttribute::RtcpMux); - let rtcpmuxonly = attribute_line_flag("rtcp-mux-only").map(|_| MediaAttribute::RtcpMuxOnly); - let rtcprsize = attribute_line_flag("rtcp-rsize").map(|_| MediaAttribute::RtcpRsize); - - // a=candidate - let cand = candidate_attribute().map(MediaAttribute::Candidate); - - // a=end-of-candidates - let endof = attribute_line_flag("end-of-candidates").map(|_| MediaAttribute::EndOfCandidates); - - let pt = || { - not_sp().and_then(|s| { - let pt = s.parse::().map_err(StreamErrorFor::::message_format)?; - // RTP payload type is 7-bit; reject out-of-range values rather than panicking later - // when PTs are claimed against a 128-entry table. - if pt > 127 { - return Err(StreamErrorFor::::message_format(format!( - "payload type out of range (0-127): {pt}" - ))); - } - Ok(Pt::from(pt)) - }) - }; - - // a=rtpmap:111 opus/48000/2 - let rtpmap = attribute_line( - "rtpmap", - ( - pt(), - token(' '), - many1::(satisfy(|c| c != '/' && c != '\r' && c != '\n')), - token('/'), - many1::(satisfy(|c| c != '/' && c != '\r' && c != '\n')) - .and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - optional(( - token('/'), - any_value().and_then(|s| s.parse::().map_err(StreamErrorFor::::message_format)), - )), // only audio has the last /2 (channels) - ), - ) - .map(|(pt, _, codec, _, clock_rate, opt_channels)| { - let channels = opt_channels.map(|(_, e)| e); - MediaAttribute::RtpMap { - pt, - value: RtpMap { - codec: codec.as_str().into(), - clock_rate, - channels, - }, - } - }); - - // a=rtcp-fb:111 transport-cc - // a=rtcp-fb:111 ccm fir - // a=rtcp-fb:111 nack - // a=rtcp-fb:111 nack pli - let rtcp_fb = attribute_line("rtcp-fb", (pt(), token(' '), any_value())) - .map(|(pt, _, value)| MediaAttribute::RtcpFb { pt, value }); - - // Tolerate horizontal whitespace around `;` and a trailing `;`. - let fmtp_param = ( - sep_end_by1(attempt(key_val()), attempt((spaces(false), token(';')))), - spaces(false), - ) - .map(|(pairs, _)| FormatParam::parse_pairs(pairs)); - - // a=fmtp:111 minptime=10; useinbandfec=1 - // a=fmtp:111 minptime=10;useinbandfec=1 - let fmtp1 = attribute_line("fmtp", (pt(), token(' '), fmtp_param)) - .map(|(pt, _, values)| MediaAttribute::Fmtp { pt, values }); - - let fmtp_unknown = attribute_line("fmtp", (pt(), optional(token(' ')), optional(any_value()))).map(|(pt, _, _)| { - MediaAttribute::Fmtp { - pt, - values: vec![FormatParam::Unknown], - } - }); - - let fmtp = choice((attempt(fmtp1), attempt(fmtp_unknown))); - - // a=rid: [pt=;]= - let rid = attribute_line( - "rid", - ( - name().map(RestrictionId::new_active), - token(' '), - choice((string("send"), string("recv"))), - optional(( - token(' '), - optional(( - string("pt="), - sep_by1::, _, _, _>(pt(), token(',')), - // TODO this is not really optional when there is - // a restriction part. It means we are incorrectly - // allowing this: a=rid:foo send pt=111max-br=64000 - optional(token(';')), - )), - sep_by::, _, _, _>(key_val(), token(';')), - )), - ), - ) - .map(|(id, _, direction, x)| { - let mut pt = vec![]; - let mut restriction = vec![]; - if let Some((_, ps, rs)) = x { - if let Some((_, ps, _)) = ps { - pt = ps; - } - restriction = rs; - } - - MediaAttribute::Rid { - id, - direction, - pt, - restriction, - } - }); - - let simul1 = |direction: &'static str| { - ( - string(direction), - token(' '), - sep_by1::>, _, _, _>( - sep_by1( - optional(token('~')).and(name()).map(|x| (x.1, x.0.is_none())), - token(','), - ), - token(';'), - ), - ) - }; - - // Parser guarantee that it's send => recv or recv => send. - let simul2 = choice(( - (simul1("send"), optional((token(' '), simul1("recv")))), - (simul1("recv"), optional((token(' '), simul1("send")))), - )); - - // a=simulcast: ;, [same] - let simulcast = attribute_line("simulcast", simul2).map(|(s1, maybe_s2)| { - let mut send = SimulcastGroups(vec![]); - let mut recv = SimulcastGroups(vec![]); - - fn to_simul(to: &mut SimulcastGroups, groups: Vec>) { - for group in groups { - // TODO: Properly support rid alternatives, for now we ignore any alternatives - // provided and use the first rid. - let first = group.into_iter().next(); - - if let Some(rid) = first.map(|(rid, active)| RestrictionId::new(rid, active)) { - to.0.push(SimulcastLayer { - restriction_id: rid, - attributes: None, - }); - } - } - } - - { - let to = if s1.0 == "send" { &mut send } else { &mut recv }; - to_simul(to, s1.2); - } - - if let Some(s2) = maybe_s2 { - let s2 = s2.1; - let to = if s2.0 == "send" { &mut send } else { &mut recv }; - to_simul(to, s2.2); - } - - MediaAttribute::Simulcast(Simulcast { - send, - recv, - is_munged: false, - }) - }); - - // a=ssrc-group:FID 1111 2222 - let ssrc_group = attribute_line( - "ssrc-group", - ( - not_sp(), - token(' '), - sep_by1( - not_sp().and_then(|s| { - s.parse::() - .map(Ssrc::from) - .map_err(StreamErrorFor::::message_format) - }), - token(' '), - ), - ), - ) - .map(|(semantics, _, ssrcs)| MediaAttribute::SsrcGroup { semantics, ssrcs }); - - // a=ssrc:3948621874 cname:xeXs3aE9AOBn00yJ - // a=ssrc:3948621874 msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1 - // a=ssrc:3948621874 mslabel:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK - // a=ssrc:3948621874 label:f78dde68-7055-4e20-bb37-433803dd1ed1 - let ssrc = attribute_line( - "ssrc", - ( - not_sp().and_then(|s| { - s.parse::() - .map(Ssrc::from) - .map_err(StreamErrorFor::::message_format) - }), - token(' '), - many1::(satisfy(|c| c != ':')), - token(':'), - any_value(), - ), - ) - .map(|(ssrc, _, attr, _, value)| MediaAttribute::Ssrc { ssrc, attr, value }); - - let unused = typed_line('a', any_value()).map(MediaAttribute::Unused); - - // Split into two choice() calls because combine's choice macro supports at most 25 parsers. - choice(( - attempt(choice(( - attempt(ice_ufrag), - attempt(ice_pwd), - attempt(ice_opt), - attempt(finger), - attempt(setup), - attempt(mid), - attempt(sctp_port), - attempt(max_message_size), - attempt(sctp_init), - attempt(extmap), - attempt(direction), - attempt(msid), - attempt(rtcp), - ))), - attempt(choice(( - attempt(rtcpmux), - attempt(rtcpmuxonly), - attempt(rtcprsize), - attempt(cand), - attempt(endof), - attempt(rtpmap), - attempt(rtcp_fb), - attempt(fmtp), - attempt(rid), - attempt(simulcast), - attempt(ssrc_group), - attempt(ssrc), - ))), - unused, - )) -} - -// /////////////////////////////////////////////////// Generic things below - -/// A specific line -fn typed_line(expected: char, val: Pval) -> impl Parser -where - Input: Stream, - Pval: Parser, - Input::Error: ParseError, -{ - line(token(expected), val) -} - -/// A line with some parser for value and parser for type. -fn line(typ: Ptyp, val: Pval) -> impl Parser -where - Ptyp: Parser, - Pval: Parser, - Input: Stream, - Input::Error: ParseError, -{ - attempt((typ, token('='), val, line_end())) - .map(|(_, _, value, _)| value) - .message("sdp line") -} - -/// alphanumeric name. -fn name() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - many1(satisfy(|c: char| c.is_alphanumeric())) -} - -/// Not SP, \r or \n -fn not_sp() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - many1(satisfy(|c| c != ' ' && c != '\r' && c != '\n')) -} - -/// Any value that isn't \r or \n. -fn any_value() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - many1(satisfy(|c| c != '\r' && c != '\n')) -} - -/// We discovered a stray \n in safari SDP. This line end handles \r\n, \n or EOF. -fn line_end() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - choice((crlf().map(|_| ()), newline().map(|_| ()), eof())) -} - -// minptime=10 -fn key_val() -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - ( - spaces(false), - many1(satisfy(|c| is_param_char(c, '='))), - token('='), - many1(satisfy(|c| is_param_char(c, ';'))), - ) - .map(|(_, key, _, val)| (key, val)) -} - -/// Skip spaces and tabs, optionally including CR and LF. -fn spaces(newline: bool) -> impl Parser -where - Input: Stream, - Input::Error: ParseError, -{ - skip_many(satisfy(move |c| { - matches!(c, ' ' | '\t') || (newline && matches!(c, '\r' | '\n')) - })) -} - -// Parameter tokens exclude horizontal whitespace, line endings, and their delimiter. -fn is_param_char(c: char, delimiter: char) -> bool { - c != delimiter && !matches!(c, ' ' | '\t' | '\r' | '\n') -} - -#[cfg(test)] -mod test { - use super::*; - use crate::vendor::str0m::format::Codec; - use crate::vendor::str0m::io::Protocol; - - #[test] - fn spaces_preserve_or_consume_line_endings() { - for end in ["\r\n", "\n", "\r"] { - let input = format!(" \t{end}next"); - let remaining = format!("{end}next"); - assert_eq!(spaces(false).parse(input.as_str()), Ok(((), remaining.as_str()))); - assert_eq!(spaces(true).parse(input.as_str()), Ok(((), "next"))); - } - } - - #[test] - fn line_a() { - assert_eq!( - line(letter(), any_value()).parse("a=mid:0"), - Ok(("mid:0".to_string(), "")) - ) - } - - #[test] - fn line_end_crlf() { - assert_eq!(line_end().parse("\r\n"), Ok(((), ""))); - } - - #[test] - fn line_end_lf() { - assert_eq!(line_end().parse("\n"), Ok(((), ""))); - } - - #[test] - fn line_end_eof() { - assert_eq!(line_end().parse(""), Ok(((), ""))); - } - - #[test] - fn typed_line_v() { - assert_eq!(typed_line('v', token('0')).parse("v=0"), Ok(('0', ""))) - } - - #[test] - fn attribute_line_flag_foo() { - assert_eq!(attribute_line_flag("foo").parse("a=foo"), Ok(((), ""))) - } - - #[test] - fn attribute_line_foo_bar() { - assert_eq!( - attribute_line("foo", any_value()).parse("a=foo:bar"), - Ok(("bar".to_string(), "")) - ) - } - - #[test] - fn session_attribute_line_simple() { - let x = session_attribute_line().parse("a=ice-lite"); - assert_eq!(x, Ok((SessionAttribute::IceLite, ""))); - } - - #[test] - fn session_attribute_line_finger() { - let x = session_attribute_line().parse("a=fingerprint:sha-256 45:AD:5C:82:F8:BE"); - assert_eq!( - x, - Ok(( - SessionAttribute::Fingerprint(Fingerprint { - hash_func: "sha-256".to_string(), - bytes: vec![69, 173, 92, 130, 248, 190], - }), - "" - )) - ); - } - - #[test] - fn media_attribute_line_fmtp_horizontal_whitespace() { - let expected = MediaAttribute::Fmtp { - pt: 111.into(), - values: vec![FormatParam::MinPTime(10), FormatParam::UseInbandFec(true)], - }; - for params in [ - "minptime=10;\tuseinbandfec=1", - "\tminptime=10;useinbandfec=1", - "minptime=10\t;useinbandfec=1", - "minptime=10;useinbandfec=1\t", - " \tminptime=10 \t; \tuseinbandfec=1 \t; \t", - ] { - for end in ["\r\n", "\n", ""] { - let next = if end.is_empty() { "" } else { "a=mid:0" }; - let line = format!("a=fmtp:111 {params}{end}{next}"); - assert_eq!( - media_attribute_line().parse(line.as_str()), - Ok((expected.clone(), next)), - "{line:?}" - ); - } - } - } - - #[test] - fn media_attribute_line_fmtp_preserves_next_line() { - for end in ["\r\n", "\n"] { - for next in ["a=mid:0", "a=sendrecv"] { - let line = format!("a=fmtp:111 minptime=10;useinbandfec=1;{end}{next}"); - let expected = MediaAttribute::Fmtp { - pt: 111.into(), - values: vec![FormatParam::MinPTime(10), FormatParam::UseInbandFec(true)], - }; - assert_eq!(media_attribute_line().parse(line.as_str()), Ok((expected, next))); - } - } - } - - #[test] - fn media_attribute_line_fmtp_separator_whitespace() { - let expected = MediaAttribute::Fmtp { - pt: 111.into(), - values: vec![FormatParam::MinPTime(10), FormatParam::UseInbandFec(true)], - }; - for line in [ - "a=fmtp:111 minptime=10;useinbandfec=1;\r\na=rtcp-fb:111 nack", - "a=fmtp:111 minptime=10;useinbandfec=1 \r\na=rtcp-fb:111 nack", - "a=fmtp:111 minptime=10 ;useinbandfec=1\r\na=rtcp-fb:111 nack", - "a=fmtp:111 minptime=10; useinbandfec=1; \r\na=rtcp-fb:111 nack", - ] { - assert_eq!( - media_attribute_line().parse(line), - Ok((expected.clone(), "a=rtcp-fb:111 nack")), - "{line:?}" - ); - } - } - - #[test] - fn media_attribute_line_rid_simple() { - let x = media_attribute_line().parse("a=rid:lo send").unwrap(); - assert_eq!("a=rid:lo send\r\n", x.0.to_string()); - } - - #[test] - fn media_attribute_line_rid_pt() { - let x = media_attribute_line().parse("a=rid:lo send pt=99,100").unwrap(); - assert_eq!("a=rid:lo send pt=99,100\r\n", x.0.to_string()); - } - - #[test] - fn media_attribute_line_rid_restr() { - let x = media_attribute_line() - .parse("a=rid:lo send max-br=64000;max-height=360") - .unwrap(); - assert_eq!("a=rid:lo send max-br=64000;max-height=360\r\n", x.0.to_string()); - } - - #[test] - fn media_attribute_line_rid_pt_restr() { - let x = media_attribute_line() - .parse("a=rid:lo send pt=99,100;max-br=64000;max-height=360") - .unwrap(); - assert_eq!( - "a=rid:lo send pt=99,100;max-br=64000;max-height=360\r\n", - x.0.to_string() - ); - } - - #[test] - fn media_attribute_line_simulcast() { - let x = media_attribute_line().parse("a=simulcast:send 3;4").unwrap(); - assert_eq!("a=simulcast:send 3;4\r\n", x.0.to_string()); - } - - #[test] - fn media_attribute_line_simulcast_alt() { - let x = media_attribute_line().parse("a=simulcast:send 2,3;4").unwrap(); - assert_eq!("a=simulcast:send 2;4\r\n", x.0.to_string()); - } - - #[test] - fn media_attribute_line_simulcast_send_recv() { - let x = media_attribute_line().parse("a=simulcast:send 2;3 recv 4").unwrap(); - assert_eq!("a=simulcast:send 2;3 recv 4\r\n", x.0.to_string()); - } - - #[test] - fn media_attribute_line_simulcast_recv_send() { - let x = media_attribute_line().parse("a=simulcast:recv 2;3 send 4").unwrap(); - assert_eq!("a=simulcast:send 4 recv 2;3\r\n", x.0.to_string()); - } - - #[test] - fn media_line_simple() { - let m = media_line().parse("m=audio 9 UDP/TLS/RTP/SAVPF 10\r\n"); - assert_eq!( - m, - Ok(((MediaType::Audio, "9".into(), Proto::Srtp, vec![10.into()],), "")) - ); - } - - #[test] - fn rtpmap_payload_type_over_127_is_rejected() { - // RTP payload type is 7-bit. An out-of-range PT in a=rtpmap must not be accepted as an - // RtpMap; otherwise it becomes a PayloadParams that panics when claimed against a - // 128-entry table. It instead falls through to Unused and is ignored (the m-line then - // fails its own "missing a=rtpmap" check). 127 is the largest valid PT. - let bad = media_attribute_line().parse("a=rtpmap:200 opus/48000/2"); - assert!( - !matches!(bad, Ok((MediaAttribute::RtpMap { .. }, _))), - "out-of-range rtpmap PT must not parse as RtpMap: {bad:?}" - ); - assert!(matches!( - media_attribute_line().parse("a=rtpmap:127 opus/48000/2"), - Ok((MediaAttribute::RtpMap { .. }, _)) - )); - } - - #[test] - fn session_parser_simple() { - let sdp = "v=0\n\ - o=- 6564425948916445306 2 IN IP4 127.0.0.1\n\ - s=-\n\ - t=0 0\n\ - a=group:BUNDLE 0\n\ - a=msid-semantic: WMS\n\ - m=application 9 DTLS/SCTP 5000\n\ - "; - assert_eq!( - session_parser().parse(sdp), - Ok(( - Session { - id: 6_564_425_948_916_445_306.into(), - bw: None, - attrs: vec![ - SessionAttribute::Group { - typ: "BUNDLE".into(), - mids: vec!["0".into()], - }, - SessionAttribute::Unused("msid-semantic: WMS".into()) - ], - }, - "m=application 9 DTLS/SCTP 5000\n" - )) - ); - } - - #[test] - fn session_parser_group_without_mids() { - for group in ["a=group:BUNDLE\r\n", "a=group:BUNDLE \r\n"] { - let sdp = format!( - "v=0\r\n\ - o=- 6564425948916445306 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - {group}" - ); - let (session, rest) = session_parser().parse(sdp.as_str()).unwrap(); - assert_eq!( - session.attrs, - vec![SessionAttribute::Group { - typ: "BUNDLE".into(), - mids: vec![], - }] - ); - assert_eq!(rest, ""); - } - } - - #[test] - fn session_parser_named_session() { - // A session name other than "-". - let sdp = "v=0\r\n\ - o=publisher 4489045141692799359 2 IN IP4 127.0.0.1\r\n\ - s=NamedPublishSession\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0 1\r\n\ - a=extmap-allow-mixed\r\n\ - a=msid-semantic: WMS\r\n"; - assert_eq!( - session_parser().parse(sdp), - Ok(( - Session { - id: 4_489_045_141_692_799_359.into(), - bw: None, - attrs: vec![ - SessionAttribute::Group { - typ: "BUNDLE".into(), - mids: vec!["0".into(), "1".into()], - }, - SessionAttribute::Unused("extmap-allow-mixed".into()), - SessionAttribute::Unused("msid-semantic: WMS".into()), - ], - }, - "" - )) - ); - } - - #[test] - fn session_parser_space_session_name() { - // "If a session has no meaningful name, the value "s= " SHOULD be used - // (i.e., a single space as the session name)." (RFC 8866 section 5.3) - let sdp = "v=0\n\ - o=- 6564425948916445306 2 IN IP4 127.0.0.1\n\ - s= \n\ - t=0 0\n\ - "; - assert_eq!( - session_parser().parse(sdp), - Ok(( - Session { - id: 6_564_425_948_916_445_306.into(), - bw: None, - attrs: vec![], - }, - "" - )) - ); - } - - #[test] - fn parse_sdp_firefox() { - let sdp = "v=0\r\n\ - o=mozilla...THIS_IS_SDPARTA-83.0 7052848360639826063 0 IN IP4 0.0.0.0\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=fingerprint:sha-256 \ - 37:FC:96:B5:73:98:E6:F9:C5:0B:D9:EE:B1:F8:D0:01:07:2E:75:E8:6C:A4:32:A7:DC:63:\ - 99:5E:68:5C:BF:FB\r\n\ - a=ice-options:trickle\r\n\ - a=msid-semantic:WMS *\r\n"; - - assert_eq!( - sdp_parser().parse(sdp), - Ok(( - Sdp { - session: Session { - id: 7052848360639826063.into(), - bw: None, - attrs: vec![ - SessionAttribute::Fingerprint(Fingerprint { - hash_func: "sha-256".into(), - bytes: vec![ - 0x37, 0xFC, 0x96, 0xB5, 0x73, 0x98, 0xE6, 0xF9, 0xC5, 0x0B, 0xD9, 0xEE, 0xB1, 0xF8, - 0xD0, 0x01, 0x07, 0x2E, 0x75, 0xE8, 0x6C, 0xA4, 0x32, 0xA7, 0xDC, 0x63, 0x99, 0x5E, - 0x68, 0x5C, 0xBF, 0xFB - ] - }), - SessionAttribute::IceOptions("trickle".to_string()), - SessionAttribute::MsidSemantic { - semantic: "WMS".into(), - stream_ids: vec!["*".into()] - }, - ] - }, - media_lines: vec![] - }, - "" - )) - ); - } - - #[test] - fn parse_offer_sdp_firefox() { - let sdp = "v=0\r\n\ - o=mozilla...THIS_IS_SDPARTA-84.0 9033133899747520364 1 IN IP4 0.0.0.0\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=fingerprint:sha-256 \ - AE:DC:49:AE:CA:55:35:CB:4E:FA:FE:70:99:30:C0:14:C3:B8:06:80:1F:A9:DA:9A:7C:FB:\ - B7:20:AB:83:60:45\r\n\ - a=group:BUNDLE 0\r\n\ - a=ice-options:trickle\r\n\ - a=msid-semantic:WMS *\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 109 9 0 8 101\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=sendonly\r\n\ - a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\n\ - a=extmap:2/recvonly urn:ietf:params:rtp-hdrext:csrc-audio-level\r\n\ - a=extmap:3 urn:ietf:params:rtp-hdrext:sdes:mid\r\n\ - a=fmtp:109 maxplaybackrate=48000;stereo=1;useinbandfec=1\r\n\ - a=fmtp:101 0-15\r\n\ - a=ice-pwd:cd25258044061ec2ecc73378eb3dc6a3\r\n\ - a=ice-ufrag:c1e284ad\r\n\ - a=mid:0\r\n\ - a=msid:- {5c7f12e5-b4bd-7142-9a06-2885a2d1cb66}\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:109 opus/48000/2\r\n\ - a=rtpmap:9 G722/8000/1\r\n\ - a=rtpmap:0 PCMU/8000\r\n\ - a=rtpmap:8 PCMA/8000\r\n\ - a=rtpmap:101 telephone-event/8000/1\r\n\ - a=setup:actpass\r\n\ - a=ssrc:1481683531 cname:{326ec0d2-d1ae-974c-b1ad-aea85cdfa0ad}\r\n"; - - let parsed = sdp_parser().parse(sdp); - - assert!(parsed.is_ok()); - } - - #[test] - fn parse_offer_sdp_chrome() { - let sdp = "v=0\r\n\ - o=- 5058682828002148772 3 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=msid-semantic: WMS 5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=rtcp:9 IN IP4 0.0.0.0\r\n\ - a=ice-ufrag:S5hk\r\n\ - a=ice-pwd:0zV/Yu3y8aDzbHgqWhnVQhqP\r\n\ - a=ice-options:trickle\r\n\ - a=fingerprint:sha-256 \ - 8C:64:ED:03:76:D0:3D:B4:88:08:91:64:08:80:A8:C6:5A:BF:8B:4E:38:27:96:CA:08:49:\ - 25:73:46:60:20:DC\r\n\ - a=setup:actpass\r\n\ - a=mid:0\r\n\ - a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\n\ - a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n\ - a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\n\ - a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\n\ - a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\n\ - a=extmap:6 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n\ - a=sendrecv\r\n\ - a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:111 opus/48000/2\r\n\ - a=rtcp-fb:111 transport-cc\r\n\ - a=fmtp:111 minptime=10;useinbandfec=1\r\n\ - a=rtpmap:103 ISAC/16000\r\n\ - a=rtpmap:104 ISAC/32000\r\n\ - a=rtpmap:9 G722/8000\r\n\ - a=rtpmap:0 PCMU/8000\r\n\ - a=rtpmap:8 PCMA/8000\r\n\ - a=rtpmap:106 CN/32000\r\n\ - a=rtpmap:105 CN/16000\r\n\ - a=rtpmap:13 CN/8000\r\n\ - a=rtpmap:110 telephone-event/48000\r\n\ - a=rtpmap:112 telephone-event/32000\r\n\ - a=rtpmap:113 telephone-event/16000\r\n\ - a=rtpmap:126 telephone-event/8000\r\n\ - a=ssrc:3948621874 cname:xeXs3aE9AOBn00yJ\r\n\ - a=ssrc:3948621874 msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK \ - f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\ - a=ssrc:3948621874 mslabel:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK\r\n\ - a=ssrc:3948621874 label:f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\ - "; - - let parsed = sdp_parser().parse(sdp); - - assert!(parsed.is_ok()); - } - - #[test] - fn parse_offer_sdp_ffmpeg_whip() { - // ffmpeg -re \ - // -f lavfi -i "testsrc=size=640x480:rate=30" \ - // -f lavfi -i "sine=frequency=440:sample_rate=48000" \ - // -c:v libx264 -profile:v baseline -pix_fmt yuv420p -g 60 -tune zerolatency \ - // -c:a libopus -ar 48000 -ac 2 \ - // -f whip "http://127.0.0.1:8080/whip" - let sdp = "v=0\r\n\ - o=FFmpeg 4489045141692799359 2 IN IP4 127.0.0.1\r\n\ - s=FFmpegPublishSession\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0 1\r\n\ - a=extmap-allow-mixed\r\n\ - a=msid-semantic: WMS\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=ice-ufrag:08a9c3f4\r\n\ - a=ice-pwd:a202d23be47d1decaa6f67d04d4e6c16\r\n\ - a=fingerprint:sha-256 21:69:7C:46:D3:DC:4D:D3:66:61:5C:C5:6A:0B:F7:36\ - :BD:91:A9:2A:FF:BC:1A:59:D9:38:38:C8:E2:A4:8D:AF\r\n\ - a=setup:passive\r\n\ - a=mid:0\r\n\ - a=sendonly\r\n\ - a=msid:FFmpeg audio\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:111 opus/48000/2\r\n\ - a=ssrc:3166090378 cname:FFmpeg\r\n\ - a=ssrc:3166090378 msid:FFmpeg audio\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 106 105\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=ice-ufrag:08a9c3f4\r\n\ - a=ice-pwd:a202d23be47d1decaa6f67d04d4e6c16\r\n\ - a=fingerprint:sha-256 21:69:7C:46:D3:DC:4D:D3:66:61:5C:C5:6A:0B:F7:36\ - :BD:91:A9:2A:FF:BC:1A:59:D9:38:38:C8:E2:A4:8D:AF\r\n\ - a=setup:passive\r\n\ - a=mid:1\r\n\ - a=sendonly\r\n\ - a=msid:FFmpeg video\r\n\ - a=rtcp-mux\r\n\ - a=rtcp-rsize\r\n\ - a=rtpmap:106 H264/90000\r\n\ - a=fmtp:106 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001e\r\n\ - a=rtcp-fb:106 nack\r\n\ - a=rtpmap:105 rtx/90000\r\n\ - a=fmtp:105 apt=106\r\n\ - a=ssrc-group:FID 3166090379 3166090380\r\n\ - a=ssrc:3166090379 cname:FFmpeg\r\n\ - a=ssrc:3166090379 msid:FFmpeg video\r\n\ - "; - - let (sdp, _) = sdp_parser().parse(sdp).unwrap(); - - assert_eq!(sdp.media_lines.len(), 2); - assert_eq!(sdp.media_lines[0].mid().to_string(), "0"); - assert_eq!(sdp.media_lines[1].mid().to_string(), "1"); - } - - #[test] - fn parse_safari_data_channel() { - let sdp = "v=0\r\n\ - o=- 4611516372927609806 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=extmap-allow-mixed\r\n\ - a=msid-semantic: WMS\r\n\ - m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=ice-ufrag:HhS+\r\n\ - a=ice-pwd:FhYTGhlAtKCe6KFIX8b+AThW\r\n\ - a=ice-options:trickle\r\n\ - a=fingerprint:sha-256 \ - B4:12:1C:7C:7D:ED:F1:FA:61:07:57:9C:29:BE:58:E3:BC:41:E7:13:8E:7D:D3:9D:1F:94:6E:\ - A5:23:46:94:23\r\n\ - a=setup:actpass\r\n\ - a=mid:0\r\n\ - a=sctp-port:5000\r\n\ - a=max-message-size:262144\r\n\ - "; - - let (sdp, _) = sdp_parser().parse(sdp).unwrap(); - - assert!(!sdp.media_lines.is_empty()); - assert_eq!(sdp.media_lines[0].mid().to_string(), "0"); - } - - #[test] - fn parse_minimal() { - let sdp = "v=0\r\n\ - o=- 5058682828002148772 3 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=rtcp:9 IN IP4 0.0.0.0\r\n\ - a=setup:actpass\r\n\ - a=inactive\r\n\ - a=mid:0\r\n\ - "; - - let parsed = sdp_parser().parse(sdp); - assert!(parsed.is_ok()); - } - - #[test] - fn parse_candidates() { - let a = "a=candidate:1 1 udp 1845494015 198.51.100.100 11100 typ srflx raddr \ - 203.0.113.100 rport 10100 ufrag abc\r\n"; - - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.ufrag(), Some("abc")); - - let a = "a=candidate:1 1 udp 1845494015 198.51.100.100 11100 typ host ufrag abc\r\n"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.ufrag(), Some("abc")); - - let a = "a=candidate:3684617590 1 udp 2122260223 10.217.229.219 50028 typ host \ - generation 0 network-id 1 network-cost 900"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.addr(), "10.217.229.219:50028".parse().unwrap()); - - let a = "a=candidate:387183333 1 udp 1686052607 113.185.55.72 31267 typ srflx raddr \ - 10.217.229.219 rport 50028 generation 0 network-id 1 network-cost 900"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.addr(), "113.185.55.72:31267".parse().unwrap()); - - let a = "a=candidate:2501718406 1 tcp 1518280447 10.217.229.219 9 typ host tcptype \ - active generation 0 network-id 1 network-cost 900"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.addr(), "10.217.229.219:9".parse().unwrap()); - - let a = "a=candidate:387183333 1 udp 1686052607 113.185.55.72 41775 typ srflx raddr \ - 10.217.229.219 rport 50028 generation 0 network-id 1 network-cost 900"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.addr(), "113.185.55.72:41775".parse().unwrap()); - - let a = "a=candidate:3936339338 1 udp 2122265343 fd00:f8aa:3ff5:5914:90bf:3c5:3378:9d4b 59125 \ - typ host generation 0 network-id 4 network-cost 50"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!( - c.addr(), - "[fd00:f8aa:3ff5:5914:90bf:3c5:3378:9d4b]:59125".parse().unwrap() - ); - assert_eq!(c.proto(), Protocol::Udp); - - let a = "a=candidate:2113932030 1 tcp 2113932030 142.250.82.253 19305 \ - typ host tcptype passive generation 0"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.addr(), "142.250.82.253:19305".parse().unwrap()); - assert_eq!(c.proto(), Protocol::Tcp); - assert_eq!(c.tcptype(), Some(TcpType::Passive)); - - let a = "a=candidate:2113932029 1 ssltcp 2113932029 142.250.82.252 443 typ host generation 0"; - let (c, _) = candidate_attribute().parse(a).unwrap(); - assert_eq!(c.addr(), "142.250.82.252:443".parse().unwrap()); - assert_eq!(c.proto(), Protocol::SslTcp); - assert_eq!(c.tcptype(), None); - } - - #[test] - fn parse_firefox_missing_setup_on_mid1() { - let sdp = "v=0\r\n\ - o=mozilla...THIS_IS_SDPARTA-99.0 7710052215259647220 2 IN IP4 0.0.0.0\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=fingerprint:sha-256 \ - A6:64:23:37:94:7E:4B:40:F6:62:86:8C:DD:09:D5:08:7E:D4:0E:68:58:93:45:EC:99:F2:91:\ - F7:19:72:E7:BB\r\n\ - a=group:BUNDLE 0 hxI i1X mxk B3D kNI nbB xIZ bKm Hkn\r\n\ - a=ice-options:trickle\r\n\ - a=msid-semantic:WMS *\r\n\ - m=audio 0 UDP/TLS/RTP/SAVPF 0\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=inactive\r\n\ - a=mid:1\r\n\ - a=rtpmap:0 PCMU/8000\r\n\ - "; - - let (sdp, _) = sdp_parser().parse(sdp).unwrap(); - - // Firefox 'a=setup' attribute can be missing - // the "a=setup:" sdp attribute (which should be mandatory) - // - https://www.rfc-editor.org/rfc/rfc5763#section-5 - // - https://www.rfc-editor.org/rfc/rfc4145 - - assert!(sdp.media_lines[0].setup().is_none()); // must not crash - } - - #[test] - fn parse_no_media_c_line() { - let sdp = "v=0\r\n\ - o=- 0 0 IN IP4 172.17.0.1\r\n\ - s=-\r\n\ - c=IN IP4 172.17.0.1\r\n\ - t=0 0\r\n\ - m=application 9999 UDP/DTLS/SCTP webrtc-datachannel\r\n\ - a=mid:0\r\n\ - a=ice-options:ice2\r\n\ - a=ice-ufrag:libp2p+webrtc+v1/a75469cf670c4079f8c06af4a963c8a1:\ - libp2p+webrtc+v1/a75469cf670c4079f8c06af4a963c8a1\r\n\ - a=ice-pwd:libp2p+webrtc+v1/a75469cf670c4079f8c06af4a963c8a1:\ - libp2p+webrtc+v1/a75469cf670c4079f8c06af4a963c8a1\r\n\ - a=fingerprint:sha-256 \ - FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:\ - FF:FF:FF:FF:FF\r\n\ - a=setup:actpass\r\n\ - a=sctp-port:5000\r\n\ - a=max-message-size:16384\r\n\ - "; - - let parsed = sdp_parser().parse(sdp); - println!("{:?}", parsed); - parsed.expect("to parse ok"); - } - - /// Test parsing an SDP offer containing H.265 with sprop-max-don-diff. - /// Verifies the fmtp line is correctly parsed into FormatParam::SpropMaxDonDiff - /// alongside H265ProfileTierLevel. - #[test] - fn parse_sdp_h265_with_sprop_max_don_diff() { - // Fingerprint split across lines to stay within 110 cols. - let sdp = concat!( - "v=0\r\n", - "o=- 1234567890 2 IN IP4 127.0.0.1\r\n", - "s=-\r\n", - "t=0 0\r\n", - "a=group:BUNDLE 0\r\n", - "a=fingerprint:sha-256 ", - "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:", - "66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:", - "22:33:44:55:66:77:88:99\r\n", - "a=msid-semantic: WMS\r\n", - "m=video 9 UDP/TLS/RTP/SAVPF 102 103\r\n", - "c=IN IP4 0.0.0.0\r\n", - "a=rtcp:9 IN IP4 0.0.0.0\r\n", - "a=ice-ufrag:abcd\r\n", - "a=ice-pwd:abcdefghijklmnopqrstuv\r\n", - "a=ice-options:trickle\r\n", - "a=fingerprint:sha-256 ", - "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:", - "66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:", - "22:33:44:55:66:77:88:99\r\n", - "a=setup:actpass\r\n", - "a=mid:0\r\n", - "a=sendrecv\r\n", - "a=rtpmap:102 H265/90000\r\n", - "a=fmtp:102 profile-id=1;tier-flag=0;", - "level-id=93;sprop-max-don-diff=32\r\n", - "a=rtpmap:103 rtx/90000\r\n", - "a=fmtp:103 apt=102\r\n", - ); - - let (sdp, _remaining) = sdp_parser().parse(sdp).expect("SDP should parse"); - - // Find the video media section - assert_eq!(sdp.media_lines.len(), 1); - let media = &sdp.media_lines[0]; - - // Find fmtp for PT 102 (H.265) - let fmtp_values: Vec<_> = media - .attrs - .iter() - .filter_map(|a| { - if let MediaAttribute::Fmtp { pt, values } = a { - if *pt == 102.into() { - return Some(values.clone()); - } - } - None - }) - .flatten() - .collect(); - - // Should contain H265ProfileTierLevel - assert!( - fmtp_values - .iter() - .any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))), - "Should have H265ProfileTierLevel param" - ); - - // Should contain SpropMaxDonDiff(32) - assert!( - fmtp_values - .iter() - .any(|p| matches!(p, FormatParam::SpropMaxDonDiff(32))), - "Should have SpropMaxDonDiff(32) param, got: {:?}", - fmtp_values - ); - - // Verify PTL values - if let Some(FormatParam::H265ProfileTierLevel(ptl)) = fmtp_values - .iter() - .find(|p| matches!(p, FormatParam::H265ProfileTierLevel(_))) - { - assert_eq!(ptl.profile_id(), 1); - assert_eq!(ptl.tier_flag(), 0); - assert_eq!(ptl.level_id(), 93); - } else { - panic!("H265ProfileTierLevel not found"); - } - } -} - -// Safari addTransceiver('audio', {direction: 'sendonly'})) - -// v=0 -// o=- 1625652694357831865 2 IN IP4 127.0.0.1 -// s=- -// t=0 0 -// a=group:BUNDLE 0 -// a=msid-semantic: WMS -// m=audio 9 UDP/TLS/RTP/SAVPF 111 103 9 102 0 8 105 13 110 113 126 -// c=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0 -// a=ice-ufrag:CTNF -// a=ice-pwd:XbIkl+k8mwLz60TFwb9crzbz -// a=ice-options:trickle -// a=fingerprint:sha-256 77:8C:32:B8:DA:4E:78:64:C8:4A:2A:E2:1D:60:2A:83:6B:51:B8:D5:EE:\ -// 5A:ED:75:4E:C6:98:2D:78:4D:94:D8 -// a=setup:actpass -// a=mid:0 -// a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level -// a=extmap:9 urn:ietf:params:rtp-hdrext:sdes:mid -// a=sendonly -// a=msid:- 39a7c3c3-ab8c-4b25-a47b-db52d89c2db1 -// a=rtcp-mux -// a=rtpmap:111 opus/48000/2 -// a=rtcp-fb:111 transport-cc -// a=fmtp:111 minptime=10;useinbandfec=1 -// a=rtpmap:103 ISAC/16000 -// a=rtpmap:9 G722/8000 -// a=rtpmap:102 ILBC/8000 -// a=rtpmap:0 PCMU/8000 -// a=rtpmap:8 PCMA/8000 -// a=rtpmap:105 CN/16000 -// a=rtpmap:13 CN/8000 -// a=rtpmap:110 telephone-event/48000 -// a=rtpmap:113 telephone-event/16000 -// a=rtpmap:126 telephone-event/8000 -// a=ssrc:457025658 cname:6OQ+jzZE+UnQgSUr -// a=ssrc:457025658 msid:- 39a7c3c3-ab8c-4b25-a47b-db52d89c2db1 -// a=ssrc:457025658 mslabel:- -// a=ssrc:457025658 label:39a7c3c3-ab8c-4b25-a47b-db52d89c2db1 - -// Chrome addTransceiver('audio', {direction: 'sendonly'})) - -// v=0 -// o=- 6740661649996974832 2 IN IP4 127.0.0.1 -// s=- -// t=0 0 -// a=group:BUNDLE 0 -// a=msid-semantic: WMS -// m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126 -// c=IN IP4 0.0.0.0 -// a=rtcp:9 IN IP4 0.0.0.0 -// a=ice-ufrag:Y28C -// a=ice-pwd:W6fHYINgGi9QF0BHdM/kchTW -// a=ice-options:trickle -// a=fingerprint:sha-256 E0:C0:2D:52:8D:FA:14:69:A0:A5:5D:63:E0:82:92:DB:37:38:D2:F3:12:\ -// D0:1F:4E:E5:6F:1A:F5:C3:97:6B:32 -// a=setup:actpass -// a=mid:0 -// a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level -// a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time -// a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01 -// a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid -// a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id -// a=extmap:6 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id -// a=sendonly -// a=msid:- 7a08dda6-518f-4027-b707-410a6d414176 -// a=rtcp-mux -// a=rtpmap:111 opus/48000/2 -// a=rtcp-fb:111 transport-cc -// a=fmtp:111 minptime=10;useinbandfec=1 -// a=rtpmap:103 ISAC/16000 -// a=rtpmap:104 ISAC/32000 -// a=rtpmap:9 G722/8000 -// a=rtpmap:0 PCMU/8000 -// a=rtpmap:8 PCMA/8000 -// a=rtpmap:106 CN/32000 -// a=rtpmap:105 CN/16000 -// a=rtpmap:13 CN/8000 -// a=rtpmap:110 telephone-event/48000 -// a=rtpmap:112 telephone-event/32000 -// a=rtpmap:113 telephone-event/16000 -// a=rtpmap:126 telephone-event/8000 -// a=ssrc:2147603131 cname:TbS1Ajv9obq6/63I -// a=ssrc:2147603131 msid:- 7a08dda6-518f-4027-b707-410a6d414176 -// a=ssrc:2147603131 mslabel:- -// a=ssrc:2147603131 label:7a08dda6-518f-4027-b707-410a6d414176 - -// Chrome add video -// pc.addTransceiver("video", { -// direction: 'sendonly', -// sendEncodings: [ -// { rid: 'hi' }, -// { rid: 'lo', scaleResolutionDownBy: 2 }, -// ] -// }) - -// v=0 -// o=- 2847298852000198709 3 IN IP4 127.0.0.1 -// s=- -// t=0 0 -// a=group:BUNDLE 0 -// a=extmap-allow-mixed -// a=msid-semantic: WMS -// m=video 9 UDP/TLS/RTP/SAVPF 96 97 102 103 104 105 106 107 108 109 127 125 39 40 45 46 98 99 100 101 112 113 -// 114 -// c=IN IP4 0.0.0.0 -// a=rtcp:9 IN IP4 0.0.0.0 -// a=ice-ufrag:numD -// a=ice-pwd:L/hHurqERpVUACiI8To+vXLv -// a=ice-options:trickle -// a=fingerprint:sha-256 A5:79:72:59:3D:32:74:9C:44:70:DE:39:15:C3:99:51:32:6E:0D:F0:60:\ -// DD:2F:31:90:E5:96:B4:1D:CA:48:E1 -// a=setup:actpass -// a=mid:0 -// a=extmap:1 urn:ietf:params:rtp-hdrext:toffset -// a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time -// a=extmap:3 urn:3gpp:video-orientation -// a=extmap:4 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01 -// a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay -// a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type -// a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing -// a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space -// a=extmap:9 urn:ietf:params:rtp-hdrext:sdes:mid -// a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id -// a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id -// a=extmap:13 https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension -// a=extmap:14 http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00 -// a=sendonly -// a=msid:- 7d27ad91-4770-4a4d-a053-2b06233753d2 -// a=rtcp-mux -// a=rtcp-rsize -// a=rtpmap:96 VP8/90000 -// a=rtcp-fb:96 goog-remb -// a=rtcp-fb:96 transport-cc -// a=rtcp-fb:96 ccm fir -// a=rtcp-fb:96 nack -// a=rtcp-fb:96 nack pli -// a=rtpmap:97 rtx/90000 -// a=fmtp:97 apt=96 -// a=rtpmap:102 H264/90000 -// a=rtcp-fb:102 goog-remb -// a=rtcp-fb:102 transport-cc -// a=rtcp-fb:102 ccm fir -// a=rtcp-fb:102 nack -// a=rtcp-fb:102 nack pli -// a=fmtp:102 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f -// a=rtpmap:103 rtx/90000 -// a=fmtp:103 apt=102 -// a=rtpmap:104 H264/90000 -// a=rtcp-fb:104 goog-remb -// a=rtcp-fb:104 transport-cc -// a=rtcp-fb:104 ccm fir -// a=rtcp-fb:104 nack -// a=rtcp-fb:104 nack pli -// a=fmtp:104 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f -// a=rtpmap:105 rtx/90000 -// a=fmtp:105 apt=104 -// a=rtpmap:106 H264/90000 -// a=rtcp-fb:106 goog-remb -// a=rtcp-fb:106 transport-cc -// a=rtcp-fb:106 ccm fir -// a=rtcp-fb:106 nack -// a=rtcp-fb:106 nack pli -// a=fmtp:106 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f -// a=rtpmap:107 rtx/90000 -// a=fmtp:107 apt=106 -// a=rtpmap:108 H264/90000 -// a=rtcp-fb:108 goog-remb -// a=rtcp-fb:108 transport-cc -// a=rtcp-fb:108 ccm fir -// a=rtcp-fb:108 nack -// a=rtcp-fb:108 nack pli -// a=fmtp:108 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f -// a=rtpmap:109 rtx/90000 -// a=fmtp:109 apt=108 -// a=rtpmap:127 H264/90000 -// a=rtcp-fb:127 goog-remb -// a=rtcp-fb:127 transport-cc -// a=rtcp-fb:127 ccm fir -// a=rtcp-fb:127 nack -// a=rtcp-fb:127 nack pli -// a=fmtp:127 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f -// a=rtpmap:125 rtx/90000 -// a=fmtp:125 apt=127 -// a=rtpmap:39 H264/90000 -// a=rtcp-fb:39 goog-remb -// a=rtcp-fb:39 transport-cc -// a=rtcp-fb:39 ccm fir -// a=rtcp-fb:39 nack -// a=rtcp-fb:39 nack pli -// a=fmtp:39 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f -// a=rtpmap:40 rtx/90000 -// a=fmtp:40 apt=39 -// a=rtpmap:45 AV1/90000 -// a=rtcp-fb:45 goog-remb -// a=rtcp-fb:45 transport-cc -// a=rtcp-fb:45 ccm fir -// a=rtcp-fb:45 nack -// a=rtcp-fb:45 nack pli -// a=fmtp:45 level-idx=5;profile=0;tier=0 -// a=rtpmap:46 rtx/90000 -// a=fmtp:46 apt=45 -// a=rtpmap:98 VP9/90000 -// a=rtcp-fb:98 goog-remb -// a=rtcp-fb:98 transport-cc -// a=rtcp-fb:98 ccm fir -// a=rtcp-fb:98 nack -// a=rtcp-fb:98 nack pli -// a=fmtp:98 profile-id=0 -// a=rtpmap:99 rtx/90000 -// a=fmtp:99 apt=98 -// a=rtpmap:100 VP9/90000 -// a=rtcp-fb:100 goog-remb -// a=rtcp-fb:100 transport-cc -// a=rtcp-fb:100 ccm fir -// a=rtcp-fb:100 nack -// a=rtcp-fb:100 nack pli -// a=fmtp:100 profile-id=2 -// a=rtpmap:101 rtx/90000 -// a=fmtp:101 apt=100 -// a=rtpmap:112 red/90000 -// a=rtpmap:113 rtx/90000 -// a=fmtp:113 apt=112 -// a=rtpmap:114 ulpfec/90000 -// a=rid:hi send -// a=rid:lo send -// a=simulcast:send hi;lo - -// DataChannel only in Safari -// v=0 -// o=- 4611516372927609806 2 IN IP4 127.0.0.1 -// s=- -// t=0 0 -// a=group:BUNDLE 0 -// a=extmap-allow-mixed -// a=msid-semantic: WMS -// m=application 9 UDP/DTLS/SCTP webrtc-datachannel -// c=IN IP4 0.0.0.0 -// a=ice-ufrag:HhS+ -// a=ice-pwd:FhYTGhlAtKCe6KFIX8b+AThW -// a=ice-options:trickle -// a=fingerprint:sha-256 B4:12:1C:7C:7D:ED:F1:FA:61:07:57:9C:29:BE:58:E3:BC:41:E7:13:8E:\ -// 7D:D3:9D:1F:94:6E:A5:23:46:94:23 -// a=setup:actpass -// a=mid:0 -// a=sctp-port:5000 -// a=max-message-size:262144 diff --git a/rs/moq-webrtc/src/vendor/str0m/session.rs b/rs/moq-webrtc/src/vendor/str0m/session.rs deleted file mode 100644 index 8b2d5090a1c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/session.rs +++ /dev/null @@ -1,1255 +0,0 @@ -use std::collections::{HashMap, VecDeque}; -use std::ops::RangeInclusive; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tracing::{debug, trace, warn}; - -use crate::vendor::str0m::Event; -use crate::vendor::str0m::bwe::BweKind; -use crate::vendor::str0m::config::KeyingMaterial; -use crate::vendor::str0m::config_mod::RtcpReportIntervals; -use crate::vendor::str0m::crypto::CryptoProvider; -use crate::vendor::str0m::crypto::dtls::SrtpProfile; -use crate::vendor::str0m::format::CodecConfig; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::format::Vp9PacketizerMode; -use crate::vendor::str0m::io::DatagramSend; -use crate::vendor::str0m::media::Media; -use crate::vendor::str0m::media::{KeyframeRequestKind, MID_PROBE}; -use crate::vendor::str0m::media::{MediaAdded, MediaChanged}; -use crate::vendor::str0m::pacer::NullPacer; -use crate::vendor::str0m::poll::Wake; -use crate::vendor::str0m::rtp::{Extension, RawPacket}; -use crate::vendor::str0m::rtp_::Direction; -use crate::vendor::str0m::rtp_::ExtensionValues; -use crate::vendor::str0m::rtp_::MediaTime; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::Pli; -use crate::vendor::str0m::rtp_::Pt; -use crate::vendor::str0m::rtp_::SRTCP_OVERHEAD; -use crate::vendor::str0m::rtp_::SeqNo; -use crate::vendor::str0m::rtp_::SeqNoWindow; -use crate::vendor::str0m::rtp_::TwccRecvRegister; -use crate::vendor::str0m::rtp_::{Bitrate, ExtensionMap, Goodbye, Mid, ReportList, Rtcp, RtcpFb}; -use crate::vendor::str0m::rtp_::{Dlrr, DlrrItem, ExtendedReport, ReportBlock}; -use crate::vendor::str0m::rtp_::{RtpHeader, SessionId, extend_u16}; -use crate::vendor::str0m::rtp_::{SrtpContext, Ssrc}; -use crate::vendor::str0m::streams::{RtpPacket, Streams}; -use crate::vendor::str0m::util::{Soonest, SystemTimeExt, already_happened, not_happening}; -use crate::vendor::str0m::{Reason, net}; -use crate::vendor::str0m::{RtcConfig, RtcError}; - -/// Minimum interval between NACK polls. Per-packet retries also wait for RTT. -/// Keep this high enough to avoid additional problems in very bad network conditions. -const NACK_MIN_INTERVAL: Duration = Duration::from_millis(33); - -/// Delay between reports of TWCC. This is deliberately very low. -const TWCC_INTERVAL: Duration = Duration::from_millis(50); - -/// Maximum number of pending RRTR entries before oldest are dropped. -const MAX_PENDING_RRTRS: usize = 300; - -/// Maximum number of DLRR items to include in a single ExtendedReport. -const MAX_DLRR_PER_REPORT: usize = 50; - -pub(crate) struct Session { - id: SessionId, - - // These fields are pub to allow session_sdp.rs modify them. - // Notice the fields are maybe not in m-line index order since the app - // might be spliced in somewhere. - pub medias: Vec, - - // The actual RTP encoded streams. - pub streams: Streams, - - /// The app m-line. Spliced into medias above. - app: Option<(Mid, usize)>, - - reordering_size_audio: usize, - reordering_size_video: usize, - reordering_timeout_audio: Option, - intervals: RtcpReportIntervals, - pub send_buffer_audio: usize, - pub send_buffer_video: usize, - - /// Extension mappings are _per BUNDLE_, but we can only have one a=group BUNDLE - /// in WebRTC (one ice connection), so they are effectively per session. - pub exts: ExtensionMap, - - // Configuration of how we are sending/receiving media. - pub codec_config: CodecConfig, - - // Payload params for SSRC 0 BWE probes. - // Lazy init when we see the PT. - probe_payload_params: Option, - - srtp_rx: Option, - srtp_tx: Option, - last_nack: Instant, - last_twcc: Instant, - twcc: u64, - twcc_rx_register: TwccRecvRegister, - max_rx_seq_lookup: HashMap, - - enable_twcc_feedback: bool, - - /// Picks which send queue to poll next. - pacer: NullPacer, - - // temporary buffer when getting the next (unencrypted) RTP packet from Media line. - poll_packet_buf: Vec, - - // Next packet for RtpPacket event. - pending_packet: Option, - - // Total RTP payload bytes for media, including retransmissions. - pub ice_lite: bool, - - /// Whether we are running in RTP-mode. - pub rtp_mode: bool, - - /// VP9 packetizer mode. - vp9_packetizer_mode: Vp9PacketizerMode, - - feedback_tx: VecDeque, - feedback_rx: VecDeque, - rtp_closing: bool, - - /// Pending RRTRs from remote SSRCs in FIFO order, deduplicated by SSRC. - /// A new RRTR for an already-pending SSRC updates its value in place. - /// Capped at 300 entries; at most 50 are consumed per DLRR report. - pending_rrtrs: VecDeque<(Ssrc, LastRrtr)>, - - raw_packets: Option>>, - - /// Target MTU (start) and warn threshold (end). Buffer sizing uses the - /// target; oversized outgoing datagrams above the warn threshold log a warning. - mtu: RangeInclusive, -} - -/// Last RRTR (Receiver Reference Time Report, RFC 3611 §4.4) received from a remote SSRC. -/// Stored at session level so we can respond with a DLRR regardless of which local stream -/// the remote is observing. -#[derive(Debug, Clone, Copy)] -struct LastRrtr { - /// Middle 32 bits of the RRTR NTP timestamp (compact NTP / LRR). - lrr: u32, - /// When the RRTR arrived locally. - received_at: Instant, -} - -impl Session { - pub fn new(config: &RtcConfig) -> Self { - let mut id = SessionId::new(); - // Max 2^62 - 1: https://bugzilla.mozilla.org/show_bug.cgi?id=861895 - const MAX_ID: u64 = 2_u64.pow(62) - 1; - while *id > MAX_ID { - id = (*id >> 1).into(); - } - Session { - id, - medias: vec![], - streams: Streams::new(config.pause_threshold), - app: None, - reordering_size_audio: config.reordering_size_audio, - reordering_size_video: config.reordering_size_video, - reordering_timeout_audio: config.reordering_timeout_audio, - intervals: config.intervals, - send_buffer_audio: config.send_buffer_audio, - send_buffer_video: config.send_buffer_video, - exts: config.exts.clone(), - - // Both sending and receiving starts from the configured codecs. - // These can then be changed in the SDP OFFER/ANSWER dance. - codec_config: config.codec_config.clone(), - probe_payload_params: None, - - srtp_rx: None, - srtp_tx: None, - last_nack: already_happened(), - last_twcc: already_happened(), - twcc: 0, - twcc_rx_register: TwccRecvRegister::new(100), - max_rx_seq_lookup: HashMap::new(), - enable_twcc_feedback: false, - pacer: NullPacer::default(), - poll_packet_buf: vec![0; 2000], - pending_packet: None, - ice_lite: config.ice_lite, - rtp_mode: config.rtp_mode, - vp9_packetizer_mode: config.vp9_packetizer_mode, - feedback_tx: VecDeque::new(), - feedback_rx: VecDeque::new(), - rtp_closing: false, - pending_rrtrs: VecDeque::new(), - raw_packets: if config.enable_raw_packets { - Some(VecDeque::new()) - } else { - None - }, - mtu: config.mtu.clone(), - } - } - - fn mtu(&self) -> usize { - *self.mtu.start() - } - - fn mtu_warn(&self) -> usize { - *self.mtu.end() - } - - pub fn id(&self) -> SessionId { - self.id - } - - pub fn set_app(&mut self, mid: Mid, index: usize) -> Result<(), String> { - if let Some((mid_existing, index_existing)) = self.app { - if mid_existing != mid { - return Err(format!("App mid changed {} != {}", mid, mid_existing,)); - } - if index_existing != index { - return Err(format!("App index changed {} != {}", index, index_existing,)); - } - } else { - self.app = Some((mid, index)); - } - Ok(()) - } - - pub fn app(&self) -> &Option<(Mid, usize)> { - &self.app - } - - pub fn set_keying_material( - &mut self, - mat: KeyingMaterial, - crypto: &CryptoProvider, - srtp_profile: SrtpProfile, - active: bool, - ) { - // TODO: rename this to `initialise_srtp_context`? - // Whether we're active or passive determines if we use the left or right - // hand side of the key material to derive input/output. - let left = active; - - self.srtp_rx = Some(SrtpContext::new(crypto, srtp_profile, &mat, !left)); - self.srtp_tx = Some(SrtpContext::new(crypto, srtp_profile, &mat, left)); - } - - pub fn handle_timeout(&mut self, now: Instant, wake: &mut Wake) -> Result<(), RtcError> { - if self.rtp_closing { - // Closing only drains previously queued BYEs; this timeout changes nothing. - wake.no_events(); - wake.no_timeout(); - return Ok(()); - } - - // Payload ready media. - self.do_payload(now)?; - - let sender_ssrc = self.streams.first_ssrc_local(); - - let do_nack = now >= self.nack_at().unwrap_or(not_happening()); - - self.streams.handle_timeout( - now, - sender_ssrc, - do_nack, - &self.medias, - self.intervals, - &mut self.feedback_tx, - ); - - // Flush any pending RRTRs as a DLRR alongside the Sender Report compound packet, - // so the DLRR adds no standalone RTCP traffic. - // Consume at most 50 entries per report; the rest remain for subsequent SRs. - if !self.pending_rrtrs.is_empty() && self.feedback_tx.iter().any(|r| matches!(r, Rtcp::SenderReport(_))) { - let n = self.pending_rrtrs.len().min(MAX_DLRR_PER_REPORT); - let items: Vec = self - .pending_rrtrs - .drain(..n) - .map(|(ssrc, rrtr)| { - let delay = now.saturating_duration_since(rrtr.received_at); - let last_rr_delay = ((delay.as_micros() * 65_536) / 1_000_000) as u32; - DlrrItem { - ssrc, - last_rr_time: rrtr.lrr, - last_rr_delay, - } - }) - .collect(); - - self.feedback_tx.push_back(Rtcp::ExtendedReport(ExtendedReport { - ssrc: sender_ssrc, - blocks: vec![ReportBlock::Dlrr(Dlrr { items })], - })); - } - - if do_nack { - self.last_nack = now; - } - - self.update_queue_state(now); - - if let Some(twcc_at) = self.twcc_at() { - if now >= twcc_at { - self.create_twcc_feedback(sender_ssrc, now); - } - } - - Ok(()) - } - - fn update_queue_state(&mut self, now: Instant) { - // Do not make unsendable media ready before DTLS supplies keys. - // Otherwise an immediate pacer deadline can starve the application's I/O. - if self.srtp_tx.is_none() { - return; - } - - let iter = self.streams.send_queue_states(now); - self.pacer.handle_timeout(now, iter); - } - - fn create_twcc_feedback(&mut self, sender_ssrc: Ssrc, now: Instant) -> Option<()> { - self.last_twcc = now; - let mut twcc = self.twcc_rx_register.build_report(self.mtu() - 100)?; - - // These SSRC are on media level, but twcc is on session level, - // we fill in the first discovered media SSRC in each direction. - twcc.sender_ssrc = sender_ssrc; - twcc.ssrc = self.streams.first_ssrc_remote(); - - trace!("Created feedback TWCC: {:?}", twcc); - self.feedback_tx.push_front(Rtcp::Twcc(twcc)); - Some(()) - } - - /// Enqueue a Picture Loss Indication (PLI, PT=206 FMT=1) for `media_ssrc`, to be - /// sent as part of the regular RTCP compound packet. The feedback packet's sender - /// SSRC is set to `sender_ssrc`. - pub(crate) fn send_pli_feedback(&mut self, sender_ssrc: Ssrc, media_ssrc: Ssrc) { - self.feedback_tx.push_back(Rtcp::Pli(Pli { - sender_ssrc, - ssrc: media_ssrc, - })); - } - - pub fn handle_rtp_receive(&mut self, now: Instant, message: &[u8], wake: &mut Wake) { - let Some(header) = RtpHeader::parse(message, &self.exts) else { - // Parsing has not touched stream state. Later rejection paths can have. - wake.no_events(); - wake.no_timeout(); - trace!("Failed to parse RTP header"); - return; - }; - - self.handle_rtp(now, header, message); - } - - pub fn handle_rtcp_receive(&mut self, now: Instant, message: &[u8], wake: &mut Wake) { - // According to spec, the outer enclosing SRTCP packet should always be a SR or RR, - // even if it's irrelevant and empty. - // In practice I'm not sure that is happening, because libWebRTC hates empty packets. - if self.handle_rtcp(now, message, wake).is_none() { - // Missing keys or failed authentication: no reports reached the session. - wake.no_events(); - wake.no_timeout(); - } - } - - fn mid_and_ssrc_for_header(&mut self, now: Instant, header: &RtpHeader) -> Option<(Mid, Ssrc)> { - let ssrc_header = header.ssrc; - - // SSRC 0 is used for non-media BWE probes from libwebrtc. - // These probes need TWCC feedback but don't carry actual media. - if ssrc_header.is_probe() { - return self.ensure_probe_stream(header.payload_type); - } - - if let Some(r) = self.streams.mid_ssrc_rx_by_ssrc_or_rtx(now, ssrc_header) { - return Some(r); - } - - // Attempt to dynamically map this header to some Media/ReceiveStream. - self.map_dynamic(header); - - // The dynamic mapping might have added an entry by now. - if let Some(r) = self.streams.mid_ssrc_rx_by_ssrc_or_rtx(now, ssrc_header) { - return Some(r); - } - - None - } - - /// Creates the probe stream on-demand for handling SSRC 0 BWE probes. - /// - /// No Media is created since probes don't carry real media - they only need - /// SRTP decryption and TWCC feedback. - fn ensure_probe_stream(&mut self, pt: Pt) -> Option<(Mid, Ssrc)> { - let ssrc: Ssrc = 0.into(); - let midrid = MidRid(MID_PROBE, None); - - // Add PayloadParams for this PT if not already configured. - // Probes may use different PTs, so we add them as we see them. - if self.probe_payload_params.as_ref().is_none_or(|p| p.pt() != pt) { - self.probe_payload_params = Some(PayloadParams::new_probe(pt)); - } - - // Create the stream with NACK suppressed (probes don't need retransmission). - // Reusing it must not invalidate the cached NACK state on every packet. - if !self.streams.has_stream_rx(ssrc) { - self.streams.expect_stream_rx(ssrc, None, midrid, true); - } - - Some((MID_PROBE, ssrc)) - } - - fn map_dynamic(&mut self, header: &RtpHeader) { - // There are two strategies for dynamically mapping SSRC. Both use the RTP "mid" - // header extension. - // A) Mid+Rid - used when doing simulcast. Rid points out which - // simulcast layer is in use. There is a separate header - // to indicate repair (RTX) stream. - // B) Mid+PT - when not doing simulcast, the PT identifies whether - // this is a repair stream. - - let Some(mid) = header.ext_vals.mid else { - return; - }; - let rid = header.ext_vals.rid.or(header.ext_vals.rid_repair); - - // The media the mid points out. Bail if the mid points to something - // we don't know about. - let Some(media) = self.medias.iter_mut().find(|m| m.mid() == mid) else { - return; - }; - - // Figure out which payload the PT maps to. Either main or RTX. - let maybe_payload = self - .codec_config - .iter() - .find(|p| p.pt() == header.payload_type || p.resend() == Some(header.payload_type)); - - // If we don't find it, bail out. - let Some(payload) = maybe_payload else { - return; - }; - - if let Some(rid) = rid { - // Case A - use the rid_repair header to identify RTX. - let is_main = header.ext_vals.rid.is_some(); - - let midrid = MidRid(mid, Some(rid)); - - self.streams - .map_dynamic_by_rid(header.ssrc, midrid, media, *payload, is_main); - } else { - // Case B - the payload type identifies RTX. - let is_main = payload.pt() == header.payload_type; - - let midrid = MidRid(mid, None); - - self.streams - .map_dynamic_by_pt(header.ssrc, midrid, media, *payload, is_main); - } - } - - pub(crate) fn handle_rtp(&mut self, now: Instant, mut header: RtpHeader, buf: &[u8]) { - // Rewrite absolute-send-time (if present) to be relative to now. - header.ext_vals.update_absolute_send_time(now); - - trace!("Handle RTP: {:?}", header); - - // Early repair padding has no main stream yet, but still needs transport feedback. - let mapped = self.mid_and_ssrc_for_header(now, &header); - let can_receive = mapped.is_some() || self.is_early_rtx_padding(&header); - if !can_receive { - trace!("No mid/SSRC for header: {:?}", header); - return; - } - - let srtp = match self.srtp_rx.as_mut() { - Some(v) => v, - None => { - trace!("Rejecting SRTP while missing SrtpContext"); - return; - } - }; - - let mut stream = mapped.and_then(|(_, ssrc)| self.streams.stream_rx(&ssrc)); - let maybe_params = if header.ssrc.is_probe() { - self.probe_payload_params.as_ref() - } else { - main_payload_params(&self.codec_config, header.payload_type) - }; - - let params = match maybe_params { - Some(p) => p, - None => { - trace!( - "No payload params could be found (main or RTX) for {:?}", - header.payload_type - ); - return; - } - }; - let clock_rate = params.spec().clock_rate; - let pt = params.pt(); - // RTX padding may use the main payload type, so an associated RTX SSRC takes precedence. - let repair_ssrc = stream.as_ref().and_then(|s| s.rtx()); - let is_repair = repair_ssrc == Some(header.ssrc) || pt != header.payload_type; - let history = self.max_rx_seq_lookup.get(&header.ssrc); - let mut seq_no = if let Some(stream) = &mut stream { - let max_seq_lookup = make_max_seq_lookup(&self.max_rx_seq_lookup); - stream.extend_seq(&header, is_repair, max_seq_lookup) - } else { - let max_seq = history.map(|s| s.max_seq()); - header.sequence_number(max_seq) - }; - let is_repair_padding = is_repair && header.has_padding; - let use_session_history = is_repair_padding || stream.is_none(); - // A newly discovered stream restores only the RTX maximum and blocks older packets. - // Keep using the session bitmap for padding so unseen reordered packets still count, - // while padding already received before discovery remains protected against replay. - let is_new = if use_session_history { - history.is_none_or(|history| history.accepts(seq_no)) - } else { - let stream = stream.as_ref().unwrap(); - stream.is_new_packet(is_repair, seq_no) - }; - if !is_new { - trace!("Ignoring dupe packet ssrc: {} seq_no: {}", header.ssrc, seq_no); - return; - } - - // The decrypted plaintext borrows from the SRTP scratch buffer. We - // narrow it down to the actual payload via slicing only, then build - // the final `Arc<[u8]>` in a single allocation at the end. - let data = match srtp.unprotect_rtp(buf, &header, *seq_no) { - Some(d) => d, - None => { - trace!( - "Failed to unprotect SRTP for SSRC: {} pt: {} mid: {:?} \ - rid: {:?} seq_no: {} is_repair: {}", - header.ssrc, - pt, - header.ext_vals.mid, - header.ext_vals.rid.or(header.ext_vals.rid_repair), - seq_no, - is_repair - ); - return; - } - }; - - let data = if header.has_padding { - match RtpHeader::unpad_payload(data) { - Some(d) => d, - None => { - trace!("unpadding of unprotected payload failed"); - return; - } - } - } else { - data - }; - - // The header padding flag alone does not mean the packet contains only padding. - // Authenticate and unpad first; media payload needs a mapped stream to be processed. - if stream.is_none() && !data.is_empty() { - return; - } - - if let Some(raw_packets) = &mut self.raw_packets { - raw_packets.push_back(Box::new(RawPacket::RtpRx(header.clone(), data.to_vec()))); - } - - // Mark as received for TWCC purposes - if let Some(transport_cc) = header.ext_vals.transport_cc { - let prev = self.twcc_rx_register.max_seq(); - let extended = extend_u16(prev.map(|s| *s), transport_cc); - self.twcc_rx_register.update_seq(extended.into(), now); - } - - // Store largest seen seq_no for the SSRC. This is used in case we get SSRC changes - // like A -> B -> A. When we go back to A, we must keep the ROC. - update_max_seq(&mut self.max_rx_seq_lookup, header.ssrc, seq_no); - - let Some(stream) = stream else { - return; - }; - // A receive stream exists only when MID/SSRC mapping succeeded. - let (mid, ssrc) = mapped.unwrap(); - - // Register reception in nack registers. - let receipt_outer = stream.update_register(now, &header, clock_rate, is_repair, seq_no); - - // RTX packets must be rewritten to be a normal packet. This only changes the - // the seq_no, however MediaTime might be different when interpreted against the - // the "main" register. - let (receipt, data) = if is_repair { - // Drop RTX packets that are just empty padding. The payload here - // is empty because we would have done RtpHeader::unpad_payload above. - // For unpausing, it's enough with the stream.update() already done above. - if data.is_empty() { - return; - } - - // Rewrite the header, and strip the resent seq_no prefix from the body. - let data = stream.un_rtx(&mut header, data, pt); - - let max_seq_lookup = make_max_seq_lookup(&self.max_rx_seq_lookup); - - // Header has changed, which means we extend a new seq_no. This time - // without is_repair since this is the wrapped resend. This is the - // extended number of the main stream. - seq_no = stream.extend_seq(&header, false, max_seq_lookup); - - // header.ssrc is changed by un_rtx() above to be main SSRC. - update_max_seq(&mut self.max_rx_seq_lookup, header.ssrc, seq_no); - - // Now update the "main" register with the repaired packet info. - let receipt = stream.update_register(now, &header, clock_rate, false, seq_no); - (receipt, data) - } else { - // This is not RTX, the outer seq and time is what we use. The first - // stream.update will have updated the main register. - (receipt_outer, data) - }; - - // Probe packets (SSRC 0) contain only padding, no real media to process - if ssrc.is_probe() { - return; - } - - let rx_bytes = data.len(); - - // One-shot conversion to Arc<[u8]>: a single allocation that copies - // only the trimmed payload bytes out of the SRTP scratch buffer. - let payload: Arc<[u8]> = Arc::from(data); - - let packet = stream.handle_rtp(now, header, payload, seq_no, receipt.time, rx_bytes); - - if self.rtp_mode { - // In RTP mode, we store the packet temporarily here for the next poll_output(). - // However only if this is a packet not seen before. This filters out spurious - // resends for padding. - if receipt.is_new_packet { - self.pending_packet = Some(packet); - } - } else { - // In non-RTP mode, we let the Media use a Depayloader. - // unwrap is fine because mid_and_ssrc_for_header guarantees it. - let media = self.medias.iter_mut().find(|m| m.mid() == mid).unwrap(); - media.depayload( - stream.rid(), - packet, - self.reordering_size_audio, - self.reordering_size_video, - &self.codec_config, - ); - } - } - - /// Identifies candidates for padding receipt before the main SSRC is discovered. - /// - /// MID and repair RID must identify a negotiated simulcast layer, and the codec must - /// support RTX. This limits the fallback to expected repair traffic instead of accepting - /// arbitrary unmapped SSRCs. These header checks do not authenticate the packet or prove - /// it contains only padding; the receive path verifies both before recording a receipt. - fn is_early_rtx_padding(&self, header: &RtpHeader) -> bool { - let Some(mid) = header.ext_vals.mid else { - return false; - }; - let Some(media) = self.medias.iter().find(|m| m.mid() == mid) else { - return false; - }; - let params = main_payload_params(&self.codec_config, header.payload_type); - let has_rtx = params.is_some_and(|p| p.resend().is_some()); - let repair_rid = header.ext_vals.rid_repair; - let is_expected_rid = repair_rid.is_some_and(|rid| media.rids_rx().contains(rid)); - // A regular RID identifies primary traffic, which must go through normal stream discovery. - header.has_padding && header.ext_vals.rid.is_none() && has_rtx && is_expected_rid - } - - fn handle_rtcp(&mut self, now: Instant, buf: &[u8], wake: &mut Wake) -> Option<()> { - let srtp: &mut SrtpContext = self.srtp_rx.as_mut()?; - let unprotected = srtp.unprotect_rtcp(buf)?; - - Rtcp::read_packet(&unprotected, &mut self.feedback_rx); - let mut may_move_timeout = false; - - if let Some(raw_packets) = &mut self.raw_packets { - for fb in &self.feedback_rx { - raw_packets.push_back(Box::new(RawPacket::RtcpRx(fb.clone()))); - } - } - - for fb in RtcpFb::from_rtcp(self.feedback_rx.drain(..)) { - may_move_timeout = true; - - if let RtcpFb::Twcc(twcc) = fb { - // Without a bandwidth estimator, transport feedback has no consumer. - trace!("Ignore TWCC: {:?}", twcc); - continue; - } - - if let RtcpFb::Rrtr((rrtr, ssrc)) = fb { - // DLRR responder (RFC 3611 §4.5): store the remote's RRTR so we can - // reply with a DLRR, letting the remote compute RTT. - let lrr = (rrtr.ntp_time.as_ntp_64() >> 16) as u32; - let entry = LastRrtr { lrr, received_at: now }; - - // Update in place if this SSRC is already pending (preserves queue order). - if let Some(existing) = self.pending_rrtrs.iter_mut().find(|(s, _)| *s == ssrc) { - existing.1 = entry; - } else { - // Cap at 300 entries; drop the oldest if full. - if self.pending_rrtrs.len() >= MAX_PENDING_RRTRS { - self.pending_rrtrs.pop_front(); - } - self.pending_rrtrs.push_back((ssrc, entry)); - } - continue; - } - - if let RtcpFb::DlrrItem(dlrr) = fb { - self.streams.handle_dlrr(now, dlrr); - continue; - } - - if fb.is_for_rx() { - let Some(stream) = self.streams.stream_rx(&fb.ssrc()) else { - continue; - }; - stream.handle_rtcp(now, fb); - } else { - let Some(stream) = self.streams.stream_tx(&fb.ssrc()) else { - continue; - }; - stream.handle_rtcp(now, fb); - } - } - - if !may_move_timeout { - // Also covers empty reports; raw-packet capture only queues events. - wake.no_timeout(); - } - - Some(()) - } - - pub fn poll_event(&mut self) -> Option { - // If we're not ready to flow media, don't send any events. - if !self.ready_for_srtp() { - return None; - } - - if let Some(raw_packets) = &mut self.raw_packets { - if let Some(p) = raw_packets.pop_front() { - return Some(Event::RawPacket(p)); - } - } - - // This must be before pending_packet.take() since we need to emit the unpaused event - // before the first packet causing the unpause. - if let Some(paused) = self.streams.poll_stream_paused() { - return Some(Event::StreamPaused(paused)); - } - - if self.rtp_mode { - if let Some(packet) = self.pending_packet.take() { - return Some(Event::RtpPacket(packet)); - } - } - - if let Some(req) = self.streams.poll_keyframe_request() { - return Some(Event::KeyframeRequest(req)); - } - - if let Some(report) = self.streams.poll_sender_feedback() { - return Some(Event::SenderFeedback(report)); - } - - if let Some((mid, bitrate)) = self.streams.poll_remb_request() { - return Some(Event::EgressBitrateEstimate(BweKind::Remb { estimate: bitrate, mid })); - } - - for media in &mut self.medias { - if media.need_open_event { - media.need_open_event = false; - - return Some(Event::MediaAdded(MediaAdded { - mid: media.mid(), - kind: media.kind(), - direction: media.direction(), - simulcast: media.simulcast().map(|s| s.clone().into()), - })); - } - - if media.need_changed_event { - media.need_changed_event = false; - return Some(Event::MediaChanged(MediaChanged { - mid: media.mid(), - direction: media.direction(), - })); - } - } - - None - } - - fn update_receive_recovery(&mut self) { - for media in self.medias.iter_mut().filter(|m| m.kind().is_video()) { - let mid = media.mid(); - for (rid, buf) in media.receive_buffers() { - let deadline = buf.recovery_candidate().and_then(|(range, received)| { - match self.streams.stream_rx_by_midrid(MidRid(mid, rid)) { - Some(stream) => stream.recovery_deadline(range, received), - None => received.checked_add(Duration::from_millis(300)), - } - }); - buf.set_recovery_deadline(deadline); - } - } - } - - pub fn poll_event_fallible(&mut self, now: Instant) -> Result, RtcError> { - // Not relevant in rtp_mode, where the packets are picked up by poll_event(). - if self.rtp_mode { - return Ok(None); - } - - self.update_receive_recovery(); - for media in &mut self.medias { - if let Some(e) = media.poll_sample(&self.codec_config, now, self.reordering_timeout_audio)? { - return Ok(Some(Event::MediaData(e))); - } - } - - Ok(None) - } - - fn ready_for_srtp(&self) -> bool { - self.srtp_rx.is_some() && self.srtp_tx.is_some() - } - - pub fn poll_datagram(&mut self, now: Instant) -> Option { - // Time must have progressed forward from start value. - if now == already_happened() { - return None; - } - - let x = if self.rtp_closing { - self.poll_feedback() - } else { - None.or_else(|| self.poll_feedback()).or_else(|| self.poll_packet(now)) - }; - - if let Some(x) = &x { - // In RTP mode we trust the API user feeds the RTP packet sizes they - // need for the MTU they are targeting. This warning is only for when - // str0m does the RTP packetization. - if !self.rtp_mode && x.len() > self.mtu_warn() { - warn!("RTP above MTU {}: {}", self.mtu_warn(), x.len()); - } - } - - x - } - - /// To be called in lieu of [`Self::poll_datagram`] when the owner is not in a position to transmit any - /// generated feedback, and thus such feedback should be dropped. - pub fn clear_feedback(&mut self) { - self.feedback_rx.clear(); - self.feedback_tx.clear(); - } - - pub fn close_rtp(&mut self) { - if self.rtp_closing { - return; - } - - self.rtp_closing = true; - self.clear_feedback(); - self.streams.reset_send_buffers(); - - for reports in ReportList::lists_from_iter(self.streams.local_sender_ssrcs()) { - self.feedback_tx.push_back(Rtcp::Goodbye(Goodbye { reports })); - } - } - - pub fn is_rtp_closed(&self) -> bool { - self.rtp_closing && self.feedback_tx.is_empty() - } - - fn poll_feedback(&mut self) -> Option { - if self.feedback_tx.is_empty() { - return None; - } - - // Round to nearest multiple of 4 bytes. - let encryptable_mtu: usize = (self.mtu() - SRTCP_OVERHEAD) & !3; - assert!(encryptable_mtu.is_multiple_of(4)); - - let mut data = vec![0_u8; encryptable_mtu]; - - let mut raw_packets = self.raw_packets.as_mut(); - let output = move |fb| { - if let Some(raw_packets) = &mut raw_packets { - raw_packets.push_back(Box::new(RawPacket::RtcpTx(fb))); - } - }; - - let len = Rtcp::write_packet(&mut self.feedback_tx, &mut data, output); - - if len == 0 { - return None; - } - - data.truncate(len); - - let srtp = self.srtp_tx.as_mut()?; - let protected = srtp.protect_rtcp(&data); - - assert!(protected.len() < self.mtu(), "Encrypted SRTCP should be less than MTU"); - - Some(protected.into()) - } - - fn poll_packet(&mut self, now: Instant) -> Option { - let srtp_tx = self.srtp_tx.as_mut()?; - - // Figure out which, if any, queue to poll - let midrid = self.pacer.poll_queue()?; - let stream = self.streams.stream_tx_by_midrid(midrid)?; - let Some(media) = self.medias.iter().find(|m| m.mid() == stream.mid()) else { - trace!("Pacer pointed to mid {} which has no media", midrid.mid()); - return None; - }; - let buf = &mut self.poll_packet_buf; - let params = &self.codec_config; - let exts = media.remote_extmap(); - - // TWCC might not be enabled for this m-line. Firefox do use TWCC, but not - // for audio. This is indiciated via the SDP. - let twcc_enabled = exts.id_of(Extension::TransportSequenceNumber).is_some(); - let twcc = twcc_enabled.then_some(&mut self.twcc); - - let receipt = stream.poll_packet(now, exts, twcc, params, buf)?; - - let PacketReceipt { - header, - seq_no, - payload_size, - } = receipt; - - trace!(payload_size, "Poll RTP: {:?}", header); - - self.pacer.register_send(now, payload_size.into(), midrid); - - if let Some(raw_packets) = &mut self.raw_packets { - raw_packets.push_back(Box::new(RawPacket::RtpTx(header.clone(), buf.clone()))); - } - - let protected = srtp_tx.protect_rtp(buf, &header, *seq_no); - - Some(protected.into()) - } - - pub fn poll_timeout(&mut self) -> (Option, Reason) { - if self.rtp_closing { - return if self.feedback_tx.is_empty() { - (None, Reason::NotHappening) - } else { - (Some(already_happened()), Reason::Feedback) - }; - } - - self.update_receive_recovery(); - let feedback_at = self.regular_feedback_at(); - let nack_at = self.nack_at(); - let twcc_at = self.twcc_at(); - let pacing_at = self.pacer.poll_timeout(); - let packetize_at = self.medias.iter().filter_map(|m| m.poll_timeout()).min(); - let receive_at = self - .medias - .iter_mut() - .filter_map(|media| media.poll_receive_timeout(self.reordering_timeout_audio)) - .min(); - let paused_at = self.paused_at(); - let send_stream_at = self.streams.send_stream(); - let request_at = self.streams.pending_request(); - - (feedback_at, Reason::Feedback) - .soonest((request_at, Reason::Feedback)) - .soonest((nack_at, Reason::Nack)) - .soonest((twcc_at, Reason::Twcc)) - .soonest(pacing_at) - .soonest((receive_at, Reason::ReceiveReorder)) - .soonest((packetize_at, Reason::Packetize)) - .soonest((paused_at, Reason::PauseCheck)) - .soonest((send_stream_at, Reason::SendStream)) - } - - pub fn has_mid(&self, mid: Mid) -> bool { - self.medias.iter().any(|m| m.mid() == mid) || self.app.is_some_and(|(app_mid, _)| app_mid == mid) - } - - fn regular_feedback_at(&self) -> Option { - self.streams.regular_feedback_at(self.intervals) - } - - fn paused_at(&self) -> Option { - self.streams.paused_at() - } - - fn nack_at(&self) -> Option { - // Paused streams stop counting as NACK-enabled once their pending retries finish, - // so an idle session doesn't wake every NACK_MIN_INTERVAL for as long as it lives. - if !self.streams.any_nack_enabled() { - return None; - } - - Some(self.last_nack + NACK_MIN_INTERVAL) - } - - fn twcc_at(&self) -> Option { - // Early RTX padding can create transport receipts before any receive stream exists. - // Scheduling by pending receipts ensures that padding still receives timely feedback. - if self.enable_twcc_feedback && self.twcc_rx_register.has_unreported() { - Some(self.last_twcc + TWCC_INTERVAL) - } else { - None - } - } - - pub fn enable_twcc_feedback(&mut self) { - if !self.enable_twcc_feedback { - debug!("Enable TWCC feedback"); - self.enable_twcc_feedback = true; - } - } - - #[allow(dead_code)] - pub fn line_count(&self) -> usize { - self.medias.len() + if self.app.is_some() { 1 } else { 0 } - } - - pub fn add_media(&mut self, media: Media) { - self.medias.push(media); - } - - pub fn medias(&self) -> &[Media] { - &self.medias - } - - pub fn remove_media(&mut self, mid: Mid) { - self.medias.retain(|media| media.mid() != mid); - self.streams.remove_streams_by_mid(mid); - } - - pub fn media_by_mid(&self, mid: Mid) -> Option<&Media> { - self.medias.iter().find(|m| m.mid() == mid) - } - - pub fn media_by_mid_mut(&mut self, mid: Mid) -> Option<&mut Media> { - self.medias.iter_mut().find(|m| m.mid() == mid) - } - - fn do_payload(&mut self, now: Instant) -> Result<(), RtcError> { - let mtu = self.mtu(); - for m in &mut self.medias { - m.do_payload( - now, - &mut self.streams, - &self.codec_config, - self.vp9_packetizer_mode, - mtu, - )?; - } - - Ok(()) - } - - pub fn set_direction(&mut self, mid: Mid, direction: Direction) -> bool { - let Some(media) = self.media_by_mid_mut(mid) else { - return false; - }; - let old_dir = media.direction(); - if old_dir == direction { - return false; - } - - media.set_direction(direction); - - if old_dir.is_sending() && !direction.is_sending() { - self.streams.reset_buffers_tx(mid); - } - - let max_seq_lookup = make_max_seq_lookup(&self.max_rx_seq_lookup); - if old_dir.is_receiving() && !direction.is_receiving() { - self.streams.reset_buffers_rx(mid, max_seq_lookup); - } - - true - } - - pub fn stop_media(&mut self, mid: Mid) -> bool { - let Some(media) = self.media_by_mid_mut(mid) else { - return false; - }; - if media.disabled() { - return false; - } - - media.mark_stopped(); - self.set_direction(mid, Direction::Inactive); - - true - } - - pub fn is_request_keyframe_possible(&self, kind: KeyframeRequestKind) -> bool { - // TODO: It's possible to have different set of feedback enabled for different - // payload types. I.e. we could have FIR enabled for H264, but not for VP8. - // We might want to make this check more fine grained by testing which PT is - // in "active use" right now. - self.codec_config.iter().any(|r| match kind { - KeyframeRequestKind::Pli => r.fb_pli, - KeyframeRequestKind::Fir => r.fb_fir, - }) - } - - /// Checks whether the SRTP contexts are up. - pub fn is_connected(&self) -> bool { - self.srtp_rx.is_some() && self.srtp_tx.is_some() - } -} - -pub struct PacketReceipt { - pub header: RtpHeader, - pub seq_no: SeqNo, - pub payload_size: usize, -} - -/// Find the PayloadParams for the given Pt, either when the Pt is the main Pt for the Codec or -/// when it's the RTX Pt. -fn main_payload_params(c: &CodecConfig, pt: Pt) -> Option<&PayloadParams> { - c.iter().find(|p| p.pt == pt || p.resend == Some(pt)) -} - -fn make_max_seq_lookup(map: &HashMap) -> impl Fn(Ssrc) -> Option + '_ { - |ssrc| map.get(&ssrc).map(|s| s.max_seq()) -} - -fn update_max_seq(map: &mut HashMap, ssrc: Ssrc, seq_no: SeqNo) { - map.entry(ssrc) - .and_modify(|window| window.update(seq_no)) - .or_insert_with(|| SeqNoWindow::new(seq_no)); -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::vendor::str0m::RtcConfig; - use crate::vendor::str0m::io::DATAGRAM_MTU_TARGET; - - use crate::vendor::str0m::poll::Readiness; - use crate::vendor::str0m::rtp_::RtcpPacket; - - fn keyed_session() -> Session { - let mut session = Session::new(&RtcConfig::default()); - let crypto = crate::vendor::str0m::crypto::test_default_provider(); - let profile = SrtpProfile::AEAD_AES_128_GCM; - let mat = KeyingMaterial::new(&vec![0; profile.keying_material_len()]); - session.set_keying_material(mat, crypto, profile, true); - session - } - - #[test] - fn readiness_closed_session_timeout_preserves_pending_bye() { - let now = Instant::now(); - let mut session = keyed_session(); - session - .streams - .declare_stream_tx(42.into(), None, MidRid("vid".into(), None)); - session.close_rtp(); - let before = session.poll_timeout(); - assert_eq!(before.1, Reason::Feedback); - let mut readiness = Readiness::idle(); - session.handle_timeout(now, &mut readiness.wake()).unwrap(); - assert!(!readiness.wants_events()); - assert!(!readiness.wants_timeout()); - assert_eq!(session.poll_timeout(), before); - assert!(session.poll_datagram(now).is_some(), "existing BYE must still drain"); - } - - #[test] - fn readiness_malformed_rtp_does_not_wake() { - let mut session = keyed_session(); - let before = session.poll_timeout(); - let mut readiness = Readiness::idle(); - session.handle_rtp_receive(Instant::now(), &[0x80], &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(!readiness.wants_timeout()); - assert_eq!(session.poll_timeout(), before); - assert!(session.poll_event().is_none()); - } - - #[test] - fn readiness_valid_rtp_header_keeps_wake_even_without_keys() { - let mut session = Session::new(&RtcConfig::default()); - let mut readiness = Readiness::idle(); - // SSRC 0 creates a probe receive stream before the missing-key check. - let packet = [0x80, 96, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]; - session.handle_rtp_receive(Instant::now(), &packet, &mut readiness.wake()); - assert!(session.streams.has_stream_rx(0.into())); - assert!(readiness.wants_events()); - assert!(readiness.wants_timeout()); - } - - #[test] - fn readiness_rejected_rtcp_does_not_wake() { - for mut session in [Session::new(&RtcConfig::default()), keyed_session()] { - let before = session.poll_timeout(); - let mut readiness = Readiness::idle(); - session.handle_rtcp_receive(Instant::now(), &[0; 32], &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(!readiness.wants_timeout()); - assert_eq!(session.poll_timeout(), before); - assert!(session.poll_event().is_none()); - } - } - - #[test] - fn readiness_empty_rtcp_report_keeps_raw_packet_events() { - let mut session = keyed_session(); - session.raw_packets = Some(VecDeque::new()); - let before = session.poll_timeout(); - let packet = session - .srtp_tx - .as_mut() - .unwrap() - .protect_rtcp(&[0x80, 201, 0, 1, 0, 0, 0, 1]); - let mut readiness = Readiness::idle(); - session.handle_rtcp_receive(Instant::now(), &packet, &mut readiness.wake()); - assert!(readiness.wants_events()); - assert!(!readiness.wants_timeout()); - assert!(matches!(session.poll_event(), Some(Event::RawPacket(_)))); - assert_eq!(session.poll_timeout(), before); - } - - #[test] - fn session_mtu_matches_config() { - let cfg = RtcConfig::default(); - let s = Session::new(&cfg); - assert_eq!(s.mtu(), DATAGRAM_MTU_TARGET); - - let cfg = RtcConfig::default().set_mtu(900..=1280); - let s = Session::new(&cfg); - assert_eq!(s.mtu(), 900); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/mod.rs b/rs/moq-webrtc/src/vendor/str0m/streams/mod.rs deleted file mode 100644 index 72e0213dda2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/mod.rs +++ /dev/null @@ -1,671 +0,0 @@ -use std::collections::{HashMap, VecDeque}; -use std::fmt::{self}; -use std::sync::Arc; -use std::time::Duration; -use std::time::Instant; -use tracing::trace; - -use crate::vendor::str0m::config_mod::RtcpReportIntervals; -use crate::vendor::str0m::format::CodecConfig; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::media::{KeyframeRequest, MID_PROBE, Media, SenderFeedback}; -use crate::vendor::str0m::pacer::QueueState; -use crate::vendor::str0m::packet::Vp8Patch; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::Ssrc; -use crate::vendor::str0m::rtp_::{Bitrate, Pt}; -use crate::vendor::str0m::rtp_::{DlrrItem, Rtcp, RtcpFb, RtpHeader}; -use crate::vendor::str0m::rtp_::{MediaTime, SenderInfo}; -use crate::vendor::str0m::rtp_::{Mid, Rid, SeqNo}; -use crate::vendor::str0m::util::already_happened; - -pub use self::receive::StreamRx; -pub use self::send::{RtpWrite, StreamTx, StreamTxQueueInfo}; - -mod receive; -pub(crate) mod register; -pub(crate) mod register_nack; -mod rtx_cache; -pub(crate) mod rtx_cache_buf; -mod send; -mod send_queue; -mod send_stats; - -pub(crate) use send::{DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP}; - -/// Packet of RTP data. -/// -/// As emitted by [`Event::RtpPacket`][crate::vendor::str0m::Event::RtpPacket] when using rtp mode. -#[derive(PartialEq, Eq)] -pub struct RtpPacket { - /// Extended sequence number to avoid having to deal with ROC. - pub seq_no: SeqNo, - - /// Extended RTP time in the clock frequency of the codec. To avoid dealing with ROC. - /// - /// For a newly scheduled outgoing packet, the clock_rate is not correctly set until - /// we do the poll_output(). - pub time: MediaTime, - - /// Parsed RTP header. - pub header: RtpHeader, - - /// RTP payload. This contains no header. - pub payload: Arc<[u8]>, - - vp8_patch: Option, - - /// str0m server timestamp. - /// - /// This timestamp has nothing to do with RTP itself. For outgoing packets, this is when - /// the packet was first handed over to str0m and enqueued in the outgoing send buffers. - /// For incoming packets it's the time we received the network packet. - pub timestamp: Instant, - - /// Sender information from the most recent Sender Report(SR). - /// - /// If no Sender Report(SR) has been received or this packet is being sent by str0m this is [`None`]. - pub last_sender_info: Option, - - /// Whether this packet can be nacked. - /// - /// This is often false for audio, but might also be false for discardable frames when - /// using temporal encoding as in a VP8 simulcast situation. - pub(crate) nackable: bool, -} - -/// Event when an encoded stream is considered paused/unpaused. -/// -/// This means the stream has not received any data for some time (default 1.5 seconds). -#[derive(Debug)] -pub struct StreamPaused { - /// The main SSRC of the encoded stream that paused. - pub ssrc: Ssrc, - - /// The mid the encoded stream belongs to. - pub mid: Mid, - - /// The rid, if the encoded stream has a rid. - pub rid: Option, - - /// Whether the stream is paused or not. - pub paused: bool, -} - -/// Holder of incoming/outgoing encoded streams. -/// -/// Each encoded stream is uniquely identified by an SSRC. The concept of mid/rid sits on the Media -/// level together with the ability to translate a mid/rid to an encoded stream. -#[derive(Debug)] -pub(crate) struct Streams { - /// All incoming encoded streams. - streams_rx: HashMap, - - /// Each incoming SSRC is mapped to a Mid/Ssrc. The Ssrc in the value is for the case - /// where the incoming SSRC is for an RTX and we want the "main". - rx_lookup: HashMap, - - /// Time we last cleaned up unused entries from source_keys_rx. - last_rx_lookup_cleanup: Instant, - - /// All outgoing encoded streams. - streams_tx: HashMap, - - /// Local SSRC used before we got any StreamTx. This is used for RTCP if we don't - /// have any reasonable value to use. - default_ssrc_tx: Ssrc, - - /// We need to report all RR/SR for a Mid together in one RTCP. This is a dynamic - /// list that we don't want to allocate on every handle_timeout. - mids_to_report: Vec, - - pause_threshold: Duration, -} - -/// Delay between cleaning up the RxLookup. -const RX_LOOKUP_CLEANUP_INTERVAL: Duration = Duration::from_millis(10_000); - -/// How old an RxLookup entry may be. -const RX_LOOKUP_EXPIRY: Duration = Duration::from_millis(30_000); - -#[derive(Debug)] -struct RxLookup { - mid: Mid, - main: Ssrc, - last_used: Instant, -} - -impl Streams { - pub(crate) fn new(pause_threshold: Duration) -> Self { - Self { - streams_rx: Default::default(), - rx_lookup: Default::default(), - last_rx_lookup_cleanup: already_happened(), - streams_tx: Default::default(), - default_ssrc_tx: 0.into(), // this will be changed - mids_to_report: Vec::with_capacity(10), - pause_threshold, - } - } - - pub(crate) fn map_dynamic_by_rid( - &mut self, - ssrc: Ssrc, - midrid: MidRid, - media: &mut Media, - payload: PayloadParams, - is_main: bool, - ) { - // This is the point of the function. - let rid = midrid.rid().expect("map_dynamic_by_rid to be called with Rid"); - - // Check if the mid/rid combo is not expected - if !media.rids_rx().contains(rid) { - trace!("Mid does not expect rid: {} {}", midrid.mid(), rid); - return; - } - - let maybe_stream = self.stream_rx_by_midrid(midrid); - - let (ssrc_main, rtx) = if is_main { - let maybe_rtx = maybe_stream.and_then(|s| s.rtx()); - (ssrc, maybe_rtx) - } else { - // This can bail if the main SSRC has not been discovered yet. - let Some(stream) = maybe_stream else { - return; - }; - (stream.ssrc(), Some(ssrc)) - }; - - self.map_dynamic_finish(midrid, ssrc_main, rtx, media, payload); - } - - pub(crate) fn map_dynamic_by_pt( - &mut self, - ssrc: Ssrc, - midrid: MidRid, - media: &mut Media, - payload: PayloadParams, - is_main: bool, - ) { - if media.rids_rx().is_specific() { - trace!("Media expects rid and RTP packet has only mid: {:?}", media.rids_rx()); - return; - } - - let maybe_stream = self.stream_rx_by_midrid(midrid); - - let (ssrc_main, rtx) = if is_main { - let maybe_rtx = maybe_stream.and_then(|s| s.rtx()); - (ssrc, maybe_rtx) - } else { - // This can bail if the main SSRC has not been discovered yet. - let Some(stream) = maybe_stream else { - return; - }; - // The main is the SSRC in the stream already. The incoming is RTX. - let ssrc_main = stream.ssrc(); - (ssrc_main, Some(ssrc)) - }; - - self.map_dynamic_finish(midrid, ssrc_main, rtx, media, payload); - } - - #[allow(clippy::too_many_arguments)] - fn map_dynamic_finish( - &mut self, - midrid: MidRid, - ssrc_main: Ssrc, - rtx: Option, - media: &mut Media, - payload: PayloadParams, - ) { - let maybe_stream = self.stream_rx_by_midrid(midrid); - - if let Some(stream) = maybe_stream { - let ssrc_from = stream.ssrc(); - let rtx_from = stream.rtx(); - - // Handle changes in SSRC. - if ssrc_from != ssrc_main { - // We got a change in main SSRC for this stream. - let did_change = self.change_stream_rx_ssrc(ssrc_from, ssrc_main); - - // When the SSRC changes, any payload type on this RID can start with - // a new sequence number. Reset all depayloaders for the RID. - if did_change { - media.reset_depayloaders_for_rid(midrid.rid()); - } - } - - // Handle changes in RTX - if let (Some(rtx_from), Some(rtx_to)) = (rtx_from, rtx) { - if rtx_from != rtx_to { - self.change_stream_rx_rtx(rtx_from, rtx_to); - } - } - } - - // If we don't have an RTX PT configured, we don't want NACK. - let suppress_nack = payload.resend.is_none(); - - // If stream already exists, this might only "fill in" the RTX. - self.expect_stream_rx(ssrc_main, rtx, midrid, suppress_nack); - } - - pub fn expect_stream_rx( - &mut self, - ssrc: Ssrc, - rtx: Option, - midrid: MidRid, - suppress_nack: bool, - ) -> &mut StreamRx { - let stream = self - .streams_rx - .entry(ssrc) - .or_insert_with(|| StreamRx::new(ssrc, midrid, suppress_nack, self.pause_threshold)); - - if let Some(rtx) = rtx { - stream.maybe_reset_rtx(rtx); - } - - stream - } - - pub fn remove_stream_rx(&mut self, ssrc: Ssrc) -> bool { - let stream = self.streams_rx.remove(&ssrc); - let existed = stream.is_some(); - - self.rx_lookup.retain(|k, l| *k != ssrc && l.main != ssrc); - - existed - } - - pub fn declare_stream_tx(&mut self, ssrc: Ssrc, rtx: Option, midrid: MidRid) -> &mut StreamTx { - self.streams_tx - .entry(ssrc) - .or_insert_with(|| StreamTx::new(ssrc, rtx, midrid)) - } - - pub fn remove_stream_tx(&mut self, ssrc: Ssrc) -> bool { - self.streams_tx.remove(&ssrc).is_some() - } - - pub(crate) fn local_sender_ssrcs(&self) -> Vec { - self.streams_tx - .values() - .flat_map(|s| std::iter::once(s.ssrc()).chain(s.rtx())) - .collect() - } - - pub(crate) fn reset_send_buffers(&mut self) { - for stream in self.streams_tx.values_mut() { - stream.reset_buffers(); - } - } - - pub fn stream_rx(&mut self, ssrc: &Ssrc) -> Option<&mut StreamRx> { - self.streams_rx.get_mut(ssrc) - } - - pub fn stream_tx(&mut self, ssrc: &Ssrc) -> Option<&mut StreamTx> { - self.streams_tx.get_mut(ssrc) - } - - /// Lookup the "main" SSRC and mid for a given SSRC(main or RTX). - pub(crate) fn mid_ssrc_rx_by_ssrc_or_rtx(&mut self, now: Instant, ssrc: Ssrc) -> Option<(Mid, Ssrc)> { - // A direct hit on SSRC is to prefer. The idea is that mid/rid are only sent - // for the initial x seconds and then we start using SSRC only instead. - if let Some(r) = self.rx_lookup.get_mut(&ssrc) { - r.last_used = now; - return Some((r.mid, r.main)); - } - - let maybe_stream = self.stream_rx_by_ssrc_or_rtx(ssrc); - if let Some(stream) = maybe_stream { - let mid = stream.mid(); - let ssrc_main = stream.ssrc(); - - self.rx_lookup.insert( - ssrc, - RxLookup { - mid, - main: ssrc_main, - last_used: now, - }, - ); - - return Some((mid, ssrc_main)); - } - - None - } - - pub(crate) fn regular_feedback_at(&self, i: RtcpReportIntervals) -> Option { - let r = self - .streams_rx - .values() - .filter(|s| !s.ssrc().is_probe()) - .map(|s| s.receiver_report_at(i)); - let s = self.streams_tx.values().map(|s| s.sender_report_at(i)); - r.chain(s).min() - } - - pub(crate) fn paused_at(&self) -> Option { - self.streams_rx.values().find_map(|s| s.paused_at()) - } - - pub(crate) fn send_stream(&self) -> Option { - if self.streams_tx.values().any(|s| s.need_timeout()) { - Some(already_happened()) - } else { - None - } - } - - pub(crate) fn pending_request(&self) -> Option { - if self.streams_rx.values().any(|s| s.has_pending_request()) { - Some(already_happened()) - } else { - None - } - } - - pub(crate) fn handle_timeout( - &mut self, - now: Instant, - sender_ssrc: Ssrc, - do_nack: bool, - medias: &[Media], - intervals: RtcpReportIntervals, - feedback: &mut VecDeque, - ) { - self.mids_to_report.clear(); // Clear for checking StreamRx. - for stream in self.streams_rx.values() { - if stream.need_rr(now, intervals) { - self.mids_to_report.push(stream.mid()); - } - } - - for stream in self.streams_rx.values_mut() { - stream.maybe_create_keyframe_request(sender_ssrc, feedback); - stream.maybe_create_remb_request(sender_ssrc, feedback); - - // All StreamRx belonging to the same Mid are reported together. - if self.mids_to_report.contains(&stream.mid()) { - stream.create_rr_and_update(now, sender_ssrc, feedback); - } - - if do_nack { - stream.maybe_create_nack(now, sender_ssrc, feedback); - } - - stream.handle_timeout(now); - } - - self.mids_to_report.clear(); // start over for StreamTx. - for stream in self.streams_tx.values() { - if stream.need_sr(now, intervals) { - self.mids_to_report.push(stream.mid()); - } - } - - for stream in self.streams_tx.values_mut() { - let mid = stream.mid(); - - // All StreamTx belonging to the same Mid are reported together. - if self.mids_to_report.contains(&mid) { - stream.create_sr_and_update(now, feedback); - } - - // Finding the Media is only needed on the first timeout. - // The unwrap is okay because we cannot have StreamTx with a Mid without the corresponding Media. - let get_media = move || medias.iter().find(|m| m.mid() == mid).unwrap(); - - stream.handle_timeout(now, get_media); - } - - if now > self.rx_lookup_at() { - self.rx_lookup.retain(|_, l| now - l.last_used <= RX_LOOKUP_EXPIRY); - self.last_rx_lookup_cleanup = now; - } - } - - pub(crate) fn poll_keyframe_request(&mut self) -> Option { - self.streams_tx.values_mut().find_map(|s| { - let kind = s.poll_keyframe_request()?; - Some(KeyframeRequest { - mid: s.mid(), - rid: s.rid(), - kind, - }) - }) - } - - pub(crate) fn poll_sender_feedback(&mut self) -> Option { - self.streams_rx.values_mut().find_map(|s| { - let (sender_info, at) = s.poll_sender_info()?; - - Some(SenderFeedback { - mid: s.mid(), - rid: s.rid(), - received_at: at, - sender_info, - }) - }) - } - - pub(crate) fn poll_remb_request(&mut self) -> Option<(Mid, Bitrate)> { - self.streams_tx - .values_mut() - .find_map(|s| s.poll_remb_request().map(|b| (s.mid(), b))) - } - - pub(crate) fn poll_stream_paused(&mut self) -> Option { - self.streams_rx.values_mut().find_map(|s| s.poll_paused()) - } - - pub(crate) fn has_stream_rx(&self, ssrc: Ssrc) -> bool { - self.streams_rx.contains_key(&ssrc) - } - - pub(crate) fn has_stream_tx(&self, ssrc: Ssrc) -> bool { - self.streams_tx.contains_key(&ssrc) - } - - pub(crate) fn handle_dlrr(&mut self, now: Instant, dlrr: DlrrItem) { - let is_default_ssrc = !self.default_ssrc_tx.is_probe() && dlrr.ssrc == self.default_ssrc_tx; - if !is_default_ssrc && !self.has_stream_tx(dlrr.ssrc) { - trace!("Ignoring DLRR for unknown local SSRC: {}", dlrr.ssrc); - return; - } - - // DLRR identifies our RRTR sender, not a remote media SSRC. The measured - // round trip is shared by receive streams on this peer's transport. - for stream in self.streams_rx.values_mut() { - stream.handle_rtcp(now, RtcpFb::DlrrItem(dlrr)); - } - } - - pub(crate) fn streams_rx(&mut self) -> impl Iterator { - self.streams_rx.values_mut() - } - - pub(crate) fn streams_tx(&mut self) -> impl Iterator { - self.streams_tx.values_mut() - } - - pub(crate) fn ssrcs_tx(&self, mid: Mid) -> Vec<(Ssrc, Option)> { - self.streams_tx - .values() - .filter(|s| s.mid() == mid) - .map(|s| (s.ssrc(), s.rtx())) - .collect() - } - - pub(crate) fn new_ssrc(&self) -> Ssrc { - loop { - // This new guarantees we never get SSRC 0 (reserved for BWE probes) - let ssrc = Ssrc::new(); - - let has_ssrc = self.has_stream_rx(ssrc) || self.has_stream_tx(ssrc); - - if has_ssrc { - continue; - } - - // Need to check RTX as well. - let has_rtx_rx = self.streams_rx.values().any(|s| s.rtx() == Some(ssrc)); - if has_rtx_rx { - continue; - } - - let has_rtx_tx = self.streams_tx.values().any(|s| s.rtx() == Some(ssrc)); - if has_rtx_tx { - continue; - } - - // Not used - break ssrc; - } - } - - pub fn new_ssrc_pair(&self) -> (Ssrc, Ssrc) { - let ssrc = self.new_ssrc(); - - let rtx = loop { - let proposed = self.new_ssrc(); - // Avoid clashing with just allocated main SSRC. - if proposed != ssrc { - break proposed; - } - }; - - (ssrc, rtx) - } - - pub(crate) fn first_ssrc_remote(&self) -> Ssrc { - *self.streams_rx.keys().next().unwrap_or(&0.into()) - } - - pub(crate) fn first_ssrc_local(&mut self) -> Ssrc { - if let Some(ssrc) = self.streams_tx.keys().next() { - // If there is some local Tx SSRC, use that. - *ssrc - } else { - // Fallback in case we don't have any Tx SSRC. - if *self.default_ssrc_tx == 0 { - // Do not use 0, allocate one that is not in session already. - self.default_ssrc_tx = self.new_ssrc(); - } - self.default_ssrc_tx - } - } - - pub(crate) fn send_queue_states(&mut self, now: Instant) -> impl Iterator { - self.streams_tx.values_mut().map(move |stream| stream.queue_state(now)) - } - - pub(crate) fn stream_tx_by_midrid(&mut self, midrid: MidRid) -> Option<&mut StreamTx> { - self.streams_tx.values_mut().find(|s| s.is_midrid(midrid)) - } - - pub(crate) fn stream_rx_by_midrid(&mut self, midrid: MidRid) -> Option<&mut StreamRx> { - self.streams_rx.values_mut().find(|s| s.is_midrid(midrid)) - } - - pub(crate) fn remove_streams_by_mid(&mut self, mid: Mid) { - self.streams_tx.retain(|_, s| s.mid() != mid); - self.streams_rx.retain(|_, s| s.mid() != mid); - self.rx_lookup.retain(|_, v| v.mid != mid); - } - - /// An iterator over all the tx streams for a given mid. - pub(crate) fn streams_tx_by_mid(&mut self, mid: Mid) -> impl Iterator { - self.streams_tx.values_mut().filter(move |s| s.mid() == mid) - } - - /// An iterator over all the rx streams for a given mid. - pub(crate) fn streams_rx_by_mid(&mut self, mid: Mid) -> impl Iterator { - self.streams_rx.values_mut().filter(move |s| s.mid() == mid) - } - - pub(crate) fn reset_buffers_tx(&mut self, mid: Mid) { - for s in self.streams_tx_by_mid(mid) { - s.reset_buffers(); - } - } - - pub(crate) fn reset_buffers_rx(&mut self, mid: Mid, max_seq_lookup: impl Fn(Ssrc) -> Option) { - for s in self.streams_rx_by_mid(mid) { - s.reset_buffers(&max_seq_lookup); - } - } - - pub(crate) fn change_stream_rx_ssrc(&mut self, ssrc_from: Ssrc, ssrc_to: Ssrc) -> bool { - // This unwrap is OK, because we can't call change_stream_rx_ssrc without first - // knowing there is such a StreamRx. - let maybe_change = self.streams_rx.get_mut(&ssrc_from).unwrap(); - - // The StreamRx is allowed to not change the SSRC in case it is switching back - // to the previous SSRC. This is to avoid flapping in case RTP packets arrive - // out of order. - let did_change = maybe_change.change_ssrc(ssrc_to); - - if did_change { - // Unwrap is OK, see above. - let to_change = self.streams_rx.remove(&ssrc_from).unwrap(); - - // Reinsert under new SSRC key. - self.streams_rx.insert(ssrc_to, to_change); - - // Remove previous mappings for the SSRC - self.rx_lookup.retain(|k, l| *k != ssrc_from && l.main != ssrc_from); - } - - did_change - } - - fn change_stream_rx_rtx(&mut self, rtx_from: Ssrc, rtx_to: Ssrc) { - // Remove the SSRC mapping - self.rx_lookup.remove(&rtx_from); - - let Some(to_change) = self.streams_rx.values_mut().find(|s| s.rtx() == Some(rtx_from)) else { - // If there's no main stream associated with the RTX our job is done. - return; - }; - - to_change.maybe_reset_rtx(rtx_to); - } - - fn stream_rx_by_ssrc_or_rtx(&self, ssrc: Ssrc) -> Option<&StreamRx> { - self.streams_rx - .values() - .find(|s| s.ssrc() == ssrc || s.rtx() == Some(ssrc)) - } - - /// Whether any receive stream currently needs NACK reports (see [`StreamRx::nack_enabled`]). - /// - /// Not cached: the answer changes with pause state and pending NACK retries. - pub(crate) fn any_nack_enabled(&self) -> bool { - self.streams_rx.values().any(|s| s.nack_enabled()) - } - - fn rx_lookup_at(&self) -> Instant { - self.last_rx_lookup_cleanup + RX_LOOKUP_CLEANUP_INTERVAL - } -} - -impl fmt::Debug for RtpPacket { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RtpPacket") - .field("seq_no", &self.seq_no) - .field("time", &self.time) - .field("header", &self.header) - .field("payload", &self.payload.len()) - .field("nackable", &self.nackable) - .field("timestamp", &self.timestamp) - .finish() - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/receive.rs b/rs/moq-webrtc/src/vendor/str0m/streams/receive.rs deleted file mode 100644 index 11b13bfac22..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/receive.rs +++ /dev/null @@ -1,1098 +0,0 @@ -use std::collections::VecDeque; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tracing::{debug, trace}; - -use crate::vendor::str0m::config_mod::RtcpReportIntervals; -use crate::vendor::str0m::media::KeyframeRequestKind; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::SeqNoWindow; -use crate::vendor::str0m::rtp_::{Bitrate, DlrrItem, ExtendedReport, extend_u32}; -use crate::vendor::str0m::rtp_::{Fir, FirEntry, Frequency, MediaTime, Remb}; -use crate::vendor::str0m::rtp_::{Mid, Pli, Pt, ReceiverReport}; -use crate::vendor::str0m::rtp_::{ReportBlock, ReportList, Rid, Rrtr, Rtcp}; -use crate::vendor::str0m::rtp_::{RtcpFb, RtpHeader, SenderInfo, SeqNo}; -use crate::vendor::str0m::rtp_::{SdesType, Ssrc}; -use crate::vendor::str0m::util::{InstantExt, SystemTimeExt}; -use crate::vendor::str0m::util::{already_happened, calculate_rtt}; - -use super::RtpPacket; -use super::StreamPaused; -use super::register::ReceiverRegister; - -/// Incoming encoded stream. -/// -/// A stream is a primary SSRC + optional RTX SSRC. -/// -/// This is RTP level API. For frame level API see [`Rtc::writer`][crate::vendor::str0m::Rtc::writer]. -#[derive(Debug)] -pub struct StreamRx { - /// Unique idenfier of the remote stream. - /// - /// If the remote changes the SSRC, we will create a new stream, not change this id. - ssrc: Ssrc, - - /// Identifier of a resend (RTX) stream. This can be set later, once we discover it. - rtx: Option, - - /// Previous main SSRC. This is to ensure we never go "backwards" in terms - /// of changing SSRC (for FF). - previous_ssrc: Option, - - /// The Media mid/rid this stream belongs to. - midrid: MidRid, - - /// Incoming CNAME in Sdes reports. - cname: Option, - - /// Whether we explicitly want to supress NACK sending. This is normally done by not - /// setting an RTX, however this can be toggled off manually despite RTX being there. - /// - /// This is also set to true if the SDP negotiation disables RTX. - /// - /// Defaults to false. - suppress_nack: bool, - - /// Timestamp when we got some indication of remote using this stream. - last_used: Instant, - - /// Last seen pt and clock_rate in - last_clock_rate: Option<(Pt, Frequency)>, - - /// Last received sender info. - sender_info: Option, - - /// ROC to reset with on next incoming packet. - reset_roc: Option, - - /// Register of received packets. For NACK handling. - /// - /// Set on first ever packet. - register: Option, - - /// Sequence and replay tracking for RTX. NACKs and reception reports use the main register. - /// - /// Set on the first authenticated RTX packet or restored from remembered sequence history. - register_rtx: Option, - - /// Last observed media time in an RTP packet. - last_time: Option, - - /// If we have a pending keyframe request to send. - pending_request_keyframe: Option, - - /// If we have a pending REMB request to send. - pending_request_remb: Option, - - /// Sequence number of the next FIR. - fir_seq_no: u8, - - /// Last time we produced regular feedback RR. - last_receiver_report: Instant, - - /// Statistics of incoming data. - stats: StreamRxStats, - - /// When we need to evaluate the paused state. - /// - /// now + pause_threshold - check_paused_at: Option, - - /// Whether we consider this StreamRx paused. - /// - /// A stream is considered paused if it has received no packets for some (configurable) duration. - /// This defaults to 1.5s. - paused: bool, - - /// Whether we need to emit a paused event for the current paused state. - need_paused_event: bool, - - /// The configured threshold before considering the lack of packets as going into paused. - pause_threshold: Duration, -} - -/// The last sender info we recieved. -#[derive(Debug)] -pub(crate) struct LastSenderInfo { - /// When this SenderInfo was received. - received_at: Instant, - /// The sender info itself. - info: SenderInfo, - /// Whether we have emitted it yet via `poll_sender_info` - emitted: bool, -} - -/// Holder of stats. -#[derive(Debug, Default)] -pub(crate) struct StreamRxStats { - /// count of bytes received, including retransmissions - bytes: u64, - /// count of packets received, including retransmissions - packets: u64, - /// count of FIR requests sent - firs: u64, - /// count of PLI requests sent - plis: u64, - /// count of NACKs sent - nacks: u64, - /// interarrival jitter (RTP timestamp units) from the last RR we sent - jitter: u32, - /// round trip time from the last DLRR, if any - rtt: Option, - /// fraction of packets lost from the last RR, if any - loss: Option, -} - -impl StreamRx { - pub(crate) fn new(ssrc: Ssrc, midrid: MidRid, suppress_nack: bool, pause_threshold: Duration) -> Self { - debug!("Create StreamRx for SSRC: {}", ssrc); - - StreamRx { - ssrc, - rtx: None, - previous_ssrc: None, - midrid, - cname: None, - suppress_nack, - last_used: already_happened(), - last_clock_rate: None, - sender_info: None, - reset_roc: None, - register: None, - register_rtx: None, - last_time: None, - pending_request_keyframe: None, - pending_request_remb: None, - fir_seq_no: 0, - last_receiver_report: already_happened(), - stats: StreamRxStats::default(), - check_paused_at: None, - paused: true, - need_paused_event: false, - pause_threshold, - } - } - - /// The (primary) SSRC of this encoded stream. - pub fn ssrc(&self) -> Ssrc { - self.ssrc - } - - /// The resend (RTX) SSRC of this encoded stream. - pub fn rtx(&self) -> Option { - self.rtx - } - - /// Mid for this stream. - /// - /// In SDP this corresponds to m-line and "Media". - pub fn mid(&self) -> Mid { - self.midrid.mid() - } - - /// Rid for this stream. - /// - /// This is used to separate streams with the same [`Mid`] when using simulcast. - pub fn rid(&self) -> Option { - self.midrid.rid() - } - - /// CNAME as sent by remote peer in a Sdes. - /// - /// The value is None until we receive a first report with the value set. - pub fn cname(&self) -> Option<&str> { - self.cname.as_deref() - } - - /// Set threshold duration for emitting the paused event. - /// - /// This event is emitted when no packet have received for this duration. - pub fn set_pause_threshold(&mut self, t: Duration) { - self.pause_threshold = t; - } - - /// The last time we received a packet. - /// - /// Resets if the SSRC changes. - pub fn last_time(&self) -> Option { - self.last_time - } - - /// Request a keyframe for an incoming encoded stream. - /// - /// * SSRC the identifier of the remote encoded stream to request a keyframe for. - /// * kind PLI or FIR. - pub fn request_keyframe(&mut self, kind: KeyframeRequestKind) { - self.pending_request_keyframe = Some(kind); - } - - /// Request max recv bitrate for an incoming encoded stream. - /// - /// * bitrate Bitrate. - pub fn request_remb(&mut self, bitrate: Bitrate) { - self.pending_request_remb = Some(bitrate); - } - - /// Suppress NACK sending. - /// - /// Normally NACK is disabled by not having an RTX SSRC set. In some situations it might be - /// desirable to manually suppress NACK sending regardless of RTX setting. - pub fn suppress_nack(&mut self, suppress: bool) { - self.suppress_nack = suppress; - } - - fn is_audio(&self) -> bool { - self.rtx.is_none() // this is maybe not correct, but it's all we got. - } - - pub(crate) fn receiver_report_at(&self, intervals: RtcpReportIntervals) -> Instant { - self.last_receiver_report + intervals.for_audio(self.is_audio()) - } - - pub(crate) fn handle_rtcp(&mut self, now: Instant, fb: RtcpFb) { - use RtcpFb::*; - match fb { - SenderInfo(v) => { - self.set_sender_info(now, v); - } - SourceDescription(v) => { - for (sdes, st) in v.values { - if sdes == SdesType::CNAME { - if st.is_empty() { - // In simulcast, chrome doesn't send the SSRC lines, but - // expects us to infer that from rtp headers. It does - // however send the SourceDescription RTCP with an empty - // string CNAME. ¯\_(ツ)_/¯ - return; - } - - // Here we _could_ check CNAME here matches something. But - // CNAMEs are a bit unfashionable. - self.cname = Some(st); - return; - } - } - } - DlrrItem(v) => { - self.set_dlrr_item(now, v); - } - Goodbye(_v) => { - // We get Goodbye at weird times, like SDP renegotiation, which makes - // pausing on the BYE not a good idea. Chrome also reuses the SSRC it - // just sent BYE on. Very not helpful. - } - _ => {} - } - } - - fn set_sender_info(&mut self, now: Instant, mut info: SenderInfo) { - // Extend the incoming time given our knowledge of last time. - let extended = { - let prev = self.sender_info.as_ref().map(|last| last.info.rtp_time.numer()); - let r_u32 = info.rtp_time.numer() as u32; - extend_u32(prev, r_u32) - }; - - // The MediaTime has a base 1 after being parsed. At this point - // we know whether it's audio or video and set the base accordingly. - let clock_rate = self.last_clock_rate.map(|(_, r)| r).unwrap_or(Frequency::SECONDS); - - // Clock rate is that of the last received packet. - info.rtp_time = MediaTime::new(extended, clock_rate); - - self.sender_info = Some(LastSenderInfo { - received_at: now, - info, - emitted: false, - }); - } - - fn set_dlrr_item(&mut self, now: Instant, dlrr: DlrrItem) { - let ntp_time = now.to_ntp_duration(); - let rtt = calculate_rtt(ntp_time, dlrr.last_rr_delay, dlrr.last_rr_time); - self.stats.rtt = rtt; - } - - pub(crate) fn paused_at(&self) -> Option { - self.check_paused_at - } - - pub(crate) fn has_pending_request(&self) -> bool { - self.pending_request_keyframe.is_some() || self.pending_request_remb.is_some() - } - - pub(crate) fn handle_timeout(&mut self, now: Instant) { - // No scheduled paused check? - if self.check_paused_at.is_none() { - return; - } - - // Not reached scheduled paused check? - if Some(now) < self.check_paused_at { - return; - } - - // Every update() schedules a paused check in the future. If we have reached that - // future we have implicitly also paused. - self.check_paused_at = None; - - self.paused = true; - self.need_paused_event = true; - } - - pub(crate) fn extend_seq( - &mut self, - header: &RtpHeader, - is_repair: bool, - max_seq_lookup: impl Fn(Ssrc) -> Option, - ) -> SeqNo { - // RTX has its own sequence series and only needs a replay window. - if is_repair { - if self.register_rtx.is_none() { - self.register_rtx = max_seq_lookup(header.ssrc).map(SeqNoWindow::new_after); - } - return header.sequence_number(self.register_rtx.as_ref().map(|r| r.max_seq())); - } - - let register = self - .register - .get_or_insert_with(|| ReceiverRegister::new(max_seq_lookup(header.ssrc))); - - // If the user has called `reset_seq_no`, this is the time to handle it, but only - // if the incoming packet is for main (not repair). - let mut reset_seq_no = None; - if let Some(reset_roc) = self.reset_roc.take() { - let s: SeqNo = (reset_roc << 16 | header.sequence_number as u64).into(); - reset_seq_no = Some(s); - } - - if let Some(reset_seq_no) = reset_seq_no { - reset_seq_no - } else { - header.sequence_number(register.max_seq()) - } - } - - pub(crate) fn is_new_packet(&self, is_repair: bool, seq_no: SeqNo) -> bool { - if is_repair { - self.register_rtx.as_ref().is_none_or(|r| r.accepts(seq_no)) - } else { - // extend_seq() initializes the main register before this check. - self.register.as_ref().unwrap().accepts(seq_no) - } - } - - pub(crate) fn update_register( - &mut self, - now: Instant, - header: &RtpHeader, - clock_rate: Frequency, - is_repair: bool, - seq_no: SeqNo, - ) -> RegisterUpdateReceipt { - self.last_used = now; - - let was_paused = self.paused; - if was_paused { - self.paused = false; - self.need_paused_event = true; - } - self.check_paused_at = Some(now + self.pause_threshold); - - let is_new_packet = if is_repair { - let is_new = self.is_new_packet(true, seq_no); - self.register_rtx - .get_or_insert_with(|| SeqNoWindow::new(seq_no)) - .update(seq_no); - is_new - } else { - // extend_seq() initializes the main register before this update. - self.register - .as_mut() - .unwrap() - .update(seq_no, now, header.timestamp, clock_rate.get()) - }; - - // Get the previous time for comparison - let previous_time = self.last_time.map(|t| t.numer()); - - // Calculate the extended timestamp - let mut time_u32 = extend_u32(previous_time, header.timestamp); - - if was_paused && Some(time_u32) < previous_time { - // In 32-bit RTP timestamps, adding 2^31 (MAX/2) flips to the other half of timestamp space - // This forces extend_u32 to produce a value in the next cycle - const HALF_CYCLE: u32 = 1u32 << 31; - let adjusted_ts = header.timestamp.wrapping_add(HALF_CYCLE); - - // Recalculate extended timestamp with adjusted value - let adjusted_time_u32 = extend_u32(previous_time, adjusted_ts); - - // If this adjusted timestamp moves time forward, use it - if adjusted_time_u32 > previous_time.unwrap() { - time_u32 = adjusted_time_u32; - } else { - // Fallback - time_u32 = header.timestamp as u64; - } - } - - let time = MediaTime::new(time_u32, clock_rate); - - if !is_repair { - self.last_time = Some(time); - } - - RegisterUpdateReceipt { time, is_new_packet } - } - - #[allow(clippy::too_many_arguments)] - pub(crate) fn handle_rtp( - &mut self, - now: Instant, - header: RtpHeader, - payload: Arc<[u8]>, - seq_no: SeqNo, - time: MediaTime, - wire_payload_len: usize, - ) -> RtpPacket { - let packet = self.make_rtp_packet(now, header, payload, seq_no, time); - - // `payload` may be narrower than what was on the wire (RED unwrapped to its primary - // block); count what was received, matching the sender's egress accounting. - self.stats.bytes += wire_payload_len as u64; - self.stats.packets += 1; - - packet - } - - /// Build an [`RtpPacket`] WITHOUT counting it in receive stats. Used for RFC 2198 - /// FEC-recovered packets, which were never received on the wire (the carrying packet's - /// bytes are already counted by `handle_rtp`). - pub(crate) fn make_rtp_packet( - &mut self, - now: Instant, - header: RtpHeader, - payload: Arc<[u8]>, - seq_no: SeqNo, - time: MediaTime, - ) -> RtpPacket { - trace!("Handle RTP: {:?}", header); - - let need_clock_rate = self.last_clock_rate.map(|(pt, _)| pt) != Some(header.payload_type); - if need_clock_rate { - self.last_clock_rate = Some((header.payload_type, time.frequency())); - - // If we get an SR before the first packet, we update the potential clock rate. - if let Some(i) = &mut self.sender_info { - i.info.rtp_time = MediaTime::new(i.info.rtp_time.numer(), time.frequency()); - } - } - - RtpPacket { - seq_no, - time, - header, - payload, - vp8_patch: None, - nackable: false, - last_sender_info: self.sender_info.as_ref().map(|l| l.info), - timestamp: now, - } - } - - /// Rewrites the header to be the un-RTX'd original packet, and returns - /// `data` with the original sequence number prefix stripped. - pub(crate) fn un_rtx<'a>(&self, header: &mut RtpHeader, data: &'a [u8], pt: Pt) -> &'a [u8] { - let mut orig_seq_no_16 = 0; - - let n = RtpHeader::read_original_sequence_number(data, &mut orig_seq_no_16); - - trace!("Repaired seq no {} -> {}", header.sequence_number, orig_seq_no_16); - - header.sequence_number = orig_seq_no_16; - - header.ssrc = self.ssrc; - header.payload_type = pt; - header.ext_vals.rid = header.ext_vals.rid_repair.take(); - - &data[n..] - } - - pub(crate) fn maybe_create_keyframe_request(&mut self, sender_ssrc: Ssrc, feedback: &mut VecDeque) { - let Some(kind) = self.pending_request_keyframe.take() else { - return; - }; - - let ssrc = self.ssrc; - - match kind { - KeyframeRequestKind::Pli => { - self.stats.plis += 1; - feedback.push_back(Rtcp::Pli(Pli { sender_ssrc, ssrc })) - } - KeyframeRequestKind::Fir => { - self.stats.firs += 1; - feedback.push_back(Rtcp::Fir(Fir { - sender_ssrc, - reports: FirEntry { - ssrc, - seq_no: self.next_fir_seq_no(), - } - .into(), - })) - } - } - } - - pub(crate) fn maybe_create_remb_request(&mut self, sender_ssrc: Ssrc, feedback: &mut VecDeque) { - let Some(bitrate) = self.pending_request_remb.take() else { - return; - }; - - feedback.push_back(Rtcp::Remb(Remb { - sender_ssrc, - ssrc: 0.into(), - bitrate: bitrate.as_f64() as f32, - ssrcs: vec![*self.ssrc], - })) - } - - fn next_fir_seq_no(&mut self) -> u8 { - let x = self.fir_seq_no; - self.fir_seq_no = self.fir_seq_no.wrapping_add(1); - x - } - - pub(crate) fn need_rr(&self, now: Instant, intervals: RtcpReportIntervals) -> bool { - if self.ssrc.is_probe() { - return false; - } - - now >= self.receiver_report_at(intervals) - } - - pub(crate) fn create_rr_and_update(&mut self, now: Instant, sender_ssrc: Ssrc, feedback: &mut VecDeque) { - let mut rr = self.create_receiver_report(now); - rr.sender_ssrc = sender_ssrc; - - if !rr.reports.is_empty() { - let report = &rr.reports[rr.reports.len() - 1]; - self.stats.update_loss(report.fraction_lost); - self.stats.jitter = report.jitter; - } - - let xr = self.create_extended_receiver_report(now, sender_ssrc); - - trace!("Created feedback RR/XR ({:?}): {:?} {:?}", self.midrid, rr, xr); - feedback.push_back(Rtcp::ReceiverReport(rr)); - feedback.push_back(Rtcp::ExtendedReport(xr)); - - self.last_receiver_report = now; - } - - fn create_receiver_report(&mut self, now: Instant) -> ReceiverReport { - let Some(mut report) = self.register.as_mut().and_then(|r| r.reception_report()) else { - return ReceiverReport { - sender_ssrc: 0.into(), // set one level up - reports: ReportList::new(), - }; - }; - report.ssrc = self.ssrc; - - // The middle 32 bits out of 64 in the NTP timestamp (as explained in - // Section 4) received as part of the most recent RTCP sender report - // (SR) packet from source SSRC_n. If no SR has been received yet, - // the field is set to zero. - report.last_sr_time = { - let t64 = self.sender_info.as_ref().map_or(0u64, |l| l.info.ntp_time.as_ntp_64()); - - (t64 >> 16) as u32 - }; - - // The delay, expressed in units of 1/65_536 seconds, between - // receiving the last SR packet from source SSRC_n and sending this - // reception report block. If no SR packet has been received yet - // from SSRC_n, the DLSR field is set to zero. - report.last_sr_delay = if let Some(l) = self.sender_info.as_ref() { - let t = l.received_at; - let delay = now - t; - ((delay.as_micros() * 65_536) / 1_000_000) as u32 - } else { - 0 - }; - - ReceiverReport { - sender_ssrc: 0.into(), // set one level up - reports: report.into(), - } - } - - fn create_extended_receiver_report(&self, now: Instant, sender_ssrc: Ssrc) -> ExtendedReport { - // we only want to report our time to measure RTT, - // the source will answer with Dlrr feedback, allowing us to calculate RTT - let block = ReportBlock::Rrtr(Rrtr { - ntp_time: now.to_system_time(), - }); - ExtendedReport { - ssrc: sender_ssrc, - blocks: vec![block], - } - } - - pub(crate) fn recovery_deadline(&self, range: std::ops::Range, received: Instant) -> Option { - if !self.suppress_nack { - if let Some(register) = &self.register { - return register.recovery_deadline(range, received, self.stats.rtt); - } - } - let rtt = self.stats.rtt.unwrap_or(super::register_nack::DEFAULT_RTT); - received.checked_add(rtt.saturating_mul(3)) - } - - /// Whether this stream should keep its NACK timer active. - /// - /// Paused streams finish pending retries before disabling NACK reports. - pub(crate) fn nack_enabled(&self) -> bool { - // Deliberately don't look at RTX is_some() here, since when using dynamic SSRC, we might need - // to send NACK before discovering the remote RTX. - if self.suppress_nack { - return false; - } - - if !self.paused { - return true; - } - - let Some(register) = &self.register else { - return false; - }; - - register.has_pending_nacks() - } - - pub(crate) fn maybe_create_nack( - &mut self, - now: Instant, - sender_ssrc: Ssrc, - feedback: &mut VecDeque, - ) -> Option<()> { - if !self.nack_enabled() { - return None; - } - - let nacks = self - .register - .as_mut() - .and_then(|r| r.nack_report(now, self.stats.rtt))?; - - for mut nack in nacks { - nack.sender_ssrc = sender_ssrc; - nack.ssrc = self.ssrc; - - trace!("Created feedback NACK: {:?}", nack); - feedback.push_back(Rtcp::Nack(nack)); - self.stats.nacks += 1; - } - - Some(()) - } - - pub(crate) fn poll_paused(&mut self) -> Option { - if self.ssrc.is_probe() { - return None; - } - - if !self.need_paused_event { - return None; - } - - self.need_paused_event = false; - - debug!( - "{} StreamRx with {:?} and SSRC: {}", - if self.paused { "Paused" } else { "Unpaused" }, - self.midrid, - self.ssrc - ); - - Some(StreamPaused { - ssrc: self.ssrc, - mid: self.midrid.mid(), - rid: self.midrid.rid(), - paused: self.paused, - }) - } - - /// Poll the most recent sender info and when it was received - pub(crate) fn poll_sender_info(&mut self) -> Option<(SenderInfo, Instant)> { - let i = self.sender_info.as_mut()?; - if i.emitted { - return None; - } - - i.emitted = true; - - Some((i.info, i.received_at)) - } - - pub(crate) fn reset_buffers(&mut self, max_seq_lookup: impl Fn(Ssrc) -> Option) { - if let Some(r) = &mut self.register { - r.clear(max_seq_lookup(self.ssrc)); - } - - if self.register_rtx.is_some() { - self.register_rtx = self.rtx.and_then(max_seq_lookup).map(SeqNoWindow::new_after); - } - self.pending_request_keyframe = None; - } - - #[must_use] - pub(crate) fn change_ssrc(&mut self, ssrc: Ssrc) -> bool { - // Avoid flapping - if ssrc == self.ssrc || Some(ssrc) == self.previous_ssrc { - return false; - } - - debug!("Change main SSRC: {} -> {} {:?}", self.ssrc, ssrc, self.midrid); - - // Remember which was the previous in case a stray packet turns up - // so do we don't go "backwards". - self.previous_ssrc = Some(self.ssrc); - self.ssrc = ssrc; - - // Reset all SSRC-specific state - self.register = None; - self.last_time = None; - self.last_clock_rate = None; - self.sender_info = None; - self.last_receiver_report = already_happened(); - self.fir_seq_no = 0; - self.pending_request_keyframe = None; - self.pending_request_remb = None; - self.reset_roc = None; - - // Note: We don't reset the RTX register here, as the RTX SSRC is managed separately - // via maybe_reset_rtx() and is not directly tied to the main SSRC change. - - true - } - - pub(crate) fn maybe_reset_rtx(&mut self, rtx: Ssrc) { - if let Some(current) = self.rtx { - if current == rtx { - return; - } - - debug!( - "Change RTX SSRC {} -> {} for main SSRC: {} {:?}", - current, rtx, self.ssrc, self.midrid - ); - } else { - debug!("SSRC {} associated with RTX: {}", self.ssrc, rtx); - } - - self.rtx = Some(rtx); - self.register_rtx = None; - } - - /// Reset the current rollover counter (ROC). - /// - /// This is used in scenarios where we use a single sequence number across all - /// receivers of the same stream (as opposed to a sequence number unique per peer). - /// - /// The ROC is not carried in the RTP header. Obtain it through out-of-band - /// signaling and call this before handling the first SRTP packet for the stream. - /// See [`RtpWrite::new`][crate::vendor::str0m::rtp::RtpWrite::new] for sender and receiver examples. - /// - /// [RFC3711](https://datatracker.ietf.org/doc/html/rfc3711#section-3.3.1): - /// - /// > Receivers joining an on-going session MUST be given the - /// > current ROC value using out-of-band signaling such as key-management - /// > signaling. Furthermore, the receiver SHALL initialize s_l to the RTP - /// > sequence number (SEQ) of the first observed SRTP packet (unless the - /// > initial value is provided by out of band signaling such as key - /// > management). - pub fn reset_roc(&mut self, roc: u64) { - self.register = None; - self.register_rtx = None; - self.reset_roc = Some(roc); - } - - pub(crate) fn is_midrid(&self, midrid: MidRid) -> bool { - midrid.special_equals(&self.midrid) - } -} - -impl StreamRxStats { - fn update_loss(&mut self, fraction_lost: u8) { - self.loss = Some(fraction_lost as f32 / u8::MAX as f32) - } -} - -#[derive(Debug, Clone, Copy)] -pub(crate) struct RegisterUpdateReceipt { - pub time: MediaTime, - pub is_new_packet: bool, -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn paused_timestamp_repair_moves_time_forward() { - let now = already_happened(); - let mut stream = StreamRx::new(7.into(), MidRid("mid".into(), None), false, Duration::from_millis(1500)); - let previous_time = 1; - stream.last_time = Some(MediaTime::new(previous_time, Frequency::NINETY_KHZ)); - stream.paused = true; - - let header = RtpHeader { - payload_type: Pt::new_with_value(96), - sequence_number: 42, - timestamp: 0, - ssrc: 7.into(), - ..Default::default() - }; - - let seq_no = stream.extend_seq(&header, false, |_| None); - let receipt = stream.update_register(now, &header, Frequency::NINETY_KHZ, false, seq_no); - - assert!( - receipt.time.numer() > previous_time, - "expected repaired media time to move forward" - ); - assert!(!stream.paused); - } - - /// Feed packets `(seq, rtp_time)` into a fresh stream, as received on the wire. - fn stream_with(packets: &[(u16, u32)]) -> StreamRx { - let now = already_happened(); - let mut stream = StreamRx::new(7.into(), MidRid("mid".into(), None), false, Duration::from_millis(1500)); - for (seq, ts) in packets { - let header = RtpHeader { - payload_type: Pt::new_with_value(111), - sequence_number: *seq, - timestamp: *ts, - ssrc: 7.into(), - ..Default::default() - }; - let seq_no = stream.extend_seq(&header, false, |_| None); - stream.update_register(now, &header, Frequency::FORTY_EIGHT_KHZ, false, seq_no); - } - stream - } - - #[test] - fn dlrr_for_local_ssrc_updates_receive_streams() { - let mut streams = crate::vendor::str0m::streams::Streams::new(Duration::from_millis(1500)); - for (ssrc, mid) in [(7, "video"), (8, "audio")] { - streams.expect_stream_rx(ssrc.into(), None, MidRid(mid.into(), None), false); - } - let default_ssrc = streams.first_ssrc_local(); - streams.declare_stream_tx(9.into(), None, MidRid("send".into(), None)); - let now = Instant::now(); - let last_rr_time = ((now - Duration::from_millis(250)).to_system_time().as_ntp_64() >> 16) as u32; - - // Ignore a sub-block addressed to the remote media source instead of us. - streams.handle_dlrr( - now, - DlrrItem { - ssrc: 7.into(), - last_rr_time, - last_rr_delay: 3276, - }, - ); - assert_eq!(streams.stream_rx(&7.into()).unwrap().stats.rtt, None); - - // Accept both an active sender and the fallback SSRC used before it existed. - for local_ssrc in [9.into(), default_ssrc] { - for ssrc in [7, 8] { - streams.stream_rx(&ssrc.into()).unwrap().stats.rtt = None; - } - streams.handle_dlrr( - now, - DlrrItem { - ssrc: local_ssrc, - last_rr_time, - last_rr_delay: 3276, - }, - ); - for ssrc in [7, 8] { - let rtt = streams.stream_rx(&ssrc.into()).unwrap().stats.rtt.unwrap(); - assert!((Duration::from_millis(199)..=Duration::from_millis(201)).contains(&rtt)); - } - } - } - - #[test] - fn nack_retries_use_receive_stream_rtt() { - for rtt in [Duration::from_millis(20), Duration::from_millis(250)] { - let mut stream = stream_with(&[(10, 0), (12, 1920)]); - stream.stats.rtt = Some(rtt); - let now = Instant::now(); - let mut feedback = VecDeque::new(); - assert!(stream.maybe_create_nack(now, 1.into(), &mut feedback).is_some()); - let due = now + rtt + Duration::from_millis(5); - assert!( - stream - .maybe_create_nack(due - Duration::from_nanos(1), 1.into(), &mut feedback) - .is_none() - ); - assert_eq!(feedback.len(), 1); - assert!(stream.maybe_create_nack(due, 1.into(), &mut feedback).is_some()); - assert_eq!(feedback.len(), 2); - } - } - - #[test] - fn paused_stream_finishes_pending_nack_retries() { - let mut stream = stream_with(&[(10, 0), (12, 1920)]); - let mut now = stream.paused_at().unwrap(); - stream.handle_timeout(now); - assert!(stream.paused); - - let mut feedback = VecDeque::new(); - for _ in 0..5 { - assert!(stream.nack_enabled()); - assert!(stream.maybe_create_nack(now, 1.into(), &mut feedback).is_some()); - assert!(stream.maybe_create_nack(now, 1.into(), &mut feedback).is_none()); - now += Duration::from_millis(105); - } - assert_eq!(feedback.len(), 5); - assert!( - feedback.iter().all(|rtcp| { - matches!(rtcp, Rtcp::Nack(nack) if nack.reports.len() == 1 && nack.reports[0].pid == 11) - }) - ); - - assert!(!stream.nack_enabled()); - assert!(stream.maybe_create_nack(now, 1.into(), &mut feedback).is_none()); - assert_eq!(feedback.len(), 5); - } - - #[test] - fn receiver_report_uses_supplied_intervals() { - let mut stream = StreamRx::new(7.into(), MidRid("mid".into(), None), false, Duration::from_millis(1500)); - let now = Instant::now(); - stream.last_receiver_report = now; - - assert_eq!( - stream.receiver_report_at(RtcpReportIntervals { - audio: Duration::from_millis(750), - video: Duration::from_millis(500), - }), - now + Duration::from_millis(750) - ); - } - - #[test] - fn rtx_tracks_rollover_and_reordering_only_after_receipt() { - let mut stream = rtx_stream(); - let header = rtx_header(8, 50000); - stream.extend_seq(&header, true, |_| None); - assert!( - stream.register_rtx.is_none(), - "unverified headers must not advance the window" - ); - - for seq in [65535, 65536, 65538, 65537] { - record_rtx(&mut stream, seq); - assert!(!stream.is_new_packet(true, seq.into())); - } - assert!( - stream.register.is_none(), - "RTX must not update primary reception reports" - ); - let mut feedback = VecDeque::new(); - assert!( - stream - .maybe_create_nack(Instant::now(), 1.into(), &mut feedback) - .is_none() - ); - assert!(feedback.is_empty()); - } - - #[test] - fn rtx_uses_the_full_128_position_window() { - let mut stream = rtx_stream(); - record_rtx(&mut stream, 0); - record_rtx(&mut stream, 200); - assert!(!stream.is_new_packet(true, 72.into())); - assert!(stream.is_new_packet(true, 73.into())); - record_rtx(&mut stream, 73); - assert!(!stream.is_new_packet(true, 73.into())); - } - - #[test] - fn rtx_buffer_and_roc_resets_preserve_remembered_replay_floor() { - let mut stream = rtx_stream(); - record_rtx(&mut stream, 65535); - record_rtx(&mut stream, 65537); - assert!(stream.is_new_packet(true, 65536.into())); - let history = |ssrc| (ssrc == 8.into()).then_some(65537.into()); - stream.reset_buffers(history); - assert!(!stream.is_new_packet(true, 65536.into())); - assert!(!stream.is_new_packet(true, 65537.into())); - - stream.reset_roc(5); - let header = rtx_header(8, 2); - assert_eq!(stream.extend_seq(&header, true, history), 65538.into()); - assert!(!stream.is_new_packet(true, 65536.into())); - assert!(stream.is_new_packet(true, 65538.into())); - // The requested ROC applies to the main stream, not the RTX sequence series. - let main = RtpHeader { - ssrc: 7.into(), - sequence_number: 10, - ..Default::default() - }; - assert_eq!(stream.extend_seq(&main, false, history), ((5u64 << 16) + 10).into()); - } - - #[test] - fn rtx_ssrc_changes_restore_history_and_main_changes_preserve_it() { - let mut stream = rtx_stream(); - record_rtx(&mut stream, 65535); - assert!(stream.change_ssrc(9.into())); - assert!(!stream.is_new_packet(true, 65535.into())); - stream.maybe_reset_rtx(8.into()); - assert!(!stream.is_new_packet(true, 65535.into())); - - stream.maybe_reset_rtx(10.into()); - assert!(stream.register_rtx.is_none()); - record_rtx(&mut stream, 0); - stream.maybe_reset_rtx(8.into()); - let header = rtx_header(8, 0); - let seq = stream.extend_seq(&header, true, |ssrc| (ssrc == 8.into()).then_some(65535.into())); - assert_eq!(seq, 65536.into()); - assert!(!stream.is_new_packet(true, 65534.into())); - assert!(!stream.is_new_packet(true, 65535.into())); - assert!(stream.is_new_packet(true, seq)); - record_rtx(&mut stream, 65536); - } - - fn rtx_stream() -> StreamRx { - let mut stream = StreamRx::new(7.into(), MidRid("mid".into(), None), false, Duration::from_millis(1500)); - stream.maybe_reset_rtx(8.into()); - stream - } - - fn record_rtx(stream: &mut StreamRx, seq: u64) { - let header = rtx_header(*stream.rtx().unwrap(), seq as u16); - let extended = stream.extend_seq(&header, true, |_| None); - assert_eq!(extended, seq.into()); - assert!(stream.is_new_packet(true, extended)); - let receipt = stream.update_register(already_happened(), &header, Frequency::NINETY_KHZ, true, extended); - assert!(receipt.is_new_packet); - } - - fn rtx_header(ssrc: u32, seq: u16) -> RtpHeader { - RtpHeader { - ssrc: ssrc.into(), - sequence_number: seq, - payload_type: 97.into(), - ..Default::default() - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/register.rs b/rs/moq-webrtc/src/vendor/str0m/streams/register.rs deleted file mode 100644 index 084aa70d3bc..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/register.rs +++ /dev/null @@ -1,470 +0,0 @@ -use std::time::{Duration, Instant}; -use tracing::trace; - -use crate::vendor::str0m::rtp_::{Nack, ReceptionReport, SeqNo}; - -use super::register_nack::NackRegister; - -#[derive(Debug)] -pub struct ReceiverRegister { - nack: NackRegister, - - /// First sequence number received - first: Option, - - /// Number of packets received - count: u64, - - /// Previously received time point. - time_point_prior: Option, - - /// Expected at last reception report generation. - expected_prior: i64, - - /// Received at last reception report generation. - received_prior: i64, - - /// Interarrival jitter in **microseconds**. - /// - /// RTCP carries jitter in **RTP timestamp units** so use - /// [`ReceiverRegister::jitter_in_rtp_ts`] for the wire value. - jitter: f32, -} - -#[derive(Debug, Clone, Copy)] -struct TimePoint { - arrival: Instant, - rtp_time: u32, - clock_rate: u32, -} - -impl TimePoint { - fn is_same(&self, other: TimePoint) -> bool { - self.rtp_time == other.rtp_time - } - - fn delta(&self, other: TimePoint) -> f32 { - // See - // https://www.rfc-editor.org/rfc/rfc3550#appendix-A.8 - // - // rdur is often i 90kHz (for video) or 48kHz (for audio). we need - // a time unit of Duration, that is likely to give us an increase between - // 1 in rdur. milliseconds is thus "too coarse" - - // wrapping_sub to handle RTP time rollover - let rtp_diff = self.rtp_time.wrapping_sub(other.rtp_time) as i32; - let rdur = rtp_diff as f32 * 1_000_000.0 / self.clock_rate as f32; - - let tdur = (self.arrival - other.arrival).as_micros() as f32; - - let d = (tdur - rdur).abs(); - - trace!("Timepoint delta: {}", d); - - d - } -} - -impl ReceiverRegister { - pub fn new(max_seq_no: Option) -> Self { - ReceiverRegister { - nack: NackRegister::new(max_seq_no), - first: None, - count: 0, - time_point_prior: None, - expected_prior: 0, - received_prior: 0, - jitter: 0.0, - } - } - - pub fn accepts(&self, seq: SeqNo) -> bool { - self.nack.accepts(seq) - } - - pub fn update(&mut self, seq: SeqNo, arrival: Instant, rtp_time: u32, clock_rate: u32) -> bool { - if self.first.is_none() { - self.first = Some(seq); - } - - let new = self.nack.update(seq); - - if new { - self.count += 1; - } - - self.update_time(arrival, rtp_time, clock_rate); - - new - } - - pub fn recovery_deadline( - &self, - range: std::ops::Range, - received: Instant, - rtt: Option, - ) -> Option { - self.nack.recovery_deadline(range, received, rtt) - } - - pub fn has_pending_nacks(&self) -> bool { - self.nack.has_pending_nacks() - } - - /// Generates a NACK report - pub fn nack_report(&mut self, now: Instant, rtt: Option) -> Option> { - self.nack.nack_reports(now, rtt) - } - - /// Create a new reception report. - /// - /// This modifies the state since fraction_lost is calculated - /// since the last call to this function. - pub fn reception_report(&mut self) -> Option { - let first = self.first?; - let last = self.max_seq()?; - - let expected = expected(first, last); - - Some(ReceptionReport { - ssrc: 0.into(), - fraction_lost: self.fraction_lost(expected, self.count as i64), - packets_lost: packets_lost(expected, self.count as i64), - max_seq: (*last % ((u32::MAX as u64) + 1_u64)) as u32, - jitter: self.jitter_in_rtp_ts(), - last_sr_time: 0, - last_sr_delay: 0, - }) - } - - pub fn max_seq(&self) -> Option { - self.nack.max_seq() - } - - pub fn clear(&mut self, max_seq_no: Option) { - self.nack = NackRegister::new(max_seq_no); - self.count = 0; - self.first = None; - self.time_point_prior = None; - self.expected_prior = 0; - self.received_prior = 0; - self.jitter = 0.0; - } - - fn update_time(&mut self, arrival: Instant, rtp_time: u32, clock_rate: u32) { - let tp = TimePoint { - arrival, - rtp_time, - clock_rate, - }; - - if let Some(prior) = self.time_point_prior { - if tp.is_same(prior) { - // rtp_time didn't move forward. this is quite normal - // when multiple rtp packets are needed for one keyframe. - - // https://www.cs.columbia.edu/~hgs/rtp/faq.html#jitter - // - // If several packets, say, within a video frame, bear the - // same timestamp, it is advisable to only use the first - // packet in a frame to compute the jitter. (This issue may - // be addressed in a future version of the specification.) - // Jitter is computed in timestamp units. For example, for - // an audio stream sampled at 8,000 Hz, the arrival time - // measured with the local clock is converted by multiplying - // the seconds by 8,000. - // - // Steve Casner wrote: - // - // For encodings such as MPEG that transmit data in a - // different order than it was sampled, this adds noise - // into the jitter calculation. I have heard handwavy - // arguments that this factor can be calculated out given - // that you know the shape of the noise, but my math - // isn't strong enough for that. - // - // In many of the cases that we care about, the jitter - // introduced by MPEG will be small enough that when the - // network jitter is of the same order we don't have a - // problem anyway. - // - // There is another problem for video in that all of the - // packets of a frame have the same timestamp because the - // whole frame is sampled at once. However, the - // dispersion in time of those packets really is all part - // of the network transfer process that the receiver must - // accommodate with its buffer. - // - // It has been suggested that jitter be calculated only - // on the first packet of a video frame, or only on "I" - // frames for MPEG. However, that may color the results - // also because those packets may see transit delays - // different than the following packets see. - // - // The main point to remember is that the primary - // function of the RTP timestamp is to represent the - // inherent notion of real time associated with the - // media. It also turns out to be useful for the jitter - // measure, but that is a secondary function. - // - // The jitter value is not expected to be useful as an - // absolute value. It is more useful as a means of - // comparing the reception quality at two receiver or - // comparing the reception quality 5 minutes ago to now. - - return; - } - - // update jitter. - let d = tp.delta(prior); - - self.jitter += (1.0 / 16.0) * (d - self.jitter); - } - - self.time_point_prior = Some(tp); - } - - // Calculations from here - // https://www.rfc-editor.org/rfc/rfc3550#appendix-A.3 - - /// Fraction lost since last call. - fn fraction_lost(&mut self, expected: i64, received: i64) -> u8 { - let expected_interval = expected - self.expected_prior; - self.expected_prior = expected; - - let received_interval = received - self.received_prior; - self.received_prior = received; - - let lost_interval = expected_interval - received_interval; - - let lost = if expected_interval == 0 || lost_interval <= 0 { - 0 - } else { - ((lost_interval << 8) / expected_interval).min(255) - } as u8; - - trace!("Reception fraction lost: {}", lost); - - lost - } - - /// Jitter in RTP timestamp units. - fn jitter_in_rtp_ts(&self) -> u32 { - let Some(sample_rate) = self.time_point_prior.map(|tp| tp.clock_rate) else { - return 0; - }; - (self.jitter / 1_000_000.0 * sample_rate as f32).round() as u32 - } -} - -/// Absolute number of lost packets. -fn packets_lost(expected: i64, received: i64) -> u32 { - // Since this signed number is carried in 24 bits, it should be clamped - // at 0x7fffff for positive loss or 0x800000 for negative loss rather - // than wrapping around. - let lost_t = expected - received; - if lost_t > 0x7fffff { - 0x7fffff_u32 - } else if lost_t < -0x7fffff { - 0x8000000_u32 - } else { - lost_t as u32 - } -} - -fn expected(first: SeqNo, last: SeqNo) -> i64 { - let delta = (*last - *first) as i64; - delta.saturating_add(1) -} - -#[cfg(test)] -mod test { - use std::time::{Duration, Instant}; - - use crate::vendor::str0m::streams::register::{ReceiverRegister, expected, packets_lost}; - - #[test] - fn clearing_register_resets_nack_timing() { - let mut reg = ReceiverRegister::new(None); - let now = Instant::now(); - reg.update(10.into(), now, 0, 90_000); - reg.update(12.into(), now, 3000, 90_000); - assert!(reg.nack_report(now, None).is_some()); - assert!(reg.nack_report(now, None).is_none()); - reg.clear(Some(10.into())); - assert!(!reg.has_pending_nacks()); - reg.update(12.into(), now, 3000, 90_000); - let nacks: Vec<_> = reg.nack_report(now, None).expect("fresh loss").collect(); - assert_eq!(nacks[0].reports[0].pid, 11); - } - - #[test] - fn jitter_at_0() { - let mut r = ReceiverRegister::new(None); - - // 100 fps in clock rate 90kHz => 90_000/100 = 900 per frame - // 1/100 * 1_000_000 = 10_000 microseconds per frame. - - let start = Instant::now(); - let dur = Duration::from_micros(10_000); - - r.update_time(start + 4 * dur, 1234 + 4 * 900, 90_000); - r.update_time(start + 5 * dur, 1234 + 5 * 900, 90_000); - r.update_time(start + 6 * dur, 1234 + 6 * 900, 90_000); - r.update_time(start + 7 * dur, 1234 + 7 * 900, 90_000); - assert_eq!(r.jitter, 0.0); - } - - #[test] - fn jitter_at_20() { - let mut r = ReceiverRegister::new(None); - - // 100 fps in clock rate 90kHz => 90_000/100 = 900 per frame - // 1/100 * 1_000_000 = 10_000 microseconds per frame. - - let start = Instant::now(); - let dur = Duration::from_micros(10_000); - let off = Duration::from_micros(10); - - for i in 4..1000 { - let arrival = if i % 2 == 0 { - start + (i * dur).checked_sub(off).unwrap() - } else { - start + i * dur + off - }; - r.update((i as u64).into(), arrival, 1234 + i * 900, 90_000); - } - - // jitter should converge on 20.0 - assert!( - (20.0 - r.jitter).abs() < 0.01, - "Expected jitter to converge at 20.0, jitter was: {}", - r.jitter - ); - - // jitter is also present in reception report - let report = r.reception_report().expect("some report"); - // 90kHz is 11.1us ticks, so 20us jitter is 1.8 tick which equals 2 - // after rounding to int. - assert_eq!(report.jitter, 2); - assert_eq!(report.jitter, r.jitter_in_rtp_ts()); - } - - #[test] - fn fraction_lost_is_zero_when_an_interval_receives_more_than_expected() { - let mut reg = ReceiverRegister::new(None); - - assert_eq!(reg.fraction_lost(120, 118), 4); - assert_eq!(reg.fraction_lost(240, 240), 0); - } - - #[test] - fn fraction_lost_saturates_when_everything_is_lost() { - let mut reg = ReceiverRegister::new(None); - - assert_eq!(reg.fraction_lost(100, 0), 255); - } - - #[test] - fn expected_received_loss() { - let first = 14.into(); - let last = 17.into(); - let expected = expected(first, last); - assert_eq!(expected, 4); - // none of 4 was lost - assert_eq!(packets_lost(expected, 4), 0); - // one of 4 was lost:329 - assert_eq!(packets_lost(expected, 3), 1); - } - - #[test] - fn expected_overflow() { - let last = 0x7fff_ffff_ffff_ffff_u64.into(); - let first = 0_u64.into(); - let expected = expected(first, last); - assert_eq!(expected, i64::MAX); - } - - #[test] - fn receiver_report() { - let mut r = ReceiverRegister::new(None); - let now = Instant::now(); - let rtp_time = 0; - - // 50 % lost - for i in 10..14 { - r.update((i as u64).into(), now, rtp_time, 90_000); - } - r.update(19.into(), now, rtp_time, 90_000); - - let report = r.reception_report().expect("some report"); - assert_eq!(128, report.fraction_lost); - assert_eq!(5, report.packets_lost); - assert_eq!(19, report.max_seq); - assert_eq!(0, report.jitter); - } - - #[test] - fn simple_jitter_computation() { - // SimpleJitterComputation from receive_statistics_unittest.cc - const MS_PER_PACKET: u64 = 20; - const CODEC_SAMPLE_RATE: u32 = 48_000; - const SAMPLES_PER_PACKET: u32 = MS_PER_PACKET as u32 * CODEC_SAMPLE_RATE / 1_000; - const LATE_ARRIVAL_DELTA_MS: u64 = 100; - const LATE_DELTA_SAMPLES: u32 = LATE_ARRIVAL_DELTA_MS as u32 * CODEC_SAMPLE_RATE / 1_000; - - let mut clock = Instant::now(); - let mut r = ReceiverRegister::new(None); - - r.update_time(clock, 0, CODEC_SAMPLE_RATE); - clock += Duration::from_millis(MS_PER_PACKET + LATE_ARRIVAL_DELTA_MS); - r.update_time(clock, SAMPLES_PER_PACKET, CODEC_SAMPLE_RATE); - - assert_eq!(r.jitter_in_rtp_ts(), LATE_DELTA_SAMPLES / 16); - } - - #[test] - fn all_packets_have_same_frequency() { - // AllPacketsHaveSamePayloadTypeFrequency from receive_statistics_unittest.cc - let mut clock = Instant::now(); - let mut r = ReceiverRegister::new(None); - - r.update_time(clock, 1, 8_000); - clock += Duration::from_millis(50); - r.update_time(clock, 1 + 160, 8_000); - clock += Duration::from_millis(50); - r.update_time(clock, 1 + 160 + 160, 8_000); - - // packet1: no jitter calculation - // packet2: jitter = 0[jitter] + (abs(50[receive time ms] * - // 8[frequency KHz] - 160[timestamp diff]) * 16 - 0[jitter] + 8) - // / 16 = 240 - // packet3: jitter = 240[jitter] + (abs(50[receive time ms] * - // 8[frequency KHz] - 160[timestamp diff]) * 16 - 240[jitter] + 8) - // / 16 = 465 - // final jitter: 465 / 16 = 29 - assert_eq!(r.jitter_in_rtp_ts(), 29); - } - - #[test] - fn jitter_rtp_timestamp_rollover() { - // Same as jitter_same_frequency_three_packets but the timestamps are - // anchored so the u32 boundary falls between packets 1 and 2. - - let rtp_time_1 = u32::MAX - 79; - let rtp_time_2 = rtp_time_1.wrapping_add(160); - let rtp_time_3 = rtp_time_2.wrapping_add(160); - - let mut clock = Instant::now(); - let mut r = ReceiverRegister::new(None); - - r.update_time(clock, rtp_time_1, 8_000); - clock += Duration::from_millis(50); - r.update_time(clock, rtp_time_2, 8_000); - clock += Duration::from_millis(50); - r.update_time(clock, rtp_time_3, 8_000); - - // Same result as jitter_same_frequency_three_packets. - assert_eq!(r.jitter_in_rtp_ts(), 29); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/register_nack.rs b/rs/moq-webrtc/src/vendor/str0m/streams/register_nack.rs deleted file mode 100644 index 2d56c37cc4b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/register_nack.rs +++ /dev/null @@ -1,944 +0,0 @@ -use std::ops::Range; -use std::time::{Duration, Instant}; -use tracing::trace; - -use crate::vendor::str0m::rtp_::{Nack, NackEntry, ReportList, SeqNo}; - -/// Number of out of order packets we keep track of for reports -const MAX_MISORDER: u64 = 100; - -/// The max number of NACKs we perform for a single packet -const MAX_NACKS: u8 = 5; - -pub(super) const DEFAULT_RTT: Duration = Duration::from_millis(100); -const NACK_RETRY_MARGIN: Duration = Duration::from_millis(5); - -/// Circular buffer size -const BUFFER_SIZE: u64 = MAX_MISORDER + 1; - -#[derive(Debug)] -pub struct NackRegister { - /// Status of packets indexed by wrapping SeqNo. - packets: Vec, - - /// Range of seq numbers considered NACK reporting. - active: Option>, -} - -#[derive(Debug, Default, Clone, Copy)] -struct PacketStatus { - received: bool, - nack_count: u8, - last_nack_at: Option, -} - -impl PacketStatus { - fn needs_nack(&self) -> bool { - !self.received && self.nack_count < MAX_NACKS - } - - fn is_nack_due(&self, now: Instant, retry_interval: Duration) -> bool { - self.needs_nack() - && self - .last_nack_at - .is_none_or(|last| now.saturating_duration_since(last) >= retry_interval) - } - - fn mark_nacked(&mut self, now: Instant) { - self.nack_count += 1; - self.last_nack_at = Some(now); - } - - fn mark_received(&mut self) -> bool { - let new = !self.received; - self.received = true; - self.nack_count = 0; - self.last_nack_at = None; - new - } - - fn reset(&mut self) { - *self = Self::default(); - } -} - -struct NackIterator<'a> { - reg: &'a mut NackRegister, - next: u64, - end: u64, - now: Instant, - retry_interval: Duration, -} - -impl<'a> Iterator for NackIterator<'a> { - type Item = NackEntry; - - fn next(&mut self) -> Option { - self.next = - (self.next..=self.end).find(|s| self.reg.packet((*s).into()).is_nack_due(self.now, self.retry_interval))?; - - let mut entry = NackEntry { - pid: self.next as u16, - blp: 0, - }; - - self.reg.packet_mut(self.next.into()).mark_nacked(self.now); - self.next += 1; - - for (i, s) in (self.next..self.end).take(16).enumerate() { - let packet = self.reg.packet_mut(s.into()); - if packet.is_nack_due(self.now, self.retry_interval) { - packet.mark_nacked(self.now); - entry.blp |= 1 << i - } - self.next += 1; - } - - Some(entry) - } -} - -impl NackRegister { - /// Creates a new register. - /// - /// The max_seq_no is to provide a starting point for ROC calculations. - pub fn new(max_seq_no: Option) -> Self { - let mut n = NackRegister { - packets: vec![PacketStatus::default(); BUFFER_SIZE as usize], - active: None, - }; - - if let Some(seq) = max_seq_no { - n.init_with_seq(seq); - } - - n - } - - pub fn accepts(&self, seq: SeqNo) -> bool { - let Some(active) = self.active.clone() else { - // if we don't have initialized, we do want the first packet. - return true; - }; - - // behind the window - if seq < active.start { - return false; - } - - !self.packet(seq).received || seq > active.end - } - - pub fn update(&mut self, seq: SeqNo) -> bool { - let Some(active) = self.active.clone() else { - // automatically pick up the first seq number - self.init_with_seq(seq); - return true; - }; - - if seq < active.start { - // skip old seq numbers, report as not new - return false; - } - - let new = !self.packet_mut(seq).received || seq > active.end; - - let end = active.end.max(seq); - - let start: SeqNo = { - let min = end.saturating_sub(MAX_MISORDER); - let mut start = (*active.start).max(min); - while start < *end { - if !self.packet_mut(start.into()).received && start != *seq { - break; - } - start += 1; - } - start.into() - }; - - // reset packets that are rolling our of the nack window - for (i, s) in (*active.start..*start).enumerate() { - let p = self.packet_mut(s.into()); - if !p.received && s != *seq { - trace!("Seq no {} missing after {} attempts", s, p.nack_count); - } - self.packet_mut(s.into()).reset(); - - if i > self.packets.len() { - // we have reset all entries already - break; - } - } - - if (start..=end).contains(&seq) { - self.packet_mut(seq).mark_received(); - } - - self.active = Some(start..end); - - new - } - - fn init_with_seq(&mut self, seq: SeqNo) { - self.active = Some(seq..seq); - self.packet_mut(seq).mark_received(); - } - - pub fn max_seq(&self) -> Option { - self.active.as_ref().map(|a| a.end) - } - - /// Whether a missing packet still has NACK attempts remaining. - /// - /// Includes retries that are waiting for their RTT deadline. - pub fn has_pending_nacks(&self) -> bool { - let Some(active) = &self.active else { - return false; - }; - - (*active.start..=*active.end).any(|seq| self.packet(seq.into()).needs_nack()) - } - - /// Create NACK reports for packets whose requests are due. - /// - /// First requests are immediately eligible. Retries wait one receive-stream RTT plus - /// 5 ms, using 100 ms until RTT is known. Only included packets consume an attempt. - pub fn nack_reports(&mut self, now: Instant, rtt: Option) -> Option> { - let retry_interval = rtt.unwrap_or(DEFAULT_RTT).saturating_add(NACK_RETRY_MARGIN); - let Range { start, end } = self.active.clone()?; - let start = (*start..=*end).find(|s| self.packet((*s).into()).is_nack_due(now, retry_interval))?; - - Some( - ReportList::lists_from_iter(NackIterator { - reg: self, - next: start, - end: *end, - now, - retry_interval, - }) - .into_iter() - .map(|reports| { - Nack { - sender_ssrc: 0.into(), - ssrc: 0.into(), // changed when sending - reports, - } - }), - ) - } - - /// Deadline for abandoning missing packets in a candidate's preceding sequence range. - /// None means a relevant packet still has NACK attempts remaining. - pub fn recovery_deadline( - &self, - range: Range, - candidate_received: Instant, - rtt: Option, - ) -> Option { - let grace = rtt.unwrap_or(DEFAULT_RTT).saturating_mul(3); - let fallback = candidate_received.checked_add(grace); - let Some(active) = &self.active else { - return fallback; - }; - let mut deadline = None; - for seq in *range.start.max(active.start)..*range.end.min(active.end) { - let packet = self.packet(seq.into()); - if packet.received { - continue; - } - if packet.needs_nack() { - return None; - } - let at = packet.last_nack_at?.checked_add(grace)?; - deadline = Some(deadline.map_or(at, |previous: Instant| previous.max(at))); - } - // Gaps outside the bounded NACK window and missing tail markers have no final - // request to time from. Give them a candidate-relative grace period instead. - deadline.or(fallback) - } - - fn as_index(&self, seq: SeqNo) -> usize { - (*seq % self.packets.len() as u64) as usize - } - - fn packet(&self, seq: SeqNo) -> &PacketStatus { - let index = self.as_index(seq); - &self.packets[index] - } - - fn packet_mut(&mut self, seq: SeqNo) -> &mut PacketStatus { - let index = self.as_index(seq); - &mut self.packets[index] - } -} - -#[cfg(test)] -mod test { - use std::ops::Range; - use std::time::{Duration, Instant}; - - use crate::vendor::str0m::rtp_::NackEntry; - use crate::vendor::str0m::streams::register_nack::MAX_MISORDER; - - use super::NackRegister; - - #[test] - fn recovery_waits_for_final_nack_and_three_rtts() { - for rtt in [None, Some(Duration::from_millis(20)), Some(Duration::from_millis(400))] { - let base = Instant::now(); - let measured = rtt.unwrap_or(Duration::from_millis(100)); - let mut reg = NackRegister::new(None); - reg.update(10.into()); - reg.update(12.into()); - let mut now = base; - for attempt in 0..5 { - assert_eq!(reg.recovery_deadline(10.into()..12.into(), base, rtt), None); - assert_eq!(nack_entries(&mut reg, now, rtt).len(), 1); - if attempt < 4 { - now += measured + Duration::from_millis(5); - } - } - let deadline = Some(now + measured * 3); - // Include a received packet before the active window; it must not add a fallback wait. - assert_eq!(reg.recovery_deadline(10.into()..12.into(), base, rtt), deadline); - reg.update(14.into()); - assert_eq!(reg.recovery_deadline(10.into()..12.into(), base, rtt), deadline); - assert_eq!(reg.recovery_deadline(10.into()..14.into(), base, rtt), None); - reg.update(11.into()); - assert_eq!( - reg.recovery_deadline(10.into()..12.into(), base, rtt), - Some(base + measured * 3) - ); - } - } - - #[test] - fn pending_nacks_follow_repair_and_retry_exhaustion() { - let mut reg = NackRegister::new(None); - assert!(!reg.has_pending_nacks()); - - reg.update(10.into()); - assert!(!reg.has_pending_nacks()); - - reg.update(12.into()); - assert!(reg.has_pending_nacks()); - reg.update(11.into()); - assert!(!reg.has_pending_nacks()); - - reg.update(14.into()); - let mut now = Instant::now(); - for _ in 0..super::MAX_NACKS { - assert!(reg.has_pending_nacks()); - let reports: Vec<_> = reg.nack_reports(now, None).expect("pending retry").collect(); - assert_eq!(reports.len(), 1); - assert_eq!(reports[0].reports[0].pid, 13); - now += Duration::from_millis(105); - } - assert!(!reg.has_pending_nacks()); - assert!(reg.nack_reports(now, None).is_none()); - } - - fn nack_entries(reg: &mut NackRegister, now: Instant, rtt: Option) -> Vec { - reg.nack_reports(now, rtt) - .into_iter() - .flatten() - .flat_map(|nack| nack.reports) - .collect() - } - - #[test] - fn nack_retry_deadlines_and_limit() { - for (rtt, interval_ms) in [ - (None, 105), - (Some(Duration::ZERO), 5), - (Some(Duration::from_millis(20)), 25), - (Some(Duration::from_millis(250)), 255), - ] { - let mut reg = NackRegister::new(None); - reg.update(10.into()); - reg.update(13.into()); - let now = Instant::now(); - let interval = Duration::from_millis(interval_ms); - let expected = [NackEntry { pid: 11, blp: 1 }]; - - for attempt in 0..super::MAX_NACKS { - let due = now + interval * u32::from(attempt); - if attempt > 0 { - assert!(nack_entries(&mut reg, due - Duration::from_nanos(1), rtt).is_empty()); - } - assert!(reg.has_pending_nacks()); - assert_eq!(nack_entries(&mut reg, due, rtt), expected); - assert!(nack_entries(&mut reg, due, rtt).is_empty()); - for seq in [11, 12] { - let packet = reg.packet(seq.into()); - assert_eq!(packet.nack_count, attempt + 1); - assert_eq!(packet.last_nack_at, Some(due)); - } - } - - assert!(!reg.has_pending_nacks()); - assert!(nack_entries(&mut reg, now + interval * 10, rtt).is_empty()); - } - } - - #[test] - fn nack_new_losses_and_retries_have_independent_deadlines() { - let mut reg = NackRegister::new(None); - let now = Instant::now(); - reg.update(10.into()); - reg.update(12.into()); - assert_eq!(nack_entries(&mut reg, now, None), [NackEntry { pid: 11, blp: 0 }]); - - reg.update(14.into()); - assert_eq!( - nack_entries(&mut reg, now + Duration::from_millis(30), None), - [NackEntry { pid: 13, blp: 0 }] - ); - assert_eq!(reg.packet(11.into()).last_nack_at, Some(now)); - - reg.update(16.into()); - // 11 is due again and 15 is new, but 13 must not be included in the bitmask yet. - assert_eq!( - nack_entries(&mut reg, now + Duration::from_millis(105), None), - [NackEntry { pid: 11, blp: 0b1000 }] - ); - assert_eq!(reg.packet(13.into()).nack_count, 1); - assert_eq!( - reg.packet(13.into()).last_nack_at, - Some(now + Duration::from_millis(30)) - ); - assert_eq!( - nack_entries(&mut reg, now + Duration::from_millis(135), None), - [NackEntry { pid: 13, blp: 0 }] - ); - assert_eq!( - nack_entries(&mut reg, now + Duration::from_millis(210), None), - [NackEntry { pid: 11, blp: 0b1000 }] - ); - assert_eq!(reg.packet(11.into()).nack_count, 3); - assert_eq!(reg.packet(15.into()).nack_count, 2); - } - - #[test] - fn nack_retry_uses_updated_rtt() { - let mut reg = NackRegister::new(None); - reg.update(10.into()); - reg.update(12.into()); - let now = Instant::now(); - assert_eq!(nack_entries(&mut reg, now, None).len(), 1); - assert_eq!( - nack_entries( - &mut reg, - now + Duration::from_millis(50), - Some(Duration::from_millis(20)) - ) - .len(), - 1 - ); - let rtt = Some(Duration::from_millis(200)); - assert!(nack_entries(&mut reg, now + Duration::from_millis(254), rtt).is_empty()); - assert_eq!(nack_entries(&mut reg, now + Duration::from_millis(255), rtt).len(), 1); - } - - #[test] - fn nack_repair_clears_only_recovered_packet_state() { - let mut reg = NackRegister::new(None); - reg.update(10.into()); - reg.update(14.into()); - let now = Instant::now(); - assert_eq!(nack_entries(&mut reg, now, None), [NackEntry { pid: 11, blp: 3 }]); - reg.update(12.into()); - let packet = reg.packet(12.into()); - assert!(packet.received); - assert_eq!(packet.nack_count, 0); - assert_eq!(packet.last_nack_at, None); - assert_eq!( - nack_entries(&mut reg, now + Duration::from_millis(105), None), - [NackEntry { pid: 11, blp: 0b10 }] - ); - } - - #[test] - fn nack_window_reuse_clears_retry_state() { - let mut reg = NackRegister::new(None); - reg.update(10.into()); - reg.update(12.into()); - let now = Instant::now(); - assert_eq!(nack_entries(&mut reg, now, None).len(), 1); - for seq in 13..112 { - reg.update(seq.into()); - } - reg.update(113.into()); - assert_eq!(reg.as_index(11.into()), reg.as_index(112.into())); - assert_eq!(reg.packet(112.into()).nack_count, 0); - assert_eq!(reg.packet(112.into()).last_nack_at, None); - assert_eq!(nack_entries(&mut reg, now, None), [NackEntry { pid: 112, blp: 0 }]); - assert_not_dirty(®); - } - - #[test] - fn nack_retry_timing_across_sequence_rollover() { - let mut reg = NackRegister::new(None); - reg.update(65_534.into()); - reg.update(65_538.into()); - let now = Instant::now(); - assert_eq!(nack_entries(&mut reg, now, None), [NackEntry { pid: 65_535, blp: 3 }]); - reg.update(65_536.into()); - assert!(nack_entries(&mut reg, now + Duration::from_millis(104), None).is_empty()); - assert_eq!( - nack_entries(&mut reg, now + Duration::from_millis(105), None), - [NackEntry { pid: 65_535, blp: 0b10 }] - ); - } - - fn assert_update( - reg: &mut NackRegister, - seq: u64, - expect_new: bool, - expect_received: bool, - expect_active: Range, - ) { - assert_eq!( - reg.update(seq.into()), - expect_new, - "seq {} was expected to{} be new", - seq, - if expect_new { "" } else { " NOT" } - ); - let active = reg.active.clone().expect("nack range"); - assert_eq!( - reg.packet_mut(seq.into()).received, - expect_received, - "seq {} expected to{} be received in {:?}", - seq, - if expect_received { "" } else { " NOT" }, - active - ); - assert_eq!(active, expect_active.start.into()..expect_active.end.into()); - assert_not_dirty(reg); - } - - fn assert_not_dirty(reg: &NackRegister) { - // we should leave no dirty state outside of the nack window - let active = reg.active.clone().expect("nack range"); - let active = (*active.start..=*active.end) - .map(|seq| reg.as_index(seq.into())) - .collect::>(); - - for i in 0..reg.packets.len() { - if active.contains(&i) { - continue; - } - assert!( - !reg.packets[i].received && reg.packets[i].nack_count == 0 && reg.packets[i].last_nack_at.is_none(), - "dirty state at index {} outside of nack window {:?}", - i, - active, - ); - } - } - - #[test] - fn active_window_sliding() { - let mut reg = NackRegister::new(None); - - assert!(reg.accepts(10.into())); - assert_update(&mut reg, 10, true, true, 10..10); - - // packet before window start is ignored - assert!(!reg.accepts(9.into())); - assert_update(&mut reg, 9, false, false, 10..10); - - // duped packet - assert!(!reg.accepts(10.into())); - assert_update(&mut reg, 10, false, true, 10..10); - - // future packets accepted, window not sliding - let next = 10 + MAX_MISORDER; - assert!(reg.accepts(next.into())); - assert_update(&mut reg, next, true, true, 11..next); - let next = 11 + MAX_MISORDER; - assert!(reg.accepts(next.into())); - assert_update(&mut reg, next, true, true, 11..next); - - // future packet accepted, sliding window - let next = 12 + MAX_MISORDER; - assert!(reg.accepts(next.into())); - assert_update(&mut reg, next, true, true, 12..next); - - // older packet received within window - let next = 13; - assert!(reg.accepts(next.into())); - assert_update(&mut reg, next, true, true, 12..(12 + MAX_MISORDER)); - - // do not want the same packet again - assert!(!reg.accepts(next.into())); - - // future packet accepted, sliding window start skips over received - let next = 13 + MAX_MISORDER; - assert!(reg.accepts(next.into())); - assert_update(&mut reg, next, true, true, 14..next); - - // do not want the same packet again - assert!(!reg.accepts(next.into())); - - // older packet accepted, window star moves ahead - let next = 14; - assert!(reg.accepts(next.into())); - assert_update(&mut reg, next, true, false, 15..(13 + MAX_MISORDER)); - } - - #[test] - fn nack_report_none() { - let mut reg = NackRegister::new(None); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - - reg.update(110.into()); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - - reg.update(111.into()); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - } - - #[test] - fn nack_test_huge_seq_gap_no_hang() { - let mut reg = NackRegister::new(None); - - reg.update(0.into()); - reg.update(18446744073709551515.into()); - } - - #[test] - fn nack_report_one() { - let mut reg = NackRegister::new(None); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - - reg.update(110.into()); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - - reg.update(112.into()); - let report = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert!(report.len() == 1); - assert_eq!(report[0].reports.len(), 1); - assert_eq!(report[0].reports[0].pid, 111); - assert_eq!(report[0].reports[0].blp, 0); - } - - #[test] - fn nack_report_two() { - let mut reg = NackRegister::new(None); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - - reg.update(110.into()); - assert!(reg.nack_reports(Instant::now(), None).is_none()); - - reg.update(113.into()); - let report = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert!(report.len() == 1); - assert_eq!(report[0].reports.len(), 1); - assert_eq!(report[0].reports[0].pid, 111); - assert_eq!(report[0].reports[0].blp, 0b1); - } - - #[test] - fn nack_report_with_hole() { - let mut reg = NackRegister::new(None); - - for i in &[100, 101, 103, 105, 106, 107, 108, 109, 110] { - reg.update((*i).into()); - } - - let report = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert!(report.len() == 1); - assert_eq!(report[0].reports.len(), 1); - assert_eq!(report[0].reports[0].pid, 102); - assert_eq!(report[0].reports[0].blp, 0b10); - } - - #[test] - fn nack_report_stop_at_17() { - let mut reg = NackRegister::new(None); - - let seq = &[ - 100, 101, 103, 104, 105, 106, 107, 108, 109, 110, // - 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, // - 121, 122, 123, 125, - ]; - - for i in seq { - reg.update((*i).into()); - } - - let report = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert_eq!(report.len(), 1); - assert_eq!(report[0].reports.len(), 2); - assert_eq!(report[0].reports[0].pid, 102); - assert_eq!(report[0].reports[0].blp, 0); - } - - #[test] - fn nack_report_hole_at_17() { - let mut reg = NackRegister::new(None); - - let seq = &[ - 100, 101, 103, 104, 105, 106, 107, 108, 109, 110, // - 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, // - 122, 123, 124, 125, 126, 127, 128, 129, - ]; - - for i in seq { - reg.update((*i).into()); - } - - let report = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert_eq!(report.len(), 1); - assert_eq!(report[0].reports.len(), 1); - assert_eq!(report[0].reports[0].pid, 102); - assert_eq!(report[0].reports[0].blp, 0b1000_0000_0000_0000); - } - - #[test] - fn nack_report_no_stop_all_there() { - let mut reg = NackRegister::new(None); - - let seq = &[ - 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, // - 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, // - 122, 123, 124, 125, 126, 127, 128, 129, - ]; - - for i in seq { - reg.update((*i).into()); - } - - assert!(reg.nack_reports(Instant::now(), None).is_none()); - } - - #[test] - fn nack_report_rtx() { - let mut reg = NackRegister::new(None); - for i in &[ - 100, 101, 102, 103, 104, 105, // - ] { - reg.update((*i).into()); - } - assert!(reg.nack_reports(Instant::now(), None).is_none()); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 105); - - for i in &[ - 106, 108, 109, 110, 111, 112, 113, 114, 115, // - ] { - reg.update((*i).into()); - } - assert!(reg.nack_reports(Instant::now(), None).is_some()); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 107); - - reg.update(107.into()); // Got 107 via RTX - - let nacks = reg.nack_reports(Instant::now(), None).map(Vec::from_iter); - assert!( - nacks.is_none(), - "Expected no NACKs to be generated after repairing the stream, got {nacks:?}" - ); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 115); - } - - #[test] - fn nack_report_rollover_rtx() { - // This test is checking that after rollover nacks are not skipped because of - // packet position that would remain marked as received from before the rollover - let mut reg = NackRegister::new(None); - for i in &[ - 100, 101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, - ] { - reg.update((*i).into()); - } - - reg.update(107.into()); // Got 107 via RTX - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 115); - - for i in 116..3106 { - reg.update(i.into()); - } - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 3105); - - for i in &[3106, 3108, 3109, 3110, 3111, 3112, 3113, 3114, 3115] { - reg.update((*i).into()); // Missing at postion 107 again - } - - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 3107); - } - - #[test] - fn nack_report_rollover_rtx_with_seq_jump() { - let mut reg = NackRegister::new(None); - - // 2999 is missing - for i in 0..2999 { - reg.update(i.into()); - } - - // 3002 is missing - reg.update(3003.into()); - reg.update(3004.into()); - reg.update(3000.into()); - reg.update(3001.into()); - - let reports = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert_eq!(reports.len(), 1); - assert_eq!(reports[0].reports[0].pid, 2999); - assert_eq!(reports[0].reports[0].blp, 4); - } - - #[test] - fn out_of_order_and_rollover() { - let mut reg = NackRegister::new(None); - - reg.update(2998.into()); - reg.update(2999.into()); - - // receive older packet - reg.update(2995.into()); - - // wrap - for i in 3000..5995 { - reg.update(i.into()); - } - - // 5995 is missing - - reg.update(5996.into()); - reg.update(5997.into()); - - let reports = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - assert_eq!(reports.len(), 1); - assert_eq!(reports[0].reports[0].pid, 5995); - } - - #[test] - fn nack_check_on_seq_rollover() { - let range = 65530..65541; - let missing = [65535_u64, 65536_u64, 65537_u64]; - let expected = [65535_u16, 0_u16, 1_u16]; - - for (missing, expected) in missing.iter().zip(expected.iter()) { - let mut seqs: Vec<_> = range.clone().collect(); - let mut reg = NackRegister::new(None); - - seqs.retain(|x| *x != *missing); - for i in seqs.as_slice() { - reg.update((*i).into()); - } - - let reports = reg - .nack_reports(Instant::now(), None) - .map(Vec::from_iter) - .expect("some report"); - let pid = reports[0].reports[0].pid; - assert_eq!(pid, *expected); - } - } - - #[test] - fn nack_check_forward_at_boundary() { - let mut reg = NackRegister::new(None); - for i in 2996..=3003 { - reg.update(i.into()); - } - - assert!(reg.nack_reports(Instant::now(), None).is_none()); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 3003); - - for i in 3004..=3008 { - reg.update(i.into()); - } - - let report = reg.nack_reports(Instant::now(), None).map(Vec::from_iter); - assert!(report.is_none(), "Expected empty NACKs got {:?}", report); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 3008); - } - - #[test] - fn nack_check_forward_at_u16_boundary() { - let mut reg = NackRegister::new(None); - for i in 65500..=65534 { - reg.update(i.into()); - } - assert!(reg.nack_reports(Instant::now(), None).is_none()); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 65534); - - for i in 65536..=65566 { - reg.update(i.into()); - } - - assert!(reg.nack_reports(Instant::now(), None).is_some()); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 65535); - - for i in 65567..=65666 { - reg.update(i.into()); - } - - reg.update(65535.into()); - - assert!(reg.nack_reports(Instant::now(), None).is_none()); - let active = reg.active.clone().expect("nack range"); - assert_eq!(*active.start, 65666); - } - - #[test] - fn nack_reports_on_boundaries() { - let mut reg = NackRegister::new(None); - - for i in 0..=20 { - // gap must be at least 17 packets to separate the reports. - if i == 2 || i == 19 { - continue; - } - reg.update(i.into()); - } - - let reports: Vec<_> = reg - .nack_reports(Instant::now(), None) - .expect("should generate reports") - .flat_map(|nack| nack.reports) - .collect(); - - assert_eq!(reports.len(), 2, "Should have found two NACK entries"); - assert_eq!(reports[0].pid, 2, "First missing packet should be 2"); - assert_eq!(reports[0].blp, 0, "No missing packets in blp bits following 2"); - assert_eq!(reports[1].pid, 19, "Second missing packet should be 19"); - assert_eq!(reports[1].blp, 0, "No missing packets in blp bits following 19"); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/rtx_cache.rs b/rs/moq-webrtc/src/vendor/str0m/streams/rtx_cache.rs deleted file mode 100644 index 4a32f7bbbde..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/rtx_cache.rs +++ /dev/null @@ -1,152 +0,0 @@ -use std::time::Duration; -use std::time::Instant; - -use crate::vendor::str0m::rtp_::SeqNo; - -use super::RtpPacket; -use super::rtx_cache_buf::EvictingBuffer; - -#[derive(Debug)] -pub(crate) struct RtxCache { - // Data, new additions here probably need to be cleared in [`clear`]. - packet_by_seq_no: EvictingBuffer, -} - -impl RtxCache { - pub fn new(max_packet_count: usize, max_packet_age: Duration) -> Self { - Self { - packet_by_seq_no: EvictingBuffer::new(10, max_packet_age, max_packet_count), - } - } - - pub fn cache_sent_packet(&mut self, packet: RtpPacket, now: Instant) { - assert!(packet.nackable); - self.packet_by_seq_no.push(*packet.seq_no, now, packet); - self.remove_old_packets(now); - } - - pub fn last_cached_seq_no(&self) -> Option { - Some(self.packet_by_seq_no.last_position()?.into()) - } - - pub fn get_cached_packet_by_seq_no(&mut self, seq_no: SeqNo) -> Option<&mut RtpPacket> { - self.packet_by_seq_no.get_mut(*seq_no) - } - - fn remove_old_packets(&mut self, now: Instant) { - self.packet_by_seq_no.maybe_evict(now); - } - - pub(crate) fn last_packet(&self) -> Option<&[u8]> { - let packet = self.packet_by_seq_no.last()?; - Some(packet.payload.as_ref()) - } - - pub(crate) fn clear(&mut self) { - self.packet_by_seq_no.clear(); - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::rtp_::MediaTime; - use crate::vendor::str0m::rtp_::RtpHeader; - - use super::*; - - fn after(now: Instant, millis: u64) -> Instant { - now + Duration::from_millis(millis) - } - - fn packet(now: Instant, seq_no: u64, millis: u64) -> RtpPacket { - RtpPacket { - header: RtpHeader::default(), - seq_no: seq_no.into(), - time: MediaTime::from_90khz(0), - payload: millis.to_be_bytes().into(), - vp8_patch: None, - timestamp: after(now, millis), - last_sender_info: None, - nackable: true, - } - } - - #[test] - fn rtx_cache_0_sized() { - let now = Instant::now(); - let mut rtx_cache = RtxCache::new(0, Duration::from_secs(3)); - rtx_cache.cache_sent_packet(packet(now, 1, 10), after(now, 10)); - assert_eq!( - Some(&mut packet(now, 1, 10)), - rtx_cache.get_cached_packet_by_seq_no(1.into()) - ); - } - - #[test] - fn rtx_cache_0_duration() { - let now = Instant::now(); - let mut rtx_cache = RtxCache::new(10, Duration::from_secs(0)); - rtx_cache.cache_sent_packet(packet(now, 1, 10), after(now, 10)); - assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(1.into())); - } - - #[test] - fn rtx_cache_1_sized() { - let now = Instant::now(); - let mut rtx_cache = RtxCache::new(1, Duration::from_secs(3)); - rtx_cache.cache_sent_packet(packet(now, 1, 10), after(now, 10)); - assert_eq!( - Some(&mut packet(now, 1, 10)), - rtx_cache.get_cached_packet_by_seq_no(1.into()) - ); - rtx_cache.cache_sent_packet(packet(now, 2, 20), after(now, 20)); - assert_eq!( - Some(&mut packet(now, 2, 20)), - rtx_cache.get_cached_packet_by_seq_no(2.into()) - ); - } - - #[test] - fn rtx_cache_100_sized_backwards() { - let now = Instant::now(); - let mut rtx_cache = RtxCache::new(100, Duration::from_secs(3)); - - for i in 1..=200 { - let seq_no = 201 - i; - let pkt = packet(now, seq_no, (201 - i) * 10); - let now = after(now, i * 10); - rtx_cache.cache_sent_packet(pkt, now); - } - - assert_eq!( - Some(&mut packet(now, 200, 2000)), - rtx_cache.get_cached_packet_by_seq_no(200.into()) - ); - assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(100.into())); - assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(101.into())); - } - - #[test] - fn rtx_cache_eviction() { - let now = Instant::now(); - // Cache can take all entries - let mut rtx_cache = RtxCache::new(400, Duration::from_secs(1)); - for i in 1..=200 { - let seq_no = i; - let pkt = packet(now, seq_no, i * 10); - let now = after(now, i * 10); - rtx_cache.cache_sent_packet(pkt, now); - } - - assert_eq!(None, rtx_cache.get_cached_packet_by_seq_no(99.into())); - - assert_eq!( - Some(&mut packet(now, 100, 1000)), - rtx_cache.get_cached_packet_by_seq_no(100.into()) - ); - assert_eq!( - Some(&mut packet(now, 200, 2000)), - rtx_cache.get_cached_packet_by_seq_no(200.into()) - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/rtx_cache_buf.rs b/rs/moq-webrtc/src/vendor/str0m/streams/rtx_cache_buf.rs deleted file mode 100644 index 2657f357ec5..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/rtx_cache_buf.rs +++ /dev/null @@ -1,374 +0,0 @@ -#![allow(missing_docs)] - -use std::mem; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::util::already_happened; - -/// Fixed size buffer that evicts the oldest entries based on time. -/// -/// The buffer is ringbuffer-esque in that all elements are inserted with a position that is modulo to an -/// insert index into the buffer. That makes lookups very fast since they are fixed offsets. -/// -/// The buffer evicts values based on time. If the size of the buffer is too small and would -/// overwrite an entry that has not been evicted due to age, the buffer grows. -#[derive(Debug)] -pub struct EvictingBuffer { - buf: Vec>>, - /// How long to keep entries for. - max_age: Duration, - /// The maximum size allowed to grow to. Once this sized is reached, new pushed - /// entries will overwrite older entries even if they haven't reached max_age. - max_size: usize, - /// Last inserted position - last_position: Option, - /// Next element to evict. - next_evict: Option, - // Last timeout when we evicted elements. - last_timeout: Instant, -} - -/// Entry in the buffer to keep track of position and time separately. -#[derive(Debug)] -struct Entry { - /// Position is offset modulus the buffer size. - position: u64, - /// Entry time. Used for eviction. - timestamp: Instant, - /// The value held at this entry. - value: T, -} - -// We don't want to require that T is Clone/Copy, which means we -// must do this instead of using the vec![] macro. -fn prepare_buf(len: usize) -> Vec> { - let mut buf = Vec::with_capacity(len); - for _ in 0..len { - buf.push(None); - } - buf -} - -impl EvictingBuffer { - /// Creates a new buffer with an initial size. - pub fn new(initial_size: usize, max_age: Duration, max_size: usize) -> Self { - Self { - buf: prepare_buf(initial_size), - max_age, - max_size, - last_position: None, - next_evict: None, - last_timeout: already_happened(), - } - } - - fn index_for_position(&self, position: u64) -> usize { - (position % self.buf.len() as u64) as usize - } - - #[inline(always)] - fn is_inert(&self) -> bool { - self.buf.is_empty() || self.max_age.is_zero() - } - - /// Push a new entry. - /// - /// Position is an increasing sequence number. The sequence can be out of order. - pub fn push(&mut self, position: u64, timestamp: Instant, value: T) { - if self.is_inert() { - return; - } - - if timestamp < self.last_timeout { - // Value is already considered evicted. - return; - } - - let next_evict = if let Some(v) = self.next_evict { - v - } else { - // First ever cached value sets the initial evict position. - self.next_evict = Some(position); - position - }; - - if position < next_evict { - // Do not cache values preceding evict position. - return; - } - - let mut index = self.index_for_position(position); - - if let Some(entry) = &self.buf[index] { - // If the position is exactly the same, we allow it since it's - // replacing the current T value. If position differs, we've - // wrapped around. - if entry.position != position { - // Make space to continue. - self.grow(); - index = self.index_for_position(position); - } - } - self.last_position = Some(position); - - self.buf[index] = Some(Entry { - position, - timestamp, - value, - }); - } - - /// Get the entry for the previously inserted position. - #[allow(unused)] - pub fn get(&self, position: u64) -> Option<&T> { - if self.is_inert() { - return None; - } - - let index = (position % self.buf.len() as u64) as usize; - if let Some(entry) = &self.buf[index] { - if entry.position == position { - return Some(&entry.value); - } - } - None - } - - pub fn get_mut(&mut self, position: u64) -> Option<&mut T> { - if self.is_inert() { - return None; - } - - let index = (position % self.buf.len() as u64) as usize; - if let Some(entry) = &mut self.buf[index] { - if entry.position == position { - return Some(&mut entry.value); - } - } - None - } - - pub fn maybe_evict(&mut self, now: Instant) { - if self.is_inert() { - return; - } - - if now < self.last_timeout { - // Time cannot go backwards. - return; - } - self.last_timeout = now; - - self.evict(now); - } - - fn evict(&mut self, now: Instant) { - let Some(start_position) = self.next_evict else { - // Before first element been pushed. - return; - }; - - let mut position = start_position; - let start_index = self.index_for_position(position); - - loop { - let index = self.index_for_position(position); - - if index == start_index && position > start_position { - // looped around without finding the end. Means there are no elements. - break; - } - - let Some(entry) = &self.buf[index] else { - // No entry means we might have a gap. We can't break on gaps because - // there might be entries to evict later. Skip the position and check - // until we find a timestamp. - position += 1; - continue; - }; - - let age = now.saturating_duration_since(entry.timestamp); - - if age > self.max_age { - // Evict. - self.buf[index] = None; - } else { - // We assume entries are roughly in time order (some jumble is allowed). - // Once we reach an element we should not evict, stop. - break; - } - - position += 1; - } - - self.next_evict = Some(position); - } - - fn grow(&mut self) { - if self.buf.len() >= self.max_size { - // No growing. - return; - } - - // This is the new sized buffer. We can make other strategies for growing. - let new_size = self.max_size.min((self.buf.len() * 133) / 100).max(self.buf.len() + 1); - - let old_buffer = mem::replace(&mut self.buf, prepare_buf(new_size)); - - // Move all entries over to the new buffer. Changing the buffer size might alter the - // index position. However max_position and next_evict are already containing positions - // not index, which means they stay correct. - for e in old_buffer.into_iter().flatten() { - let index = self.index_for_position(e.position); - self.buf[index] = Some(e); - } - } - - pub fn last_position(&self) -> Option { - if self.is_inert() { - return None; - } - - self.last_position - } - - pub fn last(&self) -> Option<&T> { - if self.is_inert() { - return None; - } - - let last = self.last_position?; - self.get(last) - } - - pub fn clear(&mut self) { - for i in 0..self.buf.len() { - self.buf[i] = None; - } - self.last_position = None; - self.next_evict = None; - self.last_timeout = already_happened(); - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn push_and_get() { - let mut buf = EvictingBuffer::new(1, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(5, now, 'A'); - - assert_eq!(buf.index_for_position(5), buf.index_for_position(3)); - assert_eq!(buf.get(5), Some(&'A')); - assert_eq!(buf.get(3), None); // modulo to same index - } - - #[test] - fn push_over_capacity() { - let mut buf = EvictingBuffer::new(2, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(5, now + Duration::from_secs(0), 'A'); - buf.push(6, now + Duration::from_secs(1), 'B'); - buf.push(7, now + Duration::from_secs(2), 'C'); - - // The size is 2, we should have grown to accomodate. - assert_eq!(buf.get(5), Some(&'A')); - assert_eq!(buf.get(6), Some(&'B')); - assert_eq!(buf.get(7), Some(&'C')); - } - - #[test] - fn push_before_next_evict() { - let mut buf = EvictingBuffer::new(2, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(6, now + Duration::from_secs(0), 'B'); - assert_eq!(buf.next_evict, Some(6)); - - // Before the initial evict position, thus ignored. - buf.push(5, now + Duration::from_secs(1), 'A'); - - assert_eq!(buf.get(5), None); - } - - #[test] - fn evict_oldest() { - let mut buf = EvictingBuffer::new(2, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(5, now + Duration::from_secs(0), 'A'); - buf.push(6, now + Duration::from_secs(1), 'B'); - - // Nothing should go - buf.maybe_evict(now + Duration::from_secs(1)); - assert_eq!(buf.get(5), Some(&'A')); - assert_eq!(buf.get(6), Some(&'B')); - - // One entry gone. - buf.maybe_evict(now + Duration::from_secs(11)); - assert_eq!(buf.get(5), None); - assert_eq!(buf.get(6), Some(&'B')); - } - - #[test] - fn evict_with_gap() { - let mut buf = EvictingBuffer::new(4, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(5, now + Duration::from_secs(0), 'A'); - // GAP - buf.push(7, now + Duration::from_secs(2), 'C'); - buf.push(8, now + Duration::from_secs(3), 'D'); - - // Should evict A and C - buf.maybe_evict(now + Duration::from_secs(13)); - - assert_eq!(buf.get(5), None); - assert_eq!(buf.get(7), None); - assert_eq!(buf.get(8), Some(&'D')); - } - - #[test] - fn evict_all() { - let mut buf = EvictingBuffer::new(4, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(5, now + Duration::from_secs(0), 'A'); - buf.push(6, now + Duration::from_secs(1), 'B'); - - // Should evict A and B - buf.maybe_evict(now + Duration::from_secs(12)); - - assert_eq!(buf.get(5), None); - assert_eq!(buf.get(6), None); - } - - fn buffer_cmp(b: &EvictingBuffer) -> Vec> { - b.buf.iter().map(|e| e.as_ref().map(|v| v.value)).collect() - } - - #[test] - fn grow_and_reindex() { - let mut buf = EvictingBuffer::new(2, Duration::from_secs(10), 10); - let now = Instant::now(); - - buf.push(2, now + Duration::from_secs(0), 'A'); - buf.push(3, now + Duration::from_secs(1), 'B'); - - assert_eq!(buffer_cmp(&buf), &[Some('A'), Some('B')]); - - // overwrites 2, thus grows - buf.push(4, now + Duration::from_secs(2), 'C'); - - assert_eq!(buffer_cmp(&buf), &[Some('B'), Some('C'), Some('A')]); - - assert_eq!(buf.get(2), Some(&'A')); - assert_eq!(buf.get(3), Some(&'B')); - assert_eq!(buf.get(4), Some(&'C')); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/send.rs b/rs/moq-webrtc/src/vendor/str0m/streams/send.rs deleted file mode 100644 index 4e984d3190e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/send.rs +++ /dev/null @@ -1,1108 +0,0 @@ -use std::collections::VecDeque; -use std::sync::Arc; -use std::time::Duration; -use std::time::Instant; -use tracing::{debug, trace, warn}; - -use crate::vendor::str0m::config_mod::RtcpReportIntervals; -use crate::vendor::str0m::format::CodecConfig; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::io::DATAGRAM_MAX_PACKET_SIZE; -use crate::vendor::str0m::media::KeyframeRequestKind; -use crate::vendor::str0m::media::Media; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::pacer::QueuePriority; -use crate::vendor::str0m::pacer::QueueSnapshot; -use crate::vendor::str0m::pacer::QueueState; -use crate::vendor::str0m::packet::Vp8Patch; -use crate::vendor::str0m::rtp_::MidRid; -use crate::vendor::str0m::rtp_::{Bitrate, Descriptions, Extension, ExtensionMap, ExtensionValues, Frequency}; -use crate::vendor::str0m::rtp_::{MediaTime, Mid, NackEntry, ReportList, Rtcp, RtpHeader}; -use crate::vendor::str0m::rtp_::{Pt, Rid, RtcpFb, SenderInfo, SenderReport, Ssrc}; -use crate::vendor::str0m::rtp_::{SRTP_BLOCK_SIZE, SeqNo}; -use crate::vendor::str0m::rtp_::{Sdes, SdesType}; -use crate::vendor::str0m::session::PacketReceipt; -use crate::vendor::str0m::util::value_history::ValueHistory; -use crate::vendor::str0m::util::{InstantExt, already_happened, not_happening}; - -use super::RtpPacket; -use super::rtx_cache::RtxCache; -use super::send_queue::SendQueue; -use super::send_stats::StreamTxStats; - -pub const DEFAULT_RTX_CACHE_DURATION: Duration = Duration::from_secs(3); - -pub const DEFAULT_RTX_RATIO_CAP: Option = Some(0.15f32); - -/// A recently sampled view of an outgoing stream's send queue. -/// -/// str0m refreshes this information as part of its regular pacer and bandwidth-estimation -/// processing. Reading it does not cause a new value to be computed. -pub trait StreamTxQueueInfo { - /// When this queue information was sampled. - /// - /// Compare this value between reads to determine whether str0m has computed a new sample. - fn created_at(&self) -> Instant; - - /// Total number of bytes in the queue. - fn byte_size(&self) -> usize; - - /// Total number of packets in the queue. - fn packet_count(&self) -> usize; - - /// When the first packet still in the queue was enqueued. - fn first_unsent(&self) -> Option; -} - -impl StreamTxQueueInfo for QueueSnapshot { - fn created_at(&self) -> Instant { - self.created_at - } - - fn byte_size(&self) -> usize { - self.byte_size - } - - fn packet_count(&self) -> usize { - self.packet_count as usize - } - - fn first_unsent(&self) -> Option { - self.first_unsent - } -} - -/// Outgoing encoded stream. -/// -/// A stream is a primary SSRC + optional RTX SSRC. -/// -/// This is RTP level API. For frame level API see [`Rtc::writer`][crate::vendor::str0m::Rtc::writer]. -#[derive(Debug)] -pub struct StreamTx { - /// Unique identifier of the remote encoded stream. - ssrc: Ssrc, - - /// Identifier of a resend (RTX) stream. If we are doing resends. - rtx: Option, - - /// The Media mid and rid this stream belongs to. - midrid: MidRid, - - /// Set on first handle_timeout. - kind: Option, - - /// Set on first handle_timeout. - cname: Option, - - /// The last main payload clock rate that was sent. - clock_rate: Option, - - /// If we are doing seq_no ourselves (frame mode or SSRC 0 probing). - seq_no: SeqNo, - - /// If we are using RTX, this is the seq no counter. - seq_no_rtx: SeqNo, - - /// The last seq_no that we sent, either by increasing seq_no ourselves (media API), or by - /// direct RTP mode writing. - last_sent_seq_no: SeqNo, - - /// When we last sent something for this encoded stream, packet or RTCP. - last_used: Instant, - - /// Last written media + wallclock time. - rtp_and_wallclock: Option<(u32, Instant)>, - - /// Queue of packets to send. - /// - /// The packets here do not have correct sequence numbers, header extension values etc. - /// They must be updated when we are about to send. - send_queue: SendQueue, - - /// The queue information sampled during the latest pacer update. - queue_info: Option, - - /// Scheduled resends due to NACK. - resends: VecDeque, - - /// Cache of sent packets to be able to answer to NACKs. - rtx_cache: RtxCache, - - /// Determines retransmitted bytes ratio value to clear queued resends. - rtx_ratio_cap: Option, - - /// Last time we produced a SR. - last_sender_report: Instant, - - /// If we have a pending incoming keyframe request. - pending_request_keyframe: Option, - - /// If we have a pending incoming remb request. - pending_request_remb: Option, - - /// Statistics of outgoing data. - /// - /// Stats are use to calculate the rtx ratio also when statistics events are disabled. - stats: StreamTxStats, - - // downsampled rtx ratio (value, last calculation) - rtx_ratio: (f32, Instant), - - /// Whether a receiver report has been received for this SSRC, thus acknowledging - /// that the receiver has bound the Mid/Rid tuple to the SSRC and no longer - /// needs to be sent on every packet - remote_acked_ssrc: bool, - - // Same as `remote_acked_ssrc`, but for the RTX SSRC - remote_acked_rtx_ssrc: bool, -} - -/// RTP packet data to enqueue on a direct RTP send stream. -/// -/// The payload is the RTP payload only, without the RTP header. -/// -/// Optional RTP fields default to the common unmarked non-nackable packet with -/// no header extension values, no CSRC entries and no VP8 rewrite. -#[derive(Debug)] -pub struct RtpWrite { - pt: Pt, - seq_no: SeqNo, - time: u32, - wallclock: Instant, - marker: bool, - ext_vals: ExtensionValues, - nackable: bool, - payload: Arc<[u8]>, - csrc_count: usize, - csrc: [u32; 15], - vp8_patch: Option, -} - -impl RtpWrite { - /// Create a direct RTP write command. - /// - /// The `payload` argument is expected to be only the RTP payload, not the - /// RTP packet header. - /// - /// * `pt` Payload type. Declared in the [`Media`][crate::vendor::str0m::media::Media] this - /// encoded stream belongs to. - /// * `seq_no` Extended sequence number to use for this packet. Only the low - /// 16 bits are carried in the RTP header. The upper bits - /// (`seq_no.roc()`) supply the SRTP rollover counter (ROC) used - /// for the per-packet IV and authentication. See below for - /// initializing a stream with a nonzero ROC. - /// * `time` Time in whatever the clock rate is for the media in question - /// (normally 90_000 for video and 48_000 for audio). - /// * `wallclock` Real world time that corresponds to the media time in the - /// RTP packet. For an SFU, this can be hard to know because - /// RTP packets typically only contain the media time (RTP - /// time). In the simplest SFU setup, the wallclock could - /// simply be the arrival time of the incoming RTP data. For - /// better synchronization the SFU probably needs to weigh in - /// clock drifts and data provided via the statistics, receiver - /// reports etc. - /// * `payload` RTP packet payload, without header. - /// - /// Optional fields default to an unmarked packet with no header extension - /// values, no CSRC entries, no VP8 patch and no NACK support. - /// [`RtpWrite::marker`] for video frame boundaries, - /// [`RtpWrite::ext_vals`] for RTP header extension values, - /// [`RtpWrite::nackable`] for packets that may answer incoming NACKs, - /// [`RtpWrite::csrc`] for contributing source identifiers, - /// [`RtpWrite::vp8_patch`] to apply a prevalidated VP8 payload descriptor patch during RTP serialization. - /// - /// # Initializing the rollover counter - /// - /// The ROC is not carried in the RTP header or transmitted by str0m in the - /// SRTP packet. A fresh receiver starts at ROC 0. To start a stream with a - /// higher ROC, the application must communicate that ROC and the stream's - /// SSRC to the receiver out of band, for example through its signaling - /// channel, and initialize the receiver before sending media. Otherwise, - /// sender and receiver use different packet indices and SRTP authentication - /// fails. See [RFC 3711 section 3.3.1][roc]. - /// - /// On the sender, the extended sequence number determines the ROC: - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::media::Pt; - /// # use crate::vendor::str0m::rtp::{RtpWrite, SeqNo, StreamTx}; - /// # fn send(stream: &mut StreamTx, pt: Pt, wallclock: Instant, payload: &[u8]) { - /// let seq_no: SeqNo = 100_000.into(); - /// assert_eq!(seq_no.roc(), 1); - /// assert_eq!(seq_no.as_u16(), 34_464); - /// - /// // First communicate (stream.ssrc(), seq_no.roc()) out of band and - /// // arrange for the receiver to initialize its ROC as shown below. - /// stream.write_rtp(RtpWrite::new(pt, seq_no, 0, wallclock, payload)); - /// # } - /// ``` - /// - /// On a str0m receiver, use [`StreamRx::reset_roc`][crate::vendor::str0m::rtp::StreamRx::reset_roc] - /// with the signaled ROC before handling the first SRTP packet. This example - /// assumes the media identified by `mid` has already been declared: - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// # use crate::vendor::str0m::media::Mid; - /// # use crate::vendor::str0m::rtp::Ssrc; - /// # fn initialize_receiver(rtc: &mut Rtc, mid: Mid, ssrc: Ssrc, signaled_roc: u64) { - /// // `ssrc` and `signaled_roc` come from the application's signaling channel. - /// let mut direct = rtc.direct_api(); - /// let stream = direct.expect_stream_rx(ssrc, None, mid, None); - /// stream.reset_roc(signaled_roc); // 1 for the sender example above. - /// # } - /// ``` - /// - /// Continue supplying extended sequence numbers on the sender across - /// rollovers; the receiver tracks subsequent rollovers automatically. - /// Without out-of-band ROC initialization, start the outgoing stream with - /// `seq_no < 65_536`. In particular, forwarding a long-running source's - /// extended sequence numbers to a new receiver requires either signaling - /// its initial ROC or rebasing the outgoing sequence numbers for that receiver. - /// - /// [roc]: https://www.rfc-editor.org/rfc/rfc3711.html#section-3.3.1 - pub fn new(pt: Pt, seq_no: SeqNo, time: u32, wallclock: Instant, payload: impl Into>) -> Self { - Self { - pt, - seq_no, - time, - wallclock, - marker: false, - ext_vals: ExtensionValues::default(), - nackable: false, - payload: payload.into(), - csrc_count: 0, - csrc: [0; 15], - vp8_patch: None, - } - } - - /// Set the RTP marker bit. - pub fn marker(mut self, marker: bool) -> Self { - self.marker = marker; - self - } - - /// Set RTP header extension values. - pub fn ext_vals(mut self, ext_vals: ExtensionValues) -> Self { - self.ext_vals = ext_vals; - self - } - - /// Set whether this RTP packet should respond to incoming NACKs. - pub fn nackable(mut self, nackable: bool) -> Self { - self.nackable = nackable; - self - } - - /// Set contributing source identifiers. - /// - /// # Panics - /// - /// Panics if more than 15 entries are supplied. - pub fn csrc(mut self, csrc: &[u32]) -> Self { - assert!(csrc.len() <= 15, "CSRC count must be <= 15"); - - self.csrc = [0; 15]; - self.csrc[..csrc.len()].copy_from_slice(csrc); - self.csrc_count = csrc.len(); - self - } - - /// Apply a prevalidated VP8 payload descriptor patch during RTP serialization. - /// - /// Build the patch with [`Vp8Descriptor::patch`][crate::vendor::str0m::rtp::Vp8Descriptor::patch] - /// when the caller already parsed the VP8 payload descriptor before - /// constructing this write command. - pub fn vp8_patch(mut self, patch: Vp8Patch) -> Self { - self.vp8_patch = Some(patch); - self - } -} - -impl StreamTx { - pub(crate) fn new(ssrc: Ssrc, rtx: Option, midrid: MidRid) -> Self { - debug!("Create StreamTx for SSRC: {}", ssrc); - - StreamTx { - ssrc, - rtx, - midrid, - kind: None, - cname: None, - clock_rate: None, - seq_no: SeqNo::default(), - seq_no_rtx: SeqNo::default(), - last_sent_seq_no: SeqNo::default(), - last_used: already_happened(), - rtp_and_wallclock: None, - send_queue: SendQueue::new(), - queue_info: None, - resends: VecDeque::new(), - rtx_cache: RtxCache::new(2000, DEFAULT_RTX_CACHE_DURATION), - rtx_ratio_cap: DEFAULT_RTX_RATIO_CAP, - last_sender_report: already_happened(), - pending_request_keyframe: None, - pending_request_remb: None, - stats: StreamTxStats::new(), - rtx_ratio: (0.0, already_happened()), - remote_acked_ssrc: false, - remote_acked_rtx_ssrc: false, - } - } - - /// The (primary) SSRC of this encoded stream. - pub fn ssrc(&self) -> Ssrc { - self.ssrc - } - - /// The resend (RTX) SSRC of this encoded stream. - pub fn rtx(&self) -> Option { - self.rtx - } - - /// Mid for this stream. - /// - /// In SDP this corresponds to m-line and "Media". - pub fn mid(&self) -> Mid { - self.midrid.mid() - } - - /// Rid for this stream. - /// - /// This is used to separate streams with the same [`Mid`] when using simulcast. - pub fn rid(&self) -> Option { - self.midrid.rid() - } - - /// Information sampled during the latest pacer update for this stream's send queue. - /// - /// This is `None` until the pacer has observed the stream for the first time. - /// Calling this method does not refresh the information; use - /// [`StreamTxQueueInfo::created_at()`] to determine whether a new sample is available. - pub fn queue_info(&self) -> Option<&dyn StreamTxQueueInfo> { - self.queue_info.as_ref().map(|info| info as &dyn StreamTxQueueInfo) - } - - /// Configure the RTX (resend) cache. - /// - /// This determines how old incoming NACKs we can reply to. - /// - /// `rtx_ratio_cap` determines when to clear queued resends because of too many resends, - /// i.e. if `tx_sum / (rtx_sum + tx_sum) > rtx_ratio_cap`. `None` disables this functionality - /// so all queued resends will be sent. - /// - /// The default is 1024 packets over 3 seconds and RTX cache drop ratio of 0.15. - pub fn set_rtx_cache(&mut self, max_packets: usize, max_age: Duration, rtx_ratio_cap: Option) { - // Dump old cache to avoid having to deal with resizing logic inside the cache impl. - self.rtx_cache = RtxCache::new(max_packets, max_age); - if rtx_ratio_cap.is_some() { - self.stats.bytes_transmitted.get_or_insert_with(ValueHistory::default); - self.stats.bytes_retransmitted.get_or_insert_with(ValueHistory::default); - } else { - self.stats.bytes_transmitted = None; - self.stats.bytes_retransmitted = None; - } - self.rtx_ratio_cap = rtx_ratio_cap; - } - - /// Write RTP packet to a send stream. - /// - /// The write command carries the RTP payload and optional RTP metadata. - pub fn write_rtp(&mut self, rtp: RtpWrite) { - let RtpWrite { - pt, - seq_no, - time, - wallclock, - marker, - ext_vals, - nackable, - payload, - csrc_count, - csrc, - vp8_patch, - } = rtp; - - let first_call = self.rtp_and_wallclock.is_none(); - - if first_call && seq_no.roc() > 0 { - // TODO: make it possible to supress this. - warn!( - "First SeqNo has non-zero ROC ({}), which needs out-of-band signalling \ - to remote peer", - seq_no.roc() - ); - } - - // This 1 in clock frequency will be fixed in poll_output. - let media_time = MediaTime::from_secs(time as u64); - self.rtp_and_wallclock = Some((time, wallclock)); - - let header = RtpHeader { - csrc_count, - sequence_number: *seq_no as u16, - marker, - payload_type: pt, - timestamp: time, - ssrc: self.ssrc, - csrc, - ext_vals, - ..Default::default() - }; - - let packet = RtpPacket { - seq_no, - time: media_time, - header, - payload, - vp8_patch, - nackable, - // The overall idea for str0m is to only drive time forward from handle_input. If we - // used a "now" argument to write_rtp(), we effectively get a second point that also need - // to move time forward _for all of Rtc_ – that's too complicated. - // - // Instead we set a future timestamp here. When time moves forward in the "regular way", - // in handle_timeout() we delegate to self.send_queue.handle_timeout() to mark the enqueued - // timestamp of all packets that are about to be sent. - timestamp: not_happening(), - - // This is only relevant for incoming RTP packets. - last_sender_info: None, - }; - - self.send_queue.push(packet); - } - - pub(crate) fn poll_packet( - &mut self, - now: Instant, - exts: &ExtensionMap, - twcc: Option<&mut u64>, - params: &[PayloadParams], - buf: &mut Vec, - ) -> Option { - let mid = self.midrid.mid(); - let rid = self.midrid.rid(); - let ssrc_rtx = self.rtx; - let remote_acked_ssrc = self.remote_acked_ssrc; - let remote_acked_rtx_ssrc = self.remote_acked_rtx_ssrc; - - let next = if let Some(next) = self.poll_packet_resend(now) { - next - } else { - self.poll_packet_regular(now)? - }; - - let pop_send_queue = next.kind == NextPacketKind::Regular; - - // Need the header for the receipt and modifications - // TODO: Can we remove this? - let header_ref = &mut next.pkt.header; - - // - // BUNDLE requires that the receiver "bind" the received SSRC to the values - // in the MID and/or (R)RID header extensions if present. Therefore, the - // sender can reduce overhead by omitting these header extensions once it - // knows that the receiver has "bound" the SSRC. - // - // The algorithm here is fairly simple: Always attach a MID and/or RID (if - // configured) to the outgoing packets until an RTCP receiver report comes - // back for this SSRC. That feedback indicates the receiver must have - // received a packet with the SSRC and header extension(s), so the sender - // then stops attaching the MID and RID. - if !remote_acked_ssrc { - header_ref.ext_vals.mid = Some(mid); - header_ref.ext_vals.rid = rid; - } - - let pt_main = header_ref.payload_type; - - // The pt in next.pkt is the "main" pt. - let Some(param) = params.iter().find(|p| p.pt() == pt_main) else { - // PT does not exist in the connected media. - warn!("Media is missing PT ({}) used in RTP packet", pt_main); - - // Get rid of this packet we can't send. - if pop_send_queue { - self.send_queue.pop(now); - } - - return None; - }; - - let mut set_cr = None; - - let mut header = match next.kind { - NextPacketKind::Regular => { - if param.resend().is_none() { - // If the PT we're sending on doesn't have a corresponding RTX PT, - // the packet is de-facto not nackable. - // - // This blocks incoming NACK requests and thus ensures there are no - // entries in self.retries without a RTX PT. - next.pkt.nackable = false; - } - - let clock_rate = param.spec().clock_rate; - set_cr = Some(clock_rate); - - // Modify the cached packet time. This is so write_rtp can use u32 media time without - // worrying about lengthening or the clock rate. - let time = MediaTime::new(next.pkt.time.numer(), clock_rate); - next.pkt.time = time; - - // Modify the original (and also cached) header value. - header_ref.ext_vals.rid_repair = None; - - header_ref.clone() - } - NextPacketKind::Resend(_) => { - // We will not have accepted/cached the packet unless we have a RTX PT - // (see logic setting next.pkt.nackable above). - let pt_rtx = param.resend().expect("PT for resend"); - - // Clone header to not change the original (cached) header. - let mut header = header_ref.clone(); - - // Update clone of header (to not change the cached value). - header.payload_type = pt_rtx; - header.ssrc = ssrc_rtx.expect("Should have RTX SSRC for resends"); - header.sequence_number = *next.seq_no as u16; - - header.ext_vals.rid = None; - header.ext_vals.rid_repair = rid; - - if !remote_acked_rtx_ssrc { - header.ext_vals.mid = Some(mid); - } - - header - } - }; - - // These need to match `Extension::is_supported()` so we are sending what we are - // declaring we support. - - // Absolute Send Time might not be enabled for this m-line. - if exts.id_of(Extension::AbsoluteSendTime).is_some() { - header.ext_vals.abs_send_time = Some(now); - } - - // TWCC might not be enabled for this m-line. - if let Some(twcc) = twcc { - header.ext_vals.transport_cc = Some(*twcc as u16); - *twcc += 1; - } - - buf.resize(DATAGRAM_MAX_PACKET_SIZE, 0); - - let header_len = header.write_to(buf, exts); - assert!(header_len % 4 == 0, "RTP header must be multiple of 4"); - header.header_len = header_len; - - let mut body_out = &mut buf[header_len..]; - - // For resends, the original seq_no is inserted before the payload. - let mut original_seq_len = 0; - if let NextPacketKind::Resend(orig_seq_no) = next.kind { - original_seq_len = RtpHeader::write_original_sequence_number(body_out, orig_seq_no); - body_out = &mut body_out[original_seq_len..]; - } - - let pkt = &next.pkt; - - let body_len = pkt.payload.len(); - if let Some(patch) = pkt.vp8_patch.as_ref() { - patch.copy_to(pkt.payload.as_ref(), &mut body_out[..body_len]); - } else { - body_out[..body_len].copy_from_slice(pkt.payload.as_ref()); - } - - // media packets are sent unpadded: the SRTP ciphers handle - // arbitrary body lengths (the CTR scratch alignment is internal - // to protect_rtp), and RTP-level padding breaks SFUs that - // re-marshal forwarded packets without it while keeping the P - // bit (observed with LiveKit -> Chrome, str0m issue #1014) - let body_len = body_len + original_seq_len; - - buf.truncate(header_len + body_len); - - let seq_no = next.seq_no; - if next.kind == NextPacketKind::Regular { - self.last_sent_seq_no = seq_no; - } - - self.last_used = now; - - if set_cr.is_some() && self.clock_rate != set_cr { - self.clock_rate = set_cr; - } - - if pop_send_queue { - // poll_packet_regular leaves the packet in the head of the send_queue - let pkt = self.send_queue.pop(now).expect("head of send_queue to be there"); - if pkt.nackable { - self.rtx_cache.cache_sent_packet(pkt, now); - } - } - - Some(PacketReceipt { - header, - seq_no, - payload_size: body_len, - }) - } - - fn rtx_ratio_downsampled(&mut self, now: Instant) -> f32 { - assert!(self.stats.bytes_transmitted.is_some(), "rtx_ratio_cap must be enabled"); - assert!( - self.stats.bytes_retransmitted.is_some(), - "rtx_ratio_cap must be enabled" - ); - - let (value, ts) = self.rtx_ratio; - if now - ts < Duration::from_millis(50) { - // not worth re-evaluating, return the old value - return value; - } - - // bytes stats refer to the last second by default - self.stats.bytes_transmitted.as_mut().unwrap().purge_old(now); - self.stats.bytes_retransmitted.as_mut().unwrap().purge_old(now); - - let bytes_transmitted = self.stats.bytes_transmitted.as_mut().unwrap().sum(); - let bytes_retransmitted = self.stats.bytes_retransmitted.as_mut().unwrap().sum(); - let ratio = bytes_retransmitted as f32 / (bytes_retransmitted + bytes_transmitted) as f32; - let ratio = if ratio.is_finite() { ratio } else { 0_f32 }; - self.rtx_ratio = (ratio, now); - ratio - } - - fn poll_packet_resend(&mut self, now: Instant) -> Option> { - if let Some(ratio_cap) = self.rtx_ratio_cap { - let ratio = self.rtx_ratio_downsampled(now); - - // If we hit the cap, stop doing resends by clearing those we have queued. - if ratio > ratio_cap { - self.resends.clear(); - return None; - } - } - - let seq_no = loop { - let resend = self.resends.pop_front()?; - - let pkt = self.rtx_cache.get_cached_packet_by_seq_no(resend.seq_no); - - // The seq_no could simply be too old to exist in the buffer, in which - // case we will not do a resend. - let Some(pkt) = pkt else { - continue; - }; - - // Cached packets must be nackable. This is ensured before adding the - // entry to the self.rtx_cache. - assert!(pkt.nackable); - - break pkt.seq_no; - }; - - // Borrow checker gymnastics. - let pkt = self.rtx_cache.get_cached_packet_by_seq_no(seq_no).unwrap(); - - let len = pkt.payload.len() as u64; - self.stats.update_packet_counts(len, true); - if let Some(h) = &mut self.stats.bytes_retransmitted { - h.push(now, len); - } - - let seq_no = self.seq_no_rtx.inc(); - - let orig_seq_no = pkt.seq_no; - - Some(NextPacket { - kind: NextPacketKind::Resend(orig_seq_no), - seq_no, - pkt, - }) - } - - fn poll_packet_regular(&mut self, now: Instant) -> Option> { - // exit via ? here is ok since that means there is nothing to send. - // The packet remains in the head of the send queue until we - // finish poll_packet, at which point we move it to the cache. - let pkt = self.send_queue.peek()?; - - let len = pkt.payload.len() as u64; - self.stats.update_packet_counts(len, false); - if let Some(h) = &mut self.stats.bytes_transmitted { - h.push(now, len) - } - - let seq_no = pkt.seq_no; - - Some(NextPacket { - kind: NextPacketKind::Regular, - seq_no, - pkt, - }) - } - - fn is_audio(&self) -> bool { - self.kind.is_some_and(|kind| kind.is_audio()) - } - - pub(crate) fn sender_report_at(&self, intervals: RtcpReportIntervals) -> Instant { - if self.kind.is_none() { - // First handle_timeout sets the kind. No sender report until then. - return not_happening(); - } - self.last_sender_report + intervals.for_audio(self.is_audio()) - } - - pub(crate) fn poll_keyframe_request(&mut self) -> Option { - self.pending_request_keyframe.take() - } - - pub(crate) fn poll_remb_request(&mut self) -> Option { - self.pending_request_remb.take() - } - - pub(crate) fn handle_rtcp(&mut self, now: Instant, fb: RtcpFb) { - use RtcpFb::*; - match fb { - ReceptionReport(r) => { - if let Some(rtx_ssrc) = self.rtx { - if rtx_ssrc == r.ssrc { - // Receiver has bound MidRid to RTX SSRC - self.remote_acked_rtx_ssrc = true; - } - } else if r.ssrc == self.ssrc { - // Receiver has bound MidRid to SSRC - self.remote_acked_ssrc = true; - } - - self.stats.update_with_rr(now, self.last_sent_seq_no, r) - } - Nack(_, list) => { - self.stats.increase_nacks(); - let entries = list.into_iter(); - self.handle_nack(entries, now); - } - Pli(_) => { - self.stats.increase_plis(); - self.pending_request_keyframe = Some(KeyframeRequestKind::Pli); - } - Fir(_) => { - self.stats.increase_firs(); - self.pending_request_keyframe = Some(KeyframeRequestKind::Fir); - } - Remb(r) => { - self.pending_request_remb = Some(Bitrate::from(r.bitrate as f64)); - } - Twcc(_) => unreachable!("TWCC should be handled on session level"), - _ => {} - } - } - - pub(crate) fn handle_nack(&mut self, entries: impl Iterator, now: Instant) -> Option<()> { - // Turning NackEntry into SeqNo we need to know a SeqNo "close by" to lengthen the 16 bit - // sequence number into the 64 bit we have in SeqNo. - let seq_no = self.rtx_cache.last_cached_seq_no()?; - let iter = entries.flat_map(|n| n.into_iter(seq_no)); - - // Schedule all resends. They will be handled on next poll_packet - for seq_no in iter { - let Some(packet) = self.rtx_cache.get_cached_packet_by_seq_no(seq_no) else { - // Packet was not available in RTX cache, it has probably expired. - continue; - }; - - let resend = Resend { - seq_no, - queued_at: now, - payload_size: packet.payload.len(), - }; - self.resends.push_back(resend); - } - - Some(()) - } - - pub(crate) fn need_sr(&self, now: Instant, intervals: RtcpReportIntervals) -> bool { - now >= self.sender_report_at(intervals) - } - - pub(crate) fn create_sr_and_update(&mut self, now: Instant, feedback: &mut VecDeque) { - let sr = self.create_sender_report(now); - - trace!("Created feedback SR: {:?}", sr); - feedback.push_back(Rtcp::SenderReport(sr)); - - if let Some(ds) = self.create_sdes() { - feedback.push_back(Rtcp::SourceDescription(ds)); - } - - // Update timestamp to move time when next is created. - self.last_sender_report = now; - } - - fn create_sender_report(&self, now: Instant) -> SenderReport { - SenderReport { - sender_info: self.sender_info(now), - reports: ReportList::new(), - } - } - - fn create_sdes(&self) -> Option { - // CNAME is set on first handle_timeout. No SDES before that. - let cname = self.cname.as_ref()?; - let mut s = Sdes { - ssrc: self.ssrc, - values: ReportList::new(), - }; - s.values.push((SdesType::CNAME, cname.to_string())); - - let mut d = Descriptions { - reports: Box::new(ReportList::new()), - }; - d.reports.push(s); - - Some(d) - } - - fn sender_info(&self, now: Instant) -> SenderInfo { - let rtp_time = self.current_rtp_time(now).unwrap_or(MediaTime::ZERO); - - SenderInfo { - ssrc: self.ssrc, - ntp_time: now.to_system_time(), - rtp_time, - sender_packet_count: self.stats.packets as u32, - sender_octet_count: self.stats.bytes as u32, - } - } - - fn current_rtp_time(&self, now: Instant) -> Option { - // This is the RTP time and the wallclock from the last written media. - // We use that as an offset to current time (now), to calculate the - // current RTP time. - let (t_u32, w) = self.rtp_and_wallclock?; - - let clock_rate = self.clock_rate?; - let t = MediaTime::new(t_u32 as u64, clock_rate); - - // Wallclock needs to be in the past. - if w > now { - let delta = w - now; - debug!("write_rtp wallclock is in the future: {:?}", delta); - return None; - } - let offset = now - w; - - // This might be in the wrong base. - let rtp_time = t + offset.into(); - - Some(rtp_time.rebase(clock_rate)) - } - - pub(crate) fn next_seq_no(&mut self) -> SeqNo { - self.seq_no.inc() - } - - pub(crate) fn last_packet(&self) -> Option<&[u8]> { - if self.send_queue.is_empty() { - self.rtx_cache.last_packet() - } else { - self.send_queue.last().map(|q| q.payload.as_ref()) - } - } - - pub(crate) fn queue_state(&mut self, now: Instant) -> QueueState { - let mut snapshot = self.send_queue.snapshot(now); - - if let Some(snapshot_resend) = self.queue_state_resend(now) { - snapshot.merge(&snapshot_resend); - } - - self.queue_info = Some(snapshot); - - QueueState { - midrid: self.midrid, - snapshot, - } - } - - fn queue_state_resend(&self, now: Instant) -> Option { - if self.resends.is_empty() { - return None; - } - - // Outstanding resends - let mut snapshot = self.resends.iter().fold(QueueSnapshot::default(), |mut snapshot, r| { - snapshot.total_queue_time_origin += now.duration_since(r.queued_at); - snapshot.byte_size += r.payload_size; - snapshot.packet_count += 1; - snapshot.first_unsent = snapshot.first_unsent.map(|i| i.min(r.queued_at)).or(Some(r.queued_at)); - - snapshot - }); - snapshot.created_at = now; - snapshot.update_priority(QueuePriority::Media); - - Some(snapshot) - } - - pub(crate) fn need_timeout(&self) -> bool { - self.send_queue.need_timeout() - } - - pub(crate) fn handle_timeout<'a>(&mut self, now: Instant, get_media: impl FnOnce() -> &'a Media) { - // If kind is None, this is the first time we ever get a handle_timeout. - if self.kind.is_none() { - self.on_first_timeout(get_media()); - } - - self.send_queue.handle_timeout(now); - } - - fn on_first_timeout(&mut self, media: &Media) { - // Always set on first timeout. - self.kind = Some(media.kind()); - self.cname = Some(media.cname().to_string()); - } - - pub(crate) fn reset_buffers(&mut self) { - self.send_queue.clear(); - self.queue_info = None; - self.rtx_cache.clear(); - self.resends.clear(); - } - - /// Reset this stream to use a new SSRC and optionally a new RTX SSRC. - /// - /// This updates the SSRCs and resets all relevant internal fields. - pub(crate) fn reset_ssrc(&mut self, new_ssrc: Ssrc, new_rtx: Option) { - // Update the SSRC and RTX - self.ssrc = new_ssrc; - self.rtx = new_rtx; - - // Reset sequence numbers - self.seq_no = SeqNo::default(); - self.seq_no_rtx = SeqNo::default(); - - // Reset timing related fields - self.last_used = already_happened(); - self.rtp_and_wallclock = None; - self.last_sender_report = already_happened(); - - // Clear any pending requests - self.pending_request_keyframe = None; - self.pending_request_remb = None; - - // Reset all statistics. - self.stats = StreamTxStats::new(); - self.rtx_ratio = (0.0, already_happened()); - self.remote_acked_ssrc = false; - - // Clear all buffers - self.reset_buffers(); - } - - pub(crate) fn is_midrid(&self, midrid: MidRid) -> bool { - midrid.special_equals(&self.midrid) - } -} - -struct NextPacket<'a> { - kind: NextPacketKind, - seq_no: SeqNo, - pkt: &'a mut RtpPacket, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum NextPacketKind { - Regular, - Resend(SeqNo), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct Resend { - seq_no: SeqNo, - queued_at: Instant, - payload_size: usize, -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn queue_time_counts_only_unsent_packets_while_the_queue_never_empties() { - let start = Instant::now(); - let codecs = CodecConfig::new_with_defaults(); - let pt = codecs.params()[0].pt(); - let exts = ExtensionMap::standard(); - let mut streams = crate::vendor::str0m::streams::Streams::new(Duration::from_millis(1500)); - let stream = streams.declare_stream_tx(42.into(), None, MidRid("vid".into(), None)); - let mut buf = vec![]; - let mut now = start; - for i in 0..205_u64 { - now = start + Duration::from_millis(i * 10); - stream.write_rtp(RtpWrite::new(pt, i.into(), 0, now, vec![0_u8; 1000])); - stream.send_queue.handle_timeout(now); - if i >= 5 { - stream - .poll_packet(now, &exts, None, codecs.params(), &mut buf) - .expect("a queued packet to send"); - } - } - let snapshot = stream.queue_state(now).snapshot; - // The five queued packets are 0, 10, 20, 30 and 40 ms old. - assert_eq!(snapshot.packet_count, 5); - assert_eq!(snapshot.total_queue_time(now), Duration::from_millis(100)); - } - - #[test] - fn queue_info_is_cached_on_queue_state_update() { - let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None)); - - assert!(stream.queue_info().is_none()); - - let now = Instant::now(); - let first_unsent = now - Duration::from_millis(10); - stream.resends.push_back(Resend { - seq_no: 7.into(), - queued_at: first_unsent, - payload_size: 123, - }); - stream.queue_state(now); - - let info = stream.queue_info().expect("queue info after pacer update"); - assert_eq!(info.created_at(), now); - assert_eq!(info.byte_size(), 123); - assert_eq!(info.packet_count(), 1); - assert_eq!(info.first_unsent(), Some(first_unsent)); - - stream.reset_buffers(); - assert!(stream.queue_info().is_none()); - } - - #[test] - fn sender_report_uses_supplied_intervals() { - let mut stream = StreamTx::new(42.into(), None, MidRid(Mid::from("0"), None)); - let now = Instant::now(); - stream.kind = Some(MediaKind::Audio); - stream.last_sender_report = now; - - assert_eq!( - stream.sender_report_at(RtcpReportIntervals { - audio: Duration::from_millis(750), - video: Duration::from_millis(500), - }), - now + Duration::from_millis(750) - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/send_queue.rs b/rs/moq-webrtc/src/vendor/str0m/streams/send_queue.rs deleted file mode 100644 index ed32121e3b8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/send_queue.rs +++ /dev/null @@ -1,346 +0,0 @@ -use std::collections::VecDeque; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::pacer::{QueuePriority, QueueSnapshot}; -use crate::vendor::str0m::util::not_happening; - -use super::RtpPacket; - -#[derive(Debug)] -pub(crate) struct SendQueue { - queue: VecDeque, - total: TotalQueue, - last_emitted: Option, -} - -impl SendQueue { - pub fn new() -> Self { - Self { - queue: VecDeque::new(), - total: TotalQueue::default(), - last_emitted: None, - } - } - - pub fn push(&mut self, mut packet: RtpPacket) { - // Every incoming packet must be timestamped withe a handle_timeout. - // This sentinel value indicates it is needed. - packet.timestamp = not_happening(); - - self.queue.push_back(packet); - } - - pub fn handle_timeout(&mut self, now: Instant) { - for pkt in self.queue.iter_mut().rev() { - if pkt.timestamp != not_happening() { - // all enqueued packets are timestamped. - break; - } else { - pkt.timestamp = now; - self.total.increase(now, pkt.payload.len()); - } - } - } - - pub fn need_timeout(&self) -> bool { - // Packets are timestamped contiguously from the front, - // so checking the tail summarizes the entire queue's state. - self.queue - .back() - .map(|p| p.timestamp == not_happening()) - .unwrap_or_default() - } - - pub fn peek(&mut self) -> Option<&mut RtpPacket> { - let peeked = self.queue.front_mut()?; - if peeked.timestamp == not_happening() { - None - } else { - Some(peeked) - } - } - - pub fn pop(&mut self, now: Instant) -> Option { - // Don't release packets without a timestamp. - self.peek()?; - - // Unwrap is OK, because peek() above must have returned a value - // for us to be here. - let packet = self.queue.pop_front().unwrap(); - - // Must be timestamped - assert!(packet.timestamp != not_happening()); - - let queue_time = now - packet.timestamp; - self.total.decrease(now, packet.payload.len(), queue_time); - self.last_emitted = Some(now); - - Some(packet) - } - - pub fn is_empty(&self) -> bool { - self.queue.is_empty() - } - - pub fn last(&self) -> Option<&RtpPacket> { - self.queue.back() - } - - pub(crate) fn snapshot(&mut self, now: Instant) -> QueueSnapshot { - self.total.move_time_forward(now); - - QueueSnapshot { - created_at: now, - byte_size: self.total.unsent_size, - packet_count: self.total.unsent_count as u32, - total_queue_time_origin: self.total.queue_time, - last_emitted: self.last_emitted, - first_unsent: self - .queue - .iter() - .find(|p| p.timestamp != not_happening()) - .map(|p| p.timestamp), - priority: if self.total.unsent_count > 0 { - QueuePriority::Media - } else { - QueuePriority::Empty - }, - } - } - - pub(crate) fn clear(&mut self) { - self.queue.clear(); - self.total.clear(); - self.last_emitted = None; - } -} - -// Total queue time in buffer. This lovely drawing explains how to add more time. -// -// -time---------------------------------------------------------> -// -// +--------------+ -// | | -// +--------------+ -// +---------+ Already -// | | queued -// +---------+ durations -// +-----+ -// | | -// +-----+ -// +-+ -// | | <----- Add next -// +-+ packet -// -// -// -// +--------------+--------+ -// | |@@@@@@@@| -// +--------------+--------+ -// +---------+--------+ The @ is -// | |@@@@@@@@| what's -// +---------+--------+ added -// +-----+--------+ -// | |@@@@@@@@| -// +-----+--------+ -// +-+ -// |@| -// +-+ -#[derive(Debug, Default)] -struct TotalQueue { - /// Number of unsent packets. - unsent_count: usize, - /// The data size (bytes) of the unsent packets. - unsent_size: usize, - // /// When we last added some value to `queue_time`. - // last: Option, - /// The total queue time of all the unsent packets. - queue_time: Duration, - // Timestamp of the last added packet. - last: Option, -} - -impl TotalQueue { - fn move_time_forward(&mut self, now: Instant) { - if let Some(last) = self.last { - assert!(self.unsent_count > 0); - let from_last = now - last; - self.queue_time += from_last * (self.unsent_count as u32); - self.last = Some(now); - } else { - assert!(self.unsent_count == 0); - assert!(self.unsent_size == 0); - assert!(self.queue_time == Duration::ZERO); - } - } - - fn increase(&mut self, now: Instant, size: usize) { - self.move_time_forward(now); - self.unsent_count += 1; - self.unsent_size += size; - self.last = Some(now); - } - - fn decrease(&mut self, now: Instant, size: usize, queue_time: Duration) { - self.move_time_forward(now); - - self.unsent_count -= 1; - self.unsent_size -= size; - - self.queue_time -= queue_time; - - if self.unsent_count == 0 { - assert!(self.unsent_size == 0); - self.queue_time = Duration::ZERO; - self.last = None; - } - } - - fn clear(&mut self) { - *self = Self::default(); - } -} - -#[cfg(test)] -mod test { - use crate::vendor::str0m::rtp_::MediaTime; - use crate::vendor::str0m::rtp_::RtpHeader; - - use super::*; - - #[test] - fn peek_pop_no_timestamp() { - let mut queue = SendQueue::new(); - - queue.push(RtpPacket { - seq_no: 0.into(), - time: MediaTime::from_90khz(10), - header: RtpHeader::default(), - payload: [].into(), - vp8_patch: None, - timestamp: Instant::now(), - last_sender_info: None, - nackable: true, - }); - - assert!(queue.peek().is_none()); - assert!(queue.pop(Instant::now()).is_none()); - assert!(queue.need_timeout()); - - let snapshot_at = Instant::now() + Duration::from_secs(3); - assert_eq!( - queue.snapshot(snapshot_at), - QueueSnapshot { - created_at: snapshot_at, - packet_count: 0, - byte_size: 0, - total_queue_time_origin: Duration::ZERO, - first_unsent: None, - priority: QueuePriority::Empty, - ..Default::default() - } - ); - } - - #[test] - fn peek_pop_after_timestamp() { - let mut queue = SendQueue::new(); - - let start = Instant::now(); - - queue.push(RtpPacket { - seq_no: 0.into(), - time: MediaTime::from_90khz(10), - header: RtpHeader::default(), - payload: [42, 42].into(), - vp8_patch: None, - timestamp: start, - last_sender_info: None, - nackable: true, - }); - - queue.handle_timeout(start); - - assert!(queue.peek().is_some()); - assert!(!queue.need_timeout()); - - let snapshot_at = start + Duration::from_secs(3); - assert_eq!( - queue.snapshot(snapshot_at), - QueueSnapshot { - created_at: snapshot_at, - packet_count: 1, - byte_size: 2, - total_queue_time_origin: Duration::from_secs(3), - first_unsent: Some(start), - priority: QueuePriority::Media, - ..Default::default() - } - ); - - assert!(queue.pop(Instant::now()).is_some()); - } - - #[test] - fn untimed_packets_are_contiguous_at_tail() { - let mut queue = SendQueue::new(); - let start = Instant::now(); - - queue.push(RtpPacket { - seq_no: 0.into(), - time: MediaTime::from_90khz(10), - header: RtpHeader::default(), - payload: [0; 10].into(), - vp8_patch: None, - timestamp: start, - last_sender_info: None, - nackable: true, - }); - queue.push(RtpPacket { - seq_no: 1.into(), - time: MediaTime::from_90khz(20), - header: RtpHeader::default(), - payload: [1; 10].into(), - vp8_patch: None, - timestamp: start, - last_sender_info: None, - nackable: true, - }); - queue.push(RtpPacket { - seq_no: 2.into(), - time: MediaTime::from_90khz(20), - header: RtpHeader::default(), - payload: [1; 10].into(), - vp8_patch: None, - timestamp: start, - last_sender_info: None, - nackable: true, - }); - - assert!( - queue.queue.iter().all(|q| q.timestamp == not_happening()), - "expect every new packet's timestamp to start with the sentinel value" - ); - assert!(queue.need_timeout()); - - let now = start + Duration::from_millis(10); - queue.handle_timeout(now); - - assert!( - queue.queue.iter().all(|q| q.timestamp != not_happening()), - "expect handle_timeout to have timestamped every packet" - ); - assert!(!queue.need_timeout()); - } - - #[test] - fn total_queue() { - let mut total_queue = TotalQueue::default(); - let now = Instant::now(); - total_queue.increase(now, 0); - total_queue.increase(now, 1); - total_queue.decrease(now, 1, Duration::ZERO); - // Doesn't panic - total_queue.move_time_forward(now + Duration::from_millis(1)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/streams/send_stats.rs b/rs/moq-webrtc/src/vendor/str0m/streams/send_stats.rs deleted file mode 100644 index 39d110ff515..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/streams/send_stats.rs +++ /dev/null @@ -1,93 +0,0 @@ -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::rtp::SeqNo; -use crate::vendor::str0m::rtp_::{ReceptionReport, extend_u32}; -use crate::vendor::str0m::util::value_history::ValueHistory; -use crate::vendor::str0m::util::{InstantExt, calculate_rtt}; - -use super::MidRid; - -/// Holder of stats. -#[derive(Debug)] -pub(crate) struct StreamTxStats { - /// count of bytes sent, including retransmissions - /// - pub bytes: u64, - /// count of retransmitted bytes alone - bytes_resent: u64, - /// count of packets sent, including retransmissions - /// - pub packets: u64, - /// count of retransmitted packets alone - packets_resent: u64, - /// count of FIR requests received - firs: u64, - /// count of PLI requests received - plis: u64, - /// count of NACKs received - nacks: u64, - /// round trip time - /// Can be null in case of missing or bad reports - rtt: Option, - /// The last reception report for the stream, if any. - /// - /// The SeqNo is the extended max_seq of the reception report, extended - /// using the last sent sequence number. - last_rr: Option<(SeqNo, ReceptionReport)>, - - /// `None` if `rtx_ratio_cap` is `None`. - pub bytes_transmitted: Option>, - - /// `None` if `rtx_ratio_cap` is `None`. - pub bytes_retransmitted: Option>, -} - -impl StreamTxStats { - pub fn new() -> Self { - Self { - bytes: 0, - bytes_resent: 0, - packets: 0, - packets_resent: 0, - firs: 0, - plis: 0, - nacks: 0, - rtt: None, - last_rr: None, - bytes_transmitted: Some(Default::default()), - bytes_retransmitted: Some(Default::default()), - } - } - - pub fn update_packet_counts(&mut self, bytes: u64, is_resend: bool) { - self.packets += 1; - self.bytes += bytes; - if is_resend { - self.bytes_resent += bytes; - self.packets_resent += 1; - } - } - - pub fn increase_nacks(&mut self) { - self.nacks += 1; - } - - pub fn increase_plis(&mut self) { - self.plis += 1; - } - - pub fn increase_firs(&mut self) { - self.firs += 1; - } - - pub fn update_with_rr(&mut self, now: Instant, last_sent_seq_no: SeqNo, r: ReceptionReport) { - let ntp_time = now.to_ntp_duration(); - let rtt = calculate_rtt(ntp_time, r.last_sr_delay, r.last_sr_time); - self.rtt = rtt; - - // The last_sent_seq_no should be in the vicinity of the rr.max_seq. - let ext_seq = extend_u32(Some(*last_sent_seq_no), r.max_seq).into(); - - self.last_rr = Some((ext_seq, r)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/abs-capture-time.rs b/rs/moq-webrtc/src/vendor/str0m/tests/abs-capture-time.rs deleted file mode 100644 index 55ee644b9be..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/abs-capture-time.rs +++ /dev/null @@ -1,140 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::{Extension, ExtensionMap}; -use crate::vendor::str0m::{Event, Rtc, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn abs_capture_time_negotiation() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Configure abs-capture-time extension on both peers - let mut exts = ExtensionMap::standard(); - exts.set(9, Extension::AbsoluteCaptureTime); - - let now = std::time::Instant::now(); - let mut l_rtc = Rtc::builder(); - *l_rtc.extension_map() = exts.clone(); - let mut l = TestRtc::new_with_rtc(Peer::Left.span(), l_rtc.build(now)); - - let mut r_rtc = Rtc::builder(); - *r_rtc.extension_map() = exts.clone(); - let mut r = TestRtc::new_with_rtc(Peer::Right.span(), r_rtc.build(now)); - - l.set_forced_time_advance(Duration::from_millis(1)); - r.set_forced_time_advance(Duration::from_millis(1)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Setup audio media - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - // Verify the offer contains abs-capture-time extension - let offer_str = offer.to_sdp_string(); - assert!( - offer_str.contains("abs-capture-time"), - "SDP offer should contain abs-capture-time extension" - ); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Wait for connection - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data = vec![1_u8; 80]; - - // Send some packets - for _ in 0..10 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - - progress(&mut l, &mut r)?; - } - - // Verify we received MediaData events - let media_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!( - media_count >= 5, - "Should have received at least 5 media packets, got {}", - media_count - ); - - Ok(()) -} - -#[test] -pub fn abs_capture_time_sdp_roundtrip() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Test that abs-capture-time extension properly roundtrips through SDP - let mut exts = ExtensionMap::standard(); - exts.set(9, Extension::AbsoluteCaptureTime); - - let now = std::time::Instant::now(); - let mut l_rtc = Rtc::builder(); - *l_rtc.extension_map() = exts.clone(); - let mut l = TestRtc::new_with_rtc(Peer::Left.span(), l_rtc.build(now)); - - let mut r = TestRtc::new(Peer::Right); - - l.set_forced_time_advance(Duration::from_millis(1)); - r.set_forced_time_advance(Duration::from_millis(1)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let _mid = change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - // Verify offer contains abs-capture-time - let offer_sdp = offer.to_sdp_string(); - assert!( - offer_sdp.contains("http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"), - "Offer SDP should contain abs-capture-time URI" - ); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - - // Verify answer also contains abs-capture-time (if receiver supports it) - let answer_sdp = answer.to_sdp_string(); - assert!( - answer_sdp.contains("abs-capture-time") || answer_sdp.contains("a=extmap"), - "Answer SDP should contain extension mapping" - ); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/amr-wb.rs b/rs/moq-webrtc/src/vendor/str0m/tests/amr-wb.rs deleted file mode 100644 index 8f2a41514a3..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/amr-wb.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! AMR-WB (RFC 4867) negotiation and media round-trip tests. - -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::change::{SdpAnswer, SdpOffer}; -use crate::vendor::str0m::format::{Codec, FormatParams}; -use crate::vendor::str0m::media::{Direction, Frequency, MediaKind, MediaTime}; -use crate::vendor::str0m::{Event, RtcConfig}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -/// Speech bits of the speech (0..=8) and SID (9) frame types, RFC 4867 Table 1a. -const FRAME_BITS: [usize; 10] = [132, 177, 253, 285, 317, 365, 397, 461, 477, 40]; - -/// A 3GPP IF frame of `frame_type` (Q=1) whose speech bytes are `fill`, padding cleared. -fn if_frame(frame_type: usize, fill: u8) -> Vec { - let bits = FRAME_BITS[frame_type]; - let mut frame = vec![((frame_type as u8) << 3) | 0x04]; - frame.extend(std::iter::repeat_n(fill, bits.div_ceil(8))); - if bits % 8 != 0 { - *frame.last_mut().unwrap() &= 0xff << (8 - bits % 8); - } - frame -} - -/// A single AMR-WB payload type with the given layout. -fn amr_wb_config(octet_align: Option) -> impl FnOnce(RtcConfig) -> RtcConfig { - move |c| { - let mut c = c.clear_codecs(); - c.codec_config().add_config( - 122.into(), - None, - Codec::AmrWb, - Frequency::SIXTEEN_KHZ, - Some(1), - FormatParams { - octet_align, - ..Default::default() - }, - ); - c - } -} - -fn amr_wb_format(peer: &TestRtc) -> FormatParams { - peer.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::AmrWb) - .expect("AMR-WB to be configured") - .spec() - .format -} - -/// Sends every speech mode and SID, one 20 ms frame per write, and checks each -/// received frame and its media time. -fn round_trip(octet_align: Option) { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new_with_config(Peer::Left, amr_wb_config(octet_align)); - let mut r = TestRtc::new_with_config(Peer::Right, amr_wb_config(octet_align)); - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer).unwrap(); - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - - while !l.is_connected() || !r.is_connected() { - progress(&mut l, &mut r).unwrap(); - } - - let mut sent = Vec::new(); - let start = l.duration(); - while l.duration() - start < Duration::from_secs(1) { - let frame = if_frame(sent.len() % FRAME_BITS.len(), sent.len() as u8); - let time = MediaTime::new(sent.len() as u64 * 320, Frequency::SIXTEEN_KHZ); - let wallclock = l.start + l.duration(); - l.writer(mid) - .unwrap() - .write(122.into(), wallclock, time, frame.clone()) - .unwrap(); - sent.push(frame); - progress(&mut l, &mut r).unwrap(); - } - - let received: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| match e { - Event::MediaData(d) => Some(d), - _ => None, - }) - .collect(); - - assert!(received.len() > FRAME_BITS.len(), "{octet_align:?}"); - assert!(received.iter().any(|d| d.data[0] >> 3 == 9), "no SID frame"); - for d in received { - assert_eq!(d.params.spec().codec, Codec::AmrWb); - assert_eq!(d.time.frequency(), Frequency::SIXTEEN_KHZ); - assert_eq!(d.time.numer() % 320, 0); - let index = (d.time.numer() / 320) as usize; - assert_eq!(d.data[..], sent[index][..], "frame {index} {octet_align:?}"); - } -} - -#[test] -fn amr_wb_octet_aligned_round_trip() { - round_trip(Some(true)); -} - -#[test] -fn amr_wb_bandwidth_efficient_round_trip() { - round_trip(None); -} - -#[test] -fn amr_wb_default_config_negotiates_octet_aligned() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new_with_config(Peer::Left, |c| c.clear_codecs().enable_amr_wb(true)); - let mut r = TestRtc::new_with_config(Peer::Right, |c| c.clear_codecs().enable_amr_wb(true)); - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let offer_sdp = offer.to_sdp_string(); - assert!(offer_sdp.contains("a=rtpmap:122 AMR-WB/16000/1\r\n")); - assert!(offer_sdp.contains("a=fmtp:122 octet-align=1\r\n")); - - let answer = r.rtc.sdp_api().accept_offer(offer).unwrap(); - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - - for peer in [&l, &r] { - assert_eq!(amr_wb_format(peer).octet_align, Some(true)); - } -} - -/// RFC 4867 §8.3.1: the answer repeats the offer's octet-align, channels and -/// mode-set, drops parameters str0m doesn't use, and the mode-set then binds both -/// peers. -#[test] -fn amr_wb_answer_echoes_offer_and_mode_set_binds_both_sides() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new_with_config(Peer::Left, amr_wb_config(None)); - let mut r = TestRtc::new_with_config(Peer::Right, amr_wb_config(None)); - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let offer_sdp = offer.to_sdp_string().replace( - "a=rtpmap:122 AMR-WB/16000/1\r\n", - "a=rtpmap:122 AMR-WB/16000\r\n\ - a=fmtp:122 octet-align=0;mode-set=0,1,2;mode-change-capability=2;\ - max-red=0;crc=0;robust-sorting=0\r\n", - ); - let offer = SdpOffer::from_sdp_string(&offer_sdp).unwrap(); - - let answer_sdp = r.rtc.sdp_api().accept_offer(offer).unwrap().to_sdp_string(); - assert!(answer_sdp.contains("a=rtpmap:122 AMR-WB/16000\r\n")); - assert!(answer_sdp.contains("a=fmtp:122 octet-align=0;mode-set=0,1,2\r\n")); - - let answer = SdpAnswer::from_sdp_string(&answer_sdp).unwrap(); - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - - for peer in [&l, &r] { - assert_eq!(amr_wb_format(peer).mode_set, Some(0b111)); - } -} - -#[test] -fn amr_wb_unsupported_offers_are_declined() { - init_log(); - init_crypto_default(); - - for (from, to) in [ - ("octet-align=1", "octet-align=1;crc=1"), - ("octet-align=1", "octet-align=1;robust-sorting=1"), - ("octet-align=1", "octet-align=1;interleaving=30"), - ("octet-align=1", "octet-align=1;mode-change-period=2"), - ("AMR-WB/16000/1", "AMR-WB/16000/2"), - ] { - let mut l = TestRtc::new_with_config(Peer::Left, |c| c.clear_codecs().enable_amr_wb(true)); - let mut r = TestRtc::new_with_config(Peer::Right, |c| c.clear_codecs().enable_amr_wb(true)); - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, _) = change.apply().unwrap(); - let offer_sdp = offer.to_sdp_string().replace(from, to); - let offer = SdpOffer::from_sdp_string(&offer_sdp).unwrap(); - - let answer_sdp = r.rtc.sdp_api().accept_offer(offer).unwrap().to_sdp_string(); - assert!(!answer_sdp.contains("AMR-WB"), "accepted `{to}`:\n{answer_sdp}"); - } -} - -#[test] -fn amr_wb_out_of_range_mode_set_is_ignored() { - for mode in [9, 15, 16, 31, 32, 255] { - assert_eq!( - FormatParams::parse_line(&format!("mode-set={mode}")).mode_set, - None, - "invalid speech mode {mode}" - ); - } -} - -#[test] -fn amr_wb_invalid_mode_set_in_other_codec_sdp_does_not_panic() { - init_crypto_default(); - - let mut l = TestRtc::new_with_config(Peer::Left, |c| c); - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, _) = change.apply().unwrap(); - let offer_sdp = offer.to_sdp_string().replace( - "a=rtpmap:111 opus/48000/2\r\n", - "a=rtpmap:111 opus/48000/2\r\na=fmtp:111 mode-set=16\r\n", - ); - assert!(offer_sdp.contains("mode-set=16")); - - SdpOffer::from_sdp_string(&offer_sdp).unwrap(); -} - -#[test] -fn amr_wb_alternative_mode_sets_accept_one_unrestricted_remote_payload() { - init_crypto_default(); - - let mut l = TestRtc::new_with_config(Peer::Left, |c| c.clear_codecs().enable_amr_wb(true)); - let mut r = TestRtc::new_with_config(Peer::Right, |c| { - let mut c = c.clear_codecs(); - for (pt, mode_set) in [(122, 0b111), (123, 0b111000)] { - c.codec_config().add_config( - pt.into(), - None, - Codec::AmrWb, - Frequency::SIXTEEN_KHZ, - Some(1), - FormatParams { - octet_align: Some(true), - mode_set: Some(mode_set), - ..Default::default() - }, - ); - } - c - }); - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer).unwrap(); - let answer_sdp = answer.to_sdp_string(); - - // The offer has no mode-set, so RFC 4867 §8.3.1 lets the answerer choose - // either local alternative for the one offered payload type. - assert_eq!(answer_sdp.matches("AMR-WB/16000/1").count(), 1); - assert!( - ["0,1,2", "3,4,5"] - .iter() - .any(|modes| { answer_sdp.contains(&format!("a=fmtp:122 octet-align=1;mode-set={modes}\r\n")) }) - ); - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs b/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs deleted file mode 100644 index d2c26dd038f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs +++ /dev/null @@ -1,252 +0,0 @@ -//! Tests for API misuse and error conditions. - -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// Test that disconnect() API works and is_alive() returns false after. -#[test] -fn api_disconnect_and_is_alive() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - // Connect first - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - assert!(l.rtc.is_alive(), "Should be alive before disconnect"); - - // Disconnect - l.rtc.disconnect(); - - assert!(!l.rtc.is_alive(), "Should not be alive after disconnect"); - - Ok(()) -} - -/// Test that RecvOnly direction is properly set. -#[test] -fn api_error_not_sending_direction() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // L is RecvOnly - cannot send - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::RecvOnly, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // L's direction should be RecvOnly - let media = l.media(mid); - assert!(media.is_some(), "Media should exist"); - assert_eq!(media.unwrap().direction(), Direction::RecvOnly, "L should be RecvOnly"); - - // R's direction should be SendOnly (inverse) - let r_media = r.media(mid); - assert!(r_media.is_some(), "R media should exist"); - assert_eq!( - r_media.unwrap().direction(), - Direction::SendOnly, - "R should be SendOnly (inverse of L's RecvOnly)" - ); - - Ok(()) -} - -/// Test that SendOnly direction prevents receiving. -#[test] -fn api_error_not_receiving_direction() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // L is SendOnly - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // L's direction is SendOnly, so R is RecvOnly and cannot request keyframes to L - // (no sender source on R's side for this media) - let media = l.media(mid); - assert!(media.is_some(), "Media should exist"); - assert_eq!(media.unwrap().direction(), Direction::SendOnly, "L should be SendOnly"); - - Ok(()) -} - -/// Test that operations on disconnected Rtc are handled gracefully. -#[test] -fn api_operations_after_disconnect() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // Disconnect - l.rtc.disconnect(); - - // After disconnect, writer should be None or return error on write - // Get params before writer to avoid borrow issues - let params = l.params_opus(); - let pt = params.pt(); - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - - if let Some(w) = l.writer(mid) { - // Write may fail or succeed but won't actually send anything - let _ = w.write(pt, wallclock, time, vec![0u8; 80]); - } - - Ok(()) -} - -/// Test IceConnectionStateChange events are generated. -#[test] -fn api_ice_state_change_events() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - // Check that we received ICE state change events - let ice_events: Vec<_> = l - .events - .iter() - .filter(|(_, e)| matches!(e, Event::IceConnectionStateChange(_))) - .collect(); - - assert!( - !ice_events.is_empty(), - "Should have received IceConnectionStateChange events" - ); - - Ok(()) -} - -/// Test Connected event is generated. -#[test] -fn api_connected_event() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - // Check that we received Connected event - let connected = l.events.iter().any(|(_, e)| matches!(e, Event::Connected)); - - assert!(connected, "Should have received Connected event"); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/bidirectional.rs b/rs/moq-webrtc/src/vendor/str0m/tests/bidirectional.rs deleted file mode 100644 index e963112c8cf..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/bidirectional.rs +++ /dev/null @@ -1,86 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn bidirectional_same_m_line() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data_a = vec![1_u8; 80]; - let data_b = vec![2_u8; 80]; - - loop { - { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data_a.clone())?; - } - - progress(&mut l, &mut r)?; - - { - let wallclock = r.start + r.duration(); - let time = l.duration().into(); - r.writer(mid).unwrap().write(pt, wallclock, time, data_b.clone())?; - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(12) { - break; - } - } - - let media_count_r = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!(media_count_r > 170, "Not enough MediaData at R: {}", media_count_r); - - let media_count_l = l - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!(media_count_l > 300, "Not enough MediaData at L: {}", media_count_l); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/change-ssrc-reset-receive.rs b/rs/moq-webrtc/src/vendor/str0m/tests/change-ssrc-reset-receive.rs deleted file mode 100644 index 21457d948ec..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/change-ssrc-reset-receive.rs +++ /dev/null @@ -1,372 +0,0 @@ -use std::collections::VecDeque; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Frequency, MediaKind, MediaTime, Mid, Pt, Rid}; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, Rtc, RtcError}; -use tracing::info; - -use super::common; -use common::{TestRtc, connect_l_r, connect_l_r_with_rtc, init_crypto_default, init_log, progress}; - -fn send_frame( - l: &mut TestRtc, - r: &mut TestRtc, - mid: Mid, - rid: Rid, - pt: Pt, - seq: u64, - timestamp: u32, - payload: &'static [u8], -) -> Result<(), RtcError> { - let at = l.last.max(r.last) + Duration::from_millis(10); - l.direct_api() - .stream_tx_by_mid(mid, Some(rid)) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), timestamp, at, payload).marker(true)); - for _ in 0..100 { - progress(l, r)?; - } - Ok(()) -} - -fn received_frame(r: &TestRtc, pt: Pt, seq: u64) -> bool { - r.events.iter().any(|(_, event)| match event { - Event::MediaData(frame) => frame.pt == pt && frame.seq_range.contains(&seq.into()), - _ => false, - }) -} - -#[test] -fn ssrc_change_resets_every_payload_type_on_the_stream() -> Result<(), RtcError> { - init_crypto_default(); - let now = Instant::now(); - let (mut l, mut r) = connect_l_r_with_rtc(Rtc::builder().set_rtp_mode(true).build(now), Rtc::builder().build(now)); - let mid = "vid".into(); - let rid = "hi".into(); - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(42.into(), None, mid, Some(rid)); - r.direct_api().declare_media(mid, MediaKind::Video).expect_rid_rx(rid); - let vp8_pt = l.params_vp8().pt(); - let h264_pt = l.params_h264().pt(); - - send_frame(&mut l, &mut r, mid, rid, vp8_pt, 100, 90_000, &[0x10, 0x01, 0xaa])?; - assert!(received_frame(&r, vp8_pt, 100)); - - l.direct_api() - .reset_stream_tx(mid, Some(rid), 84.into(), None) - .expect("SSRC reset"); - // The first packet on the new SSRC uses H.264, so it resets that depacketizer. - send_frame(&mut l, &mut r, mid, rid, h264_pt, 1, 180_000, &[0x65, 0xaa])?; - assert!(received_frame(&r, h264_pt, 1)); - // VP8 must also start fresh on the new SSRC, even though it was not the - // payload type of the packet that signaled the change. - send_frame(&mut l, &mut r, mid, rid, vp8_pt, 2, 270_000, &[0x10, 0x01, 0xbb])?; - assert!( - received_frame(&r, vp8_pt, 2), - "VP8 frame on the replacement SSRC was lost to the old depacketizer state" - ); - Ok(()) -} - -#[test] -pub fn change_ssrc_reset_receive() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let rid = "hi".into(); - - // Initial SSRC - let ssrc_tx_initial: Ssrc = 42.into(); - // New SSRC to use after reset - let ssrc_tx_new: Ssrc = 84.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx_initial, None, mid, Some(rid)); - - r.direct_api().declare_media(mid, MediaKind::Audio).expect_rid_rx(rid); - - // Set initial timing - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, Some(rid)).unwrap().ssrc(); - assert_eq!(ssrc, ssrc_tx_initial, "Initial SSRC should match what we set"); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - // First batch of packets with initial SSRC - // We'll create a batch with several packets to cause timestamp rollover - let first_batch: Vec<&[u8]> = vec![ - &[0x1, 0x2, 0x3, 0x4], // packet at a timestamp close to rollover - &[0x5, 0x6, 0x7, 0x8], // packet at rollover point - &[0x9, 0xa, 0xb, 0xc], // packet after rollover - &[0xd, 0xe, 0xf, 0x0], // another packet after rollover - ]; - - let mut first_batch: VecDeque<_> = first_batch.into(); - - // Create a timestamp sequence that will cross the rollover boundary (close to 2^32) - // 32-bit timestamp max is 4,294,967,295 (0xFFFFFFFF) - // Start at a value very close to rollover - let rollover_threshold: u32 = 0xFFFFFFFF; - let timestamp_increment: u32 = 1000; // standard increment (e.g., for Opus) - - // Start our timeline near the rollover point - let start_timestamp: u32 = rollover_threshold - timestamp_increment * 2; - - // Counts for each packet - they'll increase, causing timestamp to roll over - let mut first_counts: Vec = vec![0, 1, 2, 3]; - let mut write_at = l.last + Duration::from_millis(300); - - // Send first batch with initial SSRC - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = first_batch.pop_front() { - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx_by_mid(mid, Some(rid)).unwrap(); - - let count = first_counts.remove(0); - // Calculate timestamp to create rollover scenario - let time = start_timestamp.wrapping_add(count as u32 * timestamp_increment); - - info!( - "Sending packet {} with timestamp: {} on SSRC: {}", - count, time, ssrc_tx_initial - ); - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if first_batch.is_empty() && first_counts.is_empty() { - break; - } - } - - // Run a bit longer to ensure first batch of packets arrive - for _ in 0..20 { - progress(&mut l, &mut r)?; - } - - info!("First batch sent with SSRC: {}", ssrc_tx_initial); - - // Reset the SSRC with None for RTX since the stream doesn't use RTX - let mut api = l.direct_api(); - let result = api.reset_stream_tx(mid, Some(rid), ssrc_tx_new, None); - assert!(result.is_some(), "Reset should succeed with valid new SSRC"); - - // Verify the SSRC was changed - let updated_ssrc = l.direct_api().stream_tx_by_mid(mid, Some(rid)).unwrap().ssrc(); - assert_eq!(updated_ssrc, ssrc_tx_new, "SSRC should be updated to new value"); - - // Wait to ensure pause detection occurs (default threshold is 1.5s) - let pause_duration = Duration::from_millis(2000); - let pause_end = l.last + pause_duration; - while l.last < pause_end { - progress(&mut l, &mut r)?; - } - - info!( - "Advanced time by {} ms to potentially trigger pause", - pause_duration.as_millis() - ); - - // Check if the stream was paused - let mut seen_paused = false; - for (_, event) in &r.events { - if let Event::StreamPaused(stream_paused) = event { - if stream_paused.paused { - seen_paused = true; - info!("Confirmed stream is paused"); - break; - } - } - } - - // Second batch of packets with new SSRC, but with timestamps that would appear to go - // backward if last_time is not reset during change_ssrc - let second_batch: Vec<&[u8]> = vec![&[0x9, 0xa, 0xb, 0xc], &[0xd, 0xe, 0xf, 0x10]]; - - let mut second_batch: VecDeque<_> = second_batch.into(); - let mut second_counts: Vec = vec![0, 1]; - write_at = l.last + Duration::from_millis(300); - - // Calculate a timestamp that would appear to go backward if last_time isn't reset - // The first batch used timestamps starting at 47_000_000 - // We'll use a timestamp that's lower, which would be interpreted as going backward - // if the internal state isn't reset - let backwards_base_timestamp: u32 = 1_000_000; - - // Send second batch with new SSRC and potentially problematic timestamps - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = second_batch.pop_front() { - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx_by_mid(mid, Some(rid)).unwrap(); - - let count = second_counts.remove(0); - // Use a timestamp that would appear to go backward if last_time isn't reset - let time = (count as u32) * 1000 + backwards_base_timestamp; - let seq_no = (48_000 + count).into(); // Different seq range - - let exts = ExtensionValues { - audio_level: Some(-52 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - info!( - "Sending packet with potentially backward timestamp: {} on SSRC: {}", - time, ssrc_tx_new - ); - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if second_batch.is_empty() && second_counts.is_empty() { - // Run a bit longer to ensure packets arrive - for _ in 0..20 { - progress(&mut l, &mut r)?; - } - break; - } - } - - // Collect all received media packets and Media events - let media_packets: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - info!("Collected {} RTP packets", media_packets.len(),); - - // Should have received all 6 packets (4 from first batch + 2 from second batch) - assert_eq!(media_packets.len(), 6, "Should have received all 6 packets"); - - // Verify that we have packets with both SSRCs - let first_ssrc_packets: Vec<_> = media_packets - .iter() - .filter(|p| p.header.ssrc == ssrc_tx_initial) - .collect(); - let second_ssrc_packets: Vec<_> = media_packets.iter().filter(|p| p.header.ssrc == ssrc_tx_new).collect(); - - assert_eq!(first_ssrc_packets.len(), 4, "Should have 4 packets with initial SSRC"); - assert_eq!(second_ssrc_packets.len(), 2, "Should have 2 packets with new SSRC"); - - // Verify the stream was unpaused after receiving the second batch with new SSRC - let mut stream_unpaused_after_new_ssrc = false; - for (_, event) in &r.events { - if let Event::StreamPaused(stream_paused) = event { - if !stream_paused.paused && stream_paused.ssrc == ssrc_tx_new { - stream_unpaused_after_new_ssrc = true; - info!("Confirmed stream unpaused after new SSRC packets"); - break; - } - } - } - - // If we saw a pause event, we should also see an unpause event after the new packets - if seen_paused { - assert!( - stream_unpaused_after_new_ssrc, - "Stream should have unpaused after receiving packets with new SSRC" - ); - } - - // Verify the first batch packets sequence numbers - for (i, packet) in first_ssrc_packets.iter().enumerate() { - assert_eq!( - packet.header.sequence_number, - 47000 + i as u16, - "First batch packet {} should have correct sequence number", - i - ); - } - - // Verify first batch timestamps - they should cross the rollover boundary - // First two packets should be before rollover, second two after rollover - // Calculating expected timestamps for verification - let expected_timestamps: Vec = (0..4) - .map(|i| start_timestamp.wrapping_add(i as u32 * timestamp_increment)) - .collect(); - - // Verify the rollover pattern - // Based on the logs, we can see that packets 1, 2, and 3 have timestamps close to max, - // and only the 4th packet rolls over - info!("Checking timestamp pattern for packets crossing rollover"); - for (i, ts) in expected_timestamps.iter().enumerate() { - info!("Packet {} timestamp: {}", i, ts); - } - - // Verify the actual timestamps match our expected values - for (i, packet) in first_ssrc_packets.iter().enumerate() { - assert_eq!( - packet.header.timestamp, expected_timestamps[i], - "First batch packet {} should have expected timestamp after rollover", - i - ); - } - - // Verify second batch (new SSRC) sequence numbers - for (i, packet) in second_ssrc_packets.iter().enumerate() { - assert_eq!( - packet.header.sequence_number, - 48000 + i as u16, - "Second batch packet {} should have correct sequence number", - i - ); - } - - // The timestamps for the second batch are much lower, but should be interpreted correctly - // because the internal state was reset by change_ssrc() - assert_eq!( - second_ssrc_packets[0].header.timestamp, backwards_base_timestamp, - "First packet with new SSRC should have expected timestamp" - ); - assert_eq!( - second_ssrc_packets[1].header.timestamp, - backwards_base_timestamp + 1000, - "Second packet with new SSRC should have expected timestamp" - ); - - let mut api = r.direct_api(); - let rx = api.stream_rx_by_mid(mid, Some(rid)).unwrap(); - - // If we don't reset the state properly on SSRC change, this will be - // a crazy value. - assert_eq!( - rx.last_time(), - Some(MediaTime::new(1001000, Frequency::FORTY_EIGHT_KHZ)) - ); - - // This test verifies two key behaviors: - // 1. Timestamp rollover is handled correctly within a single SSRC - // 2. After SSRC change, timestamp history is reset so a low timestamp - // doesn't appear to go backward from the high timestamp of the previous SSRC - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/common.rs b/rs/moq-webrtc/src/vendor/str0m/tests/common.rs deleted file mode 100644 index 291319b5271..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/common.rs +++ /dev/null @@ -1,565 +0,0 @@ -#![allow(unused)] -use std::cell::Cell; -use std::io::Cursor; -use std::net::{Ipv4Addr, SocketAddr}; -use std::ops::{Deref, DerefMut}; -use std::sync::{Arc, Once}; -use std::time::{Duration, Instant}; - -use crate::vendor::netem::{Input as NetemInput, Netem, NetemConfig, Output as NetemOutput}; - -use crate::vendor::str0m::Candidate; -use crate::vendor::str0m::change::SdpApi; -use crate::vendor::str0m::crypto::CryptoProvider; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::net::Protocol; -use crate::vendor::str0m::net::Receive; -use crate::vendor::str0m::rtp::ExtensionMap; -use crate::vendor::str0m::rtp::RtpHeader; -use crate::vendor::str0m::{Event, Input, Output, Rtc, RtcConfig, RtcError}; -use pcap_file::pcap::PcapReader; -use tracing::Span; -use tracing::info_span; - -/// Peer for test peers - Left or Right. -/// Used to determine which crypto provider to use based on environment variables. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Peer { - Left, - Right, -} - -impl Peer { - /// Create a tracing span for this peer. - pub fn span(&self) -> Span { - match self { - Peer::Left => info_span!("L"), - Peer::Right => info_span!("R"), - } - } - - /// Get the crypto provider for this peer based on environment variables. - /// Returns None if no environment variable is set. - pub fn crypto_provider(&self) -> Option> { - let env_var = match self { - Peer::Left => "L_CRYPTO", - Peer::Right => "R_CRYPTO", - }; - - if let Ok(crypto_name) = std::env::var(env_var) { - Some(Arc::new(get_crypto_provider_by_name(&crypto_name))) - } else { - None - } - } -} - -/// Owned version of Receive for queueing. -#[derive(Clone)] -pub struct PendingPacket { - pub proto: Protocol, - pub source: SocketAddr, - pub destination: SocketAddr, - pub contents: Vec, -} - -impl AsRef<[u8]> for PendingPacket { - fn as_ref(&self) -> &[u8] { - &self.contents - } -} - -pub struct TestRtc { - pub span: Span, - pub rtc: Rtc, - pub start: Instant, - pub last: Instant, - pub events: Vec<(Instant, Event)>, - pub pending: Netem, - pub forced_time_advance: Duration, -} - -impl TestRtc { - pub fn new(peer: Peer) -> Self { - let now = Instant::now(); - let rtc = if let Some(crypto) = peer.crypto_provider() { - Rtc::builder().set_crypto_provider(crypto).build(now) - } else { - Rtc::new(now) - }; - - Self::new_with_rtc(peer.span(), rtc) - } - - /// Like [`TestRtc::new`], but lets the caller customise the `RtcConfig` - /// builder - e.g. to enable a non-default codec such as H.266. - pub fn new_with_config(peer: Peer, f: impl FnOnce(RtcConfig) -> RtcConfig) -> Self { - let now = Instant::now(); - let builder = Rtc::builder(); - let builder = if let Some(crypto) = peer.crypto_provider() { - builder.set_crypto_provider(crypto) - } else { - builder - }; - let rtc = f(builder).build(now); - Self::new_with_rtc(peer.span(), rtc) - } - - pub fn new_with_rtc(span: Span, rtc: Rtc) -> Self { - let now = Instant::now(); - TestRtc { - span, - rtc, - start: now, - last: now, - events: vec![], - pending: Netem::new(NetemConfig::new()), - forced_time_advance: Duration::from_millis(10), - } - } - - /// Set the forced time advance duration when RTC returns v==rtc.last. - /// This prevents the test from getting stuck when RTC has no pending timeouts. - /// Should be set to the packet interval for the target bitrate (e.g., 0.2ms for 50 Mbps). - pub fn set_forced_time_advance(&mut self, duration: Duration) { - self.forced_time_advance = duration; - } - - /// Configure network emulation for incoming traffic to this RTC. - /// Call this on the RECEIVER to affect traffic coming TO this peer. - /// This preserves any packets already queued in the netem. - pub fn set_netem(&mut self, config: NetemConfig) { - self.pending.set_config(config); - } - - pub fn add_host_candidate(&mut self, socket: SocketAddr) -> Candidate { - self.rtc - .add_local_candidate(Candidate::host(socket, "udp").unwrap()) - .unwrap() - .clone() - } - - pub fn duration(&self) -> Duration { - self.last - self.start - } - - pub fn params_opus(&self) -> PayloadParams { - self.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::Opus) - .cloned() - .unwrap() - } - - pub fn params_vp8(&self) -> PayloadParams { - self.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::Vp8) - .cloned() - .unwrap() - } - - pub fn params_vp9(&self) -> PayloadParams { - self.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::Vp9) - .cloned() - .unwrap() - } - - pub fn params_h264(&self) -> PayloadParams { - self.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::H264) - .cloned() - .unwrap() - } - - pub fn params_av1(&self) -> PayloadParams { - self.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::Av1) - .cloned() - .unwrap() - } - - pub fn params_h265(&self) -> PayloadParams { - self.rtc - .codec_config() - .find(|p| p.spec().codec == Codec::H265) - .cloned() - .unwrap() - } -} - -/// Progress time forward by processing the next event. -/// -/// We have 4 event sources: -/// - l.last: l's rtc timeout -/// - r.last: r's rtc timeout -/// - l.pending: packet ready to deliver to l -/// - r.pending: packet ready to deliver to r -/// -/// Pick the earliest, process it, then try to progress again for any -/// more even that is within 5ms of the first time. -pub fn progress(l: &mut TestRtc, r: &mut TestRtc) -> Result<(), RtcError> { - let mut first_time = None; - - loop { - // Find earliest event - let l_netem = l.pending.poll_timeout(); - let r_netem = r.pending.poll_timeout(); - - // Determine which event is next: (time, is_l, is_netem) - let mut next = (l.last, true, false); // default: l's rtc - - if r.last < next.0 { - next = (r.last, false, false); - } - if l_netem < next.0 { - next = (l_netem, true, true); - } - if r_netem < next.0 { - next = (r_netem, false, true); - } - - let (time, is_l, is_netem) = next; - - if let Some(first_time) = first_time { - // The idea is that we try to advance all the components that might be - // within some distance of each other. - let elapsed = time.saturating_duration_since(first_time); - if elapsed >= Duration::from_millis(5) { - break; - } - } else { - first_time = Some(time); - } - - progress_one(l, r, time, is_l, is_netem)?; - } - - Ok(()) -} - -thread_local! { - /// When set, [`rtc_poll_to_timeout`] asserts every [`Output::Transmit`] - /// for which `contents.len() <= mtu`. - static STRICT_MTU: Cell> = const { Cell::new(None) }; -} - -struct StrictMtuGuard(Option); -impl Drop for StrictMtuGuard { - fn drop(&mut self) { - STRICT_MTU.with(|c| c.set(self.0)); - } -} - -/// Like [`progress`] but asserts every outgoing datagram is `<= mtu` bytes. -pub fn progress_strict_mtu(l: &mut TestRtc, r: &mut TestRtc, mtu: usize) -> Result<(), RtcError> { - let prev = STRICT_MTU.with(|c| c.replace(Some(mtu))); - let _guard = StrictMtuGuard(prev); - progress(l, r) -} - -fn progress_one(l: &mut TestRtc, r: &mut TestRtc, time: Instant, is_l: bool, is_netem: bool) -> Result<(), RtcError> { - if is_netem { - // Deliver packet from netem to rtc (no timeout processing) - if is_l { - netem_to_rtc(l, time, &mut r.pending)?; - } else { - netem_to_rtc(r, time, &mut l.pending)?; - } - } else { - // Process rtc timeout and poll outputs - if is_l { - rtc_timeout(l, time, &mut r.pending)?; - } else { - rtc_timeout(r, time, &mut l.pending)?; - } - } - Ok(()) -} - -/// Deliver one packet from rtc.pending to rtc. No timeout processing. -fn netem_to_rtc(rtc: &mut TestRtc, time: Instant, other_netem: &mut Netem) -> Result<(), RtcError> { - rtc.pending.handle_input(NetemInput::Timeout(time)); - - let Some(NetemOutput::Packet(packet)) = rtc.pending.poll_output() else { - return Ok(()); - }; - - let input = Input::Receive( - time, - Receive { - proto: packet.proto, - source: packet.source, - destination: packet.destination, - contents: (&packet.contents[..]).try_into()?, - }, - ); - rtc.span.in_scope(|| rtc.rtc.handle_input(input))?; - - rtc_poll_to_timeout(rtc, time, other_netem)?; - - Ok(()) -} - -/// Process rtc timeout and poll until next timeout, queueing transmits in other_netem. -fn rtc_timeout(rtc: &mut TestRtc, time: Instant, other_netem: &mut Netem) -> Result<(), RtcError> { - rtc.span.in_scope(|| rtc.rtc.handle_input(Input::Timeout(time)))?; - - rtc_poll_to_timeout(rtc, time, other_netem)?; - - Ok(()) -} - -fn rtc_poll_to_timeout( - rtc: &mut TestRtc, - time: Instant, - other_netem: &mut Netem, -) -> Result<(), RtcError> { - loop { - let next = rtc.span.in_scope(|| rtc.rtc.poll_output())?; - // println!("next: {:?}", next); - match next { - Output::Timeout(v) => { - let tick = rtc.last + rtc.forced_time_advance; - rtc.last = if v == rtc.last { tick } else { tick.min(v) }; - break; - } - Output::Transmit(v) => { - if let Some(mtu) = STRICT_MTU.with(|c| c.get()) { - assert!( - v.contents.len() <= mtu, - "outgoing datagram {} bytes exceeds strict mtu {} (proto={:?}, {}->{})", - v.contents.len(), - mtu, - v.proto, - v.source, - v.destination, - ); - } - let packet = PendingPacket { - proto: v.proto, - source: v.source, - destination: v.destination, - contents: v.contents.to_vec(), - }; - other_netem.handle_input(NetemInput::Packet(time, packet)); - } - Output::Event(v) => { - rtc.events.push((rtc.last, v)); - } - } - } - Ok(()) -} - -/// Perform a change to the session via an offer and answer. -/// -/// The closure is passed the [`SdpApi`] for the offer side to make any changes, these are then -/// applied locally and the offer is negotiated with the answerer. -pub fn negotiate(offerer: &mut TestRtc, answerer: &mut TestRtc, mut do_change: F) -> R -where - F: FnMut(&mut SdpApi) -> R, -{ - let (offer, pending, result) = offerer.span.in_scope(|| { - let mut change = offerer.rtc.sdp_api(); - - let result = do_change(&mut change); - - let (offer, pending) = change.apply().unwrap(); - - (offer, pending, result) - }); - - let answer = answerer - .span - .in_scope(|| answerer.rtc.sdp_api().accept_offer(offer).unwrap()); - - offerer.span.in_scope(|| { - offerer.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - }); - - result -} - -// Upstream's `_internal_test_exports` peeked at these for its integration tests. -impl Rtc { - pub fn _mids(&self) -> Vec { - self.session - .medias - .iter() - .map(crate::vendor::str0m::media::Media::mid) - .collect() - } - - pub fn _exts(&self) -> &ExtensionMap { - &self.session.exts - } - - pub fn _local_ice_creds(&self) -> crate::vendor::is::IceCreds { - self.ice.local_credentials().clone() - } -} - -impl PayloadParams { - pub fn _is_locked(&self) -> bool { - self.locked - } -} - -impl Deref for TestRtc { - type Target = Rtc; - - fn deref(&self) -> &Self::Target { - &self.rtc - } -} - -impl DerefMut for TestRtc { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.rtc - } -} - -pub fn init_log() { - use tracing_subscriber::{EnvFilter, fmt, prelude::*}; - - let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("off")); - - static START: Once = Once::new(); - - START.call_once(|| { - tracing_subscriber::registry() - .with(fmt::layer()) - .with(env_filter) - .init(); - }); -} - -pub fn init_crypto_default() { - crate::vendor::str0m::crypto::from_feature_flags().install_process_default(); -} - -/// Create a crypto provider from a string name. Only "rind" is vendored. -fn get_crypto_provider_by_name(name: &str) -> CryptoProvider { - match name { - "rind" => crate::vendor::str0m_rind::default_provider().unwrap(), - _ => panic!("Unknown or unavailable crypto provider '{name}'. Available providers: [rind]"), - } -} - -pub fn connect_l_r() -> (TestRtc, TestRtc) { - let mut rtc1_builder = Rtc::builder().set_rtp_mode(true).enable_raw_packets(true); - - if let Some(crypto) = Peer::Left.crypto_provider() { - rtc1_builder = rtc1_builder.set_crypto_provider(crypto); - } - - let mut rtc2_builder = Rtc::builder().set_rtp_mode(true).enable_raw_packets(true); - - if let Some(crypto) = Peer::Right.crypto_provider() { - rtc2_builder = rtc2_builder.set_crypto_provider(crypto); - } - - let now = Instant::now(); - connect_l_r_with_rtc(rtc1_builder.build(now), rtc2_builder.build(now)) -} - -pub fn connect_l_r_with_rtc(rtc1: Rtc, rtc2: Rtc) -> (TestRtc, TestRtc) { - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc1); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc2); - - let host1 = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host2 = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - l.add_local_candidate(host1.clone()); - l.add_remote_candidate(host2.clone()); - r.add_local_candidate(host2); - r.add_remote_candidate(host1); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - l.direct_api().start_dtls(true).unwrap(); - r.direct_api().start_dtls(false).unwrap(); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r).expect("clean progress"); - } - - (l, r) -} - -pub type PcapData = Vec<(Duration, RtpHeader, Vec)>; - -pub fn vp8_data() -> PcapData { - load_pcap_data(include_bytes!("data/vp8.pcap")) -} - -pub fn vp9_contiguous_data() -> PcapData { - load_pcap_data(include_bytes!("data/contiguous_vp9.pcap")) -} - -pub fn vp9_data() -> PcapData { - load_pcap_data(include_bytes!("data/vp9.pcap")) -} - -pub fn h264_data() -> PcapData { - load_pcap_data(include_bytes!("data/h264.pcap")) -} - -pub fn av1_data() -> PcapData { - load_pcap_data(include_bytes!("data/av1.pcap")) -} - -pub fn h265_data() -> PcapData { - load_pcap_data(include_bytes!("data/h265.pcap")) -} - -pub fn load_pcap_data(data: &[u8]) -> PcapData { - let reader = Cursor::new(data); - let mut r = PcapReader::new(reader).expect("pcap reader"); - - let exts = ExtensionMap::standard(); - - let mut ret = vec![]; - - let mut first = None; - - while let Some(pkt) = r.next_packet() { - let pkt = pkt.unwrap(); - - if first.is_none() { - first = Some(pkt.timestamp); - } - let relative_time = pkt.timestamp - first.unwrap(); - - // This magic number 42 is the ethernet/IP/UDP framing of the packet. - let rtp_data = &pkt.data[42..]; - - let header = RtpHeader::parse(rtp_data, &exts).unwrap(); - let payload = &rtp_data[header.header_len..]; - - ret.push((relative_time, header, payload.to_vec())); - } - - ret -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs b/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs deleted file mode 100644 index 92cf60fdfd3..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs +++ /dev/null @@ -1,387 +0,0 @@ -//! Tests for configuration edge cases and validation. - -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcConfig, RtcError}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// Test set_reordering_size_audio() and set_reordering_size_video() with custom sizes. -#[test] -fn config_reordering_size_custom() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Verify config builder correctly sets and retrieves values - let config = RtcConfig::new() - .set_reordering_size_audio(20) - .set_reordering_size_video(50); - - // Verify the config has correct values before building - assert_eq!(config.reordering_size_audio(), 20, "Audio reordering size should be 20"); - assert_eq!(config.reordering_size_video(), 50, "Video reordering size should be 50"); - - // Verify default values are different - let default_config = RtcConfig::new(); - assert_eq!( - default_config.reordering_size_audio(), - 15, - "Default audio reordering should be 15" - ); - assert_eq!( - default_config.reordering_size_video(), - 30, - "Default video reordering should be 30" - ); - - // Build and verify the Rtc works with custom config - let rtc = config.build(Instant::now()); - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - // Send and receive data to verify the config doesn't break functionality - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - for _ in 0..20 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Verify data was received - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!( - received_count > 10, - "Should receive media data with custom reordering config, got {}", - received_count - ); - - Ok(()) -} - -/// Test timeout defaults and configuration round-trips, including large durations. -#[test] -fn config_audio_reordering_timeout_custom() { - assert_eq!( - RtcConfig::new().reordering_timeout_audio(), - Some(Duration::from_secs(1)) - ); - for timeout in [ - None, - Some(Duration::ZERO), - Some(Duration::from_millis(250)), - Some(Duration::from_secs(601)), - Some(Duration::MAX), - ] { - let config = RtcConfig::new().set_reordering_timeout_audio(timeout); - assert_eq!(config.reordering_timeout_audio(), timeout); - assert_eq!(config.clone().reordering_timeout_audio(), timeout); - } -} - -/// Test enable_raw_packets(true) produces RawPacket events. -#[test] -fn config_raw_packets_enabled() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let rtc = RtcConfig::new().enable_raw_packets(true).build(Instant::now()); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - - let rtc_r = RtcConfig::new().enable_raw_packets(true).build(Instant::now()); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - // Clear previous events - l.events.clear(); - r.events.clear(); - - // Send some audio data - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - for _ in 0..20 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Check for RawPacket events - let raw_packet_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::RawPacket(_))) - .count(); - - assert!( - raw_packet_count > 0, - "Should have RawPacket events with enable_raw_packets(true)" - ); - - Ok(()) -} - -#[test] -fn config_rtcp_report_intervals() { - let default_config = RtcConfig::new(); - assert_eq!(default_config.rtcp_report_interval_audio(), Duration::from_secs(5)); - assert_eq!(default_config.rtcp_report_interval_video(), Duration::from_secs(1)); - - let config = RtcConfig::new() - .set_rtcp_report_interval_audio(Duration::from_millis(750)) - .set_rtcp_report_interval_video(Duration::from_millis(500)); - assert_eq!(config.rtcp_report_interval_audio(), Duration::from_millis(750)); - assert_eq!(config.rtcp_report_interval_video(), Duration::from_millis(500)); -} - -#[test] -#[should_panic] -fn config_rejects_zero_audio_rtcp_report_interval() { - RtcConfig::new().set_rtcp_report_interval_audio(Duration::ZERO); -} - -#[test] -#[should_panic] -fn config_rejects_zero_video_rtcp_report_interval() { - RtcConfig::new().set_rtcp_report_interval_video(Duration::ZERO); -} - -/// Test set_fingerprint_verification(false) allows connection with wrong fingerprint. -#[test] -fn config_fingerprint_verification_disabled() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - use crate::vendor::str0m::Candidate; - use crate::vendor::str0m::crypto::Fingerprint; - - // Create RTCs with fingerprint verification DISABLED - let rtc_l = RtcConfig::new() - .set_fingerprint_verification(false) - .set_rtp_mode(true) - .build(Instant::now()); - - let rtc_r = RtcConfig::new() - .set_fingerprint_verification(false) - .set_rtp_mode(true) - .build(Instant::now()); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc_l); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r); - - // Set up candidates - let host1 = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host2 = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - l.add_local_candidate(host1.clone()).unwrap(); - l.add_remote_candidate(host2.clone()); - r.add_local_candidate(host2).unwrap(); - r.add_remote_candidate(host1); - - // Create CORRUPTED fingerprints (all zeros - definitely wrong) - let corrupted_fingerprint = Fingerprint { - hash_func: "sha-256".to_string(), - bytes: vec![0u8; 32], // Wrong fingerprint! - }; - - // Set the WRONG fingerprints as remote (this would fail with verification enabled) - l.direct_api().set_remote_fingerprint(corrupted_fingerprint.clone()); - r.direct_api().set_remote_fingerprint(corrupted_fingerprint); - - // Exchange ICE credentials - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - // Start DTLS - this should succeed despite wrong fingerprints - // because verification is disabled - l.direct_api().start_dtls(true).unwrap(); - r.direct_api().start_dtls(false).unwrap(); - - // Connection should succeed despite corrupted fingerprints - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect - fingerprint verification should be disabled"); - } - progress(&mut l, &mut r)?; - } - - // Verify we actually connected - assert!(l.is_connected(), "L should be connected"); - assert!(r.is_connected(), "R should be connected"); - - Ok(()) -} - -/// Test that RtcConfig can be cloned and used for multiple instances. -#[test] -fn config_clone_multiple_instances() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Create a config with custom settings (not ice_lite since both can't be ice_lite) - let config = RtcConfig::new() - .set_reordering_size_audio(20) - .set_reordering_size_video(40); - - // Clone the config and create multiple instances - let rtc1 = config.clone().build(Instant::now()); - let rtc2 = config.build(Instant::now()); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc1); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc2); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with cloned config"); - } - progress(&mut l, &mut r)?; - } - - Ok(()) -} - -/// Test set_send_buffer_audio and set_send_buffer_video configuration. -#[test] -fn config_send_buffer_sizes() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Verify config builder correctly sets and retrieves values - let config = RtcConfig::new().set_send_buffer_audio(100).set_send_buffer_video(2000); - - // Verify the config has correct values before building - assert_eq!(config.send_buffer_audio(), 100, "Audio send buffer should be 100"); - assert_eq!(config.send_buffer_video(), 2000, "Video send buffer should be 2000"); - - // Verify default values are different - let default_config = RtcConfig::new(); - assert_eq!( - default_config.send_buffer_audio(), - 50, - "Default audio send buffer should be 50" - ); - assert_eq!( - default_config.send_buffer_video(), - 1000, - "Default video send buffer should be 1000" - ); - - // Build and verify the Rtc works with custom config - let rtc = config.build(Instant::now()); - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - // Send and receive data to verify the config doesn't break functionality - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - for _ in 0..20 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Verify data was received - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!( - received_count > 10, - "Should receive media data with custom send buffer config, got {}", - received_count - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/contiguous.rs b/rs/moq-webrtc/src/vendor/str0m/tests/contiguous.rs deleted file mode 100644 index d6340383121..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/contiguous.rs +++ /dev/null @@ -1,224 +0,0 @@ -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaData, MediaKind}; -use crate::vendor::str0m::rtp::RtpWrite; -use crate::vendor::str0m::{Candidate, Event, RtcError}; -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn contiguous_all_the_way() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let output = Server::with_vp8_input().timeout(Duration::from_secs(10)).get_output()?; - let mut count = 0; - - // Contiguous all the way through. - for data in output { - assert!(data.contiguous); - count += 1; - } - - // We have 3 continuations: 104 - 3 == 101 - assert_eq!(count, 101); - - Ok(()) -} - -#[test] -pub fn not_contiguous() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let output = Server::with_vp8_input() - .skip_packet(14337) - .timeout(Duration::from_secs(5)) - .get_output()?; - let mut count = 0; - - // Contiguous all the way through. - for data in output { - count += 1; - // We dropped packet 14337, which means its dependendant 14338 is not - // emitted, and 14339 is emitted and marked as discontinuous. - let assume_contiguous = !data.seq_range.contains(&14339.into()); - assert_eq!(assume_contiguous, data.contiguous); - } - - // assert!(false); - // We have 3 continuations, 2 missing packet (14337 14338) - // 104 - 3 - 2 == 99 - assert_eq!(count, 99); - - Ok(()) -} - -#[test] -pub fn vp9_contiguous_all_the_way() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let output = Server::with_vp9_input().get_output()?; - let mut count = 0; - - // Contiguous all the way through. - for data in output { - assert!(data.contiguous); - count += 1; - } - - // The last packet is never flushed out because the depacketizer wants - // to see the next packet before releasing. - // We have one last packet missing: 16 - 1 == 15 - assert_eq!(count, 15); - - Ok(()) -} - -#[test] -pub fn vp9_not_contiguous() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let output = Server::with_vp9_input().skip_packet(30952).get_output()?; - let mut count = 0; - - // Contiguous all the way through. - for data in output { - count += 1; - // We dropped packet 19365 and next packet is emitted and marked as discontinuous. - let assume_contiguous = !data.seq_range.contains(&30953.into()); - assert_eq!(assume_contiguous, data.contiguous); - } - - // assert!(false); - // We 1 missing packet 30952, and one last - // packet missing: 16 - 1 - 1 == 14 - assert_eq!(count, 14); - - Ok(()) -} - -struct Server { - codec: Codec, - input_data: common::PcapData, - skip_packet: Option, - timeout: Option, -} - -impl Server { - fn with_vp8_input() -> Self { - Self::new(Codec::Vp8, common::vp8_data()) - } - - fn with_vp9_input() -> Self { - Self::new(Codec::Vp9, common::vp9_contiguous_data()) - } - - fn new(codec: Codec, input_data: common::PcapData) -> Self { - Self { - codec, - input_data, - skip_packet: None, - timeout: None, - } - } - - fn skip_packet(mut self, packet: u16) -> Self { - self.skip_packet = Some(packet); - self - } - - fn timeout(mut self, timeout: Duration) -> Self { - self.timeout = Some(timeout); - self - } - - fn get_output(self) -> Result, RtcError> { - let mut l = TestRtc::new(Peer::Left); - - // We need to lower the default reordering buffer size, or we won't make it - // past the dropped packet. - let rtc_r = Rtc::builder().set_reordering_size_video(5).build(Instant::now()); - - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r); - - l.add_local_candidate(Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp")?); - r.add_local_candidate(Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp")?); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = match self.codec { - Codec::Vp8 => l.params_vp8(), - Codec::Vp9 => l.params_vp9(), - _ => unimplemented!(), - }; - assert_eq!(params.spec().codec, self.codec); - - let pt = params.pt(); - - for (relative, header, payload) in self.input_data { - // Drop a random packet in the middle. - if Some(header.sequence_number) == self.skip_packet { - continue; - } - - // Keep RTC time progressed to be "in sync" with the test data. - while (l.last - max) < relative { - progress(&mut l, &mut r)?; - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .ext_vals(header.ext_vals) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - - if let Some(duration) = self.timeout { - if l.duration() > duration { - break; - } - } - } - - // Drain any remaining packets from the pacer - progress(&mut l, &mut r)?; - - let events = r - .events - .into_iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }) - .collect(); - - Ok(events) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/crypto-compliance.rs b/rs/moq-webrtc/src/vendor/str0m/tests/crypto-compliance.rs deleted file mode 100644 index 86472727cc0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/crypto-compliance.rs +++ /dev/null @@ -1,537 +0,0 @@ -/// Test algorithm implementations for the CryptoProvider -/// -/// This contains tests run against the installed crypto provider to verify -/// hash, cipher and signature implementations against known test vectors. -use crate::vendor::str0m::crypto::CryptoProvider; - -use super::common; -use common::init_crypto_default; - -fn get_provider() -> &'static CryptoProvider { - init_crypto_default(); - CryptoProvider::get_default().unwrap() -} - -/// Convert an ASCII hex array into a byte array at compile time. -macro_rules! hex_as_bytes { - ($input:expr) => {{ - const fn from_hex_char(c: u8) -> u8 { - match c { - b'0'..=b'9' => c - b'0', - b'a'..=b'f' => c - b'a' + 10, - b'A'..=b'F' => c - b'A' + 10, - _ => panic!("Invalid hex character"), - } - } - - const INPUT: &[u8] = $input; - const LEN: usize = INPUT.len(); - const OUTPUT_LEN: usize = LEN / 2; - - const fn convert() -> [u8; OUTPUT_LEN] { - assert!(LEN % 2 == 0, "Hex string length must be even"); - - let mut out = [0u8; OUTPUT_LEN]; - let mut i = 0; - while i < LEN { - out[i / 2] = (from_hex_char(INPUT[i]) << 4) | from_hex_char(INPUT[i + 1]); - i += 2; - } - out - } - - convert() - }}; -} - -mod sha1 { - fn hash(input: &[u8]) -> String { - super::get_provider() - .sha1_provider - .sha1(input) - .iter() - .map(|b| format!("{b:02x}")) - .collect() - } - - #[test] - fn test_abc() { - let provider = super::get_provider().sha1_provider; - assert_eq!( - provider.sha1(b"abc"), - hex_as_bytes!(b"a9993e364706816aba3e25717850c26c9cd0d89d") - ); - } - - #[test] - fn fips_180_vectors() { - assert_eq!(hash(b""), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); - assert_eq!(hash(b"abc"), "a9993e364706816aba3e25717850c26c9cd0d89d"); - assert_eq!( - hash(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), - "84983e441c3bd26ebaae4aa1f95129e5e54670f1" - ); - assert_eq!(hash(&[b'a'; 1_000_000]), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); - } - - #[test] - fn padding_boundaries() { - let expected = [ - (55, "c1c8bbdc22796e28c0e15163d20899b65621d65a"), - (56, "c2db330f6083854c99d4b5bfb6e8f29f201be699"), - (63, "03f09f5b158a7a8cdad920bddc29b81c18a551f5"), - (64, "0098ba824b5c16427bd7a1122a5a442a25ec644d"), - (65, "11655326c708d70319be2610e8a57d9a5b959d3b"), - ]; - for (len, digest) in expected { - assert_eq!(hash(&vec![b'a'; len]), digest, "length {len}"); - } - } -} - -mod sha256 { - fn verify_test_vector(input: &[u8], expected: &[u8; 32]) { - let sha256_provider = super::get_provider().sha256_provider; - let hash = sha256_provider.sha256(input); - assert_eq!(hash, *expected); - } - - #[test] - fn test_hello_world() { - verify_test_vector( - b"hello world", - &hex_as_bytes!(b"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"), - ); - } - - #[test] - fn test_empty() { - // SHA-256 of "" - NIST test vector - verify_test_vector( - b"", - &hex_as_bytes!(b"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), - ); - } - - #[test] - fn test_abc() { - // SHA-256 of "abc" - NIST test vector - verify_test_vector( - b"abc", - &hex_as_bytes!(b"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"), - ); - } -} - -mod sha1_hmac { - fn verify_test_vector(key: &[u8], payloads: &[&[u8]], expected: &[u8; 20]) { - let sha1_hmac_provider = super::get_provider().sha1_hmac_provider; - let hmac = sha1_hmac_provider.sha1_hmac(key, payloads); - assert_eq!(hmac, *expected); - } - - #[test] - fn test_rfc2202_test_case_1() { - verify_test_vector( - &[0x0b; 20], - &[b"Hi There"], - &hex_as_bytes!(b"b617318655057264e28bc0b6fb378c8ef146be00"), - ); - } - - #[test] - fn test_rfc2202_test_case_2() { - verify_test_vector( - b"Jefe", - &[b"what do ya want for nothing?"], - &hex_as_bytes!(b"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"), - ); - } - - #[test] - fn test_rfc2202_test_case_3() { - verify_test_vector( - &[0xaa; 20], - &[&[0xddu8; 50]], - &hex_as_bytes!(b"125d7342b9ac11cd91a39af48aa17b4f63f175d3"), - ); - } - - #[test] - fn test_rfc2202_test_case_4() { - verify_test_vector( - &[ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, - ], - &[&[0xcdu8; 50]], - &hex_as_bytes!(b"4c9007f4026250c6bc8414f9bf50c86c2d7235da"), - ); - } - - #[test] - fn test_rfc2202_test_case_5() { - verify_test_vector( - &[0x0c; 20], - &[b"Test With Truncation"], - &hex_as_bytes!(b"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04"), - ); - } - - #[test] - fn test_rfc2202_test_case_6() { - verify_test_vector( - &[0xaa; 80], - &[b"Test Using Larger Than Block-Size Key - Hash Key First"], - &hex_as_bytes!(b"aa4ae5e15272d00e95705637ce8a3b55ed402112"), - ); - } - - #[test] - fn test_rfc2202_test_case_7() { - verify_test_vector( - &[0xaa; 80], - &[ - b"Test Using Larger Than Block-Size Key and Larger ", - b"Than One Block-Size Data", - ], - &hex_as_bytes!(b"e8e99d0f45237d786d6bbaa7965c7808bbff1a91"), - ); - } -} - -mod aes_128_cm_sha1_80 { - fn verify_test_vector(key: [u8; 16], iv: [u8; 16], encrypt: bool, input: &[u8], expected: &[u8]) { - let srtp_provider = super::get_provider().srtp_provider; - let cipher_provider = srtp_provider.aes_128_cm_sha1_80(); - let mut cipher = cipher_provider.create_cipher(key, encrypt); - - let mut output = vec![0u8; input.len()]; - if encrypt { - cipher.encrypt(&iv, input, &mut output).unwrap(); - } else { - cipher.decrypt(&iv, input, &mut output).unwrap(); - } - assert_eq!(expected, &output) - } - - // AES-128-CTR Test Vectors from NIST SP 800-38A - // https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf - // Section F.5.1 - - #[test] - fn test_ctr_encrypt() { - verify_test_vector( - hex_as_bytes!(b"2b7e151628aed2a6abf7158809cf4f3c"), - hex_as_bytes!(b"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), - true, - &hex_as_bytes!(b"6bc1bee22e409f96e93d7e117393172a"), - &hex_as_bytes!(b"874d6191b620e3261bef6864990db6ce"), - ); - } - - #[test] - fn test_decrypt() { - verify_test_vector( - hex_as_bytes!(b"2b7e151628aed2a6abf7158809cf4f3c"), - hex_as_bytes!(b"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), - false, - &hex_as_bytes!(b"874d6191b620e3261bef6864990db6ce"), - &hex_as_bytes!(b"6bc1bee22e409f96e93d7e117393172a"), - ); - } - - #[test] - fn test_multiple_blocks() { - verify_test_vector( - hex_as_bytes!(b"2b7e151628aed2a6abf7158809cf4f3c"), - hex_as_bytes!(b"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), - true, - &hex_as_bytes!( - b"6bc1bee22e409f96e93d7e117393172a\ - ae2d8a571e03ac9c9eb76fac45af8e51\ - 30c81c46a35ce411e5fbc1191a0a52ef" - ), - &hex_as_bytes!( - b"874d6191b620e3261bef6864990db6ce\ - 9806f66b7970fdff8617187bb9fffdff\ - 5ae4df3edbd5d35e5b4f09020db03eab" - ), - ); - } -} - -mod aead_aes_128_gcm { - fn verify_test_vector(key: [u8; 16], iv: [u8; 12], encrypt: bool, aads: &[&[u8]], input: &[u8], expected: &[u8]) { - let srtp_provider = super::get_provider().srtp_provider; - let cipher_provider = srtp_provider.aead_aes_128_gcm(); - let mut cipher = cipher_provider.create_cipher(key, encrypt); - - let output_len = if encrypt { input.len() + 16 } else { input.len() - 16 }; - let mut output = vec![0u8; output_len]; - if encrypt { - cipher.encrypt(&iv, aads[0], input, &mut output).unwrap(); - } else { - cipher.decrypt(&iv, aads, input, &mut output).unwrap(); - } - assert_eq!(expected, &output) - } - - // AES-128-GCM Test Vectors from NIST SP 800-38D - // https://csrc.nist.gov/publications/detail/sp/800-38d/final - // Test Case 4 - - #[test] - fn test_encrypt() { - verify_test_vector( - hex_as_bytes!(b"feffe9928665731c6d6a8f9467308308"), - hex_as_bytes!(b"cafebabefacedbaddecaf888"), - true, - &[&hex_as_bytes!( - b"feedfacedeadbeeffeedfacedeadbeef\ - abaddad2" - )], - &hex_as_bytes!( - b"d9313225f88406e5a55909c5aff5269a\ - 86a7a9531534f7da2e4c303d8a318a72\ - 1c3c0c95956809532fcf0e2449a6b525\ - b16aedf5aa0de657ba637b39" - ), - &hex_as_bytes!( - b"42831ec2217774244b7221b784d0d49c\ - e3aa212f2c02a4e035c17e2329aca12e\ - 21d514b25466931c7d8f6a5aac84aa05\ - 1ba30b396a0aac973d58e091\ - 5bc94fbc3221a5db94fae95ae7121a47" - ), - ); - } - - #[test] - fn test_decrypt() { - verify_test_vector( - hex_as_bytes!(b"feffe9928665731c6d6a8f9467308308"), - hex_as_bytes!(b"cafebabefacedbaddecaf888"), - false, - &[&hex_as_bytes!( - b"feedfacedeadbeeffeedfacedeadbeef\ - abaddad2" - )], - &hex_as_bytes!( - b"42831ec2217774244b7221b784d0d49c\ - e3aa212f2c02a4e035c17e2329aca12e\ - 21d514b25466931c7d8f6a5aac84aa05\ - 1ba30b396a0aac973d58e091\ - 5bc94fbc3221a5db94fae95ae7121a47" - ), - &hex_as_bytes!( - b"d9313225f88406e5a55909c5aff5269a\ - 86a7a9531534f7da2e4c303d8a318a72\ - 1c3c0c95956809532fcf0e2449a6b525\ - b16aedf5aa0de657ba637b39" - ), - ); - } - - #[test] - fn test_decrypt_invalid_tag() { - let srtp_provider = super::get_provider().srtp_provider; - let cipher_provider = srtp_provider.aead_aes_128_gcm(); - let mut cipher = cipher_provider.create_cipher(hex_as_bytes!(b"feffe9928665731c6d6a8f9467308308"), false); - - let mut output = vec![0u8; 1024]; - let result = cipher.decrypt( - &hex_as_bytes!(b"cafebabefacedbaddecaf888"), - &[&hex_as_bytes!( - b"feedfacedeadbeeffeedfacedeadbeef\ - abaddad2" - )], - &hex_as_bytes!( - b"42831ec2217774244b7221b784d0d49c\ - e3aa212f2c02a4e035c17e2329aca12e\ - 21d514b25466931c7d8f6a5aac84aa05\ - 1ba30b396a0aac973d58e091\ - 000000000000000000000000000000" - ), - &mut output, - ); - assert!(result.is_err()); - } -} - -mod aead_aes_256_gcm { - fn verify_test_vector(key: [u8; 32], iv: [u8; 12], encrypt: bool, aads: &[&[u8]], input: &[u8], expected: &[u8]) { - let srtp_provider = super::get_provider().srtp_provider; - let cipher_provider = srtp_provider.aead_aes_256_gcm(); - let mut cipher = cipher_provider.create_cipher(key, encrypt); - - let output_len = if encrypt { input.len() + 16 } else { input.len() - 16 }; - let mut output = vec![0u8; output_len]; - if encrypt { - cipher.encrypt(&iv, aads[0], input, &mut output).unwrap(); - } else { - cipher.decrypt(&iv, aads, input, &mut output).unwrap(); - } - assert_eq!(expected, &output) - } - - // AES-256-GCM Test Vectors from NIST SP 800-38D - // Test Case 16 - - #[test] - fn test_encrypt() { - verify_test_vector( - hex_as_bytes!( - b"feffe9928665731c6d6a8f9467308308\ - feffe9928665731c6d6a8f9467308308" - ), - hex_as_bytes!(b"cafebabefacedbaddecaf888"), - true, - &[&hex_as_bytes!( - b"feedfacedeadbeeffeedfacedeadbeef\ - abaddad2" - )], - &hex_as_bytes!( - b"d9313225f88406e5a55909c5aff5269a\ - 86a7a9531534f7da2e4c303d8a318a72\ - 1c3c0c95956809532fcf0e2449a6b525\ - b16aedf5aa0de657ba637b39" - ), - &hex_as_bytes!( - b"522dc1f099567d07f47f37a32a84427d\ - 643a8cdcbfe5c0c97598a2bd2555d1aa\ - 8cb08e48590dbb3da7b08b1056828838\ - c5f61e6393ba7a0abcc9f662\ - 76fc6ece0f4e1768cddf8853bb2d551b" - ), - ); - } - - #[test] - fn test_decrypt() { - verify_test_vector( - hex_as_bytes!( - b"feffe9928665731c6d6a8f9467308308\ - feffe9928665731c6d6a8f9467308308" - ), - hex_as_bytes!(b"cafebabefacedbaddecaf888"), - false, - &[&hex_as_bytes!( - b"feedfacedeadbeeffeedfacedeadbeef\ - abaddad2" - )], - &hex_as_bytes!( - b"522dc1f099567d07f47f37a32a84427d\ - 643a8cdcbfe5c0c97598a2bd2555d1aa\ - 8cb08e48590dbb3da7b08b1056828838\ - c5f61e6393ba7a0abcc9f662\ - 76fc6ece0f4e1768cddf8853bb2d551b" - ), - &hex_as_bytes!( - b"d9313225f88406e5a55909c5aff5269a\ - 86a7a9531534f7da2e4c303d8a318a72\ - 1c3c0c95956809532fcf0e2449a6b525\ - b16aedf5aa0de657ba637b39" - ), - ); - } -} - -mod srtp_aes_128_ecb_round { - const TEST_KEY: [u8; 16] = hex_as_bytes!(b"2b7e151628aed2a6abf7158809cf4f3c"); - - fn verify_test_vector(key: &[u8], input: &[u8], expected: &[u8]) { - let srtp_provider = super::get_provider().srtp_provider; - let mut out = [0u8; 2048]; - srtp_provider.srtp_aes_128_ecb_round(key, input, out.as_mut_slice()); - assert_eq!(expected, &out[0..input.len()]) - } - - // Test vectors from NIST SP 800-38A: - // https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf - - #[test] - fn test_vec_1() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"6bc1bee22e409f96e93d7e117393172a"), - &hex_as_bytes!(b"3ad77bb40d7a3660a89ecaf32466ef97"), - ); - } - - #[test] - fn test_vec_2() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"ae2d8a571e03ac9c9eb76fac45af8e51"), - &hex_as_bytes!(b"f5d3d58503b9699de785895a96fdbaaf"), - ); - } - - #[test] - fn test_vec_3() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"30c81c46a35ce411e5fbc1191a0a52ef"), - &hex_as_bytes!(b"43b1cd7f598ece23881b00e3ed030688"), - ); - } - - #[test] - fn test_vec_4() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"f69f2445df4f9b17ad2b417be66c3710"), - &hex_as_bytes!(b"7b0c785e27e8ad3f8223207104725dd4"), - ); - } -} - -mod srtp_aes_256_ecb_round { - const TEST_KEY: [u8; 32] = hex_as_bytes!(b"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"); - - fn verify_test_vector(key: &[u8], input: &[u8], expected: &[u8]) { - let srtp_provider = super::get_provider().srtp_provider; - let mut out = [0u8; 2048]; - srtp_provider.srtp_aes_256_ecb_round(key, input, out.as_mut_slice()); - assert_eq!(expected, &out[0..input.len()]) - } - - // Test vectors from NIST SP 800-38A: - // https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf - - #[test] - fn test_vec_1() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"6bc1bee22e409f96e93d7e117393172a"), - &hex_as_bytes!(b"f3eed1bdb5d2a03c064b5a7e3db181f8"), - ); - } - - #[test] - fn test_vec_2() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"ae2d8a571e03ac9c9eb76fac45af8e51"), - &hex_as_bytes!(b"591ccb10d410ed26dc5ba74a31362870"), - ); - } - - #[test] - fn test_vec_3() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"30c81c46a35ce411e5fbc1191a0a52ef"), - &hex_as_bytes!(b"b6ed21b99ca6f4f9f153e7b1beafed1d"), - ); - } - - #[test] - fn test_vec_4() { - verify_test_vector( - &TEST_KEY, - &hex_as_bytes!(b"f69f2445df4f9b17ad2b417be66c3710"), - &hex_as_bytes!(b"23304b7a39f9f3ff067d8d8f9e24ecc7"), - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/av1.pcap b/rs/moq-webrtc/src/vendor/str0m/tests/data/av1.pcap deleted file mode 100644 index 7a80fc7f877..00000000000 Binary files a/rs/moq-webrtc/src/vendor/str0m/tests/data/av1.pcap and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/av1.txt b/rs/moq-webrtc/src/vendor/str0m/tests/data/av1.txt deleted file mode 100644 index 204e4fd33e8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data/av1.txt +++ /dev/null @@ -1,201 +0,0 @@ -1 0.000000 10.2.2.2 10.1.1.1 RTP 1034 PT=Unassigned, SSRC=0xD465AC89, Seq=7485, Time=4244970353 -2 0.011000 10.2.2.2 10.1.1.1 RTP 1032 PT=Unassigned, SSRC=0xD465AC89, Seq=7486, Time=4244970353, Mark -3 0.032000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7487, Time=4244973233, Mark -4 0.058000 10.2.2.2 10.1.1.1 RTP 723 PT=Unassigned, SSRC=0xD465AC89, Seq=7488, Time=4244976203 -5 0.058000 10.2.2.2 10.1.1.1 RTP 720 PT=Unassigned, SSRC=0xD465AC89, Seq=7489, Time=4244976203, Mark -6 0.092000 10.2.2.2 10.1.1.1 RTP 817 PT=Unassigned, SSRC=0xD465AC89, Seq=7490, Time=4244979263 -7 0.092000 10.2.2.2 10.1.1.1 RTP 814 PT=Unassigned, SSRC=0xD465AC89, Seq=7491, Time=4244979263, Mark -8 0.126000 10.2.2.2 10.1.1.1 RTP 1030 PT=Unassigned, SSRC=0xD465AC89, Seq=7492, Time=4244982323 -9 0.130000 10.2.2.2 10.1.1.1 RTP 1030 PT=Unassigned, SSRC=0xD465AC89, Seq=7493, Time=4244982323 -10 0.131000 10.2.2.2 10.1.1.1 RTP 1026 PT=Unassigned, SSRC=0xD465AC89, Seq=7494, Time=4244982323, Mark -11 0.161000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7495, Time=4244985383 -12 0.161000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7496, Time=4244985383 -13 0.161000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7497, Time=4244985383 -14 0.161000 10.2.2.2 10.1.1.1 RTP 1085 PT=Unassigned, SSRC=0xD465AC89, Seq=7498, Time=4244985383, Mark -15 0.194000 10.2.2.2 10.1.1.1 RTP 926 PT=Unassigned, SSRC=0xD465AC89, Seq=7499, Time=4244988443 -16 0.194000 10.2.2.2 10.1.1.1 RTP 926 PT=Unassigned, SSRC=0xD465AC89, Seq=7500, Time=4244988443 -17 0.194000 10.2.2.2 10.1.1.1 RTP 923 PT=Unassigned, SSRC=0xD465AC89, Seq=7501, Time=4244988443, Mark -18 0.226000 10.2.2.2 10.1.1.1 RTP 744 PT=Unassigned, SSRC=0xD465AC89, Seq=7502, Time=4244991233 -19 0.226000 10.2.2.2 10.1.1.1 RTP 742 PT=Unassigned, SSRC=0xD465AC89, Seq=7503, Time=4244991233, Mark -20 0.260000 10.2.2.2 10.1.1.1 RTP 742 PT=Unassigned, SSRC=0xD465AC89, Seq=7504, Time=4244994293 -21 0.260000 10.2.2.2 10.1.1.1 RTP 739 PT=Unassigned, SSRC=0xD465AC89, Seq=7505, Time=4244994293, Mark -22 0.293000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7506, Time=4244997353 -23 0.293000 10.2.2.2 10.1.1.1 RTP 1152 PT=Unassigned, SSRC=0xD465AC89, Seq=7507, Time=4244997353, Mark -24 0.326000 10.2.2.2 10.1.1.1 RTP 971 PT=Unassigned, SSRC=0xD465AC89, Seq=7508, Time=4245000323 -25 0.326000 10.2.2.2 10.1.1.1 RTP 971 PT=Unassigned, SSRC=0xD465AC89, Seq=7509, Time=4245000323 -26 0.326000 10.2.2.2 10.1.1.1 RTP 967 PT=Unassigned, SSRC=0xD465AC89, Seq=7510, Time=4245000323, Mark -27 0.363000 10.2.2.2 10.1.1.1 RTP 1223 PT=Unassigned, SSRC=0xD465AC89, Seq=7511, Time=4245003473 -28 0.363000 10.2.2.2 10.1.1.1 RTP 1223 PT=Unassigned, SSRC=0xD465AC89, Seq=7512, Time=4245003473 -29 0.363000 10.2.2.2 10.1.1.1 RTP 1223 PT=Unassigned, SSRC=0xD465AC89, Seq=7513, Time=4245003473 -30 0.363000 10.2.2.2 10.1.1.1 RTP 1216 PT=Unassigned, SSRC=0xD465AC89, Seq=7514, Time=4245003473, Mark -31 0.394000 10.2.2.2 10.1.1.1 RTP 960 PT=Unassigned, SSRC=0xD465AC89, Seq=7515, Time=4245006443 -32 0.394000 10.2.2.2 10.1.1.1 RTP 960 PT=Unassigned, SSRC=0xD465AC89, Seq=7516, Time=4245006443 -33 0.394000 10.2.2.2 10.1.1.1 RTP 960 PT=Unassigned, SSRC=0xD465AC89, Seq=7517, Time=4245006443 -34 0.394000 10.2.2.2 10.1.1.1 RTP 955 PT=Unassigned, SSRC=0xD465AC89, Seq=7518, Time=4245006443, Mark -35 0.428000 10.2.2.2 10.1.1.1 RTP 853 PT=Unassigned, SSRC=0xD465AC89, Seq=7519, Time=4245009413 -36 0.428000 10.2.2.2 10.1.1.1 RTP 853 PT=Unassigned, SSRC=0xD465AC89, Seq=7520, Time=4245009413 -37 0.428000 10.2.2.2 10.1.1.1 RTP 850 PT=Unassigned, SSRC=0xD465AC89, Seq=7521, Time=4245009413, Mark -38 0.461000 10.2.2.2 10.1.1.1 RTP 951 PT=Unassigned, SSRC=0xD465AC89, Seq=7522, Time=4245012383 -39 0.461000 10.2.2.2 10.1.1.1 RTP 948 PT=Unassigned, SSRC=0xD465AC89, Seq=7523, Time=4245012383, Mark -40 0.495000 10.2.2.2 10.1.1.1 RTP 902 PT=Unassigned, SSRC=0xD465AC89, Seq=7524, Time=4245015443 -41 0.495000 10.2.2.2 10.1.1.1 RTP 902 PT=Unassigned, SSRC=0xD465AC89, Seq=7525, Time=4245015443 -42 0.495000 10.2.2.2 10.1.1.1 RTP 898 PT=Unassigned, SSRC=0xD465AC89, Seq=7526, Time=4245015443, Mark -43 0.528000 10.2.2.2 10.1.1.1 RTP 941 PT=Unassigned, SSRC=0xD465AC89, Seq=7527, Time=4245018413 -44 0.528000 10.2.2.2 10.1.1.1 RTP 941 PT=Unassigned, SSRC=0xD465AC89, Seq=7528, Time=4245018413 -45 0.528000 10.2.2.2 10.1.1.1 RTP 938 PT=Unassigned, SSRC=0xD465AC89, Seq=7529, Time=4245018413, Mark -46 0.562000 10.2.2.2 10.1.1.1 RTP 959 PT=Unassigned, SSRC=0xD465AC89, Seq=7530, Time=4245021473 -47 0.562000 10.2.2.2 10.1.1.1 RTP 959 PT=Unassigned, SSRC=0xD465AC89, Seq=7531, Time=4245021473 -48 0.562000 10.2.2.2 10.1.1.1 RTP 959 PT=Unassigned, SSRC=0xD465AC89, Seq=7532, Time=4245021473 -49 0.562000 10.2.2.2 10.1.1.1 RTP 955 PT=Unassigned, SSRC=0xD465AC89, Seq=7533, Time=4245021473, Mark -50 0.594000 10.2.2.2 10.1.1.1 RTP 1068 PT=Unassigned, SSRC=0xD465AC89, Seq=7534, Time=4245024353 -51 0.594000 10.2.2.2 10.1.1.1 RTP 1068 PT=Unassigned, SSRC=0xD465AC89, Seq=7535, Time=4245024353 -52 0.594000 10.2.2.2 10.1.1.1 RTP 1068 PT=Unassigned, SSRC=0xD465AC89, Seq=7536, Time=4245024353 -53 0.594000 10.2.2.2 10.1.1.1 RTP 1068 PT=Unassigned, SSRC=0xD465AC89, Seq=7537, Time=4245024353 -54 0.594000 10.2.2.2 10.1.1.1 RTP 1063 PT=Unassigned, SSRC=0xD465AC89, Seq=7538, Time=4245024353, Mark -55 0.628000 10.2.2.2 10.1.1.1 RTP 1137 PT=Unassigned, SSRC=0xD465AC89, Seq=7539, Time=4245027323 -56 0.628000 10.2.2.2 10.1.1.1 RTP 1137 PT=Unassigned, SSRC=0xD465AC89, Seq=7540, Time=4245027323 -57 0.628000 10.2.2.2 10.1.1.1 RTP 1137 PT=Unassigned, SSRC=0xD465AC89, Seq=7541, Time=4245027323 -58 0.628000 10.2.2.2 10.1.1.1 RTP 1137 PT=Unassigned, SSRC=0xD465AC89, Seq=7542, Time=4245027323 -59 0.628000 10.2.2.2 10.1.1.1 RTP 1132 PT=Unassigned, SSRC=0xD465AC89, Seq=7543, Time=4245027323, Mark -60 0.662000 10.2.2.2 10.1.1.1 RTP 1142 PT=Unassigned, SSRC=0xD465AC89, Seq=7544, Time=4245030473 -61 0.662000 10.2.2.2 10.1.1.1 RTP 1142 PT=Unassigned, SSRC=0xD465AC89, Seq=7545, Time=4245030473 -62 0.662000 10.2.2.2 10.1.1.1 RTP 1142 PT=Unassigned, SSRC=0xD465AC89, Seq=7546, Time=4245030473 -63 0.662000 10.2.2.2 10.1.1.1 RTP 1142 PT=Unassigned, SSRC=0xD465AC89, Seq=7547, Time=4245030473 -64 0.662000 10.2.2.2 10.1.1.1 RTP 1136 PT=Unassigned, SSRC=0xD465AC89, Seq=7548, Time=4245030473, Mark -65 0.695000 10.2.2.2 10.1.1.1 RTP 1077 PT=Unassigned, SSRC=0xD465AC89, Seq=7549, Time=4245033443 -66 0.695000 10.2.2.2 10.1.1.1 RTP 1077 PT=Unassigned, SSRC=0xD465AC89, Seq=7550, Time=4245033443 -67 0.696000 10.2.2.2 10.1.1.1 RTP 1077 PT=Unassigned, SSRC=0xD465AC89, Seq=7551, Time=4245033443 -68 0.696000 10.2.2.2 10.1.1.1 RTP 1077 PT=Unassigned, SSRC=0xD465AC89, Seq=7552, Time=4245033443 -69 0.696000 10.2.2.2 10.1.1.1 RTP 1070 PT=Unassigned, SSRC=0xD465AC89, Seq=7553, Time=4245033443, Mark -70 0.727000 10.2.2.2 10.1.1.1 RTP 1203 PT=Unassigned, SSRC=0xD465AC89, Seq=7554, Time=4245036323 -71 0.727000 10.2.2.2 10.1.1.1 RTP 1203 PT=Unassigned, SSRC=0xD465AC89, Seq=7555, Time=4245036323 -72 0.727000 10.2.2.2 10.1.1.1 RTP 1203 PT=Unassigned, SSRC=0xD465AC89, Seq=7556, Time=4245036323 -73 0.727000 10.2.2.2 10.1.1.1 RTP 1203 PT=Unassigned, SSRC=0xD465AC89, Seq=7557, Time=4245036323 -74 0.727000 10.2.2.2 10.1.1.1 RTP 1198 PT=Unassigned, SSRC=0xD465AC89, Seq=7558, Time=4245036323, Mark -75 0.762000 10.2.2.2 10.1.1.1 RTP 1200 PT=Unassigned, SSRC=0xD465AC89, Seq=7559, Time=4245039473 -76 0.762000 10.2.2.2 10.1.1.1 RTP 1200 PT=Unassigned, SSRC=0xD465AC89, Seq=7560, Time=4245039473 -77 0.763000 10.2.2.2 10.1.1.1 RTP 1200 PT=Unassigned, SSRC=0xD465AC89, Seq=7561, Time=4245039473 -78 0.763000 10.2.2.2 10.1.1.1 RTP 1200 PT=Unassigned, SSRC=0xD465AC89, Seq=7562, Time=4245039473 -79 0.763000 10.2.2.2 10.1.1.1 RTP 1200 PT=Unassigned, SSRC=0xD465AC89, Seq=7563, Time=4245039473 -80 0.763000 10.2.2.2 10.1.1.1 RTP 1194 PT=Unassigned, SSRC=0xD465AC89, Seq=7564, Time=4245039473, Mark -81 0.795000 10.2.2.2 10.1.1.1 RTP 1185 PT=Unassigned, SSRC=0xD465AC89, Seq=7565, Time=4245042443 -82 0.795000 10.2.2.2 10.1.1.1 RTP 1185 PT=Unassigned, SSRC=0xD465AC89, Seq=7566, Time=4245042443 -83 0.795000 10.2.2.2 10.1.1.1 RTP 1185 PT=Unassigned, SSRC=0xD465AC89, Seq=7567, Time=4245042443 -84 0.795000 10.2.2.2 10.1.1.1 RTP 1185 PT=Unassigned, SSRC=0xD465AC89, Seq=7568, Time=4245042443 -85 0.795000 10.2.2.2 10.1.1.1 RTP 1185 PT=Unassigned, SSRC=0xD465AC89, Seq=7569, Time=4245042443 -86 0.795000 10.2.2.2 10.1.1.1 RTP 1185 PT=Unassigned, SSRC=0xD465AC89, Seq=7570, Time=4245042443 -87 0.795000 10.2.2.2 10.1.1.1 RTP 1172 PT=Unassigned, SSRC=0xD465AC89, Seq=7571, Time=4245042443, Mark -88 0.828000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7572, Time=4245045323 -89 0.828000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7573, Time=4245045323 -90 0.828000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7574, Time=4245045323 -91 0.828000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7575, Time=4245045323 -92 0.828000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7576, Time=4245045323 -93 0.828000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7577, Time=4245045323 -94 0.828000 10.2.2.2 10.1.1.1 RTP 1127 PT=Unassigned, SSRC=0xD465AC89, Seq=7578, Time=4245045323, Mark -95 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7579, Time=4245048383 -96 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7580, Time=4245048383 -97 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7581, Time=4245048383 -98 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7582, Time=4245048383 -99 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7583, Time=4245048383 -100 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7584, Time=4245048383 -101 0.862000 10.2.2.2 10.1.1.1 RTP 1138 PT=Unassigned, SSRC=0xD465AC89, Seq=7585, Time=4245048383 -102 0.862000 10.2.2.2 10.1.1.1 RTP 1128 PT=Unassigned, SSRC=0xD465AC89, Seq=7586, Time=4245048383, Mark -103 0.895000 10.2.2.2 10.1.1.1 RTP 1171 PT=Unassigned, SSRC=0xD465AC89, Seq=7587, Time=4245051353 -104 0.895000 10.2.2.2 10.1.1.1 RTP 1171 PT=Unassigned, SSRC=0xD465AC89, Seq=7588, Time=4245051353 -105 0.895000 10.2.2.2 10.1.1.1 RTP 1171 PT=Unassigned, SSRC=0xD465AC89, Seq=7589, Time=4245051353 -106 0.895000 10.2.2.2 10.1.1.1 RTP 1171 PT=Unassigned, SSRC=0xD465AC89, Seq=7590, Time=4245051353 -107 0.895000 10.2.2.2 10.1.1.1 RTP 1171 PT=Unassigned, SSRC=0xD465AC89, Seq=7591, Time=4245051353 -108 0.895000 10.2.2.2 10.1.1.1 RTP 1163 PT=Unassigned, SSRC=0xD465AC89, Seq=7592, Time=4245051353, Mark -109 0.926000 10.2.2.2 10.1.1.1 RTP 1102 PT=Unassigned, SSRC=0xD465AC89, Seq=7593, Time=4245054323 -110 0.926000 10.2.2.2 10.1.1.1 RTP 1102 PT=Unassigned, SSRC=0xD465AC89, Seq=7594, Time=4245054323 -111 0.926000 10.2.2.2 10.1.1.1 RTP 1102 PT=Unassigned, SSRC=0xD465AC89, Seq=7595, Time=4245054323 -112 0.926000 10.2.2.2 10.1.1.1 RTP 1102 PT=Unassigned, SSRC=0xD465AC89, Seq=7596, Time=4245054323 -113 0.927000 10.2.2.2 10.1.1.1 RTP 1102 PT=Unassigned, SSRC=0xD465AC89, Seq=7597, Time=4245054323 -114 0.927000 10.2.2.2 10.1.1.1 RTP 1093 PT=Unassigned, SSRC=0xD465AC89, Seq=7598, Time=4245054323, Mark -115 0.962000 10.2.2.2 10.1.1.1 RTP 1134 PT=Unassigned, SSRC=0xD465AC89, Seq=7599, Time=4245057473 -116 0.962000 10.2.2.2 10.1.1.1 RTP 1134 PT=Unassigned, SSRC=0xD465AC89, Seq=7600, Time=4245057473 -117 0.963000 10.2.2.2 10.1.1.1 RTP 1134 PT=Unassigned, SSRC=0xD465AC89, Seq=7601, Time=4245057473 -118 0.963000 10.2.2.2 10.1.1.1 RTP 1134 PT=Unassigned, SSRC=0xD465AC89, Seq=7602, Time=4245057473 -119 0.963000 10.2.2.2 10.1.1.1 RTP 1134 PT=Unassigned, SSRC=0xD465AC89, Seq=7603, Time=4245057473 -120 0.963000 10.2.2.2 10.1.1.1 RTP 1124 PT=Unassigned, SSRC=0xD465AC89, Seq=7604, Time=4245057473, Mark -121 0.994000 10.2.2.2 10.1.1.1 RTP 1219 PT=Unassigned, SSRC=0xD465AC89, Seq=7605, Time=4245060353 -122 0.994000 10.2.2.2 10.1.1.1 RTP 1219 PT=Unassigned, SSRC=0xD465AC89, Seq=7606, Time=4245060353 -123 0.994000 10.2.2.2 10.1.1.1 RTP 1219 PT=Unassigned, SSRC=0xD465AC89, Seq=7607, Time=4245060353 -124 0.994000 10.2.2.2 10.1.1.1 RTP 1219 PT=Unassigned, SSRC=0xD465AC89, Seq=7608, Time=4245060353 -125 0.994000 10.2.2.2 10.1.1.1 RTP 1219 PT=Unassigned, SSRC=0xD465AC89, Seq=7609, Time=4245060353 -126 0.994000 10.2.2.2 10.1.1.1 RTP 1219 PT=Unassigned, SSRC=0xD465AC89, Seq=7610, Time=4245060353 -127 0.994000 10.2.2.2 10.1.1.1 RTP 1212 PT=Unassigned, SSRC=0xD465AC89, Seq=7611, Time=4245060353, Mark -128 1.027000 10.2.2.2 10.1.1.1 RTP 1205 PT=Unassigned, SSRC=0xD465AC89, Seq=7612, Time=4245063323 -129 1.027000 10.2.2.2 10.1.1.1 RTP 1205 PT=Unassigned, SSRC=0xD465AC89, Seq=7613, Time=4245063323 -130 1.027000 10.2.2.2 10.1.1.1 RTP 1205 PT=Unassigned, SSRC=0xD465AC89, Seq=7614, Time=4245063323 -131 1.027000 10.2.2.2 10.1.1.1 RTP 1205 PT=Unassigned, SSRC=0xD465AC89, Seq=7615, Time=4245063323 -132 1.027000 10.2.2.2 10.1.1.1 RTP 1205 PT=Unassigned, SSRC=0xD465AC89, Seq=7616, Time=4245063323 -133 1.027000 10.2.2.2 10.1.1.1 RTP 1199 PT=Unassigned, SSRC=0xD465AC89, Seq=7617, Time=4245063323, Mark -134 1.062000 10.2.2.2 10.1.1.1 RTP 1221 PT=Unassigned, SSRC=0xD465AC89, Seq=7618, Time=4245066473 -135 1.062000 10.2.2.2 10.1.1.1 RTP 1221 PT=Unassigned, SSRC=0xD465AC89, Seq=7619, Time=4245066473 -136 1.062000 10.2.2.2 10.1.1.1 RTP 1221 PT=Unassigned, SSRC=0xD465AC89, Seq=7620, Time=4245066473 -137 1.062000 10.2.2.2 10.1.1.1 RTP 1221 PT=Unassigned, SSRC=0xD465AC89, Seq=7621, Time=4245066473 -138 1.062000 10.2.2.2 10.1.1.1 RTP 1221 PT=Unassigned, SSRC=0xD465AC89, Seq=7622, Time=4245066473 -139 1.062000 10.2.2.2 10.1.1.1 RTP 1213 PT=Unassigned, SSRC=0xD465AC89, Seq=7623, Time=4245066473, Mark -140 1.095000 10.2.2.2 10.1.1.1 RTP 1240 PT=Unassigned, SSRC=0xD465AC89, Seq=7624, Time=4245069443 -141 1.095000 10.2.2.2 10.1.1.1 RTP 1240 PT=Unassigned, SSRC=0xD465AC89, Seq=7625, Time=4245069443 -142 1.095000 10.2.2.2 10.1.1.1 RTP 1240 PT=Unassigned, SSRC=0xD465AC89, Seq=7626, Time=4245069443 -143 1.095000 10.2.2.2 10.1.1.1 RTP 1240 PT=Unassigned, SSRC=0xD465AC89, Seq=7627, Time=4245069443 -144 1.095000 10.2.2.2 10.1.1.1 RTP 1240 PT=Unassigned, SSRC=0xD465AC89, Seq=7628, Time=4245069443 -145 1.095000 10.2.2.2 10.1.1.1 RTP 1201 PT=Unassigned, SSRC=0xD465AC89, Seq=7629, Time=4245069443, Mark -146 1.129000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7630, Time=4245072413 -147 1.129000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7631, Time=4245072413 -148 1.129000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7632, Time=4245072413 -149 1.129000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7633, Time=4245072413 -150 1.129000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7634, Time=4245072413 -151 1.129000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7635, Time=4245072413 -152 1.129000 10.2.2.2 10.1.1.1 RTP 1081 PT=Unassigned, SSRC=0xD465AC89, Seq=7636, Time=4245072413, Mark -153 1.164000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7637, Time=4245075653 -154 1.164000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7638, Time=4245075653 -155 1.164000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7639, Time=4245075653 -156 1.164000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7640, Time=4245075653 -157 1.164000 10.2.2.2 10.1.1.1 RTP 1155 PT=Unassigned, SSRC=0xD465AC89, Seq=7641, Time=4245075653 -158 1.164000 10.2.2.2 10.1.1.1 RTP 1146 PT=Unassigned, SSRC=0xD465AC89, Seq=7642, Time=4245075653, Mark -159 1.195000 10.2.2.2 10.1.1.1 RTP 1226 PT=Unassigned, SSRC=0xD465AC89, Seq=7643, Time=4245078443 -160 1.195000 10.2.2.2 10.1.1.1 RTP 1226 PT=Unassigned, SSRC=0xD465AC89, Seq=7644, Time=4245078443 -161 1.195000 10.2.2.2 10.1.1.1 RTP 1226 PT=Unassigned, SSRC=0xD465AC89, Seq=7645, Time=4245078443 -162 1.195000 10.2.2.2 10.1.1.1 RTP 1226 PT=Unassigned, SSRC=0xD465AC89, Seq=7646, Time=4245078443 -163 1.195000 10.2.2.2 10.1.1.1 RTP 1220 PT=Unassigned, SSRC=0xD465AC89, Seq=7647, Time=4245078443, Mark -164 1.228000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7648, Time=4245081413 -165 1.228000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7649, Time=4245081413 -166 1.228000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7650, Time=4245081413 -167 1.228000 10.2.2.2 10.1.1.1 RTP 1090 PT=Unassigned, SSRC=0xD465AC89, Seq=7651, Time=4245081413 -168 1.228000 10.2.2.2 10.1.1.1 RTP 1081 PT=Unassigned, SSRC=0xD465AC89, Seq=7652, Time=4245081413, Mark -169 1.261000 10.2.2.2 10.1.1.1 RTP 1207 PT=Unassigned, SSRC=0xD465AC89, Seq=7653, Time=4245084383 -170 1.261000 10.2.2.2 10.1.1.1 RTP 1207 PT=Unassigned, SSRC=0xD465AC89, Seq=7654, Time=4245084383 -171 1.261000 10.2.2.2 10.1.1.1 RTP 1207 PT=Unassigned, SSRC=0xD465AC89, Seq=7655, Time=4245084383 -172 1.261000 10.2.2.2 10.1.1.1 RTP 1202 PT=Unassigned, SSRC=0xD465AC89, Seq=7656, Time=4245084383, Mark -173 1.295000 10.2.2.2 10.1.1.1 RTP 1057 PT=Unassigned, SSRC=0xD465AC89, Seq=7657, Time=4245087443 -174 1.295000 10.2.2.2 10.1.1.1 RTP 1057 PT=Unassigned, SSRC=0xD465AC89, Seq=7658, Time=4245087443 -175 1.295000 10.2.2.2 10.1.1.1 RTP 1057 PT=Unassigned, SSRC=0xD465AC89, Seq=7659, Time=4245087443 -176 1.295000 10.2.2.2 10.1.1.1 RTP 1057 PT=Unassigned, SSRC=0xD465AC89, Seq=7660, Time=4245087443 -177 1.295000 10.2.2.2 10.1.1.1 RTP 1048 PT=Unassigned, SSRC=0xD465AC89, Seq=7661, Time=4245087443, Mark -178 1.328000 10.2.2.2 10.1.1.1 RTP 1144 PT=Unassigned, SSRC=0xD465AC89, Seq=7662, Time=4245090413 -179 1.328000 10.2.2.2 10.1.1.1 RTP 1144 PT=Unassigned, SSRC=0xD465AC89, Seq=7663, Time=4245090413 -180 1.328000 10.2.2.2 10.1.1.1 RTP 1144 PT=Unassigned, SSRC=0xD465AC89, Seq=7664, Time=4245090413 -181 1.328000 10.2.2.2 10.1.1.1 RTP 1144 PT=Unassigned, SSRC=0xD465AC89, Seq=7665, Time=4245090413 -182 1.328000 10.2.2.2 10.1.1.1 RTP 1135 PT=Unassigned, SSRC=0xD465AC89, Seq=7666, Time=4245090413, Mark -183 1.362000 10.2.2.2 10.1.1.1 RTP 1230 PT=Unassigned, SSRC=0xD465AC89, Seq=7667, Time=4245093473 -184 1.362000 10.2.2.2 10.1.1.1 RTP 1230 PT=Unassigned, SSRC=0xD465AC89, Seq=7668, Time=4245093473 -185 1.362000 10.2.2.2 10.1.1.1 RTP 1230 PT=Unassigned, SSRC=0xD465AC89, Seq=7669, Time=4245093473 -186 1.362000 10.2.2.2 10.1.1.1 RTP 1230 PT=Unassigned, SSRC=0xD465AC89, Seq=7670, Time=4245093473 -187 1.362000 10.2.2.2 10.1.1.1 RTP 1224 PT=Unassigned, SSRC=0xD465AC89, Seq=7671, Time=4245093473, Mark -188 1.394000 10.2.2.2 10.1.1.1 RTP 1071 PT=Unassigned, SSRC=0xD465AC89, Seq=7672, Time=4245096353 -189 1.394000 10.2.2.2 10.1.1.1 RTP 1071 PT=Unassigned, SSRC=0xD465AC89, Seq=7673, Time=4245096353 -190 1.394000 10.2.2.2 10.1.1.1 RTP 1071 PT=Unassigned, SSRC=0xD465AC89, Seq=7674, Time=4245096353 -191 1.394000 10.2.2.2 10.1.1.1 RTP 1071 PT=Unassigned, SSRC=0xD465AC89, Seq=7675, Time=4245096353 -192 1.394000 10.2.2.2 10.1.1.1 RTP 1071 PT=Unassigned, SSRC=0xD465AC89, Seq=7676, Time=4245096353 -193 1.394000 10.2.2.2 10.1.1.1 RTP 1060 PT=Unassigned, SSRC=0xD465AC89, Seq=7677, Time=4245096353, Mark -194 1.429000 10.2.2.2 10.1.1.1 RTP 1087 PT=Unassigned, SSRC=0xD465AC89, Seq=7678, Time=4245099503 -195 1.429000 10.2.2.2 10.1.1.1 RTP 1087 PT=Unassigned, SSRC=0xD465AC89, Seq=7679, Time=4245099503 -196 1.429000 10.2.2.2 10.1.1.1 RTP 1087 PT=Unassigned, SSRC=0xD465AC89, Seq=7680, Time=4245099503 -197 1.429000 10.2.2.2 10.1.1.1 RTP 1087 PT=Unassigned, SSRC=0xD465AC89, Seq=7681, Time=4245099503 -198 1.429000 10.2.2.2 10.1.1.1 RTP 1087 PT=Unassigned, SSRC=0xD465AC89, Seq=7682, Time=4245099503 -199 1.429000 10.2.2.2 10.1.1.1 RTP 1077 PT=Unassigned, SSRC=0xD465AC89, Seq=7683, Time=4245099503, Mark -200 1.463000 10.2.2.2 10.1.1.1 RTP 1158 PT=Unassigned, SSRC=0xD465AC89, Seq=7684, Time=4245102473 -201 1.463000 10.2.2.2 10.1.1.1 RTP 1158 PT=Unassigned, SSRC=0xD465AC89, Seq=7685, Time=4245102473 diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/contiguous_vp9.pcap b/rs/moq-webrtc/src/vendor/str0m/tests/data/contiguous_vp9.pcap deleted file mode 100644 index 36c455d01e7..00000000000 Binary files a/rs/moq-webrtc/src/vendor/str0m/tests/data/contiguous_vp9.pcap and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/h264.pcap b/rs/moq-webrtc/src/vendor/str0m/tests/data/h264.pcap deleted file mode 100644 index 3ab8380855a..00000000000 Binary files a/rs/moq-webrtc/src/vendor/str0m/tests/data/h264.pcap and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/h264.txt b/rs/moq-webrtc/src/vendor/str0m/tests/data/h264.txt deleted file mode 100644 index 7c549eb3832..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data/h264.txt +++ /dev/null @@ -1,298 +0,0 @@ -6 0.000005000 H.264 699 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19249, Time=2854912226, Mark STAP-A SPS PPS IDR-Slice -18 0.000017000 H.264 118 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19250, Time=2854921316, Mark non-IDR-Slice -20 0.000019000 H.264 1070 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19251, Time=2854930226, Mark STAP-A SPS PPS IDR-Slice -22 0.000021000 H.264 975 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19252, Time=2854939226, Mark non-IDR-Slice -24 0.000023000 H.264 710 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19253, Time=2854948226 FU-A Start:non-IDR-Slice -25 0.000024000 H.264 711 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19254, Time=2854948226, Mark FU-A End -27 0.000026000 H.264 1069 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19255, Time=2854957316 FU-A Start:non-IDR-Slice -28 0.000027000 H.264 1069 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19256, Time=2854957316, Mark FU-A End -30 0.000029000 H.264 875 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19257, Time=2854966316 FU-A Start:non-IDR-Slice -31 0.000030000 H.264 875 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19258, Time=2854966316, Mark FU-A End -34 0.000033000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19259, Time=2854975226, Mark non-IDR-Slice -35 0.000034000 H.264 869 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19260, Time=2854984226, Mark non-IDR-Slice -37 0.000036000 H.264 662 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19261, Time=2854993316, Mark non-IDR-Slice -39 0.000038000 H.264 466 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19262, Time=2855002226, Mark non-IDR-Slice -41 0.000040000 H.264 380 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19263, Time=2855011226, Mark non-IDR-Slice -43 0.000042000 H.264 335 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19264, Time=2855020226, Mark non-IDR-Slice -45 0.000044000 H.264 263 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19265, Time=2855029226, Mark non-IDR-Slice -47 0.000046000 H.264 207 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19266, Time=2855038226, Mark non-IDR-Slice -50 0.000049000 H.264 205 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19267, Time=2855047226, Mark non-IDR-Slice -52 0.000051000 H.264 208 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19268, Time=2855056226, Mark non-IDR-Slice -55 0.000054000 H.264 197 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19269, Time=2855065226, Mark non-IDR-Slice -57 0.000056000 H.264 177 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19270, Time=2855074226, Mark non-IDR-Slice -59 0.000058000 H.264 168 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19271, Time=2855083226, Mark non-IDR-Slice -62 0.000061000 H.264 141 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19272, Time=2855092226, Mark non-IDR-Slice -64 0.000063000 H.264 141 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19273, Time=2855101226, Mark non-IDR-Slice -66 0.000065000 H.264 121 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19274, Time=2855110226, Mark non-IDR-Slice -68 0.000067000 H.264 132 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19275, Time=2855119226, Mark non-IDR-Slice -70 0.000069000 H.264 134 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19276, Time=2855128226, Mark non-IDR-Slice -72 0.000071000 H.264 121 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19277, Time=2855137226, Mark non-IDR-Slice -74 0.000073000 H.264 129 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19278, Time=2855146226, Mark non-IDR-Slice -77 0.000076000 H.264 176 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19279, Time=2855155226, Mark non-IDR-Slice -79 0.000078000 H.264 167 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19280, Time=2855164226, Mark non-IDR-Slice -82 0.000081000 H.264 148 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19281, Time=2855173226, Mark non-IDR-Slice -84 0.000083000 H.264 145 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19282, Time=2855182226, Mark non-IDR-Slice -86 0.000085000 H.264 152 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19283, Time=2855191226, Mark non-IDR-Slice -88 0.000087000 H.264 122 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19284, Time=2855200226, Mark non-IDR-Slice -90 0.000089000 H.264 133 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19285, Time=2855209226, Mark non-IDR-Slice -92 0.000091000 H.264 190 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19286, Time=2855218226, Mark non-IDR-Slice -94 0.000093000 H.264 159 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19287, Time=2855227226, Mark non-IDR-Slice -96 0.000095000 H.264 137 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19288, Time=2855236226, Mark non-IDR-Slice -99 0.000098000 H.264 182 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19289, Time=2855245226, Mark non-IDR-Slice -101 0.000100000 H.264 174 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19290, Time=2855254226, Mark non-IDR-Slice -103 0.000102000 H.264 164 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19291, Time=2855263226, Mark non-IDR-Slice -105 0.000104000 H.264 148 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19292, Time=2855272226, Mark non-IDR-Slice -107 0.000106000 H.264 133 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19293, Time=2855281226, Mark non-IDR-Slice -109 0.000108000 H.264 118 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19294, Time=2855290226, Mark non-IDR-Slice -112 0.000111000 H.264 126 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19295, Time=2855299226, Mark non-IDR-Slice -114 0.000113000 H.264 123 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19296, Time=2855308226, Mark non-IDR-Slice -116 0.000115000 H.264 118 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19297, Time=2855317226, Mark non-IDR-Slice -118 0.000117000 H.264 135 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19298, Time=2855326226, Mark non-IDR-Slice -121 0.000120000 H.264 151 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19299, Time=2855335226, Mark non-IDR-Slice -123 0.000122000 H.264 131 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19300, Time=2855344316, Mark non-IDR-Slice -127 0.000126000 H.264 977 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19301, Time=2855353226, Mark STAP-A SPS PPS IDR-Slice -129 0.000128000 H.264 585 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19302, Time=2855362226, Mark non-IDR-Slice -131 0.000130000 H.264 749 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19303, Time=2855371226, Mark non-IDR-Slice -133 0.000132000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19304, Time=2855380226, Mark non-IDR-Slice -134 0.000133000 H.264 977 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19305, Time=2855389226, Mark non-IDR-Slice -137 0.000136000 H.264 811 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19306, Time=2855398226, Mark non-IDR-Slice -139 0.000138000 H.264 635 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19307, Time=2855407226, Mark non-IDR-Slice -141 0.000140000 H.264 516 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19308, Time=2855416226, Mark non-IDR-Slice -144 0.000143000 H.264 430 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19309, Time=2855425226, Mark non-IDR-Slice -146 0.000145000 H.264 359 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19310, Time=2855434226, Mark non-IDR-Slice -149 0.000148000 H.264 358 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19311, Time=2855443226, Mark non-IDR-Slice -151 0.000150000 H.264 302 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19312, Time=2855452226, Mark non-IDR-Slice -153 0.000152000 H.264 253 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19313, Time=2855461226, Mark non-IDR-Slice -155 0.000154000 H.264 270 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19314, Time=2855470226, Mark non-IDR-Slice -157 0.000156000 H.264 234 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19315, Time=2855479226, Mark non-IDR-Slice -159 0.000158000 H.264 228 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19316, Time=2855488226, Mark non-IDR-Slice -161 0.000160000 H.264 188 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19317, Time=2855497226, Mark non-IDR-Slice -164 0.000163000 H.264 193 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19318, Time=2855506226, Mark non-IDR-Slice -167 0.000166000 H.264 212 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19319, Time=2855515226, Mark non-IDR-Slice -169 0.000168000 H.264 214 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19320, Time=2855524226, Mark non-IDR-Slice -171 0.000170000 H.264 185 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19321, Time=2855533226, Mark non-IDR-Slice -173 0.000172000 H.264 173 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19322, Time=2855542316, Mark non-IDR-Slice -175 0.000174000 H.264 162 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19323, Time=2855551226, Mark non-IDR-Slice -177 0.000176000 H.264 179 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19324, Time=2855560226, Mark non-IDR-Slice -179 0.000178000 H.264 186 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19325, Time=2855569226, Mark non-IDR-Slice -181 0.000180000 H.264 187 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19326, Time=2855578226, Mark non-IDR-Slice -183 0.000182000 H.264 159 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19327, Time=2855587226, Mark non-IDR-Slice -185 0.000184000 H.264 158 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19328, Time=2855596226, Mark non-IDR-Slice -188 0.000187000 H.264 150 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19329, Time=2855605226, Mark non-IDR-Slice -190 0.000189000 H.264 148 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19330, Time=2855614226, Mark non-IDR-Slice -192 0.000191000 H.264 150 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19331, Time=2855623226, Mark non-IDR-Slice -194 0.000193000 H.264 138 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19332, Time=2855632226, Mark non-IDR-Slice -197 0.000196000 H.264 159 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19333, Time=2855641226, Mark non-IDR-Slice -199 0.000198000 H.264 170 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19334, Time=2855650226, Mark non-IDR-Slice -201 0.000200000 H.264 157 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19335, Time=2855659226, Mark non-IDR-Slice -203 0.000202000 H.264 138 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19336, Time=2855668226, Mark non-IDR-Slice -205 0.000204000 H.264 135 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19337, Time=2855677226, Mark non-IDR-Slice -207 0.000206000 H.264 135 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19338, Time=2855686226, Mark non-IDR-Slice -210 0.000209000 H.264 132 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19339, Time=2855695226, Mark non-IDR-Slice -212 0.000211000 H.264 125 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19340, Time=2855704226, Mark non-IDR-Slice -214 0.000213000 H.264 176 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19341, Time=2855713226, Mark non-IDR-Slice -216 0.000215000 H.264 159 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19342, Time=2855722226, Mark non-IDR-Slice -218 0.000217000 H.264 146 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19343, Time=2855731226, Mark non-IDR-Slice -219 0.000218000 H.264 185 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19344, Time=2855740226, Mark non-IDR-Slice -221 0.000220000 H.264 148 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19345, Time=2855749226, Mark non-IDR-Slice -224 0.000223000 H.264 147 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19346, Time=2855758226, Mark non-IDR-Slice -226 0.000225000 H.264 156 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19347, Time=2855767226, Mark non-IDR-Slice -228 0.000227000 H.264 136 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19348, Time=2855776226, Mark non-IDR-Slice -231 0.000230000 H.264 130 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19349, Time=2855785316, Mark non-IDR-Slice -233 0.000232000 H.264 112 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19350, Time=2855794226, Mark non-IDR-Slice -236 0.000235000 H.264 980 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19351, Time=2855803226, Mark STAP-A SPS PPS IDR-Slice -238 0.000237000 H.264 616 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19352, Time=2855812226, Mark non-IDR-Slice -240 0.000239000 H.264 808 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19353, Time=2855821226, Mark non-IDR-Slice -242 0.000241000 H.264 669 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19354, Time=2855830226 FU-A Start:non-IDR-Slice -243 0.000242000 H.264 670 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19355, Time=2855830226, Mark FU-A End -245 0.000244000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19356, Time=2855839226, Mark non-IDR-Slice -246 0.000245000 H.264 809 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19357, Time=2855848226, Mark non-IDR-Slice -248 0.000247000 H.264 597 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19358, Time=2855857226, Mark non-IDR-Slice -250 0.000249000 H.264 440 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19359, Time=2855866226, Mark non-IDR-Slice -253 0.000252000 H.264 369 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19360, Time=2855875226, Mark non-IDR-Slice -255 0.000254000 H.264 326 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19361, Time=2855884226, Mark non-IDR-Slice -258 0.000257000 H.264 367 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19362, Time=2855893226, Mark non-IDR-Slice -260 0.000259000 H.264 341 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19363, Time=2855902226, Mark non-IDR-Slice -262 0.000261000 H.264 306 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19364, Time=2855911316, Mark non-IDR-Slice -264 0.000263000 H.264 327 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19365, Time=2855920226, Mark non-IDR-Slice -266 0.000265000 H.264 312 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19366, Time=2855929226, Mark non-IDR-Slice -268 0.000267000 H.264 252 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19367, Time=2855938226, Mark non-IDR-Slice -270 0.000269000 H.264 239 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19368, Time=2855947226, Mark non-IDR-Slice -272 0.000271000 H.264 214 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19369, Time=2855956226, Mark non-IDR-Slice -275 0.000274000 H.264 197 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19370, Time=2855965226, Mark non-IDR-Slice -277 0.000276000 H.264 200 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19371, Time=2855974226, Mark non-IDR-Slice -279 0.000278000 H.264 191 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19372, Time=2855983226, Mark non-IDR-Slice -281 0.000280000 H.264 174 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19373, Time=2855992226, Mark non-IDR-Slice -284 0.000283000 H.264 174 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19374, Time=2856001226, Mark non-IDR-Slice -286 0.000285000 H.264 202 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19375, Time=2856010226, Mark non-IDR-Slice -288 0.000287000 H.264 216 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19376, Time=2856019226, Mark non-IDR-Slice -290 0.000289000 H.264 198 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19377, Time=2856028226, Mark non-IDR-Slice -292 0.000291000 H.264 201 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19378, Time=2856037226, Mark non-IDR-Slice -294 0.000293000 H.264 192 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19379, Time=2856046226, Mark non-IDR-Slice -297 0.000296000 H.264 162 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19380, Time=2856055226, Mark non-IDR-Slice -300 0.000299000 H.264 147 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19381, Time=2856064226, Mark non-IDR-Slice -302 0.000301000 H.264 157 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19382, Time=2856073226, Mark non-IDR-Slice -304 0.000303000 H.264 155 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19383, Time=2856082226, Mark non-IDR-Slice -306 0.000305000 H.264 160 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19384, Time=2856091226, Mark non-IDR-Slice -308 0.000307000 H.264 155 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19385, Time=2856100226, Mark non-IDR-Slice -310 0.000309000 H.264 147 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19386, Time=2856109226, Mark non-IDR-Slice -312 0.000311000 H.264 134 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19387, Time=2856118226, Mark non-IDR-Slice -314 0.000313000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19388, Time=2856127226, Mark STAP-A SPS PPS [Bad NAL Length] -315 0.000314000 H.264 322 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19389, Time=2856136226, Mark non-IDR-Slice -318 0.000317000 H.264 236 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19390, Time=2856145226, Mark non-IDR-Slice -320 0.000319000 H.264 267 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19391, Time=2856154226, Mark non-IDR-Slice -322 0.000321000 H.264 357 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19392, Time=2856163226, Mark non-IDR-Slice -324 0.000323000 H.264 385 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19393, Time=2856172226, Mark non-IDR-Slice -327 0.000326000 H.264 361 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19394, Time=2856181226, Mark non-IDR-Slice -329 0.000328000 H.264 337 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19395, Time=2856190226, Mark non-IDR-Slice -331 0.000330000 H.264 443 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19396, Time=2856199226, Mark non-IDR-Slice -333 0.000332000 H.264 454 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19397, Time=2856208226, Mark non-IDR-Slice -335 0.000334000 H.264 408 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19398, Time=2856217226, Mark non-IDR-Slice -337 0.000336000 H.264 357 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19399, Time=2856226226, Mark non-IDR-Slice -340 0.000339000 H.264 292 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19400, Time=2856235226, Mark non-IDR-Slice -344 0.000343000 H.264 90 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19401, Time=2856244226 STAP-A SPS PPS -345 0.000344000 H.264 830 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19402, Time=2856244226 FU-A Start:IDR-Slice -346 0.000345000 H.264 831 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19403, Time=2856244226, Mark FU-A End -348 0.000347000 H.264 689 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19404, Time=2856253226 FU-A Start:non-IDR-Slice -349 0.000348000 H.264 689 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19405, Time=2856253226, Mark FU-A End -351 0.000350000 H.264 920 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19406, Time=2856262226 FU-A Start:non-IDR-Slice -352 0.000351000 H.264 921 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19407, Time=2856262226, Mark FU-A End -354 0.000353000 H.264 981 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19408, Time=2856271226 FU-A Start:non-IDR-Slice -355 0.000354000 H.264 981 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19409, Time=2856271226 FU-A -356 0.000355000 H.264 982 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19410, Time=2856271226, Mark FU-A End -358 0.000357000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19411, Time=2856280226 FU-A Start:non-IDR-Slice -360 0.000359000 H.264 885 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19413, Time=2856289226 FU-A Start:non-IDR-Slice -361 0.000360000 H.264 886 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19414, Time=2856289226, Mark FU-A End -363 0.000362000 H.264 751 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19415, Time=2856298226 FU-A Start:non-IDR-Slice -364 0.000363000 H.264 752 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19416, Time=2856298226, Mark FU-A End -366 0.000365000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19417, Time=2856307226, Mark non-IDR-Slice -368 0.000367000 H.264 981 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19418, Time=2856316226, Mark non-IDR-Slice -370 0.000369000 H.264 774 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19419, Time=2856325226, Mark non-IDR-Slice -372 0.000371000 H.264 695 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19420, Time=2856334226, Mark non-IDR-Slice -374 0.000373000 H.264 716 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19421, Time=2856343226, Mark non-IDR-Slice -376 0.000375000 H.264 601 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19422, Time=2856352316, Mark non-IDR-Slice -378 0.000377000 H.264 647 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19423, Time=2856361316, Mark non-IDR-Slice -380 0.000379000 H.264 592 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19424, Time=2856370226, Mark non-IDR-Slice -382 0.000381000 H.264 536 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19425, Time=2856379226, Mark non-IDR-Slice -384 0.000383000 H.264 471 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19426, Time=2856388316, Mark non-IDR-Slice -386 0.000385000 H.264 466 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19427, Time=2856397226, Mark non-IDR-Slice -388 0.000387000 H.264 430 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19428, Time=2856406226, Mark non-IDR-Slice -392 0.000391000 H.264 362 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19429, Time=2856415226, Mark non-IDR-Slice -394 0.000393000 H.264 415 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19430, Time=2856424226, Mark non-IDR-Slice -396 0.000395000 H.264 401 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19431, Time=2856433316, Mark non-IDR-Slice -398 0.000397000 H.264 368 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19432, Time=2856442226, Mark non-IDR-Slice -400 0.000399000 H.264 380 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19433, Time=2856450866, Mark non-IDR-Slice -402 0.000401000 H.264 369 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19434, Time=2856460226, Mark non-IDR-Slice -404 0.000403000 H.264 362 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19435, Time=2856468866, Mark non-IDR-Slice -406 0.000405000 H.264 361 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19436, Time=2856478226, Mark non-IDR-Slice -408 0.000407000 H.264 371 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19437, Time=2856486866, Mark non-IDR-Slice -410 0.000409000 H.264 366 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19438, Time=2856496226, Mark non-IDR-Slice -412 0.000411000 H.264 328 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19439, Time=2856504866, Mark non-IDR-Slice -415 0.000414000 H.264 380 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19440, Time=2856514226, Mark non-IDR-Slice -416 0.000415000 H.264 419 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19441, Time=2856522866, Mark non-IDR-Slice -418 0.000417000 H.264 421 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19442, Time=2856531866, Mark non-IDR-Slice -421 0.000420000 H.264 349 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19443, Time=2856540866, Mark non-IDR-Slice -423 0.000422000 H.264 374 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19444, Time=2856549956, Mark non-IDR-Slice -425 0.000424000 H.264 364 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19445, Time=2856558956, Mark non-IDR-Slice -427 0.000426000 H.264 352 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19446, Time=2856567866, Mark non-IDR-Slice -429 0.000428000 H.264 436 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19447, Time=2856576866, Mark non-IDR-Slice -431 0.000430000 H.264 372 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19448, Time=2856585866, Mark non-IDR-Slice -434 0.000433000 H.264 354 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19449, Time=2856594866, Mark non-IDR-Slice -436 0.000435000 H.264 338 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19450, Time=2856603956, Mark non-IDR-Slice -438 0.000437000 H.264 90 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19451, Time=2856612866 STAP-A SPS PPS -439 0.000438000 H.264 802 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19452, Time=2856612866 FU-A Start:IDR-Slice -440 0.000439000 H.264 802 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19453, Time=2856612866, Mark FU-A End -442 0.000441000 H.264 762 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19454, Time=2856621866 FU-A Start:non-IDR-Slice -443 0.000442000 H.264 763 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19455, Time=2856621866, Mark FU-A End -445 0.000444000 H.264 1082 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19456, Time=2856630866 FU-A Start:non-IDR-Slice -446 0.000445000 H.264 1082 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19457, Time=2856630866, Mark FU-A End -448 0.000447000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19458, Time=2856639866 FU-A Start:non-IDR-Slice -449 0.000448000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19460, Time=2856639866, Mark FU-A End -450 0.000449000 H.264 853 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19461, Time=2856648866 FU-A Start:non-IDR-Slice -451 0.000450000 H.264 853 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19462, Time=2856648866 FU-A -452 0.000451000 H.264 854 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19463, Time=2856648866, Mark FU-A End -455 0.000454000 H.264 954 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19464, Time=2856657866 FU-A Start:non-IDR-Slice -456 0.000455000 H.264 954 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19465, Time=2856657866, Mark FU-A End -458 0.000457000 H.264 753 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19466, Time=2856666866 FU-A Start:non-IDR-Slice -459 0.000458000 H.264 754 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19467, Time=2856666866, Mark FU-A End -461 0.000460000 H.264 1076 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19468, Time=2856675866, Mark non-IDR-Slice -464 0.000463000 H.264 860 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19469, Time=2856684956, Mark non-IDR-Slice -466 0.000465000 H.264 759 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19470, Time=2856693956, Mark non-IDR-Slice -468 0.000467000 H.264 638 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19471, Time=2856702866, Mark non-IDR-Slice -470 0.000469000 H.264 545 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19472, Time=2856711866, Mark non-IDR-Slice -472 0.000471000 H.264 547 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19473, Time=2856720866, Mark non-IDR-Slice -474 0.000473000 H.264 484 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19474, Time=2856729866, Mark non-IDR-Slice -476 0.000475000 H.264 464 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19475, Time=2856738866, Mark non-IDR-Slice -478 0.000477000 H.264 381 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19476, Time=2856747866, Mark non-IDR-Slice -481 0.000480000 H.264 383 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19477, Time=2856756866, Mark non-IDR-Slice -483 0.000482000 H.264 375 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19478, Time=2856765866, Mark non-IDR-Slice -486 0.000485000 H.264 367 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19479, Time=2856774866, Mark non-IDR-Slice -488 0.000487000 H.264 370 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19480, Time=2856783866, Mark non-IDR-Slice -490 0.000489000 H.264 347 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19481, Time=2856792866, Mark non-IDR-Slice -492 0.000491000 H.264 305 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19482, Time=2856801866, Mark non-IDR-Slice -494 0.000493000 H.264 288 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19483, Time=2856810866, Mark non-IDR-Slice -496 0.000495000 H.264 264 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19484, Time=2856819866, Mark non-IDR-Slice -498 0.000497000 H.264 288 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19485, Time=2856828866, Mark non-IDR-Slice -500 0.000499000 H.264 349 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19486, Time=2856837866, Mark non-IDR-Slice -502 0.000501000 H.264 281 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19487, Time=2856846866, Mark non-IDR-Slice -504 0.000503000 H.264 381 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19488, Time=2856855866, Mark non-IDR-Slice -508 0.000507000 H.264 386 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19489, Time=2856864866, Mark non-IDR-Slice -510 0.000509000 H.264 424 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19490, Time=2856873866, Mark non-IDR-Slice -512 0.000511000 H.264 398 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19491, Time=2856882866, Mark non-IDR-Slice -514 0.000513000 H.264 408 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19492, Time=2856891866, Mark non-IDR-Slice -516 0.000515000 H.264 385 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19493, Time=2856900866, Mark non-IDR-Slice -518 0.000517000 H.264 353 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19494, Time=2856909866, Mark non-IDR-Slice -520 0.000519000 H.264 302 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19495, Time=2856918866, Mark non-IDR-Slice -522 0.000521000 H.264 319 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19496, Time=2856927866, Mark non-IDR-Slice -524 0.000523000 H.264 322 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19497, Time=2856936866, Mark non-IDR-Slice -526 0.000525000 H.264 344 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19498, Time=2856945866, Mark non-IDR-Slice -529 0.000528000 H.264 334 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19499, Time=2856954866, Mark non-IDR-Slice -532 0.000531000 H.264 320 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19500, Time=2856963866, Mark non-IDR-Slice -535 0.000534000 H.264 91 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19501, Time=2856972866 STAP-A SPS PPS -536 0.000535000 H.264 821 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19502, Time=2856972866 FU-A Start:IDR-Slice -537 0.000536000 H.264 821 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19503, Time=2856972866, Mark FU-A End -539 0.000538000 H.264 775 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19504, Time=2856981866 FU-A Start:non-IDR-Slice -540 0.000539000 H.264 775 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19505, Time=2856981866, Mark FU-A End -542 0.000541000 H.264 1062 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19506, Time=2856990866 FU-A Start:non-IDR-Slice -543 0.000542000 H.264 1063 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19507, Time=2856990866, Mark FU-A End -545 0.000544000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19508, Time=2856999866 FU-A Start:non-IDR-Slice -546 0.000545000 H.264 1085 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19510, Time=2856999866, Mark FU-A End -547 0.000546000 H.264 850 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19511, Time=2857008866 FU-A Start:non-IDR-Slice -548 0.000547000 H.264 850 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19512, Time=2857008866 FU-A -549 0.000548000 H.264 851 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19513, Time=2857008866, Mark FU-A End -551 0.000550000 H.264 849 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19514, Time=2857017866 FU-A Start:non-IDR-Slice -552 0.000551000 H.264 849 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19515, Time=2857017866, Mark FU-A End -554 0.000553000 H.264 666 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19516, Time=2857026866 FU-A Start:non-IDR-Slice -555 0.000554000 H.264 666 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19517, Time=2857026866, Mark FU-A End -557 0.000556000 H.264 1052 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19518, Time=2857035866, Mark non-IDR-Slice -561 0.000560000 H.264 880 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19519, Time=2857044866, Mark non-IDR-Slice -563 0.000562000 H.264 692 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19520, Time=2857053866, Mark non-IDR-Slice -565 0.000564000 H.264 563 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19521, Time=2857062866, Mark non-IDR-Slice -567 0.000566000 H.264 511 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19522, Time=2857071866, Mark non-IDR-Slice -569 0.000568000 H.264 507 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19523, Time=2857080956, Mark non-IDR-Slice -571 0.000570000 H.264 478 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19524, Time=2857089866, Mark non-IDR-Slice -573 0.000572000 H.264 486 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19525, Time=2857098866, Mark non-IDR-Slice -575 0.000574000 H.264 539 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19526, Time=2857107866, Mark non-IDR-Slice -577 0.000576000 H.264 453 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19527, Time=2857116866, Mark non-IDR-Slice -579 0.000578000 H.264 451 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19528, Time=2857125866, Mark non-IDR-Slice -582 0.000581000 H.264 458 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19529, Time=2857134866, Mark non-IDR-Slice -584 0.000583000 H.264 411 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19530, Time=2857143866, Mark non-IDR-Slice -586 0.000585000 H.264 353 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19531, Time=2857152866, Mark non-IDR-Slice -589 0.000588000 H.264 338 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19532, Time=2857161866, Mark non-IDR-Slice -591 0.000590000 H.264 361 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19533, Time=2857170866, Mark non-IDR-Slice -593 0.000592000 H.264 332 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19534, Time=2857179866, Mark non-IDR-Slice -595 0.000594000 H.264 310 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19535, Time=2857188866, Mark non-IDR-Slice -597 0.000596000 H.264 288 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19536, Time=2857197866, Mark non-IDR-Slice -599 0.000598000 H.264 280 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19537, Time=2857206866, Mark non-IDR-Slice -601 0.000600000 H.264 294 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19538, Time=2857215866, Mark non-IDR-Slice -603 0.000602000 H.264 275 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19539, Time=2857224956, Mark non-IDR-Slice -605 0.000604000 H.264 282 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19540, Time=2857233866, Mark non-IDR-Slice -607 0.000606000 H.264 242 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19541, Time=2857242866, Mark non-IDR-Slice -610 0.000609000 H.264 273 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19542, Time=2857251866, Mark non-IDR-Slice -612 0.000611000 H.264 248 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19543, Time=2857260866, Mark non-IDR-Slice -614 0.000613000 H.264 249 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19544, Time=2857269866, Mark non-IDR-Slice -616 0.000615000 H.264 219 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19545, Time=2857278956, Mark non-IDR-Slice -618 0.000617000 H.264 245 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19546, Time=2857287956, Mark non-IDR-Slice -619 0.000618000 H.264 249 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19547, Time=2857296956, Mark non-IDR-Slice -621 0.000620000 H.264 220 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19548, Time=2857305956, Mark non-IDR-Slice -624 0.000623000 H.264 195 PT=DynamicRTP-Type-126, SSRC=0x6A5CC848, Seq=19549, Time=2857314866, Mark non-IDR-Slice diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/h265.pcap b/rs/moq-webrtc/src/vendor/str0m/tests/data/h265.pcap deleted file mode 100644 index 8900b0f0d35..00000000000 Binary files a/rs/moq-webrtc/src/vendor/str0m/tests/data/h265.pcap and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/h265.txt b/rs/moq-webrtc/src/vendor/str0m/tests/data/h265.txt deleted file mode 100644 index fabad7d5222..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data/h265.txt +++ /dev/null @@ -1,478 +0,0 @@ -1 0.000000000 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13522, Time=2030164029 VPS -2 0.000036955 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13523, Time=2030164029 SPS -3 0.000056028 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13524, Time=2030164029 PPS -4 0.000074863 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13525, Time=2030164029 FU Start:PREFIX_SEI -5 0.000088930 H.265 854 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13526, Time=2030164029 FU End:PREFIX_SEI -6 0.000102997 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13527, Time=2030164029 VPS -7 0.000113964 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13528, Time=2030164029 SPS -8 0.000124931 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13529, Time=2030164029 PPS -9 0.000161886 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13530, Time=2030164029 FU Start:IDR_N_LP (Keyframe) -10 0.000176907 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13531, Time=2030164029 FU:IDR_N_LP -11 0.000196934 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13532, Time=2030164029 FU:IDR_N_LP -12 0.000214815 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13533, Time=2030164029 FU:IDR_N_LP -13 0.000226021 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13534, Time=2030164029 FU:IDR_N_LP -14 0.000238895 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13535, Time=2030164029 FU:IDR_N_LP -15 0.000249863 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13536, Time=2030164029 FU:IDR_N_LP -16 0.000262976 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13537, Time=2030164029 FU:IDR_N_LP -17 0.000273943 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13538, Time=2030164029 FU:IDR_N_LP -18 0.000286818 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13539, Time=2030164029 FU:IDR_N_LP -19 0.000298977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13540, Time=2030164029 FU:IDR_N_LP -20 0.000314951 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13541, Time=2030164029 FU:IDR_N_LP -21 0.000325918 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13542, Time=2030164029 FU:IDR_N_LP -22 0.000339031 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13543, Time=2030164029 FU:IDR_N_LP -23 0.000350952 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13544, Time=2030164029 FU:IDR_N_LP -24 0.000363827 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13545, Time=2030164029 FU:IDR_N_LP -25 0.000375032 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13546, Time=2030164029 FU:IDR_N_LP -26 0.000391960 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13547, Time=2030164029 FU:IDR_N_LP -27 0.000406027 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13548, Time=2030164029 FU:IDR_N_LP -28 0.000416994 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13549, Time=2030164029 FU:IDR_N_LP -29 0.000432968 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13550, Time=2030164029 FU:IDR_N_LP -30 0.000448942 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13551, Time=2030164029 FU:IDR_N_LP -31 0.000460863 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13552, Time=2030164029 FU:IDR_N_LP -32 0.000473976 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13553, Time=2030164029 FU:IDR_N_LP -33 0.000488043 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13554, Time=2030164029 FU:IDR_N_LP -34 0.000501871 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13555, Time=2030164029 FU:IDR_N_LP -35 0.000514030 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13556, Time=2030164029 FU:IDR_N_LP -36 0.000524998 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13557, Time=2030164029 FU:IDR_N_LP -37 0.000537872 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13558, Time=2030164029 FU:IDR_N_LP -38 0.000550985 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13559, Time=2030164029 FU:IDR_N_LP -39 0.000565052 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13560, Time=2030164029 FU:IDR_N_LP -40 0.000576973 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13561, Time=2030164029 FU:IDR_N_LP -41 0.000587940 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13562, Time=2030164029 FU:IDR_N_LP -42 0.000600815 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13563, Time=2030164029 FU:IDR_N_LP -43 0.000612974 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13564, Time=2030164029 FU:IDR_N_LP -44 0.000623941 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13565, Time=2030164029 FU:IDR_N_LP -45 0.000638962 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13566, Time=2030164029 FU:IDR_N_LP -46 0.000650883 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13567, Time=2030164029 FU:IDR_N_LP -47 0.000664949 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13568, Time=2030164029 FU:IDR_N_LP -48 0.000675917 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13569, Time=2030164029 FU:IDR_N_LP -49 0.000687838 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13570, Time=2030164029 FU:IDR_N_LP -50 0.000704050 H.265 1114 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13571, Time=2030164029, Mark FU End:IDR_N_LP -51 0.034286976 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13572, Time=2030164029 VPS -52 0.034333944 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13573, Time=2030164029 SPS -53 0.034358978 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13574, Time=2030164029 PPS -54 0.034590960 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13575, Time=2030164029 FU Start:TRAIL_R -55 0.034626007 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13576, Time=2030164029 FU:TRAIL_R -56 0.034652948 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13577, Time=2030164029 FU:TRAIL_R -57 0.034687996 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13578, Time=2030164029 FU:TRAIL_R -58 0.034714937 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13579, Time=2030164029 FU:TRAIL_R -59 0.034739017 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13580, Time=2030164029 FU:TRAIL_R -60 0.034765959 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13581, Time=2030164029 FU:TRAIL_R -61 0.034787893 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13582, Time=2030164029 FU:TRAIL_R -62 0.034809828 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13583, Time=2030164029 FU:TRAIL_R -63 0.034837008 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13584, Time=2030164029 FU:TRAIL_R -64 0.034858942 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13585, Time=2030164029 FU:TRAIL_R -65 0.034884930 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13586, Time=2030164029 FU:TRAIL_R -66 0.034914017 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13587, Time=2030164029 FU:TRAIL_R -67 0.034937859 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13588, Time=2030164029 FU:TRAIL_R -68 0.034966946 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13589, Time=2030164029 FU:TRAIL_R -69 0.034992933 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13590, Time=2030164029 FU:TRAIL_R -70 0.035017014 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13591, Time=2030164029 FU:TRAIL_R -71 0.035043955 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13592, Time=2030164029 FU:TRAIL_R -72 0.035064936 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13593, Time=2030164029 FU:TRAIL_R -73 0.035090923 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13594, Time=2030164029 FU:TRAIL_R -74 0.035114050 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13595, Time=2030164029 FU:TRAIL_R -75 0.035135984 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13596, Time=2030164029 FU:TRAIL_R -76 0.035159826 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13597, Time=2030164029 FU:TRAIL_R -77 0.035182953 H.265 1032 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13598, Time=2030164029, Mark FU End:TRAIL_R -78 0.068348885 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13599, Time=2030164029 VPS -79 0.068449974 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13600, Time=2030164029 SPS -80 0.068485975 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13601, Time=2030164029 PPS -81 0.068573952 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13602, Time=2030164029 FU Start:TRAIL_R -82 0.068608046 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13603, Time=2030164029 FU:TRAIL_R -83 0.068646908 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13604, Time=2030164029 FU:TRAIL_R -84 0.068673849 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13605, Time=2030164029 FU:TRAIL_R -85 0.068697929 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13606, Time=2030164029 FU:TRAIL_R -86 0.068722010 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13607, Time=2030164029 FU:TRAIL_R -87 0.068742990 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13608, Time=2030164029 FU:TRAIL_R -88 0.068763971 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13609, Time=2030164029 FU:TRAIL_R -89 0.068785906 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13610, Time=2030164029 FU:TRAIL_R -90 0.068809032 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13611, Time=2030164029 FU:TRAIL_R -91 0.068830967 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13612, Time=2030164029 FU:TRAIL_R -92 0.068851948 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13613, Time=2030164029 FU:TRAIL_R -93 0.068874836 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13614, Time=2030164029 FU:TRAIL_R -94 0.068898916 H.265 176 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13615, Time=2030164029, Mark FU End:TRAIL_R -95 0.100136042 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13616, Time=2030164029 VPS -96 0.100175858 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13617, Time=2030164029 SPS -97 0.100203991 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13618, Time=2030164029 PPS -98 0.100229979 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13619, Time=2030164029 FU Start:TRAIL_N -99 0.100255013 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13620, Time=2030164029 FU:TRAIL_N -100 0.100282907 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13621, Time=2030164029 FU:TRAIL_N -101 0.100306034 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13622, Time=2030164029 FU:TRAIL_N -102 0.100328922 H.265 860 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13623, Time=2030164029, Mark FU End:TRAIL_N -103 0.136323929 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13624, Time=2030164029 VPS -104 0.136364937 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13625, Time=2030164029 SPS -105 0.136392832 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13626, Time=2030164029 PPS -106 0.136420965 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13627, Time=2030164029 FU Start:TRAIL_N -107 0.136446953 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13628, Time=2030164029 FU:TRAIL_N -108 0.136469841 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13629, Time=2030164029 FU:TRAIL_N -109 0.136492014 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13630, Time=2030164029 FU:TRAIL_N -110 0.136518002 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13631, Time=2030164029 FU:TRAIL_N -111 0.136539936 H.265 215 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13632, Time=2030164029, Mark FU End:TRAIL_N -112 0.167584896 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13633, Time=2030164029 VPS -113 0.167621851 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13634, Time=2030164029 SPS -114 0.167649031 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13635, Time=2030164029 PPS -115 0.167690992 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13636, Time=2030164029 FU Start:TRAIL_R -116 0.167717934 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13637, Time=2030164029 FU:TRAIL_R -117 0.167739868 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13638, Time=2030164029 FU:TRAIL_R -118 0.167763948 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13639, Time=2030164029 FU:TRAIL_R -119 0.167786837 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13640, Time=2030164029 FU:TRAIL_R -120 0.167819977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13641, Time=2030164029 FU:TRAIL_R -121 0.167842865 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13642, Time=2030164029 FU:TRAIL_R -122 0.167872906 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13643, Time=2030164029 FU:TRAIL_R -123 0.167894840 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13644, Time=2030164029 FU:TRAIL_R -124 0.167923927 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13645, Time=2030164029 FU:TRAIL_R -125 0.167953968 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13646, Time=2030164029 FU:TRAIL_R -126 0.167978048 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13647, Time=2030164029 FU:TRAIL_R -127 0.167997837 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13648, Time=2030164029 FU:TRAIL_R -128 0.168020010 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13649, Time=2030164029 FU:TRAIL_R -129 0.168041945 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13650, Time=2030164029 FU:TRAIL_R -130 0.168066025 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13651, Time=2030164029 FU:TRAIL_R -131 0.168087006 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13652, Time=2030164029 FU:TRAIL_R -132 0.168107986 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13653, Time=2030164029 FU:TRAIL_R -133 0.168205976 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13654, Time=2030164029 FU:TRAIL_R -134 0.168265820 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13655, Time=2030164029 FU:TRAIL_R -135 0.168293953 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13656, Time=2030164029 FU:TRAIL_R -136 0.168318987 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13657, Time=2030164029 FU:TRAIL_R -137 0.168362856 H.265 320 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13658, Time=2030164029, Mark FU End:TRAIL_R -138 0.200876951 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13659, Time=2030164029 VPS -139 0.200917959 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13660, Time=2030164029 SPS -140 0.200943947 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13661, Time=2030164029 PPS -141 0.200999975 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13662, Time=2030164029 FU Start:TRAIL_R -142 0.201025963 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13663, Time=2030164029 FU:TRAIL_R -143 0.201047897 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13664, Time=2030164029 FU:TRAIL_R -144 0.201071978 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13665, Time=2030164029 FU:TRAIL_R -145 0.201102972 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13666, Time=2030164029 FU:TRAIL_R -146 0.201124907 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13667, Time=2030164029 FU:TRAIL_R -147 0.201146841 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13668, Time=2030164029 FU:TRAIL_R -148 0.201169968 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13669, Time=2030164029 FU:TRAIL_R -149 0.201191902 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13670, Time=2030164029 FU:TRAIL_R -150 0.201215982 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13671, Time=2030164029 FU:TRAIL_R -151 0.201238871 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13672, Time=2030164029 FU:TRAIL_R -152 0.201259851 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13673, Time=2030164029 FU:TRAIL_R -153 0.201293945 H.265 1144 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13674, Time=2030164029, Mark FU End:TRAIL_R -154 0.233485937 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13675, Time=2030164029 VPS -155 0.233535051 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13676, Time=2030164029 SPS -156 0.233561039 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13677, Time=2030164029 PPS -157 0.233589888 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13678, Time=2030164029 FU Start:TRAIL_N -158 0.233613014 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13679, Time=2030164029 FU:TRAIL_N -159 0.233649969 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13680, Time=2030164029 FU:TRAIL_N -160 0.233671904 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13681, Time=2030164029 FU:TRAIL_N -161 0.233695030 H.265 1124 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13682, Time=2030164029, Mark FU End:TRAIL_N -162 0.267554045 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13683, Time=2030164029 VPS -163 0.267593861 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13684, Time=2030164029 SPS -164 0.267617941 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13685, Time=2030164029 PPS -165 0.267658949 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13686, Time=2030164029 FU Start:TRAIL_N -166 0.267684937 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13687, Time=2030164029 FU:TRAIL_N -167 0.267712831 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13688, Time=2030164029 FU:TRAIL_N -168 0.267735004 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13689, Time=2030164029 FU:TRAIL_N -169 0.267756939 H.265 531 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13690, Time=2030164029, Mark FU End:TRAIL_N -170 0.300081968 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13691, Time=2030164029 VPS -171 0.300120831 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13692, Time=2030164029 SPS -172 0.300148010 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13693, Time=2030164029 PPS -173 0.300241947 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13694, Time=2030164029 FU Start:TRAIL_R -174 0.300282955 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13695, Time=2030164029 FU:TRAIL_R -175 0.300308943 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13696, Time=2030164029 FU:TRAIL_R -176 0.300330877 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13697, Time=2030164029 FU:TRAIL_R -177 0.300356865 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13698, Time=2030164029 FU:TRAIL_R -178 0.300384045 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13699, Time=2030164029 FU:TRAIL_R -179 0.300405025 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13700, Time=2030164029 FU:TRAIL_R -180 0.300426006 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13701, Time=2030164029 FU:TRAIL_R -181 0.300447941 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13702, Time=2030164029 FU:TRAIL_R -182 0.300474882 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13703, Time=2030164029 FU:TRAIL_R -183 0.300498962 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13704, Time=2030164029 FU:TRAIL_R -184 0.300523996 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13705, Time=2030164029 FU:TRAIL_R -185 0.300544977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13706, Time=2030164029 FU:TRAIL_R -186 0.300566912 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13707, Time=2030164029 FU:TRAIL_R -187 0.300588846 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13708, Time=2030164029 FU:TRAIL_R -188 0.300612926 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13709, Time=2030164029 FU:TRAIL_R -189 0.300637007 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13710, Time=2030164029 FU:TRAIL_R -190 0.300657988 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13711, Time=2030164029 FU:TRAIL_R -191 0.300693989 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13712, Time=2030164029 FU:TRAIL_R -192 0.300714970 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13713, Time=2030164029 FU:TRAIL_R -193 0.300736904 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13714, Time=2030164029 FU:TRAIL_R -194 0.300761938 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13715, Time=2030164029 FU:TRAIL_R -195 0.300782919 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13716, Time=2030164029 FU:TRAIL_R -196 0.300803900 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13717, Time=2030164029 FU:TRAIL_R -197 0.300830841 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13718, Time=2030164029 FU:TRAIL_R -198 0.300854921 H.265 195 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13719, Time=2030164029, Mark FU End:TRAIL_R -199 0.337365866 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13720, Time=2030164029 VPS -200 0.337409019 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13721, Time=2030164029 SPS -201 0.337435961 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13722, Time=2030164029 PPS -202 0.337466955 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13723, Time=2030164029 FU Start:TRAIL_R -203 0.337502003 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13724, Time=2030164029 FU:TRAIL_R -204 0.337528944 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13725, Time=2030164029 FU:TRAIL_R -205 0.337558031 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13726, Time=2030164029 FU:TRAIL_R -206 0.337580919 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13727, Time=2030164029 FU:TRAIL_R -207 0.337612867 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13728, Time=2030164029 FU:TRAIL_R -208 0.337644815 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13729, Time=2030164029 FU:TRAIL_R -209 0.337668896 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13730, Time=2030164029 FU:TRAIL_R -210 0.337693930 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13731, Time=2030164029 FU:TRAIL_R -211 0.337719917 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13732, Time=2030164029 FU:TRAIL_R -212 0.337744951 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13733, Time=2030164029 FU:TRAIL_R -213 0.337769985 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13734, Time=2030164029 FU:TRAIL_R -214 0.337793827 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13735, Time=2030164029 FU:TRAIL_R -215 0.337816954 H.265 108 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13736, Time=2030164029, Mark FU End:TRAIL_R -216 0.369628906 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13737, Time=2030164029 VPS -217 0.369669914 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13738, Time=2030164029 SPS -218 0.369696856 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13739, Time=2030164029 PPS -219 0.369724989 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13740, Time=2030164029 FU Start:TRAIL_N -220 0.369750023 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13741, Time=2030164029 FU:TRAIL_N -221 0.369771957 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13742, Time=2030164029 FU:TRAIL_N -222 0.369796038 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13743, Time=2030164029 FU:TRAIL_N -223 0.369822025 H.265 619 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13744, Time=2030164029, Mark FU End:TRAIL_N -224 0.402571917 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13745, Time=2030164029 VPS -225 0.402648926 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13746, Time=2030164029 SPS -226 0.402691841 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13747, Time=2030164029 PPS -227 0.402771950 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13748, Time=2030164029 FU Start:TRAIL_N -228 0.402798891 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13749, Time=2030164029 FU:TRAIL_N -229 0.402827978 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13750, Time=2030164029 FU:TRAIL_N -230 0.402848005 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13751, Time=2030164029 FU:TRAIL_N -231 0.402868032 H.265 998 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13752, Time=2030164029, Mark FU End:TRAIL_N -232 0.434742928 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13753, Time=2030164029 VPS -233 0.434788942 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13754, Time=2030164029 SPS -234 0.434818029 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13755, Time=2030164029 PPS -235 0.434963942 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13756, Time=2030164029 FU Start:TRAIL_R -236 0.435014009 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13757, Time=2030164029 FU:TRAIL_R -237 0.435040951 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13758, Time=2030164029 FU:TRAIL_R -238 0.435062885 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13759, Time=2030164029 FU:TRAIL_R -239 0.435093880 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13760, Time=2030164029 FU:TRAIL_R -240 0.435122967 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13761, Time=2030164029 FU:TRAIL_R -241 0.435147047 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13762, Time=2030164029 FU:TRAIL_R -242 0.435174942 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13763, Time=2030164029 FU:TRAIL_R -243 0.435209036 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13764, Time=2030164029 FU:TRAIL_R -244 0.435235977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13765, Time=2030164029 FU:TRAIL_R -245 0.435261011 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13766, Time=2030164029 FU:TRAIL_R -246 0.435281992 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13767, Time=2030164029 FU:TRAIL_R -247 0.435307980 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13768, Time=2030164029 FU:TRAIL_R -248 0.435330868 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13769, Time=2030164029 FU:TRAIL_R -249 0.435353041 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13770, Time=2030164029 FU:TRAIL_R -250 0.435379982 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13771, Time=2030164029 FU:TRAIL_R -251 0.435400963 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13772, Time=2030164029 FU:TRAIL_R -252 0.435425997 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13773, Time=2030164029 FU:TRAIL_R -253 0.435447931 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13774, Time=2030164029 FU:TRAIL_R -254 0.435468912 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13775, Time=2030164029 FU:TRAIL_R -255 0.435498953 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13776, Time=2030164029 FU:TRAIL_R -256 0.435520887 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13777, Time=2030164029 FU:TRAIL_R -257 0.435542822 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13778, Time=2030164029 FU:TRAIL_R -258 0.435567856 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13779, Time=2030164029 FU:TRAIL_R -259 0.435590982 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13780, Time=2030164029 FU:TRAIL_R -260 0.435626030 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13781, Time=2030164029 FU:TRAIL_R -261 0.435649872 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13782, Time=2030164029 FU:TRAIL_R -262 0.435701847 H.265 262 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13783, Time=2030164029, Mark FU End:TRAIL_R -263 0.466835022 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13784, Time=2030164029 VPS -264 0.466881990 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13785, Time=2030164029 SPS -265 0.466912031 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13786, Time=2030164029 PPS -266 0.467008829 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13787, Time=2030164029 FU Start:TRAIL_R -267 0.467057943 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13788, Time=2030164029 FU:TRAIL_R -268 0.467084885 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13789, Time=2030164029 FU:TRAIL_R -269 0.467115879 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13790, Time=2030164029 FU:TRAIL_R -270 0.467144966 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13791, Time=2030164029 FU:TRAIL_R -271 0.467169046 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13792, Time=2030164029 FU:TRAIL_R -272 0.467196941 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13793, Time=2030164029 FU:TRAIL_R -273 0.467221975 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13794, Time=2030164029 FU:TRAIL_R -274 0.467244864 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13795, Time=2030164029 FU:TRAIL_R -275 0.467272997 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13796, Time=2030164029 FU:TRAIL_R -276 0.467293978 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13797, Time=2030164029 FU:TRAIL_R -277 0.467316866 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13798, Time=2030164029 FU:TRAIL_R -278 0.467342854 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13799, Time=2030164029 FU:TRAIL_R -279 0.467365980 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13800, Time=2030164029 FU:TRAIL_R -280 0.467393875 H.265 350 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13801, Time=2030164029, Mark FU End:TRAIL_R -281 0.504904985 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13802, Time=2030164029 VPS -282 0.504951000 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13803, Time=2030164029 SPS -283 0.504972935 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13804, Time=2030164029 PPS -284 0.504992962 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13805, Time=2030164029 FU Start:TRAIL_N -285 0.505009890 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13806, Time=2030164029 FU:TRAIL_N -286 0.505028963 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13807, Time=2030164029 FU:TRAIL_N -287 0.505045891 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13808, Time=2030164029 FU:TRAIL_N -288 0.505060911 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13809, Time=2030164029 FU:TRAIL_N -289 0.505077839 H.265 284 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13810, Time=2030164029, Mark FU End:TRAIL_N -290 0.537153959 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13811, Time=2030164029 VPS -291 0.537184954 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13812, Time=2030164029 SPS -292 0.537204981 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13813, Time=2030164029 PPS -293 0.537228823 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13814, Time=2030164029 FU Start:TRAIL_N -294 0.537246943 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13815, Time=2030164029 FU:TRAIL_N -295 0.537261963 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13816, Time=2030164029 FU:TRAIL_N -296 0.537281990 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13817, Time=2030164029 FU:TRAIL_N -297 0.537297964 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13818, Time=2030164029 FU:TRAIL_N -298 0.537313938 H.265 743 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13819, Time=2030164029, Mark FU End:TRAIL_N -299 0.566679955 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13820, Time=2030164029 VPS -300 0.566728830 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13821, Time=2030164029 SPS -301 0.566746950 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13822, Time=2030164029 PPS -302 0.566794872 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13823, Time=2030164029 FU Start:TRAIL_R -303 0.566817045 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13824, Time=2030164029 FU:TRAIL_R -304 0.566834927 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13825, Time=2030164029 FU:TRAIL_R -305 0.566849947 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13826, Time=2030164029 FU:TRAIL_R -306 0.566864967 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13827, Time=2030164029 FU:TRAIL_R -307 0.566879988 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13828, Time=2030164029 FU:TRAIL_R -308 0.566891909 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13829, Time=2030164029 FU:TRAIL_R -309 0.566903830 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13830, Time=2030164029 FU:TRAIL_R -310 0.566926956 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13831, Time=2030164029 FU:TRAIL_R -311 0.566941977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13832, Time=2030164029 FU:TRAIL_R -312 0.566956043 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13833, Time=2030164029 FU:TRAIL_R -313 0.566972017 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13834, Time=2030164029 FU:TRAIL_R -314 0.567013979 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13835, Time=2030164029 FU:TRAIL_R -315 0.567042828 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13836, Time=2030164029 FU:TRAIL_R -316 0.567062855 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13837, Time=2030164029 FU:TRAIL_R -317 0.567076921 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13838, Time=2030164029 FU:TRAIL_R -318 0.567090988 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13839, Time=2030164029 FU:TRAIL_R -319 0.567106009 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13840, Time=2030164029 FU:TRAIL_R -320 0.567117929 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13841, Time=2030164029 FU:TRAIL_R -321 0.567132950 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13842, Time=2030164029 FU:TRAIL_R -322 0.567145824 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13843, Time=2030164029 FU:TRAIL_R -323 0.567158937 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13844, Time=2030164029 FU:TRAIL_R -324 0.567174911 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13845, Time=2030164029 FU:TRAIL_R -325 0.567188025 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13846, Time=2030164029 FU:TRAIL_R -326 0.567199945 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13847, Time=2030164029 FU:TRAIL_R -327 0.567214966 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13848, Time=2030164029 FU:TRAIL_R -328 0.567225933 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13849, Time=2030164029 FU:TRAIL_R -329 0.567240953 H.265 640 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13850, Time=2030164029, Mark FU End:TRAIL_R -330 0.599921942 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13851, Time=2030164029 VPS -331 0.599944830 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13852, Time=2030164029 SPS -332 0.599958897 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13853, Time=2030164029 PPS -333 0.600011826 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13854, Time=2030164029 FU Start:TRAIL_R -334 0.600039959 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13855, Time=2030164029 FU:TRAIL_R -335 0.600075006 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13856, Time=2030164029 FU:TRAIL_R -336 0.600096941 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13857, Time=2030164029 FU:TRAIL_R -337 0.600116014 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13858, Time=2030164029 FU:TRAIL_R -338 0.600128889 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13859, Time=2030164029 FU:TRAIL_R -339 0.600141048 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13860, Time=2030164029 FU:TRAIL_R -340 0.600154877 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13861, Time=2030164029 FU:TRAIL_R -341 0.600167990 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13862, Time=2030164029 FU:TRAIL_R -342 0.600181818 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13863, Time=2030164029 FU:TRAIL_R -343 0.600193977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13864, Time=2030164029 FU:TRAIL_R -344 0.600204945 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13865, Time=2030164029 FU:TRAIL_R -345 0.600219965 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13866, Time=2030164029 FU:TRAIL_R -346 0.600230932 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13867, Time=2030164029 FU:TRAIL_R -347 0.600244045 H.265 1158 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13868, Time=2030164029, Mark FU End:TRAIL_R -348 0.633379936 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13869, Time=2030164029 VPS -349 0.633426905 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13870, Time=2030164029 SPS -350 0.633481979 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13871, Time=2030164029 PPS -351 0.633502007 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13872, Time=2030164029 FU Start:TRAIL_N -352 0.633549929 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13873, Time=2030164029 FU:TRAIL_N -353 0.633560896 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13874, Time=2030164029 FU:TRAIL_N -354 0.633623838 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13875, Time=2030164029 FU:TRAIL_N -355 0.633636951 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13876, Time=2030164029 FU:TRAIL_N -356 0.633666039 H.265 515 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13877, Time=2030164029, Mark FU End:TRAIL_N -357 0.666828871 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13878, Time=2030164029 VPS -358 0.666852951 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13879, Time=2030164029 SPS -359 0.666873932 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13880, Time=2030164029 PPS -360 0.666934967 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13881, Time=2030164029 FU Start:TRAIL_N -361 0.666971922 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13882, Time=2030164029 FU:TRAIL_N -362 0.666998863 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13883, Time=2030164029 FU:TRAIL_N -363 0.667021036 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13884, Time=2030164029 FU:TRAIL_N -364 0.667048931 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13885, Time=2030164029 FU:TRAIL_N -365 0.667074919 H.265 722 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13886, Time=2030164029, Mark FU End:TRAIL_N -366 0.700294971 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13887, Time=2030164029 VPS -367 0.700321913 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13888, Time=2030164029 SPS -368 0.700377941 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13889, Time=2030164029 PPS -369 0.700568914 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13890, Time=2030164029 FU Start:TRAIL_R -370 0.700634956 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13891, Time=2030164029 FU:TRAIL_R -371 0.700673819 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13892, Time=2030164029 FU:TRAIL_R -372 0.700687885 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13893, Time=2030164029 FU:TRAIL_R -373 0.700700998 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13894, Time=2030164029 FU:TRAIL_R -374 0.700732946 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13895, Time=2030164029 FU:TRAIL_R -375 0.700762987 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13896, Time=2030164029 FU:TRAIL_R -376 0.700794935 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13897, Time=2030164029 FU:TRAIL_R -377 0.700819016 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13898, Time=2030164029 FU:TRAIL_R -378 0.700832844 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13899, Time=2030164029 FU:TRAIL_R -379 0.700845003 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13900, Time=2030164029 FU:TRAIL_R -380 0.700907946 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13901, Time=2030164029 FU:TRAIL_R -381 0.700925827 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13902, Time=2030164029 FU:TRAIL_R -382 0.700958967 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13903, Time=2030164029 FU:TRAIL_R -383 0.700994968 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13904, Time=2030164029 FU:TRAIL_R -384 0.701033831 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13905, Time=2030164029 FU:TRAIL_R -385 0.701051950 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13906, Time=2030164029 FU:TRAIL_R -386 0.701093912 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13907, Time=2030164029 FU:TRAIL_R -387 0.701221943 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13908, Time=2030164029 FU:TRAIL_R -388 0.701246977 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13909, Time=2030164029 FU:TRAIL_R -389 0.701262951 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13910, Time=2030164029 FU:TRAIL_R -390 0.701295853 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13911, Time=2030164029 FU:TRAIL_R -391 0.701313019 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13912, Time=2030164029 FU:TRAIL_R -392 0.701325893 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13913, Time=2030164029 FU:TRAIL_R -393 0.701390028 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13914, Time=2030164029 FU:TRAIL_R -394 0.701406956 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13915, Time=2030164029 FU:TRAIL_R -395 0.701455832 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13916, Time=2030164029 FU:TRAIL_R -396 0.701493979 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13917, Time=2030164029 FU:TRAIL_R -397 0.701506853 H.265 376 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13918, Time=2030164029, Mark FU End:TRAIL_R -398 0.733497858 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13919, Time=2030164029 VPS -399 0.733523846 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13920, Time=2030164029 SPS -400 0.733598948 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13921, Time=2030164029 PPS -401 0.733649015 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13922, Time=2030164029 FU Start:TRAIL_R -402 0.733676910 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13923, Time=2030164029 FU:TRAIL_R -403 0.733696938 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13924, Time=2030164029 FU:TRAIL_R -404 0.733711958 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13925, Time=2030164029 FU:TRAIL_R -405 0.733726978 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13926, Time=2030164029 FU:TRAIL_R -406 0.733742952 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13927, Time=2030164029 FU:TRAIL_R -407 0.733753920 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13928, Time=2030164029 FU:TRAIL_R -408 0.733768940 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13929, Time=2030164029 FU:TRAIL_R -409 0.733783960 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13930, Time=2030164029 FU:TRAIL_R -410 0.733796835 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13931, Time=2030164029 FU:TRAIL_R -411 0.733813047 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13932, Time=2030164029 FU:TRAIL_R -412 0.733825922 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13933, Time=2030164029 FU:TRAIL_R -413 0.733837843 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13934, Time=2030164029 FU:TRAIL_R -414 0.733850956 H.265 564 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13935, Time=2030164029, Mark FU End:TRAIL_R -415 0.767308950 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13936, Time=2030164029 VPS -416 0.767333984 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13937, Time=2030164029 SPS -417 0.767350912 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13938, Time=2030164029 PPS -418 0.767369986 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13939, Time=2030164029 FU Start:TRAIL_N -419 0.767382860 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13940, Time=2030164029 FU:TRAIL_N -420 0.767397881 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13941, Time=2030164029 FU:TRAIL_N -421 0.767410994 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13942, Time=2030164029 FU:TRAIL_N -422 0.767421961 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13943, Time=2030164029 FU:TRAIL_N -423 0.767437935 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13944, Time=2030164029 FU:TRAIL_N -424 0.767448902 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13945, Time=2030164029 FU:TRAIL_N -425 0.767462969 H.265 909 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13946, Time=2030164029, Mark FU End:TRAIL_N -426 0.805089951 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13947, Time=2030164029 VPS -427 0.805121899 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13948, Time=2030164029 SPS -428 0.805142879 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13949, Time=2030164029 PPS -429 0.805166960 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13950, Time=2030164029 FU Start:TRAIL_N -430 0.805197001 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13951, Time=2030164029 FU:TRAIL_N -431 0.805217981 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13952, Time=2030164029 FU:TRAIL_N -432 0.805238962 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13953, Time=2030164029 FU:TRAIL_N -433 0.805258989 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13954, Time=2030164029 FU:TRAIL_N -434 0.805277824 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13955, Time=2030164029 FU:TRAIL_N -435 0.805299044 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13956, Time=2030164029 FU:TRAIL_N -436 0.805316925 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13957, Time=2030164029 FU:TRAIL_N -437 0.805336952 H.265 444 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13958, Time=2030164029, Mark FU End:TRAIL_N -438 0.838366985 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13959, Time=2030164029 VPS -439 0.838407993 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13960, Time=2030164029 SPS -440 0.838433981 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13961, Time=2030164029 PPS -441 0.838467836 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13962, Time=2030164029 FU Start:TRAIL_N -442 0.838506937 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13963, Time=2030164029 FU:TRAIL_N -443 0.838531971 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13964, Time=2030164029 FU:TRAIL_N -444 0.838562012 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13965, Time=2030164029 FU:TRAIL_N -445 0.838584900 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13966, Time=2030164029 FU:TRAIL_N -446 0.838608980 H.265 1115 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13967, Time=2030164029, Mark FU End:TRAIL_N -447 0.871814966 H.265 78 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13968, Time=2030164029 VPS -448 0.871883869 H.265 96 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13969, Time=2030164029 SPS -449 0.871927023 H.265 61 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13970, Time=2030164029 PPS -450 0.872179031 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13971, Time=2030164029 FU Start:TRAIL_R -451 0.872246027 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13972, Time=2030164029 FU:TRAIL_R -452 0.872293949 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13973, Time=2030164029 FU:TRAIL_R -453 0.872339010 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13974, Time=2030164029 FU:TRAIL_R -454 0.872380018 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13975, Time=2030164029 FU:TRAIL_R -455 0.872424841 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13976, Time=2030164029 FU:TRAIL_R -456 0.872468948 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13977, Time=2030164029 FU:TRAIL_R -457 0.872494936 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13978, Time=2030164029 FU:TRAIL_R -458 0.872534990 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13979, Time=2030164029 FU:TRAIL_R -459 0.872560978 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13980, Time=2030164029 FU:TRAIL_R -460 0.872588873 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13981, Time=2030164029 FU:TRAIL_R -461 0.872611046 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13982, Time=2030164029 FU:TRAIL_R -462 0.872632027 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13983, Time=2030164029 FU:TRAIL_R -463 0.872658968 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13984, Time=2030164029 FU:TRAIL_R -464 0.872681856 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13985, Time=2030164029 FU:TRAIL_R -465 0.872704029 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13986, Time=2030164029 FU:TRAIL_R -466 0.872727871 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13987, Time=2030164029 FU:TRAIL_R -467 0.872750044 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13988, Time=2030164029 FU:TRAIL_R -468 0.872776985 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13989, Time=2030164029 FU:TRAIL_R -469 0.872797966 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13990, Time=2030164029 FU:TRAIL_R -470 0.872820854 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13991, Time=2030164029 FU:TRAIL_R -471 0.872845888 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13992, Time=2030164029 FU:TRAIL_R -472 0.872867823 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13993, Time=2030164029 FU:TRAIL_R -473 0.872890949 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13994, Time=2030164029 FU:TRAIL_R -474 0.872916937 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13995, Time=2030164029 FU:TRAIL_R -475 0.872939825 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13996, Time=2030164029 FU:TRAIL_R -476 0.872964859 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13997, Time=2030164029 FU:TRAIL_R -477 0.872987986 H.265 1242 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13998, Time=2030164029 FU:TRAIL_R -478 0.873015881 H.265 590 PT=DynamicRTP-Type-96, SSRC=0x8E80A348, Seq=13999, Time=2030164029, Mark FU End:TRAIL_R diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp8.pcap b/rs/moq-webrtc/src/vendor/str0m/tests/data/vp8.pcap deleted file mode 100644 index 56cd88dfd74..00000000000 Binary files a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp8.pcap and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp8.txt b/rs/moq-webrtc/src/vendor/str0m/tests/data/vp8.txt deleted file mode 100644 index ad6c790d56c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp8.txt +++ /dev/null @@ -1,104 +0,0 @@ -1 0.000000 VP8 191 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14260, Time=3190208834, Mark - Keyframe -2 0.001000 VP8 107 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14261, Time=3190209284, Mark - Interframe -3 0.037000 VP8 187 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14262, Time=3190211894, Mark - Keyframe -4 0.069000 VP8 866 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14263, Time=3190214684, Mark - Interframe -5 0.106000 VP8 848 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14264, Time=3190217564, Mark - Interframe -6 0.147000 VP8 960 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14265, Time=3190220444, Mark - Keyframe -7 0.166000 VP8 184 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14266, Time=3190223324, Mark - Interframe -8 0.199000 VP8 221 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14267, Time=3190226294, Mark - Interframe -9 0.237000 VP8 159 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14268, Time=3190229174, Mark - Interframe -0 0.262000 VP8 339 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14269, Time=3190232144, Mark - Interframe -1 0.294000 VP8 159 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14270, Time=3190235024, Mark - Interframe -2 0.328000 VP8 403 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14271, Time=3190237994, Mark - Interframe -3 0.359000 VP8 200 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14272, Time=3190240874, Mark - Interframe -4 0.393000 VP8 472 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14273, Time=3190243844, Mark - Interframe -5 0.422000 VP8 289 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14274, Time=3190246724, Mark - Interframe -6 0.456000 VP8 533 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14275, Time=3190249694, Mark - Interframe -7 0.487000 VP8 322 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14276, Time=3190252664, Mark - Interframe -8 0.520000 VP8 424 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14277, Time=3190255544, Mark - Interframe -9 0.554000 VP8 347 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14278, Time=3190258514, Mark - Interframe -0 0.593000 VP8 461 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14279, Time=3190261484, Mark - Interframe -1 0.625000 VP8 307 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14280, Time=3190264454, Mark - Interframe -2 0.659000 VP8 504 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14281, Time=3190267424, Mark - Interframe -3 0.691000 VP8 331 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14282, Time=3190270394, Mark - Interframe -4 0.725000 VP8 474 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14283, Time=3190273364, Mark - Interframe -5 0.760000 VP8 405 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14284, Time=3190276424, Mark - Interframe -6 0.794000 VP8 464 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14285, Time=3190279394, Mark - Interframe -7 0.824000 VP8 386 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14286, Time=3190282364, Mark - Interframe -8 0.856000 VP8 659 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14287, Time=3190285334, Mark - Interframe -9 0.890000 VP8 402 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14288, Time=3190288304, Mark - Interframe -0 0.923000 VP8 586 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14289, Time=3190291274, Mark - Interframe -1 0.961000 VP8 454 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14290, Time=3190294334, Mark - Interframe -2 0.994000 VP8 605 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14291, Time=3190297304, Mark - Interframe -3 1.027000 VP8 835 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14292, Time=3190300274, Mark - Interframe -4 1.060000 VP8 998 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14293, Time=3190303244, Mark - Interframe -5 1.091000 VP8 419 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14294, Time=3190306304, Mark - Interframe -6 1.124000 VP8 765 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14295, Time=3190309274, Mark - Interframe -7 1.156000 VP8 504 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14296, Time=3190312244, Mark - Interframe -8 1.191000 VP8 667 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14297, Time=3190315214, Mark - Interframe -9 1.223000 VP8 480 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14298, Time=3190318274, Mark - Interframe -0 1.255000 VP8 669 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14299, Time=3190321244, Mark - Interframe -1 1.291000 VP8 504 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14300, Time=3190324214, Mark - Interframe -2 1.325000 VP8 853 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14301, Time=3190327184, Mark - Interframe -3 1.357000 VP8 494 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14302, Time=3190330154, Mark - Interframe -4 1.389000 VP8 701 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14303, Time=3190333214, Mark - Interframe -5 1.425000 VP8 510 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14304, Time=3190336184, Mark - Interframe -6 1.458000 VP8 693 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14305, Time=3190339154, Mark - Interframe -7 1.490000 VP8 714 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14306, Time=3190342214, Mark - Interframe -8 1.521000 VP8 849 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14307, Time=3190345184, Mark - Interframe -9 1.561000 VP8 685 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14308, Time=3190348154, Mark - Interframe -0 1.595000 VP8 978 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14309, Time=3190351124, Mark - Interframe -1 1.627000 VP8 608 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14310, Time=3190354184, Mark - Interframe -2 1.661000 VP8 856 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14311, Time=3190357154, Mark - Interframe -3 1.692000 VP8 544 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14312, Time=3190360124, Mark - Interframe -4 1.725000 VP8 884 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14313, Time=3190363184, Mark - Interframe -5 1.757000 VP8 468 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14314, Time=3190366154, Mark - Interframe -6 1.789000 VP8 784 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14315, Time=3190369124, Mark - Interframe -7 1.821000 VP8 987 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14316, Time=3190372094, Mark - Interframe -8 1.876000 VP8 853 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14317, Time=3190375154, Mark - Interframe -9 1.909000 VP8 509 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14318, Time=3190378214, Mark - Interframe -0 1.941000 VP8 1213PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14319, Time=3190381184, Mark - Interframe -1 1.973000 VP8 543 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14320, Time=3190384244, Mark - Interframe -2 2.007000 VP8 871 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14321, Time=3190387214, Mark - Interframe -3 2.039000 VP8 842 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14322, Time=3190390274, Mark - Interframe -4 2.074000 VP8 949 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14323, Time=3190393244, Mark - Interframe -5 2.103000 VP8 460 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14324, Time=3190396304, Mark - Interframe -6 2.136000 VP8 894 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14325, Time=3190399274, Mark - Interframe -7 2.170000 VP8 651 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14326, Time=3190402334, Mark - Interframe -8 2.200000 VP8 1034PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14327, Time=3190405304, Mark - Interframe -9 2.233000 VP8 601 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14328, Time=3190408274, Mark - Interframe -0 2.263000 VP8 922 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14329, Time=3190411334, Mark - Interframe -1 2.295000 VP8 718 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14330, Time=3190414304, Mark - Interframe -2 2.329000 VP8 828 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14331, Time=3190417364, Mark - Interframe -3 2.365000 VP8 723 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14332, Time=3190420334, Mark - Interframe -4 2.398000 VP8 870 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14333, Time=3190423304, Mark - Interframe -5 2.431000 VP8 701 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14334, Time=3190426364, Mark - Interframe -6 2.462000 VP8 961 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14335, Time=3190429334, Mark - Interframe -7 2.494000 VP8 663 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14336, Time=3190432304, Mark - Interframe -8 2.527000 VP8 886 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14337, Time=3190435364, Mark - Interframe -9 2.558000 VP8 682 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14338, Time=3190438334, Mark - Interframe -0 2.592000 VP8 1164PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14339, Time=3190441304, Mark - Interframe -1 2.624000 VP8 683 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14340, Time=3190444274, Mark - Interframe -2 2.657000 VP8 965 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14341, Time=3190447334, Mark - Interframe -3 2.696000 VP8 822 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14342, Time=3190450304, Mark - Interframe -4 2.730000 VP8 1128PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14343, Time=3190453274, Mark - Interframe -5 2.762000 VP8 676 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14344, Time=3190456334, Mark - Interframe -6 2.796000 VP8 876 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14345, Time=3190459304, Mark - Interframe -7 2.829000 VP8 748 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14346, Time=3190462274, Mark - Interframe -8 2.859000 VP8 1124PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14347, Time=3190465334, Mark - Interframe -9 2.892000 VP8 824 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14348, Time=3190468304, Mark - Interframe -0 2.924000 VP8 1056PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14349, Time=3190471274, Mark - Interframe -1 2.957000 VP8 856 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14350, Time=3190474334, Mark - Interframe -2 2.990000 VP8 709 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14351, Time=3190477304 - Interframe -3 2.990000 VP8 710 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14352, Time=3190477304, Mark - Continuation -4 3.023000 VP8 975 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14353, Time=3190480274, Mark - Interframe -5 3.062000 VP8 710 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14354, Time=3190483334 - Interframe -6 3.062000 VP8 710 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14355, Time=3190483334, Mark - Continuation -7 3.093000 VP8 814 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14356, Time=3190486304, Mark - Interframe -8 3.126000 VP8 715 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14357, Time=3190489274 - Interframe -9 3.126000 VP8 715 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14358, Time=3190489274, Mark - Continuation -0 3.158000 VP8 701 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14359, Time=3190492244, Mark - Interframe -1 3.191000 VP8 919 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14360, Time=3190495304, Mark - Interframe -2 3.227000 VP8 664 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14361, Time=3190498274, Mark - Interframe -3 3.260000 VP8 1020PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14362, Time=3190501244, Mark - Interframe -4 3.294000 VP8 667 PT=DynamicRTP-Type-96, SSRC=0xEEDF3944, Seq=14363, Time=3190504304, Mark - Interframe diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp9.pcap b/rs/moq-webrtc/src/vendor/str0m/tests/data/vp9.pcap deleted file mode 100644 index 459741e2f34..00000000000 Binary files a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp9.pcap and /dev/null differ diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp9.txt b/rs/moq-webrtc/src/vendor/str0m/tests/data/vp9.txt deleted file mode 100644 index 505df32e6fc..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data/vp9.txt +++ /dev/null @@ -1,316 +0,0 @@ -291 0.000290000 VP9 255 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19357, Time=3665622181, Mark -293 0.000292000 VP9 127 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19358, Time=3665631181, Mark -295 0.000294000 VP9 157 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19359, Time=3665640541, Mark -297 0.000296000 VP9 141 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19360, Time=3665649091, Mark -299 0.000298000 VP9 195 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19361, Time=3665658181, Mark -301 0.000300000 VP9 248 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19362, Time=3665667181, Mark -303 0.000302000 VP9 236 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19363, Time=3665676181, Mark -307 0.000306000 VP9 288 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19364, Time=3665685091, Mark -329 0.000328000 VP9 253 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19365, Time=3665694091, Mark -331 0.000330000 VP9 294 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19366, Time=3665703181, Mark -333 0.000332000 VP9 330 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19367, Time=3665712091, Mark -335 0.000334000 VP9 428 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19368, Time=3665721181, Mark -337 0.000336000 VP9 831 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19369, Time=3665730181, Mark -339 0.000338000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19370, Time=3665739091, Mark -340 0.000339000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19371, Time=3665748181, Mark -341 0.000340000 VP9 773 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19372, Time=3665757091 -342 0.000341000 VP9 774 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19373, Time=3665757091, Mark -344 0.000343000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19374, Time=3665766091 -347 0.000346000 VP9 863 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19376, Time=3665775091 -348 0.000347000 VP9 864 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19377, Time=3665775091 -349 0.000348000 VP9 864 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19378, Time=3665775091, Mark -352 0.000351000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19379, Time=3665784091 -353 0.000352000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19381, Time=3665784091, Mark -354 0.000353000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19382, Time=3665793091 -355 0.000354000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19384, Time=3665793091, Mark -356 0.000355000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19385, Time=3665802091 -357 0.000356000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19387, Time=3665802091 -359 0.000358000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19389, Time=3665811091 -360 0.000359000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19391, Time=3665811091 -362 0.000361000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19393, Time=3665820091 -363 0.000362000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19395, Time=3665820091 -364 0.000363000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19397, Time=3665820091, Mark -365 0.000364000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19398, Time=3665829091 -366 0.000365000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19400, Time=3665829091 -367 0.000366000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19402, Time=3665829091, Mark -369 0.000368000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19403, Time=3665838091 -370 0.000369000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19405, Time=3665838091 -371 0.000370000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19407, Time=3665838091 -373 0.000372000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19409, Time=3665847091 -374 0.000373000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19411, Time=3665847091 -375 0.000374000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19413, Time=3665847091 -377 0.000376000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19415, Time=3665856091 -378 0.000377000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19417, Time=3665856091 -379 0.000378000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19419, Time=3665856091 -380 0.000379000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19421, Time=3665856091 -382 0.000381000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19423, Time=3665856091, Mark -383 0.000382000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19425, Time=3665865091 -384 0.000383000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19427, Time=3665865091 -385 0.000384000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19429, Time=3665865091 -386 0.000385000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19431, Time=3665865091, Mark -388 0.000387000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19432, Time=3665874091 -389 0.000388000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19434, Time=3665874091 -390 0.000389000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19436, Time=3665874091 -391 0.000390000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19438, Time=3665874091 -393 0.000392000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19440, Time=3665883091 -394 0.000393000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19442, Time=3665883091 -395 0.000394000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19444, Time=3665883091 -396 0.000395000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19446, Time=3665883091 -398 0.000397000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19448, Time=3665892091 -400 0.000399000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19450, Time=3665892091 -401 0.000400000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19452, Time=3665892091 -402 0.000401000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19454, Time=3665892091 -404 0.000403000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19456, Time=3665901091 -405 0.000404000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19458, Time=3665901091 -406 0.000405000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19460, Time=3665901091 -407 0.000406000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19462, Time=3665901091 -409 0.000408000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19464, Time=3665910091 -410 0.000409000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19466, Time=3665910091 -411 0.000410000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19468, Time=3665910091 -412 0.000411000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19470, Time=3665910091 -414 0.000413000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19472, Time=3665919091 -415 0.000414000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19474, Time=3665919091 -416 0.000415000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19476, Time=3665919091 -417 0.000416000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19478, Time=3665919091 -420 0.000419000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19480, Time=3665928091 -421 0.000420000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19482, Time=3665928091 -422 0.000421000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19484, Time=3665928091 -423 0.000422000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19486, Time=3665928091 -425 0.000424000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19488, Time=3665937091 -426 0.000425000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19490, Time=3665937091 -427 0.000426000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19492, Time=3665937091 -428 0.000427000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19494, Time=3665937091 -430 0.000429000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19496, Time=3665946091 -431 0.000430000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19498, Time=3665946091 -432 0.000431000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19500, Time=3665946091 -433 0.000432000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19502, Time=3665946091 -435 0.000434000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19504, Time=3665955091 -436 0.000435000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19506, Time=3665955091 -437 0.000436000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19508, Time=3665955091 -438 0.000437000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19510, Time=3665955091 -441 0.000440000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19512, Time=3665964091 -442 0.000441000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19514, Time=3665964091 -443 0.000442000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19516, Time=3665964091 -444 0.000443000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19518, Time=3665964091 -446 0.000445000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19520, Time=3665973091 -447 0.000446000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19522, Time=3665973091 -448 0.000447000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19524, Time=3665973091 -449 0.000448000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19526, Time=3665973091 -452 0.000451000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19528, Time=3665982091 -453 0.000452000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19530, Time=3665982091 -454 0.000453000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19532, Time=3665982091 -455 0.000454000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19534, Time=3665982091 -457 0.000456000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19536, Time=3665991091 -458 0.000457000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19538, Time=3665991091 -459 0.000458000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19540, Time=3665991091 -460 0.000459000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19542, Time=3665991091 -462 0.000461000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19544, Time=3666000091 -463 0.000462000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19546, Time=3666000091 -464 0.000463000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19548, Time=3666000091 -465 0.000464000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19550, Time=3666000091 -467 0.000466000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19552, Time=3666009091 -468 0.000467000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19554, Time=3666009091 -469 0.000468000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19556, Time=3666009091 -470 0.000469000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19558, Time=3666009091 -472 0.000471000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19560, Time=3666018091 -473 0.000472000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19562, Time=3666018091 -474 0.000473000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19564, Time=3666018091 -475 0.000474000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19565, Time=3666018091 -476 0.000475000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19567, Time=3666018091, Mark -477 0.000476000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19568, Time=3666027091 -478 0.000477000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19570, Time=3666027091 -479 0.000478000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19572, Time=3666027091 -480 0.000479000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19574, Time=3666027091 -482 0.000481000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19576, Time=3666036091 -483 0.000482000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19578, Time=3666036091 -484 0.000483000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19580, Time=3666036091 -485 0.000484000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19582, Time=3666036091 -487 0.000486000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19584, Time=3666045181 -488 0.000487000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19586, Time=3666045181 -489 0.000488000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19588, Time=3666045181 -490 0.000489000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19590, Time=3666045181 -494 0.000493000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19592, Time=3666054181 -495 0.000494000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19594, Time=3666054181 -496 0.000495000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19596, Time=3666054181 -497 0.000496000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19598, Time=3666054181 -499 0.000498000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19600, Time=3666063091 -500 0.000499000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19602, Time=3666063091 -501 0.000500000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19604, Time=3666063091 -502 0.000501000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19606, Time=3666063091 -504 0.000503000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19608, Time=3666072091 -505 0.000504000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19610, Time=3666072091 -506 0.000505000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19612, Time=3666072091 -507 0.000506000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19614, Time=3666072091 -510 0.000509000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19616, Time=3666081091 -511 0.000510000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19618, Time=3666081091 -512 0.000511000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19620, Time=3666081091 -513 0.000512000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19622, Time=3666081091 -515 0.000514000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19624, Time=3666090091 -516 0.000515000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19626, Time=3666090091 -517 0.000516000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19628, Time=3666090091 -518 0.000517000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19630, Time=3666090091 -520 0.000519000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19632, Time=3666099091 -521 0.000520000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19634, Time=3666099091 -523 0.000522000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19636, Time=3666099091 -524 0.000523000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19638, Time=3666099091 -526 0.000525000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19640, Time=3666108091 -527 0.000526000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19642, Time=3666108091 -528 0.000527000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19644, Time=3666108091 -529 0.000528000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19646, Time=3666108091 -531 0.000530000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19648, Time=3666117091 -532 0.000531000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19650, Time=3666117091 -533 0.000532000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19652, Time=3666117091 -534 0.000533000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19654, Time=3666117091 -536 0.000535000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19656, Time=3666126091 -537 0.000536000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19658, Time=3666126091 -538 0.000537000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19660, Time=3666126091 -539 0.000538000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19662, Time=3666126091 -541 0.000540000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19664, Time=3666135091 -542 0.000541000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19666, Time=3666135091 -543 0.000542000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19668, Time=3666135091 -544 0.000543000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19670, Time=3666135091 -548 0.000547000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19672, Time=3666144091 -549 0.000548000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19674, Time=3666144091 -550 0.000549000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19676, Time=3666144091 -551 0.000550000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19678, Time=3666144091 -553 0.000552000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19680, Time=3666153091 -554 0.000553000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19682, Time=3666153091 -555 0.000554000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19684, Time=3666153091 -556 0.000555000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19686, Time=3666153091 -558 0.000557000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19688, Time=3666162091 -559 0.000558000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19690, Time=3666162091 -560 0.000559000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19692, Time=3666162091 -561 0.000560000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19694, Time=3666162091 -563 0.000562000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19696, Time=3666171091 -564 0.000563000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19698, Time=3666171091 -565 0.000564000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19700, Time=3666171091 -566 0.000565000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19702, Time=3666171091 -568 0.000567000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19704, Time=3666180091 -569 0.000568000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19706, Time=3666180091 -570 0.000569000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19708, Time=3666180091 -571 0.000570000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19710, Time=3666180091 -573 0.000572000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19712, Time=3666189091 -574 0.000573000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19714, Time=3666189091 -575 0.000574000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19716, Time=3666189091 -577 0.000576000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19718, Time=3666189091 -579 0.000578000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19720, Time=3666198091 -580 0.000579000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19722, Time=3666198091 -581 0.000580000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19724, Time=3666198091 -582 0.000581000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19726, Time=3666198091 -584 0.000583000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19728, Time=3666207091 -585 0.000584000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19730, Time=3666207091 -586 0.000585000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19732, Time=3666207091 -587 0.000586000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19734, Time=3666207091 -589 0.000588000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19736, Time=3666216091 -590 0.000589000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19738, Time=3666216091 -591 0.000590000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19740, Time=3666216091 -592 0.000591000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19742, Time=3666216091 -594 0.000593000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19744, Time=3666225091 -595 0.000594000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19746, Time=3666225091 -596 0.000595000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19748, Time=3666225091 -597 0.000596000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19750, Time=3666225091 -600 0.000599000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19752, Time=3666234091 -601 0.000600000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19754, Time=3666234091 -602 0.000601000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19756, Time=3666234091 -603 0.000602000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19758, Time=3666234091 -605 0.000604000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19760, Time=3666243181 -606 0.000605000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19762, Time=3666243181 -607 0.000606000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19764, Time=3666243181 -608 0.000607000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19766, Time=3666243181 -610 0.000609000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19768, Time=3666252181 -611 0.000610000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19770, Time=3666252181 -612 0.000611000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19771, Time=3666252181 -613 0.000612000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19773, Time=3666252181 -614 0.000613000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19775, Time=3666252181, Mark -615 0.000614000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19776, Time=3666261091 -616 0.000615000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19778, Time=3666261091 -617 0.000616000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19780, Time=3666261091 -618 0.000617000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19782, Time=3666261091 -620 0.000619000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19784, Time=3666270091 -621 0.000620000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19786, Time=3666270091 -622 0.000621000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19788, Time=3666270091 -623 0.000622000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19790, Time=3666270091 -626 0.000625000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19792, Time=3666279091 -627 0.000626000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19794, Time=3666279091 -628 0.000627000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19796, Time=3666279091 -629 0.000628000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19798, Time=3666279091 -631 0.000630000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19800, Time=3666288091 -632 0.000631000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19802, Time=3666288091 -633 0.000632000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19804, Time=3666288091 -634 0.000633000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19806, Time=3666288091 -636 0.000635000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19808, Time=3666297091 -637 0.000636000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19810, Time=3666297091 -638 0.000637000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19812, Time=3666297091 -639 0.000638000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19814, Time=3666297091 -641 0.000640000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19816, Time=3666306091 -642 0.000641000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19818, Time=3666306091 -643 0.000642000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19820, Time=3666306091 -644 0.000643000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19822, Time=3666306091 -646 0.000645000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19824, Time=3666315091 -647 0.000646000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19825, Time=3666315091 -648 0.000647000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19827, Time=3666315091 -649 0.000648000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19829, Time=3666315091 -650 0.000649000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19831, Time=3666315091, Mark -652 0.000651000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19832, Time=3666324091 -653 0.000652000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19834, Time=3666324091 -654 0.000653000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19836, Time=3666324091 -655 0.000654000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19838, Time=3666324091 -657 0.000656000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19840, Time=3666333091 -658 0.000657000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19842, Time=3666333091 -659 0.000658000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19844, Time=3666333091 -660 0.000659000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19846, Time=3666333091 -662 0.000661000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19848, Time=3666342091 -663 0.000662000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19850, Time=3666342091 -664 0.000663000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19852, Time=3666342091 -665 0.000664000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19854, Time=3666342091 -667 0.000666000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19856, Time=3666351091 -668 0.000667000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19858, Time=3666351091 -669 0.000668000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19860, Time=3666351091 -670 0.000669000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19862, Time=3666351091 -672 0.000671000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19864, Time=3666360091 -673 0.000672000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19866, Time=3666360091 -674 0.000673000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19868, Time=3666360091 -675 0.000674000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19870, Time=3666360091 -677 0.000676000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19872, Time=3666369091 -678 0.000677000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19874, Time=3666369091 -679 0.000678000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19876, Time=3666369091 -680 0.000679000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19878, Time=3666369091 -682 0.000681000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19880, Time=3666378091 -683 0.000682000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19881, Time=3666378091 -684 0.000683000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19883, Time=3666378091 -685 0.000684000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19885, Time=3666378091 -686 0.000685000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19887, Time=3666378091, Mark -687 0.000686000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19889, Time=3666387091 -689 0.000688000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19891, Time=3666387091 -690 0.000689000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19893, Time=3666387091 -691 0.000690000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19895, Time=3666387091, Mark -693 0.000692000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19897, Time=3666396271 -694 0.000693000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19899, Time=3666396271 -695 0.000694000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19901, Time=3666396271 -696 0.000695000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19903, Time=3666396271, Mark -698 0.000697000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19905, Time=3666405091 -699 0.000698000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19907, Time=3666405091 -700 0.000699000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19909, Time=3666405091 -701 0.000700000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19911, Time=3666405091, Mark -702 0.000701000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19912, Time=3666414541 -704 0.000703000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19913, Time=3666414541 -705 0.000704000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19915, Time=3666414541 -706 0.000705000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19917, Time=3666414541 -707 0.000706000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19919, Time=3666414541, Mark -708 0.000707000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19921, Time=3666423721 -709 0.000708000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19922, Time=3666423721 -710 0.000709000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19924, Time=3666423721 -711 0.000710000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19926, Time=3666423721 -712 0.000711000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19928, Time=3666432091 -713 0.000712000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19930, Time=3666432091 -715 0.000714000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19932, Time=3666432091 -716 0.000715000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19934, Time=3666432091 -717 0.000716000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19936, Time=3666441181 -718 0.000717000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19938, Time=3666441181 -719 0.000718000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19939, Time=3666441181 -720 0.000719000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19941, Time=3666441181 -721 0.000720000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19943, Time=3666441181, Mark -722 0.000721000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19945, Time=3666450181 -724 0.000723000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19947, Time=3666450181 -725 0.000724000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19949, Time=3666450181 -726 0.000725000 VP9 878 PT=DynamicRTP-Type-98, SSRC=0x22D80F08, Seq=19951, Time=3666450181, Mark diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dlrr.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dlrr.rs deleted file mode 100644 index b33468a1d64..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dlrr.rs +++ /dev/null @@ -1,145 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::RawPacket; -use crate::vendor::str0m::rtp::rtcp::{ReportBlock, Rtcp}; -use crate::vendor::str0m::{Rtc, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// Verify that a StreamTx responds to an incoming RRTR with a DLRR. -/// -/// L sends audio to R. R's StreamRx generates RRTR (Receiver Reference Time Report, -/// RFC 3611 §4.4) alongside its Receiver Reports. L's StreamTx should respond with a -/// DLRR (Delay since Last Receiver Report, RFC 3611 §4.5) in its next Sender Report, -/// allowing R to compute RTT. -#[test] -pub fn dlrr_response_to_rrtr() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let l_rtc = Rtc::builder().enable_raw_packets(true).build(now); - let r_rtc = Rtc::builder().enable_raw_packets(true).build(now); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), l_rtc); - let mut r = TestRtc::new_with_rtc(info_span!("R"), r_rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // L sends audio to R: L gets a StreamTx, R gets a StreamRx. - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None) - }); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // Sync clocks. - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let data = [1_u8; 80]; - - // Run ~15s of synthetic time. R will send RRTR with its Receiver Reports - // (~every 5s), and L should reply with DLRR in its next Sender Report. - loop { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data)?; - progress(&mut l, &mut r)?; - if l.duration() > Duration::from_secs(15) { - break; - } - } - - let media_ssrc = l - .events - .iter() - .find_map(|(_, e)| match e.as_raw_packet() { - Some(RawPacket::RtpTx(header, _)) => Some(header.ssrc), - _ => None, - }) - .expect("L should have sent RTP"); - - // R should have sent at least one RRTR, using its local RTCP SSRC rather than - // the remote media SSRC it is reporting on. - let rrtr_ssrc = r - .events - .iter() - .find_map(|(_, e)| { - let Some(RawPacket::RtcpTx(Rtcp::ExtendedReport(xr))) = e.as_raw_packet() else { - return None; - }; - xr.blocks - .iter() - .any(|b| matches!(b, ReportBlock::Rrtr(_))) - .then_some(xr.ssrc) - }) - .expect("R should have sent at least one RRTR"); - assert_ne!(rrtr_ssrc, media_ssrc); - - // L should have sent at least one DLRR in response. - let dlrr_reports: Vec<_> = l - .events - .iter() - .filter_map(|(_, e)| { - if let Some(RawPacket::RtcpTx(Rtcp::ExtendedReport(xr))) = e.as_raw_packet() { - if xr.blocks.iter().any(|b| matches!(b, ReportBlock::Dlrr(_))) { - return Some(xr); - } - } - None - }) - .collect(); - assert!(!dlrr_reports.is_empty(), "L should have sent DLRR in response to RRTR"); - - // Verify the DLRR contains valid data. - let dlrr = dlrr_reports[0] - .blocks - .iter() - .find_map(|b| match b { - ReportBlock::Dlrr(d) => Some(d), - _ => None, - }) - .unwrap(); - assert!(!dlrr.items.is_empty(), "DLRR should have at least one item"); - let item = &dlrr.items[0]; - assert_eq!(item.ssrc, rrtr_ssrc); - - // The last_rr_time field must be the middle 32 bits of the RRTR's NTP timestamp. - // Verify it's non-zero and that R received the same value back (round-trip integrity). - assert!(item.last_rr_time != 0, "DLRR last_rr_time should be non-zero"); - - // Verify R actually received the DLRR that L sent. - let r_received_dlrr = r.events.iter().any(|(_, e)| { - if let Some(RawPacket::RtcpRx(Rtcp::ExtendedReport(xr))) = e.as_raw_packet() { - xr.blocks.iter().any(|b| { - if let ReportBlock::Dlrr(d) = b { - d.items.iter().any(|i| i.last_rr_time == item.last_rr_time) - } else { - false - } - }) - } else { - false - } - }); - assert!( - r_received_dlrr, - "R should have received the DLRR with matching last_rr_time" - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs deleted file mode 100644 index dd26657ef7b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! Tests for the Rtc shutdown states. - -use std::net::Ipv4Addr; -use std::time::Instant; - -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::rtcp::Rtcp; -use crate::vendor::str0m::rtp::{RawPacket, Ssrc}; -use crate::vendor::str0m::{Candidate, Event, Input, Output, Rtc, RtcConfig, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, progress}; - -fn direct_pair() -> (TestRtc, TestRtc) { - direct_pair_with_config(|c| c) -} - -fn direct_pair_with_config(configure: impl Fn(RtcConfig) -> RtcConfig) -> (TestRtc, TestRtc) { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), configure(Rtc::builder()).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), configure(Rtc::builder()).build(now)); - - let host_l = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host_r = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - l.add_local_candidate(host_l.clone()); - l.add_remote_candidate(host_r.clone()); - r.add_local_candidate(host_r); - r.add_remote_candidate(host_l); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - l.direct_api().start_dtls(true).unwrap(); - r.direct_api().start_dtls(false).unwrap(); - - progress_until(&mut l, &mut r, "DTLS handshake", |l, r| { - l.is_connected() && r.is_connected() - }); - - (l, r) -} - -fn progress_until(l: &mut TestRtc, r: &mut TestRtc, label: &str, mut done: impl FnMut(&TestRtc, &TestRtc) -> bool) { - for _ in 0..500 { - if done(l, r) { - return; - } - progress(l, r).unwrap(); - } - - panic!("{label} did not complete"); -} - -fn next_transmit(rtc: &mut TestRtc) -> crate::vendor::str0m::net::Transmit { - for _ in 0..100 { - match rtc.rtc.poll_output().unwrap() { - Output::Transmit(transmit) => return transmit, - Output::Event(event) => rtc.events.push((rtc.last, event)), - Output::Timeout(_) => {} - } - } - - panic!("expected transmit"); -} - -fn deliver(transmit: &crate::vendor::str0m::net::Transmit, rtc: &mut TestRtc) -> Result<(), RtcError> { - rtc.rtc.handle_input(Input::Receive(rtc.last, transmit.try_into()?)) -} - -fn deliver_until_closed_event(sender: &mut TestRtc, receiver: &mut TestRtc) -> Result<(), RtcError> { - for _ in 0..100 { - let transmit = next_transmit(sender); - deliver(&transmit, receiver)?; - - for _ in 0..100 { - match receiver.rtc.poll_output()? { - Output::Event(Event::Closed) => return Ok(()), - Output::Event(event) => receiver.events.push((receiver.last, event)), - Output::Transmit(_) => {} - Output::Timeout(_) => break, - } - } - } - - panic!("expected remote closed event"); -} - -#[test] -fn local_dtls_close_drains_before_rtc_closes() -> Result<(), RtcError> { - let (mut l, mut r) = direct_pair(); - - l.rtc.close()?; - - assert!(l.rtc.is_alive(), "local close_notify still needs to be emitted"); - - progress_until(&mut l, &mut r, "local DTLS close", |l, r| { - !l.rtc.is_alive() && r.events.iter().any(|(_, event)| matches!(event, Event::Closed)) - }); - - assert!(!l.rtc.is_alive()); - - Ok(()) -} - -#[test] -fn remote_dtls_close_auto_replies_before_rtc_closes() -> Result<(), RtcError> { - let (mut l, mut r) = direct_pair(); - - l.rtc.close()?; - deliver_until_closed_event(&mut l, &mut r)?; - - assert!( - r.rtc.is_alive(), - "remote close_notify should leave Rtc alive until the response close_notify drains" - ); - - progress_until(&mut l, &mut r, "remote DTLS close reply", |_, r| !r.rtc.is_alive()); - - assert!(!r.rtc.is_alive()); - - Ok(()) -} - -#[test] -fn close_sends_rtcp_bye_for_local_senders() -> Result<(), RtcError> { - let (mut l, mut r) = direct_pair_with_config(|c| c.enable_raw_packets(true)); - let mid = "aud".into(); - let ssrc: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - l.rtc.close()?; - - progress_until(&mut l, &mut r, "RTCP BYE", |l, _| { - l.events.iter().any(|(_, event)| { - matches!( - event.as_raw_packet(), - Some(RawPacket::RtcpTx(Rtcp::Goodbye(bye))) if bye.reports.iter().any(|s| *s == ssrc) - ) - }) - }); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-error-readiness.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-error-readiness.rs deleted file mode 100644 index 5ae17f12d6f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-error-readiness.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! DTLS can change its timeout even when processing a packet returns an error. - -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::net::{Protocol, Receive}; -use crate::vendor::str0m::{Input, Output, Reason, Rtc, RtcError}; - -use super::common; -use common::init_crypto_default; - -#[test] -fn rejected_client_hello_still_exposes_new_handshake_deadline() { - init_crypto_default(); - let now = Instant::now(); - let mut rtc = Rtc::builder().build(now); - rtc.direct_api().start_dtls(false).unwrap(); - match rtc.poll_output().unwrap() { - Output::Timeout(deadline) => assert!(deadline > now + Duration::from_secs(60)), - output => panic!("expected an idle timeout, got {output:?}"), - } - - // A structurally valid ClientHello starts dimpl's handshake deadline before - // its unsupported DTLS 1.0 client version is rejected by body validation. - let mut body = vec![0xfe, 0xff]; - body.extend_from_slice(&[0; 32]); // random - body.extend_from_slice(&[0, 0]); // empty session ID and cookie - body.extend_from_slice(&[0, 2, 0xc0, 0x2b]); // one cipher suite - body.extend_from_slice(&[1, 0]); // null compression - body.extend_from_slice(&[0, 0]); // no extensions - let body_len = body.len() as u8; - let mut handshake = vec![1, 0, 0, body_len, 0, 0, 0, 0, 0, 0, 0, body_len]; - handshake.extend_from_slice(&body); - let mut packet = vec![22, 0xfe, 0xfd, 0, 0, 0, 0, 0, 0, 0, 0]; - packet.extend_from_slice(&(handshake.len() as u16).to_be_bytes()); - packet.extend_from_slice(&handshake); - - let input = Input::Receive( - now, - Receive { - proto: Protocol::Udp, - source: (Ipv4Addr::LOCALHOST, 1234).into(), - destination: (Ipv4Addr::LOCALHOST, 5678).into(), - contents: packet.as_slice().try_into().unwrap(), - }, - ); - let error = rtc.handle_input(input).unwrap_err(); - assert!(matches!(error, RtcError::Dtls(_))); - assert!(error.to_string().contains("unsupported DTLS version")); - - match rtc.poll_output().unwrap() { - Output::Timeout(deadline) => assert!( - deadline <= now + Duration::from_secs(60), - "the changed DTLS deadline must replace the previously cached idle timeout" - ), - output => panic!("expected the DTLS handshake timeout, got {output:?}"), - } - assert_eq!(rtc.last_timeout_reason(), Reason::DTLS); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs deleted file mode 100644 index 69c51616c35..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs +++ /dev/null @@ -1,198 +0,0 @@ -//! The remote certificate fingerprint is verified with the hash function the -//! remote names (RFC 8122 §5): sha-256 or sha-1. - -use std::net::Ipv4Addr; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::crypto::{CryptoProvider, Fingerprint, Sha1Provider}; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Candidate, RtcConfig, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, progress}; - -/// Connects L to R, where L expects R's certificate to have the fingerprint -/// `expected(R's DER certificate)`. Returns L's error, if any. -fn connect(expected: impl Fn(&[u8]) -> Fingerprint) -> Result<(), RtcError> { - connect_with_provider(expected, crate::vendor::str0m::crypto::from_feature_flags()) -} - -fn connect_with_provider(expected: impl Fn(&[u8]) -> Fingerprint, provider: CryptoProvider) -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let cert = provider - .dtls_provider - .generate_certificate() - .expect("the provider generates certificates"); - let finger_r = expected(&cert.certificate); - - let now = Instant::now(); - let provider = Arc::new(provider); - let mut l = TestRtc::new_with_rtc( - info_span!("L"), - RtcConfig::new().set_crypto_provider(provider.clone()).build(now), - ); - let mut r = TestRtc::new_with_rtc( - info_span!("R"), - RtcConfig::new() - .set_crypto_provider(provider) - .set_dtls_cert(cert) - .build(now), - ); - - let host_l = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host_r = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - l.add_local_candidate(host_l.clone()).unwrap(); - l.add_remote_candidate(host_r.clone()); - r.add_local_candidate(host_r).unwrap(); - r.add_remote_candidate(host_l); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - // L is the DTLS client, as towards a media gateway answering `a=setup:passive`. - l.direct_api().start_dtls(true).unwrap(); - r.direct_api().start_dtls(false).unwrap(); - - while !(l.is_connected() && r.is_connected()) { - if l.duration() > Duration::from_secs(5) { - panic!("DTLS did not connect"); - } - progress(&mut l, &mut r)?; - } - Ok(()) -} - -fn reference_sha1(data: &[u8]) -> [u8; 20] { - rind::digest::digest(&rind::digest::legacy::SHA1, data) - .as_ref() - .try_into() - .unwrap() -} - -fn sha1_fingerprint(hash_func: &str, der: &[u8]) -> Fingerprint { - Fingerprint { - hash_func: hash_func.into(), - bytes: reference_sha1(der).to_vec(), - } -} - -#[test] -fn sha1_fingerprint_is_verified() -> Result<(), RtcError> { - connect(|der| sha1_fingerprint("sha-1", der)) -} - -#[test] -fn sha1_fingerprint_uses_configured_provider() -> Result<(), RtcError> { - #[derive(Debug)] - struct TrackingSha1(AtomicUsize); - - impl Sha1Provider for TrackingSha1 { - fn sha1(&self, data: &[u8]) -> [u8; 20] { - self.0.fetch_add(1, Ordering::SeqCst); - reference_sha1(data) - } - } - - static SHA1: TrackingSha1 = TrackingSha1(AtomicUsize::new(0)); - let mut provider = crate::vendor::str0m::crypto::from_feature_flags(); - provider.sha1_provider = &SHA1; - connect_with_provider(|der| sha1_fingerprint("sha-1", der), provider)?; - assert_eq!(SHA1.0.load(Ordering::SeqCst), 1); - Ok(()) -} - -#[test] -fn hash_function_names_are_case_insensitive() -> Result<(), RtcError> { - connect(|der| sha1_fingerprint("SHA-1", der)) -} - -#[test] -fn wrong_sha1_fingerprint_is_rejected() { - let error = connect(|der| { - let mut wrong = sha1_fingerprint("sha-1", der); - wrong.bytes[0] ^= 0xff; - wrong - }) - .unwrap_err(); - assert!(error.to_string().contains("remote fingerprint no match"), "{error}"); -} - -#[test] -fn unsupported_hash_function_is_rejected() { - let error = connect(|_| Fingerprint { - hash_func: "sha-512".into(), - bytes: vec![0; 64], - }) - .unwrap_err(); - assert!( - error - .to_string() - .contains("unsupported fingerprint hash function: sha-512"), - "{error}" - ); -} - -#[test] -fn stronger_fingerprint_mismatch_must_be_rejected() { - init_log(); - init_crypto_default(); - let provider = crate::vendor::str0m::crypto::from_feature_flags(); - let cert = provider.dtls_provider.generate_certificate().unwrap(); - let weak = Fingerprint { - hash_func: "sha-1".into(), - bytes: reference_sha1(&cert.certificate).to_vec(), - }; - let strong = Fingerprint { - hash_func: "sha-256".into(), - bytes: vec![0; 32], - }; - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), RtcConfig::new().build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), RtcConfig::new().set_dtls_cert(cert).build(now)); - l.add_local_candidate(Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap()) - .unwrap(); - r.add_local_candidate(Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap()) - .unwrap(); - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.sdp_api().accept_offer(offer).unwrap(); - let sdp = answer.to_sdp_string(); - let rewritten = sdp - .lines() - .map(|line| { - if line.starts_with("a=fingerprint:") { - format!("a=fingerprint:{weak}\r\na=fingerprint:{strong}\r\n") - } else { - format!("{line}\r\n") - } - }) - .collect::(); - l.sdp_api() - .accept_answer( - pending, - crate::vendor::str0m::change::SdpAnswer::from_sdp_string(&rewritten).unwrap(), - ) - .unwrap(); - while !(l.is_connected() && r.is_connected()) { - assert!(l.duration() < Duration::from_secs(5)); - if let Err(error) = progress(&mut l, &mut r) { - assert!(error.to_string().contains("remote fingerprint no match")); - return; - } - } - panic!("connected despite a mismatched offered SHA-256 fingerprint"); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs deleted file mode 100644 index b01273d3bec..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! Regression test for the DTLS retransmit bug fixed in PR #943 (refs #932). -//! -//! When a DTLS flight timeout elapses, dimpl's `handle_timeout` re-arms the -//! flight timer and queues the retransmit packet. Previously str0m ran -//! `handle_timeout` at the end of `do_poll_output`, after both the DTLS -//! `poll_output` loop and `dtls.poll_packet()` had already run - so the -//! freshly queued retransmit was left sitting in dimpl's tx queue until -//! some unrelated subsystem (typically an ICE consent check) woke the -//! caller for another poll pass. -//! -//! This test drives two peers to the mid-handshake state (L has sent -//! ClientHello, R ignores DTLS so never replies), advances L's clock past -//! the flight deadline with a single `handle_input(Timeout)`, then asserts -//! that a single `poll_output` pass emits the retransmit as a `Transmit`. -//! Without the fix, the pass instead returns `Timeout` and the retransmit -//! is stranded. -//! -//! The scenario asserted here is specific to dimpl's tx-queue semantics, -//! so the test is compiled only under dimpl-backed crypto providers. -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::dimpl::TimeoutError; -use crate::vendor::netem::{NetemConfig, Probability, RandomLoss}; -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::crypto::dtls::DtlsImplError; -use crate::vendor::str0m::crypto::{CryptoError, DtlsError}; -use crate::vendor::str0m::{Candidate, Input, Output, Reason, Rtc}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, progress}; - -#[test] -fn dtls_retransmit_emitted_in_same_poll_pass() { - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::new(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::new(now)); - - let host_l = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host_r = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - l.add_local_candidate(host_l.clone()); - l.add_remote_candidate(host_r.clone()); - r.add_local_candidate(host_r); - r.add_remote_candidate(host_l); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - // Only L starts DTLS. R receives L's ClientHello but ignores it - // (active_state is None in dtls::handle_receive), so L never gets a - // ServerHello and must retransmit. - l.direct_api().start_dtls(true).unwrap(); - - // Drive both sides until L is awaiting the DTLS flight deadline. - let mut steps = 0; - while l.rtc.last_timeout_reason() != Reason::DTLS { - progress(&mut l, &mut r).unwrap(); - steps += 1; - assert!( - steps < 200, - "failed to reach DTLS-awaiting state (last reason: {:?})", - l.rtc.last_timeout_reason() - ); - } - - // Advance past the flight deadline in one step with no network input. - // The fix causes the following poll_output pass to emit the queued - // retransmit. Without the fix, it returns Output::Timeout and the - // retransmit stays stranded in dimpl. - let deadline = l.last + Duration::from_millis(1500); - l.rtc.handle_input(Input::Timeout(deadline)).unwrap(); - - let mut got_transmit = false; - loop { - match l.rtc.poll_output().unwrap() { - Output::Timeout(_) => break, - Output::Transmit(_) => { - got_transmit = true; - break; - } - Output::Event(_) => continue, - } - } - - assert!( - got_transmit, - "poll_output should emit the DTLS retransmit in the same pass that runs handle_timeout" - ); -} - -/// A terminal dimpl handshake timeout must be returned and must leave the -/// `Rtc` inert rather than continually returning the expired DTLS deadline. -/// -/// This runs for every dimpl-backed crypto provider. It drives the scheduler -/// with the exact timeout returned by `Rtc`, which is the behavior that -/// previously caused an immediate-wake loop after dimpl had exhausted its -/// retry budget. -#[test] -fn terminal_dtls_timeout_does_not_rearm_expired_deadline() { - init_crypto_default(); - - let now = Instant::now(); - let left_rtc = Rtc::builder().build(now); - let right_rtc = Rtc::builder().build(now); - let mut left = TestRtc::new_with_rtc(info_span!("L"), left_rtc); - let mut right = TestRtc::new_with_rtc(info_span!("R"), right_rtc); - - // Responses from the passive peer are discarded after it receives the - // client's first flight, so the active peer retries until dimpl times out. - left.set_netem(NetemConfig::new().loss(RandomLoss::new(Probability::new(1.0))).seed(1)); - - let host_left = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host_right = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - left.add_local_candidate(host_left.clone()); - left.add_remote_candidate(host_right.clone()); - right.add_local_candidate(host_right); - right.add_remote_candidate(host_left); - - let fingerprint_left = left.direct_api().local_dtls_fingerprint().clone(); - let fingerprint_right = right.direct_api().local_dtls_fingerprint().clone(); - left.direct_api().set_remote_fingerprint(fingerprint_right); - right.direct_api().set_remote_fingerprint(fingerprint_left); - - let credentials_left = left.direct_api().local_ice_credentials(); - let credentials_right = right.direct_api().local_ice_credentials(); - left.direct_api().set_remote_ice_credentials(credentials_right); - right.direct_api().set_remote_ice_credentials(credentials_left); - - left.direct_api().set_ice_controlling(true); - right.direct_api().set_ice_controlling(false); - left.direct_api().start_dtls(true).unwrap(); - right.direct_api().start_dtls(false).unwrap(); - - // Let the first flight reach the passive peer and its response be dropped. - let mut setup_steps = 0; - while left.rtc.last_timeout_reason() != Reason::DTLS { - progress(&mut left, &mut right).unwrap(); - setup_steps += 1; - assert!( - setup_steps < 200, - "failed to reach a DTLS flight deadline (last reason: {:?})", - left.rtc.last_timeout_reason() - ); - } - - // Unlike TestRtc::progress, preserve an immediate timeout exactly. This - // models a scheduler that runs work scheduled for now without adding a - // retry delay of its own. - let mut last_now = left.last; - let mut terminal_error = None; - for _ in 0..1_000 { - left.rtc.handle_input(Input::Timeout(last_now)).unwrap(); - - loop { - match left.rtc.poll_output() { - Err(RtcError::Dtls(error)) => { - terminal_error = Some(error); - break; - } - Err(error) => panic!("unexpected RTC error: {error}"), - Ok(Output::Timeout(timeout)) => { - last_now = timeout; - break; - } - Ok(Output::Transmit(_)) => { - // Drop each retransmitted DTLS flight. - } - Ok(Output::Event(_)) => { - // ICE may report its disconnected state before DTLS gives up. - } - } - } - - if terminal_error.is_some() { - break; - } - } - - let terminal_error = - terminal_error.expect("terminal dimpl timeout was not returned within the bounded scheduler run"); - // The vendored stack keeps dimpl's typed timeout rather than a string. - assert!( - matches!( - terminal_error, - DtlsError::CryptoError(CryptoError::DtlsImpl(DtlsImplError::Timeout(TimeoutError::Handshake))) - ), - "unexpected terminal DTLS error: {terminal_error:?}" - ); - assert_eq!(terminal_error.to_string(), "DTLS error: timeout: handshake"); - assert!(!left.rtc.is_alive(), "terminal DTLS error must close the RTC"); - - // After the error, callers that continue polling and feeding timeout input - // must not receive another due timeout, packet, or event. - let terminal_last_now = last_now; - for _ in 0..16 { - left.rtc.handle_input(Input::Timeout(terminal_last_now)).unwrap(); - - match left.rtc.poll_output().unwrap() { - Output::Timeout(timeout) => { - assert!( - timeout > terminal_last_now, - "closed RTC returned a timeout at or before its last input" - ); - } - Output::Transmit(_) => panic!("closed RTC produced a DTLS transmission"), - Output::Event(event) => panic!("closed RTC produced an event: {event:?}"), - } - } -} - -/// End-to-end: a DTLS handshake between two peers must complete even -/// when the link drops packets. Before the fix, dropped handshake -/// packets stalled for seconds at a time because each lost flight's -/// retransmit was deferred to the next unrelated wake-up - on a lossy -/// link the handshake could miss its connect deadline entirely. -#[test] -fn dtls_handshake_completes_under_packet_loss() { - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::new(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::new(now)); - - // 30% random loss in both directions from the very first packet. - let lossy = NetemConfig::new().loss(RandomLoss::new(Probability::new(0.3))).seed(1); - l.set_netem(lossy); - r.set_netem(lossy); - - let host_l = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); - let host_r = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap(); - l.add_local_candidate(host_l.clone()); - l.add_remote_candidate(host_r.clone()); - r.add_local_candidate(host_r); - r.add_remote_candidate(host_l); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - l.direct_api().start_dtls(true).unwrap(); - r.direct_api().start_dtls(false).unwrap(); - - // Drive both sides forward. The DTLS default connect timeout is 10s, - // so a bounded iteration cap that allows well past that is enough to - // tell whether the handshake is making progress at all. - let mut iterations = 0; - while !(l.is_connected() && r.is_connected()) { - progress(&mut l, &mut r).unwrap(); - iterations += 1; - assert!( - iterations < 5000, - "DTLS handshake did not complete under 30% packet loss \ - (l_connected={}, r_connected={})", - l.is_connected(), - r.is_connected() - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs deleted file mode 100644 index 4ec43879022..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! Tests for DTLS handshake edge cases and security. - -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::media::{Direction, MediaKind}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -/// Test certificate fingerprint format and uniqueness. -#[test] -fn dtls_certificate_fingerprint_format() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Create two instances and verify they have different certificates - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Get fingerprints - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - - // Fingerprints should be different for different instances - assert_ne!( - finger_l, finger_r, - "Different Rtc instances should have different certificates" - ); - - // Fingerprint should be properly formatted (SHA-256 format) - let finger_str = format!("{}", finger_l); - assert!( - finger_str.starts_with("sha-256 ") || finger_str.contains(':'), - "Fingerprint should be in SHA-256 format: {}", - finger_str - ); - - Ok(()) -} - -/// Test that new Rtc instances get new certificates. -#[test] -fn dtls_certificate_rotation() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Create first connection using L/R peers (respects L_CRYPTO/R_CRYPTO env vars) - let mut l1 = TestRtc::new(Peer::Left); - let mut r1 = TestRtc::new(Peer::Right); - - let finger1_l = l1.direct_api().local_dtls_fingerprint().clone(); - let finger1_r = r1.direct_api().local_dtls_fingerprint().clone(); - - // Create second connection with new certificates - let mut l2 = TestRtc::new(Peer::Left); - let mut r2 = TestRtc::new(Peer::Right); - - let finger2_l = l2.direct_api().local_dtls_fingerprint().clone(); - let finger2_r = r2.direct_api().local_dtls_fingerprint().clone(); - - // All fingerprints should be unique - assert_ne!(finger1_l, finger1_r, "L1 and R1 should differ"); - assert_ne!(finger2_l, finger2_r, "L2 and R2 should differ"); - assert_ne!(finger1_l, finger2_l, "L1 and L2 should differ"); - assert_ne!(finger1_r, finger2_r, "R1 and R2 should differ"); - - Ok(()) -} - -/// Test DTLS connection with ice-lite mode (passive role). -#[test] -fn dtls_with_ice_lite() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - - // R is ice-lite (typically server-side), but still use Peer::Right crypto provider - let mut rtc_r_builder = Rtc::builder().set_ice_lite(true); - if let Some(crypto) = Peer::Right.crypto_provider() { - rtc_r_builder = rtc_r_builder.set_crypto_provider(crypto); - } - let mut r = TestRtc::new_with_rtc(Peer::Right.span(), rtc_r_builder.build(Instant::now())); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with ice-lite"); - } - progress(&mut l, &mut r)?; - } - - Ok(()) -} - -/// Test pregenerated DTLS certificate. -#[test] -fn dtls_pregenerated_certificate() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Generate a certificate using Peer::Left's crypto provider if set - let provider = Peer::Left - .crypto_provider() - .unwrap_or_else(|| std::sync::Arc::new(crate::vendor::str0m::crypto::from_feature_flags())); - let cert = provider.dtls_provider.generate_certificate().unwrap(); - - // Use the pregenerated certificate with the same crypto provider - let mut rtc_l_builder = Rtc::builder().set_dtls_cert(cert); - if let Some(crypto) = Peer::Left.crypto_provider() { - rtc_l_builder = rtc_l_builder.set_crypto_provider(crypto); - } - - let mut l = TestRtc::new_with_rtc(Peer::Left.span(), rtc_l_builder.build(Instant::now())); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with pregenerated certificate"); - } - progress(&mut l, &mut r)?; - } - - Ok(()) -} - -/// Test that same pregenerated certificate produces same fingerprint. -#[test] -fn dtls_pregenerated_certificate_same_fingerprint() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Generate a certificate using Peer::Left's crypto provider if set - let provider = Peer::Left - .crypto_provider() - .unwrap_or_else(|| std::sync::Arc::new(crate::vendor::str0m::crypto::from_feature_flags())); - let cert = provider.dtls_provider.generate_certificate().unwrap(); - let cert_clone = cert.clone(); - - // Create two instances with the same certificate - let mut rtc1_builder = Rtc::builder().set_dtls_cert(cert); - let mut rtc2_builder = Rtc::builder().set_dtls_cert(cert_clone); - if let Some(crypto) = Peer::Left.crypto_provider() { - rtc1_builder = rtc1_builder.set_crypto_provider(crypto.clone()); - rtc2_builder = rtc2_builder.set_crypto_provider(crypto); - } - - let mut l1 = TestRtc::new_with_rtc(Peer::Left.span(), rtc1_builder.build(Instant::now())); - let mut l2 = TestRtc::new_with_rtc(Peer::Left.span(), rtc2_builder.build(Instant::now())); - - let finger1 = l1.direct_api().local_dtls_fingerprint().clone(); - let finger2 = l2.direct_api().local_dtls_fingerprint().clone(); - - // Same certificate should produce same fingerprint - assert_eq!(finger1, finger2, "Same certificate should produce same fingerprint"); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/early-rtx-padding.rs b/rs/moq-webrtc/src/vendor/str0m/tests/early-rtx-padding.rs deleted file mode 100644 index aadcc46acac..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/early-rtx-padding.rs +++ /dev/null @@ -1,361 +0,0 @@ -//! Early simulcast RTX padding must receive transport feedback before its main SSRC is known. -//! -//! Negotiate and connect real peers, then inject encrypted packets through `Rtc::handle_input`. -//! Known test keys let us cover each SRTP profile and authenticate deliberately malformed payloads. - -use std::net::{Ipv4Addr, SocketAddr}; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::change::SdpOffer; -use crate::vendor::str0m::crypto::dtls::{KeyingMaterial, SrtpProfile}; -use crate::vendor::str0m::media::{Direction, MediaKind, Mid, Simulcast, SimulcastLayer}; -use crate::vendor::str0m::net::{Protocol, Receive}; -use crate::vendor::str0m::rtp::rtcp::Rtcp; -use crate::vendor::str0m::rtp::{ExtensionMap, ExtensionValues, RawPacket, RtpHeader}; -use crate::vendor::str0m::{Event, Input, Output}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -const RTX_SSRC: u32 = 426592647; -const MAIN_SSRC: u32 = 2869047233; -const L_ADDR: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 1000); -const R_ADDR: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(2, 2, 2, 2)), 2000); -const FEEDBACK_WAIT: Duration = Duration::from_millis(50); - -#[test] -fn authenticated_padding_is_reported_before_main_ssrc_discovery() { - for profile in [ - SrtpProfile::AES128_CM_SHA1_80, - SrtpProfile::AEAD_AES_128_GCM, - SrtpProfile::AEAD_AES_256_GCM, - ] { - for rtp_mode in [false, true] { - let (mut receiver, mut srtp, mid) = receiver(rtp_mode, profile); - // Cross RTP rollover, reorder two packets, and vary the padding PT. - let receipts = [(65534, 40), (65535, 41), (65537, 43), (65536, 42), (65540, 44)]; - for (seq, twcc) in receipts { - let mut header = header(mid, true, seq as u16, twcc); - if twcc == 40 { - header.payload_type = 96.into(); - } - let packet = protect(&receiver, &mut srtp, header, seq, &[0, 0, 0, 4]); - inject(&mut receiver, &packet); - inject(&mut receiver, &packet); - } - - advance(&mut receiver, FEEDBACK_WAIT); - let received = feedback(&receiver); - let expected = [(40, true), (41, true), (42, true), (43, true), (44, true)]; - assert_eq!(received, expected); - assert_eq!(raw_receipts(&receiver), 5, "replays must be rejected"); - assert_no_stream(&mut receiver, mid); - - for (_, event) in &receiver.events { - match event { - Event::MediaData(_) | Event::RtpPacket(_) | Event::StreamPaused(_) => { - panic!("early padding emitted media: {event:?}") - } - _ => {} - } - } - } - } -} - -#[test] -fn failed_authentication_and_invalid_padding_are_not_reported_received() { - let (mut receiver, mut srtp, mid) = receiver(true, SrtpProfile::AEAD_AES_128_GCM); - let forged_header = header(mid, true, 65530, 39); - let mut forged = protect(&receiver, &mut srtp, forged_header, 65530, &[0, 0, 0, 4]); - *forged.last_mut().unwrap() ^= 1; - inject(&mut receiver, &forged); - advance(&mut receiver, FEEDBACK_WAIT); - assert!(feedback(&receiver).is_empty()); - assert_eq!(raw_receipts(&receiver), 0); - - // The forged high sequence number must not advance the ROC used to decrypt these packets. - for twcc in 40..=43 { - let header = header(mid, true, twcc, twcc); - let payload: &[u8] = if twcc == 42 { &[2] } else { &[0, 0, 0, 4] }; - let mut packet = protect(&receiver, &mut srtp, header, twcc as u64, payload); - if twcc == 41 { - *packet.last_mut().unwrap() ^= 1; - } - inject(&mut receiver, &packet); - } - advance(&mut receiver, FEEDBACK_WAIT); - let received = feedback(&receiver); - // Input processing can send a report immediately, splitting the valid receipts - // across reports. Missing numbers need not appear in either report's range. - let received: Vec<_> = received.into_iter().filter(|(_, received)| *received).collect(); - assert_eq!(received, [(40, true), (43, true)]); - assert_eq!(raw_receipts(&receiver), 2); - assert_no_stream(&mut receiver, mid); -} - -#[test] -fn invalid_or_nonpadding_packets_do_not_create_receive_history() { - let (mut receiver, mut srtp, mid) = receiver(true, SrtpProfile::AEAD_AES_128_GCM); - for case in 0..6 { - let mut header = header(mid, true, 100, 40); - match case { - 0 => header.ext_vals.mid = None, - 1 => header.ext_vals.mid = Some("unknown".into()), - 2 => header.ext_vals.rid_repair = Some("unknown".into()), - 3 => header.payload_type = 127.into(), - 4 => header.has_padding = false, - 5 => {} - _ => unreachable!(), - } - let media: &[u8] = &[0, 101, 0, 1]; - let padding: &[u8] = &[0, 0, 0, 4]; - let payload = if case == 5 { media } else { padding }; - let packet = protect(&receiver, &mut srtp, header, 100, payload); - inject(&mut receiver, &packet); - } - advance(&mut receiver, FEEDBACK_WAIT); - assert!(feedback(&receiver).is_empty()); - assert_eq!(raw_receipts(&receiver), 0); - assert_no_stream(&mut receiver, mid); - - // A valid packet with the same sequence number must still be accepted: none of the - // rejected packets may consume its place in the replay window. - let header = header(mid, true, 100, 40); - let packet = protect(&receiver, &mut srtp, header, 100, &[0, 0, 0, 4]); - inject(&mut receiver, &packet); - advance(&mut receiver, FEEDBACK_WAIT); - assert_eq!(feedback(&receiver), [(40, true)]); - assert_eq!(raw_receipts(&receiver), 1); -} - -#[test] -fn main_discovery_preserves_rtx_rollover_and_replay_protection() { - let (mut receiver, mut srtp, mid) = receiver(true, SrtpProfile::AEAD_AES_128_GCM); - let mut early = header(mid, true, 65535, 40); - early.payload_type = 96.into(); - let early_packet = protect(&receiver, &mut srtp, early, 65535, &[0, 0, 0, 4]); - inject(&mut receiver, &early_packet); - assert_no_stream(&mut receiver, mid); - - let main = header(mid, false, 100, 41); - let main_packet = protect(&receiver, &mut srtp, main, 100, &[0x10, 1, 2, 3]); - inject(&mut receiver, &main_packet); - drain(&mut receiver); - assert_media_packets(&receiver, &[(100, &[0x10, 1, 2, 3])]); - - // A delayed padding packet below the early high-water mark must still count. - let delayed = header(mid, true, 65534, 39); - let delayed_packet = protect(&receiver, &mut srtp, delayed, 65534, &[0, 0, 0, 4]); - let raw_count = raw_receipts(&receiver); - inject(&mut receiver, &delayed_packet); - inject(&mut receiver, &delayed_packet); - drain(&mut receiver); - assert_eq!(raw_receipts(&receiver), raw_count + 1); - assert_media_packets(&receiver, &[(100, &[0x10, 1, 2, 3])]); - - let mut repair = header(mid, true, 0, 42); - repair.has_padding = false; - let payload = &[0, 101, 0x10, 4, 5, 6]; - let packet = protect(&receiver, &mut srtp, repair, 65536, payload); - inject(&mut receiver, &packet); - drain(&mut receiver); - let raw_count = raw_receipts(&receiver); - inject(&mut receiver, &early_packet); - advance(&mut receiver, FEEDBACK_WAIT); - assert_eq!(raw_receipts(&receiver), raw_count); - let expected: &[(u64, &[u8])] = &[(100, &[0x10, 1, 2, 3]), (101, &[0x10, 4, 5, 6])]; - assert_media_packets(&receiver, expected); - let received = feedback(&receiver); - assert_eq!(received, [(39, true), (40, true), (41, true), (42, true)]); -} - -fn receiver(rtp_mode: bool, profile: SrtpProfile) -> (TestRtc, TestSrtp, Mid) { - init_log(); - init_crypto_default(); - let configure = |config: crate::vendor::str0m::RtcConfig| { - config - .clear_codecs() - .enable_vp8(true) - .set_rtp_mode(rtp_mode) - .set_reordering_size_video(0) - .enable_raw_packets(true) - }; - let mut sender = TestRtc::new_with_config(Peer::Left, configure); - let mut receiver = TestRtc::new_with_config(Peer::Right, configure); - sender.add_host_candidate(L_ADDR); - receiver.add_host_candidate(R_ADDR); - let mut simulcast = Simulcast::new(); - for rid in ["l", "m", "h"] { - simulcast.add_send_layer(SimulcastLayer::new(rid)); - } - let mut change = sender.sdp_api(); - let kind = MediaKind::Video; - let direction = Direction::SendOnly; - let mid = change.add_media(kind, direction, None, None, Some(simulcast)); - let (offer, pending) = change.apply().unwrap(); - // Browsers can leave SSRC discovery entirely to MID/RID header extensions. - let sdp = offer - .to_sdp_string() - .lines() - .filter(|l| !l.starts_with("a=ssrc")) - .collect::>() - .join("\r\n"); - let offer = SdpOffer::from_sdp_string(&(sdp + "\r\n")).unwrap(); - let answer = receiver.sdp_api().accept_offer(offer).unwrap(); - sender.sdp_api().accept_answer(pending, answer).unwrap(); - while !sender.is_connected() || !receiver.is_connected() { - let timed_out = sender.duration() >= Duration::from_secs(10); - assert!(!timed_out, "failed to connect"); - progress(&mut sender, &mut receiver).unwrap(); - } - - // ICE and DTLS establish a real transport. Replace only the SRTP keys so the packet - // fixture can exercise every supported profile without depending on DTLS preference order. - let len = match profile { - SrtpProfile::AES128_CM_SHA1_80 => 60, - SrtpProfile::AEAD_AES_128_GCM => 56, - SrtpProfile::AEAD_AES_256_GCM => 88, - _ => unreachable!(), - }; - let crypto = crate::vendor::str0m::crypto::from_feature_flags(); - let material = KeyingMaterial::new(&vec![42; len]); - let srtp = TestSrtp::new(&crypto, profile, &material); - let crypto_provider = receiver.rtc.crypto_provider.clone(); - receiver - .rtc - .session - .set_keying_material(material, &crypto_provider, profile, false); - drain(&mut receiver); - receiver.events.clear(); - assert_no_stream(&mut receiver, mid); - (receiver, srtp, mid) -} - -fn header(mid: Mid, repair: bool, seq: u16, twcc: u16) -> RtpHeader { - let ssrc = if repair { RTX_SSRC } else { MAIN_SSRC }; - RtpHeader { - has_extension: true, - has_padding: repair, - marker: true, - ssrc: ssrc.into(), - payload_type: if repair { 97.into() } else { 96.into() }, - sequence_number: seq, - timestamp: 3000, - ext_vals: ExtensionValues { - mid: Some(mid), - rid: (!repair).then(|| "h".into()), - rid_repair: repair.then(|| "h".into()), - transport_cc: Some(twcc), - ..Default::default() - }, - ..Default::default() - } -} - -fn protect(receiver: &TestRtc, srtp: &mut TestSrtp, header: RtpHeader, seq: u64, payload: &[u8]) -> Vec { - srtp.protect(header, seq, payload, &receiver.rtc.session.exts) -} - -/// Construct authenticated RTP packets with controlled headers and payloads. -struct TestSrtp(crate::vendor::str0m::rtp_::SrtpContext); - -impl TestSrtp { - /// Use the same keys and profile as the test receiver's incoming SRTP context. - fn new(crypto: &crate::vendor::str0m::crypto::CryptoProvider, profile: SrtpProfile, mat: &KeyingMaterial) -> Self { - Self(crate::vendor::str0m::rtp_::SrtpContext::new(crypto, profile, mat, true)) - } - - /// Serialize and encrypt a supplied packet, including deliberately malformed payloads. - fn protect(&mut self, mut header: RtpHeader, seq: u64, payload: &[u8], exts: &ExtensionMap) -> Vec { - let mut buf = vec![0; 1500]; - let header_len = header.write_to(&mut buf, exts); - buf[header_len..header_len + payload.len()].copy_from_slice(payload); - header.header_len = header_len; - let packet = &buf[..header_len + payload.len()]; - self.0.protect_rtp(packet, &header, seq) - } -} - -fn inject(receiver: &mut TestRtc, packet: &[u8]) { - let receive = Receive { - proto: Protocol::Udp, - source: L_ADDR, - destination: R_ADDR, - contents: packet.try_into().unwrap(), - }; - let input = Input::Receive(receiver.last, receive); - receiver.handle_input(input).unwrap(); -} - -/// Follow the timeouts requested by `Rtc` so missing feedback scheduling fails the test. -fn advance(receiver: &mut TestRtc, duration: Duration) { - let end = receiver.last + duration; - loop { - let next = drain(receiver); - if next > end { - break; - } - receiver.last = next.max(receiver.last); - let input = Input::Timeout(receiver.last); - receiver.handle_input(input).unwrap(); - } -} - -fn drain(receiver: &mut TestRtc) -> Instant { - loop { - match receiver.poll_output().unwrap() { - Output::Event(event) => receiver.events.push((receiver.last, event)), - Output::Transmit(_) => {} - Output::Timeout(next) => return next, - } - } -} - -fn feedback(receiver: &TestRtc) -> Vec<(u64, bool)> { - let mut received = Vec::new(); - for (_, event) in &receiver.events { - match event.as_raw_packet() { - Some(RawPacket::RtcpTx(Rtcp::Twcc(twcc))) => { - let receipts = twcc.clone().into_iter(receiver.start, 0.into()); - let statuses = receipts.map(|(seq, _, received)| (*seq, received.is_some())); - received.extend(statuses); - } - Some(RawPacket::RtcpTx(Rtcp::Nack(_))) => panic!("padding caused NACK feedback"), - _ => {} - } - } - // Reordering can cause overlapping TWCC reports. Keep distinct statuses so any - // incorrect loss report remains visible, but do not count an identical report twice. - received.sort_unstable(); - received.dedup(); - received -} - -fn raw_receipts(receiver: &TestRtc) -> usize { - receiver - .events - .iter() - .filter(|(_, event)| matches!(event.as_raw_packet(), Some(RawPacket::RtpRx(_, _)))) - .count() -} - -fn assert_no_stream(receiver: &mut TestRtc, mid: Mid) { - let mut direct = receiver.direct_api(); - assert!(direct.stream_rx_by_mid(mid, Some("h".into())).is_none()); -} - -fn assert_media_packets(receiver: &TestRtc, expected: &[(u64, &[u8])]) { - let packets: Vec<_> = receiver - .events - .iter() - .filter_map(|(_, event)| { - let Event::RtpPacket(packet) = event else { - return None; - }; - assert_eq!(packet.header.ssrc, MAIN_SSRC.into()); - Some((*packet.seq_no, &*packet.payload)) - }) - .collect(); - assert_eq!(packets, expected); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs b/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs deleted file mode 100644 index 84f944de688..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs +++ /dev/null @@ -1,60 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::RtcConfig; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn flappy_ice_lite_state() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - - let rtc = RtcConfig::new().set_ice_lite(true).build(Instant::now()); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - loop { - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(120) { - break; - } - } - - let ice_events = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::IceConnectionStateChange(_))) - .count(); - - assert!(ice_events < 10); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs deleted file mode 100644 index d89eb6cf25b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs +++ /dev/null @@ -1,415 +0,0 @@ -//! Tests for ICE candidate handling and configuration. - -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::RtcConfig; -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::ice::IceCreds; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -/// Test connection with only host candidates. -#[test] -fn ice_candidate_types_host_only() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - // Add only host candidates (no srflx or relay) - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - // Should connect using host candidates - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with host-only candidates"); - } - progress(&mut l, &mut r)?; - } - - Ok(()) -} - -/// Test custom ICE credentials via set_local_ice_credentials(). -#[test] -fn ice_custom_credentials() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let custom_creds = IceCreds { - ufrag: "customufrag123".into(), - pass: "custompassword456789012".into(), - }; - - let rtc = RtcConfig::new() - .set_local_ice_credentials(custom_creds.clone()) - .build(Instant::now()); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Verify custom credentials are used - let actual_creds = l._local_ice_creds(); - assert_eq!(actual_creds.ufrag, custom_creds.ufrag, "Custom ufrag should be used"); - assert_eq!(actual_creds.pass, custom_creds.pass, "Custom password should be used"); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - // Verify custom ufrag appears in offer SDP - let offer_str = offer.to_string(); - assert!( - offer_str.contains(&custom_creds.ufrag), - "Offer SDP should contain custom ufrag" - ); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with custom credentials"); - } - progress(&mut l, &mut r)?; - } - - Ok(()) -} - -/// Test set_initial_stun_rto() configuration by measuring retransmission timing. -/// Uses a short RTO and verifies retransmissions happen at the expected interval. -#[test] -fn ice_stun_timeout_initial_rto() -> Result<(), RtcError> { - use crate::vendor::str0m::Output; - - init_log(); - init_crypto_default(); - - // Set a short initial RTO of 50ms (default is 250ms) - let custom_rto = Duration::from_millis(50); - let mut config = RtcConfig::new(); - config.set_initial_stun_rto(custom_rto); - let start = Instant::now(); - let rtc = config.build(start); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - let mut r = TestRtc::new(Peer::Right); - - // Sync TestRtc time with Rtc creation time - l.start = start; - l.last = start; - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Set up SDP exchange - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - // Track transmit times from L only (don't deliver to R, so L will retransmit) - let mut transmit_times: Vec = Vec::new(); - - // Progress L only, capture STUN transmit times - for _ in 0..30 { - l.rtc - .handle_input(crate::vendor::str0m::Input::Timeout(l.last)) - .unwrap(); - - loop { - match l.rtc.poll_output()? { - Output::Transmit(_) => { - transmit_times.push(l.last); - } - Output::Timeout(t) => { - l.last = t; - break; - } - Output::Event(_) => {} - } - } - - // Stop once we have enough samples - if transmit_times.len() >= 3 { - break; - } - } - - assert!( - transmit_times.len() >= 2, - "Should have at least 2 STUN transmissions, got {}", - transmit_times.len() - ); - - // Check the interval between first and second transmit matches initial RTO - let first_interval = transmit_times[1].duration_since(transmit_times[0]); - - // Allow some tolerance (35-65ms for 50ms RTO) - let min_expected = custom_rto - Duration::from_millis(15); - let max_expected = custom_rto + Duration::from_millis(15); - - assert!( - first_interval >= min_expected && first_interval <= max_expected, - "First retransmit interval should be ~{}ms (initial RTO), got {}ms", - custom_rto.as_millis(), - first_interval.as_millis() - ); - - Ok(()) -} - -/// Test set_max_stun_rto() configuration by verifying retransmit intervals are capped. -#[test] -fn ice_stun_timeout_max_rto() -> Result<(), RtcError> { - use crate::vendor::str0m::Output; - - init_log(); - init_crypto_default(); - - // Set initial RTO to 100ms and max RTO to 150ms - // Without max cap, RTO would double: 100 -> 200 -> 400... - // With max 150ms, it should cap at: 100 -> 150 -> 150... - let initial_rto = Duration::from_millis(100); - let max_rto = Duration::from_millis(150); - - let mut config = RtcConfig::new(); - config.set_initial_stun_rto(initial_rto); - config.set_max_stun_rto(max_rto); - let start = Instant::now(); - let rtc = config.build(start); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - let mut r = TestRtc::new(Peer::Right); - - // Sync TestRtc time with Rtc creation time - l.start = start; - l.last = start; - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - // Track transmit times from L only (don't deliver to R) - let mut transmit_times: Vec = Vec::new(); - - for _ in 0..50 { - l.rtc - .handle_input(crate::vendor::str0m::Input::Timeout(l.last)) - .unwrap(); - - loop { - match l.rtc.poll_output()? { - Output::Transmit(_) => { - transmit_times.push(l.last); - } - Output::Timeout(t) => { - l.last = t; - break; - } - Output::Event(_) => {} - } - } - - if transmit_times.len() >= 4 { - break; - } - } - - assert!( - transmit_times.len() >= 4, - "Should have at least 4 transmissions, got {}", - transmit_times.len() - ); - - // Check intervals - first should be ~100ms, subsequent should be capped at ~150ms - let interval_1_2 = transmit_times[1].duration_since(transmit_times[0]); - let interval_2_3 = transmit_times[2].duration_since(transmit_times[1]); - let interval_3_4 = transmit_times[3].duration_since(transmit_times[2]); - - // First interval should be around initial RTO (100ms) - assert!( - interval_1_2 >= Duration::from_millis(85) && interval_1_2 <= Duration::from_millis(115), - "First interval should be ~100ms (initial RTO), got {}ms", - interval_1_2.as_millis() - ); - - // Later intervals should be capped at max RTO (150ms), not doubled (200ms) - // Allow tolerance for timing - let max_allowed = max_rto + Duration::from_millis(20); - assert!( - interval_2_3 <= max_allowed, - "Second interval should be capped at ~{}ms (max RTO), got {}ms", - max_rto.as_millis(), - interval_2_3.as_millis() - ); - assert!( - interval_3_4 <= max_allowed, - "Third interval should be capped at ~{}ms (max RTO), got {}ms", - max_rto.as_millis(), - interval_3_4.as_millis() - ); - - Ok(()) -} - -/// Test set_max_stun_retransmits() configuration by counting actual retransmissions. -#[test] -fn ice_stun_max_retransmits() -> Result<(), RtcError> { - use crate::vendor::str0m::Output; - - init_log(); - init_crypto_default(); - - // Set max retransmits to 3 (default is 9) and short RTOs for faster test - let max_retransmits = 3; - let mut config = RtcConfig::new(); - config.set_max_stun_retransmits(max_retransmits); - config.set_initial_stun_rto(Duration::from_millis(20)); - config.set_max_stun_rto(Duration::from_millis(40)); - let start = Instant::now(); - let rtc = config.build(start); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc); - let mut r = TestRtc::new(Peer::Right); - - // Sync TestRtc time with Rtc creation time - l.start = start; - l.last = start; - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - // Count transmissions from L (without delivering to R) - let mut transmit_count = 0; - - for _ in 0..100 { - l.rtc - .handle_input(crate::vendor::str0m::Input::Timeout(l.last)) - .unwrap(); - - loop { - match l.rtc.poll_output()? { - Output::Transmit(_) => { - transmit_count += 1; - } - Output::Timeout(t) => { - l.last = t; - break; - } - Output::Event(_) => {} - } - } - - // Give enough time for all retransmits to happen - if l.duration() > Duration::from_millis(500) { - break; - } - } - - // With max_retransmits=3, we should see limited retransmissions - // The exact count depends on implementation details, but should be bounded - // Key verification: count should be <= max_retransmits + 1 (initial + retransmits) - let expected_max = max_retransmits + 1 + 2; // +2 for timing tolerance - - assert!( - transmit_count <= expected_max, - "Transmit count should be bounded by max_retransmits setting. \ - Expected at most {} (initial + {} retransmits + tolerance), got {}", - expected_max, - max_retransmits, - transmit_count - ); - - // Should have at least some transmissions - assert!( - transmit_count >= 2, - "Should have at least 2 transmissions (initial + at least 1 retransmit), got {}", - transmit_count - ); - - Ok(()) -} - -/// Test ICE lite mode connectivity. -#[test] -fn ice_lite_mode() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let rtc = RtcConfig::new().set_ice_lite(true).build(Instant::now()); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with ICE lite"); - } - progress(&mut l, &mut r)?; - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs deleted file mode 100644 index e92c1b4dbcc..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs +++ /dev/null @@ -1,55 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::netem::NetemConfig; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, IceConnectionState, RtcConfig, RtcError}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn ice_lite_premature_disconnect() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - - let rtc = RtcConfig::new().set_ice_lite(true).build(Instant::now()); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc); - - r.set_netem(NetemConfig::new().latency(Duration::from_millis(5))); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.sdp_api().accept_offer(offer)?; - l.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.duration() > Duration::from_secs(5) { - panic!("Timeout waiting for connection"); - } - - let r_disconnected = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::IceConnectionStateChange(IceConnectionState::Disconnected))); - - if r_disconnected { - panic!("ICE-lite peer disconnected before receiving binding requests"); - } - - if l.is_connected() && r.is_connected() { - break; - } - - progress(&mut l, &mut r)?; - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs deleted file mode 100644 index ecbadb5a2ea..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs +++ /dev/null @@ -1,79 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::netem::NetemConfig; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, IceConnectionState, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -/// Test that candidate pairs are kept alive based on incoming binding requests, -/// even when outgoing binding requests are not being responded to. -/// -/// This specifically tests the fix for issue #846 where Chrome v144+ would cause -/// disconnections when not using ICE Lite mode. The fix ensures that -/// `is_still_possible()` considers recently received binding requests as evidence -/// of connectivity, similar to how ICE Lite mode works. -#[test] -pub fn pair_kept_alive_by_remote_binding_requests() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Create two non-ICE-lite peers - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - // Add some latency to simulate real network conditions - l.set_netem(NetemConfig::new().latency(Duration::from_millis(10))); - r.set_netem(NetemConfig::new().latency(Duration::from_millis(10))); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.sdp_api().accept_offer(offer)?; - l.sdp_api().accept_answer(pending, answer)?; - - // First, establish the connection - loop { - if l.duration() > Duration::from_secs(5) { - panic!("Timeout waiting for initial connection"); - } - - if l.is_connected() && r.is_connected() { - break; - } - - progress(&mut l, &mut r)?; - } - - // Now continue running for a while to ensure the connection stays stable - // This tests that the pairs are not prematurely pruned - let stable_start = l.duration(); - loop { - if l.duration() - stable_start > Duration::from_secs(3) { - // Connection remained stable for 3 seconds - break; - } - - let l_disconnected = l - .events - .iter() - .any(|(_, e)| matches!(e, Event::IceConnectionStateChange(IceConnectionState::Disconnected))); - let r_disconnected = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::IceConnectionStateChange(IceConnectionState::Disconnected))); - - if l_disconnected || r_disconnected { - panic!("Connection was unexpectedly disconnected during stability test"); - } - - progress(&mut l, &mut r)?; - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs deleted file mode 100644 index 40b012f3697..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs +++ /dev/null @@ -1,87 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::RtcConfig; -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn ice_restart() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - - let rtc = RtcConfig::new().set_ice_lite(true).build(Instant::now()); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - - change.apply().unwrap() - }); - println!("L Initial Offer: {}", offer); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - println!("R Initial answer: {}", answer); - - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let l_creds = l._local_ice_creds(); - let r_creds = r._local_ice_creds(); - - let (offer, pending) = r.span.in_scope(|| { - let mut change = r.rtc.sdp_api(); - change.ice_restart(true); - - change.apply().expect("Should be able to apply changes") - }); - println!("R Offer: {}", offer); - - let answer = l.span.in_scope(|| l.rtc.sdp_api().accept_offer(offer))?; - println!("L Answer: {}", answer); - r.span.in_scope(|| r.rtc.sdp_api().accept_answer(pending, answer))?; - - assert!(!l.rtc.is_connected()); - assert!(!r.rtc.is_connected()); - - loop { - if l.duration() > Duration::from_secs(10) { - panic!("Failed to re-establish connectivity after ICE restart in 10 seconds"); - } - - if l.is_connected() && r.is_connected() { - break; - } - - progress(&mut l, &mut r)?; - } - - assert_ne!( - r_creds, - r._local_ice_creds(), - "After an ICE restart ICE credentials should have changed" - ); - assert_ne!( - l_creds, - l._local_ice_creds(), - "After an ICE restart ICE credentials should have changed" - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/idle-rtc.rs b/rs/moq-webrtc/src/vendor/str0m/tests/idle-rtc.rs deleted file mode 100644 index 053582e928a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/idle-rtc.rs +++ /dev/null @@ -1,53 +0,0 @@ -use std::time::{Duration, Instant}; - -use crate::vendor::is::IceConnectionState; -use crate::vendor::str0m::{Event, Input, Output, Rtc, RtcError}; - -/// Create an RTC instance, but only update its time, without feeding it any input. -/// It should not create any output, busy-loop, or error out. -#[test] -pub fn idle_rtc_instance() -> Result<(), RtcError> { - const ITERATIONS: usize = 50; - const SPIN_THRESHOLD: usize = 2; - const MAX_ADVANCE: Duration = Duration::from_secs(60 * 10); - - let mut next_time = Instant::now(); - let mut spin_count = 0; - let mut rtc = Rtc::new(next_time); - - for i in 1..(ITERATIONS + 1) { - rtc.handle_input(Input::Timeout(next_time))?; - 'poll_loop: loop { - match rtc.poll_output()? { - Output::Timeout(t) => { - if t <= next_time { - spin_count += 1; - if spin_count >= SPIN_THRESHOLD { - panic!("Rtc instance is spinning since iteration {}", i - (SPIN_THRESHOLD - 1)); - } - } else { - spin_count = 0; - } - - // Don't advance time too far. - // We're especially mindful of the `not_happening()` timeout, although we can't - // access that from this test. - let to_next = t.saturating_duration_since(next_time); - next_time = if to_next > MAX_ADVANCE { - next_time + MAX_ADVANCE - } else { - t - }; - - break 'poll_loop; - } - Output::Event(Event::IceConnectionStateChange(IceConnectionState::Checking)) => { - // We'll allow this one. - } - output => panic!("Unexpected output {output:?} at iteration {i}"), - } - } - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/keyframe-requests.rs b/rs/moq-webrtc/src/vendor/str0m/tests/keyframe-requests.rs deleted file mode 100644 index 57b77587cf8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/keyframe-requests.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! Tests for PLI/FIR keyframe request handling. - -use std::net::Ipv4Addr; - -use crate::vendor::str0m::media::{Direction, KeyframeRequestKind, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// Test PLI (Picture Loss Indication) request is sent and received. -#[test] -fn keyframe_request_pli() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // L sends video to R - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Send video from L - let params = l.params_vp8(); - let pt = params.pt(); - - for i in 0..20 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid) - .unwrap() - .write(pt, wallclock, time, vec![0x10, 0x00, 0x00, i as u8])?; - progress(&mut l, &mut r)?; - } - - // R requests a keyframe via PLI - if let Some(mut writer) = r.writer(mid) { - if writer.is_request_keyframe_possible(KeyframeRequestKind::Pli) { - writer.request_keyframe(None, KeyframeRequestKind::Pli)?; - } - } - - // Progress until L receives the keyframe request - let mut found_keyframe_request = false; - for _ in 0..100 { - progress(&mut l, &mut r)?; - - for (_, event) in &l.events { - if let Event::KeyframeRequest(req) = event { - if req.mid == mid && req.kind == KeyframeRequestKind::Pli { - found_keyframe_request = true; - break; - } - } - } - - if found_keyframe_request { - break; - } - } - - assert!(found_keyframe_request, "L should receive a PLI keyframe request from R"); - - Ok(()) -} - -/// Test FIR (Full Intra Request) is sent and received. -#[test] -fn keyframe_request_fir() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Send video from L - let params = l.params_vp8(); - let pt = params.pt(); - - for i in 0..20 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid) - .unwrap() - .write(pt, wallclock, time, vec![0x10, 0x00, 0x00, i as u8])?; - progress(&mut l, &mut r)?; - } - - // R requests a keyframe via FIR - if let Some(mut writer) = r.writer(mid) { - if writer.is_request_keyframe_possible(KeyframeRequestKind::Fir) { - writer.request_keyframe(None, KeyframeRequestKind::Fir)?; - } - } - - let mut found_keyframe_request = false; - for _ in 0..100 { - progress(&mut l, &mut r)?; - - for (_, event) in &l.events { - if let Event::KeyframeRequest(req) = event { - if req.mid == mid && req.kind == KeyframeRequestKind::Fir { - found_keyframe_request = true; - break; - } - } - } - - if found_keyframe_request { - break; - } - } - - assert!(found_keyframe_request, "L should receive a FIR keyframe request from R"); - - Ok(()) -} - -/// Test is_request_keyframe_possible() method. -#[test] -fn keyframe_request_possibility_check() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // Send some video to establish the stream - let params = l.params_vp8(); - let pt = params.pt(); - - for i in 0..5 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid) - .unwrap() - .write(pt, wallclock, time, vec![0x10, 0x00, 0x00, i as u8])?; - progress(&mut l, &mut r)?; - } - - // Check that keyframe requests are possible - if let Some(writer) = r.writer(mid) { - let pli_possible = writer.is_request_keyframe_possible(KeyframeRequestKind::Pli); - let fir_possible = writer.is_request_keyframe_possible(KeyframeRequestKind::Fir); - - // At least one should be possible with default config - assert!(pli_possible || fir_possible, "At least PLI or FIR should be possible"); - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/keyframes.rs b/rs/moq-webrtc/src/vendor/str0m/tests/keyframes.rs deleted file mode 100644 index 862b058b3b9..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/keyframes.rs +++ /dev/null @@ -1,435 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::format::{Codec, CodecExtra}; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::RtpWrite; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_log, progress}; -use common::{av1_data, h264_data, h265_data, init_crypto_default, vp8_data, vp9_data}; - -#[test] -pub fn test_vp8_keyframes_detection() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - - let data = vp8_data(); - - for (relative, header, payload) in data { - // Keep RTC time progressed to be "in sync" with the test data. - while (l.last - max) < relative { - progress(&mut l, &mut r)?; - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .ext_vals(header.ext_vals) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let iter = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - for data in iter { - let CodecExtra::Vp8(extra) = data.codec_extra else { - panic!("Got non VP8 CodecExtra") - }; - let assume_keyframe = data.seq_range.contains(&14260.into()) - || data.seq_range.contains(&14262.into()) - || data.seq_range.contains(&14265.into()); - if extra.is_keyframe { - assert!(assume_keyframe, "Expected keyframe"); - } else { - assert!(!assume_keyframe, "Not expected keyframe"); - } - } - - Ok(()) -} - -#[test] -pub fn test_vp9_keyframes_detection() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp9(); - assert_eq!(params.spec().codec, Codec::Vp9); - let pt = params.pt(); - - let data = vp9_data(); - - for (relative, header, payload) in data { - // Keep RTC time progressed to be "in sync" with the test data. - while (l.last - max) < relative { - progress(&mut l, &mut r)?; - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .ext_vals(header.ext_vals) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let iter = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - for data in iter { - let CodecExtra::Vp9(extra) = data.codec_extra else { - panic!("Got non VP9 CodecExtra") - }; - let assume_keyframe = data.seq_range.contains(&19357.into()) - || data.seq_range.contains(&20296.into()) - || data.seq_range.contains(&20301.into()) - || data.seq_range.contains(&20351.into()); - if extra.is_keyframe { - assert!(assume_keyframe, "Expected keyframe"); - } else { - assert!(!assume_keyframe, "Not expected keyframe"); - } - } - - Ok(()) -} - -#[test] -pub fn test_h264_keyframes_detection() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - let _ = progress(&mut l, &mut r); - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_h264(); - assert_eq!(params.spec().codec, Codec::H264); - let pt = params.pt(); - - let data = h264_data(); - - for (relative, header, payload) in data { - // Keep RTC time progressed to be "in sync" with the test data. - while (l.last - max) < relative { - let _ = progress(&mut l, &mut r); - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .ext_vals(header.ext_vals) - .nackable(true), - ); - - let _ = progress(&mut l, &mut r); - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let iter = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - for data in iter { - let CodecExtra::H264(extra) = data.codec_extra else { - panic!("Got non H264 CodecExtra") - }; - let assume_keyframe = data.seq_range.contains(&19249.into()) - || data.seq_range.contains(&19251.into()) - || data.seq_range.contains(&19301.into()) - || data.seq_range.contains(&19351.into()) - || data.seq_range.contains(&19403.into()) - || data.seq_range.contains(&19453.into()) - || data.seq_range.contains(&19503.into()); - if extra.is_keyframe { - assert!(assume_keyframe, "Expected keyframe"); - } else { - assert!(!assume_keyframe, "Not expected keyframe"); - } - } - - Ok(()) -} - -#[test] -fn test_av1_keyframes_detection() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendOnly. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_av1(); - assert_eq!(params.spec().codec, Codec::Av1); - let pt = params.pt(); - - let data = av1_data(); - - for (relative, header, payload) in data { - // Keep RTC time progressed to be "in sync" with the test data. - while (l.last - max) < relative { - progress(&mut l, &mut r)?; - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .ext_vals(header.ext_vals) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let iter = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - for data in iter { - let CodecExtra::Av1(extra) = data.codec_extra else { - panic!("Got non AV1 CodecExtra") - }; - let assume_keyframe = data.seq_range.contains(&7486.into()) || data.seq_range.contains(&7485.into()); - if extra.is_keyframe { - assert!(assume_keyframe, "Expected keyframe"); - } else { - assert!(!assume_keyframe, "Not expected keyframe"); - } - } - - Ok(()) -} - -#[test] -pub fn test_h265_keyframes_detection() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendOnly. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_h265(); - assert_eq!(params.spec().codec, Codec::H265); - let pt = params.pt(); - - let expected_keyframe_seqs: Vec = include_str!("data/h265.txt") - .lines() - .filter(|l| l.contains("Keyframe")) - .filter_map(|l| { - let i = l.find("Seq=")?; - let s = &l[i + 4..]; - let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()); - s[..end].parse::().ok() - }) - .collect(); - - let data = h265_data(); - - for (relative, header, payload) in data { - // Keep RTC time progressed to be "in sync" with the test data. - while (l.last - max) < relative { - progress(&mut l, &mut r)?; - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .ext_vals(header.ext_vals) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let iter = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - for data in iter { - let CodecExtra::H265(extra) = data.codec_extra else { - panic!("Got non H265 CodecExtra") - }; - let assume_keyframe = expected_keyframe_seqs - .iter() - .any(|&s| data.seq_range.contains(&(u64::from(s)).into())); - if extra.is_keyframe { - assert!(assume_keyframe, "Expected keyframe"); - } else { - assert!(!assume_keyframe, "Not expected keyframe"); - } - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/loss.rs b/rs/moq-webrtc/src/vendor/str0m/tests/loss.rs deleted file mode 100644 index dcc93d07d7f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/loss.rs +++ /dev/null @@ -1,158 +0,0 @@ -//! Tests that media is correctly delivered under packet loss conditions. -//! -//! Uses the netem crate to simulate realistic bursty packet loss and verifies -//! that RTP retransmissions recover all lost packets. - -use super::common; - -use std::time::Duration; - -use crate::vendor::netem::{GilbertElliot, LossModel, NetemConfig}; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; -use common::{connect_l_r, init_crypto_default, progress, vp8_data}; - -use crate::vendor::str0m::tests::common::init_log; - -/// Run a media transmission test with the given loss model using real VP8 data. -/// -/// Returns the number of packets received. -fn run_loss_test(loss_model: impl Into, seed: u64) -> Result { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - // Configure netem on R's incoming queue (L -> R has loss) - let config = NetemConfig::new().loss(loss_model).seed(seed); - r.set_netem(config); - - let mid = "vid".into(); - let ssrc_tx: Ssrc = 42.into(); - let ssrc_rtx: Ssrc = 44.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc_tx, Some(ssrc_rtx), mid, None); - - // Increase the RTX ratio cap to 0.2 to allow more retransmissions. - // With heavy loss, the RTX ratio naturally grows, and the default - // cap (0.15) is too low to allow all needed retransmissions. - l.direct_api() - .stream_tx(&ssrc_tx) - .unwrap() - .set_rtx_cache(1024, Duration::from_secs(3), Some(0.2)); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc_tx, Some(ssrc_rtx), mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - - let data = vp8_data(); - let packet_count = data.len(); - - for (relative, header, payload) in data { - // Keep RTC time progressed to be "in sync" with the test data - while (l.last - max) < relative { - progress(&mut l, &mut r)?; - } - - let absolute = max + relative; - - let mut direct = l.direct_api(); - let tx = direct.stream_tx(&ssrc_tx).unwrap(); - tx.write_rtp( - RtpWrite::new(pt, header.sequence_number(None), header.timestamp, absolute, payload) - .marker(header.marker) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - // Let retransmissions complete (also subject to loss) - let settle_time = l.duration() + Duration::from_secs(2); - while l.duration() < settle_time { - progress(&mut l, &mut r)?; - } - - // Count received RTP packets - let mut received_seqs: Vec = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::RtpPacket(v) = e { - Some(*v.seq_no) - } else { - None - } - }) - .collect(); - - received_seqs.sort(); - - println!( - "Sent {} packets, received {} packets", - packet_count, - received_seqs.len() - ); - - // Find which sequence numbers are missing - if !received_seqs.is_empty() { - let first = received_seqs[0]; - let last = *received_seqs.last().unwrap(); - let expected: Vec = (first..=last).collect(); - let missing: Vec = expected - .iter() - .filter(|s| !received_seqs.contains(s)) - .copied() - .collect(); - if !missing.is_empty() { - println!("Missing seq numbers from Event::RtpPacket: {:?}", missing); - } - } - - Ok(received_seqs.len()) -} - -#[test] -fn loss_light() -> Result<(), RtcError> { - // ~1% loss - should recover everything easily - let loss = GilbertElliot::wifi(); - let received = run_loss_test(loss, 12345)?; - - // VP8 data has 104 packets, with light loss we should get all - assert_eq!(received, 104, "Expected 104 packets with light loss, got {}", received); - Ok(()) -} - -#[test] -fn loss_medium() -> Result<(), RtcError> { - // ~5% loss - let loss = GilbertElliot::wifi_lossy(); - let received = run_loss_test(loss, 12345)?; - - assert_eq!(received, 104, "Expected 104 packets with medium loss, got {}", received); - Ok(()) -} - -#[test] -fn loss_heavy() -> Result<(), RtcError> { - // ~10% loss - let loss = GilbertElliot::congested(); - let received = run_loss_test(loss, 12345)?; - - assert_eq!(received, 104, "Expected 104 packets with heavy loss, got {}", received); - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/malformed-packet-injection.rs b/rs/moq-webrtc/src/vendor/str0m/tests/malformed-packet-injection.rs deleted file mode 100644 index 6ba85d0a80f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/malformed-packet-injection.rs +++ /dev/null @@ -1,242 +0,0 @@ -//! Regression tests for panics reachable from packets a peer (or, for the SRTP/SRTCP -//! cases, anyone who can send a datagram to the socket) puts on the wire. -//! -//! str0m's policy is that a panic means a bug in str0m, never bad input. Every test -//! here feeds input through a public API and asserts we survive it. - -use std::net::{Ipv4Addr, SocketAddr}; -use std::panic::AssertUnwindSafe; -use std::time::Instant; - -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::net::{Protocol, Receive}; -use crate::vendor::str0m::rtp::Ssrc; -use crate::vendor::str0m::rtp::rtcp::{Rtcp, Twcc}; -use crate::vendor::str0m::{Input, RtcError}; - -use super::common; -use common::{TestRtc, connect_l_r, init_crypto_default, init_log}; - -const L_ADDR: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 1000); -const R_ADDR: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(2, 2, 2, 2)), 2000); - -/// Feed one raw datagram straight into `Rtc::handle_input`, exactly as a socket read would. -/// -/// Returns `None` when the demuxer rejects the datagram outright (not our concern here). -fn inject(rtc: &mut TestRtc, bytes: &[u8]) -> Option> { - let now = rtc.last; - let contents = bytes.try_into().ok()?; - - let input = Input::Receive( - now, - Receive { - proto: Protocol::Udp, - source: L_ADDR, - destination: R_ADDR, - contents, - }, - ); - - Some(rtc.rtc.handle_input(input)) -} - -/// Run `f` and report a panic as `Err(message)` rather than unwinding out of the test, -/// so a sweep can report *every* bad length instead of stopping at the first. -fn catch(f: impl FnOnce()) -> Result<(), String> { - let prev = std::panic::take_hook(); - std::panic::set_hook(Box::new(|_| {})); - let res = std::panic::catch_unwind(AssertUnwindSafe(f)); - std::panic::set_hook(prev); - - res.map_err(|e| { - e.downcast_ref::() - .cloned() - .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())) - .unwrap_or_else(|| "".to_string()) - }) -} - -/// Build a bare RTCP-shaped datagram of exactly `len` bytes. -/// -/// byte0 = 0x80 and byte1 = 201 (Receiver Report) is what `MultiplexKind` uses to route -/// a datagram to the SRTCP path, so this is all it takes to reach `unprotect_rtcp`. -fn rtcp_shaped(len: usize) -> Vec { - let mut v = vec![0u8; len]; - if len > 0 { - v[0] = 0x80; - } - if len > 1 { - v[1] = 201; - } - v -} - -/// Build an RTP-shaped datagram: 12-byte minimal header (no CSRC, no extension) -/// plus `payload_len` bytes of payload. -fn rtp_shaped(pt: u8, ssrc: Ssrc, seq: u16, payload_len: usize) -> Vec { - let mut v = Vec::with_capacity(12 + payload_len); - v.push(0x80); // version 2, no padding, no extension, csrc count 0 - v.push(pt); // marker 0 - v.extend_from_slice(&seq.to_be_bytes()); - v.extend_from_slice(&0u32.to_be_bytes()); // timestamp - v.extend_from_slice(&(*ssrc).to_be_bytes()); - v.resize(12 + payload_len, 0); - v -} - -/// A datagram that demuxes as SRTCP but is too short to hold the SRTCP header, -/// the SRTCP index and the AEAD tag must be dropped, not panicked on. -/// -/// The guard in `SrtpContext::unprotect_rtcp` only requires `SRTCP_INDEX_LEN + TAG_LEN` -/// (20 bytes), but the code then builds `vec![0; buf.len() - TAG_LEN - SRTCP_INDEX_LEN]` -/// and immediately writes 8 bytes into it. For 20..28 bytes that vec is shorter than 8. -/// -/// This is reachable *before any authentication*: `Rtc::do_handle_receive` routes RTCP -/// straight to the session with no source or ICE check, and `unprotect_rtcp` is the -/// first code to touch the bytes. -#[test] -fn srtcp_shorter_than_srtcp_overhead() { - init_log(); - init_crypto_default(); - - let (_l, mut r) = connect_l_r(); - - let mut panics = Vec::new(); - - for len in 3..=64usize { - let packet = rtcp_shaped(len); - - if let Err(msg) = catch(|| { - // Ignore the Result, only the absence of a panic matters. - let _ = inject(&mut r, &packet); - }) { - panics.push((len, msg)); - } - } - - assert!( - panics.is_empty(), - "short SRTCP datagrams panicked at these lengths: {:#?}", - panics - ); -} - -/// An RTP packet whose payload is shorter than the AEAD tag must be dropped. -/// -/// `unprotect_rtp` guards on `buf.len() < TAG_LEN`, but then computes -/// `input.len() - TAG_LEN` where `input` is everything *after* the RTP header. A 12-byte -/// header plus a 4..15 byte payload underflows: a subtract-overflow panic in debug, and in -/// release a wrapped `out_len` that makes `rx_scratch.resize()` abort. -/// -/// Also pre-authentication, since for the GCM profiles the decrypt *is* the authentication. -#[test] -fn srtp_payload_shorter_than_aead_tag() { - init_log(); - init_crypto_default(); - - let (_l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let ssrc: Ssrc = 42.into(); - r.direct_api().declare_media(mid, MediaKind::Audio); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let pt = *r.params_opus().pt(); - - let mut panics = Vec::new(); - - for payload_len in 0..=32usize { - // A fresh seq each time so the replay/dupe filter doesn't short-circuit us. - let packet = rtp_shaped(pt, ssrc, payload_len as u16, payload_len); - - if let Err(msg) = catch(|| { - let _ = inject(&mut r, &packet); - }) { - panics.push((payload_len, msg)); - } - } - - assert!( - panics.is_empty(), - "short RTP payloads panicked at these payload lengths: {:#?}", - panics - ); -} - -/// REMB carries an attacker-controlled SSRC count in a single byte, and the parser -/// indexes `buf[16 + i * 4 ..]` for each of them without checking the buffer holds them. -/// -/// Reachable by an SRTCP-authenticated peer, i.e. the remote side of any call. -#[test] -fn remb_ssrc_count_beyond_buffer() { - init_log(); - - // RTCP header: version 2, fmt 15 (application layer), PT 206 (payload specific feedback). - let mut buf = vec![0x80 | 15, 206, 0, 4]; - buf.extend_from_slice(&1u32.to_be_bytes()); // sender ssrc - buf.extend_from_slice(&0u32.to_be_bytes()); // media ssrc, must be zero - buf.extend_from_slice(b"REMB"); // unique identifier - buf.push(255); // ssrc count: claims 255 trailing SSRCs... - buf.extend_from_slice(&[0x1a, 0x20, 0xdf]); // exp + mantissa - - assert_eq!(buf.len(), 20, "...but the packet ends right here"); - - let res = catch(|| { - // Must be an error, never a panic. - let _ = Rtcp::try_from(&buf[..]); - }); - - assert!( - res.is_ok(), - "parsing REMB with an oversized ssrc count panicked: {}", - res.unwrap_err() - ); - - // It must not come out as a REMB. (Falling through to the generic - // application-specific feedback parser is fine.) - assert!( - !matches!(Rtcp::try_from(&buf[..]), Ok(Rtcp::Remb(_))), - "a REMB claiming 255 SSRCs in a 20 byte packet must be rejected" - ); -} - -/// A TWCC run-length vector chunk encodes each packet status in 2 bits, so `0b11` is -/// perfectly representable on the wire. The parser accepts it (mapping it to -/// `PacketStatus::Unknown` and consuming no delta), but `TwccIter::next` has no arm for -/// `Unknown` and falls through to `unreachable!()`. -/// -/// Reachable by an SRTCP-authenticated peer. -#[test] -fn twcc_vector_double_with_unknown_symbol() { - init_log(); - - // RTCP header: version 2, fmt 15 (transport wide), PT 205 (transport layer feedback). - let mut buf = vec![0x80 | 15, 205, 0, 5]; - buf.extend_from_slice(&1u32.to_be_bytes()); // sender ssrc - buf.extend_from_slice(&2u32.to_be_bytes()); // media ssrc - buf.extend_from_slice(&0u16.to_be_bytes()); // base seq - buf.extend_from_slice(&7u16.to_be_bytes()); // status count: one full VectorDouble - buf.extend_from_slice(&[0, 0, 0]); // reference time (24 bit) - buf.push(0); // feedback count - - // 0b11 in the top bits marks a "vector, 2-bit symbols" chunk. The first symbol is - // 0b11, the remaining six are 0b00 (not received). - buf.extend_from_slice(&0xF000u16.to_be_bytes()); - - let Ok(Rtcp::Twcc(twcc)) = Rtcp::try_from(&buf[..]) else { - panic!("a well-formed TWCC chunk should parse"); - }; - let _: Twcc = twcc.clone(); - - let res = catch(move || { - let count = twcc.into_iter(Instant::now(), 0.into()).count(); - // Reaching here at all is the point. - let _ = count; - }); - - assert!( - res.is_ok(), - "iterating a TWCC report with a 0b11 vector symbol panicked: {}", - res.unwrap_err() - ); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/mediatime-backwards.rs b/rs/moq-webrtc/src/vendor/str0m/tests/mediatime-backwards.rs deleted file mode 100644 index c073b8f852b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/mediatime-backwards.rs +++ /dev/null @@ -1,190 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind, MediaTime}; -use crate::vendor::str0m::rtp::RawPacket; -use crate::vendor::str0m::{Event, RtcError}; -use tracing::info; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn mediatime_backwards() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - // Enable raw packets to trace the RTP headers - r.rtc = crate::vendor::str0m::Rtc::builder() - .enable_raw_packets(true) - .build(Instant::now()); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data_a = vec![1_u8; 80]; - - // First, send some normal packets with timestamps < 2^31 - let base_timestamp = 1_000_000_u32; // Well below 2^31 - - // Send 10 normal packets - for i in 0..10 { - let wallclock = l.start + l.duration(); - let timestamp = base_timestamp + i * 960; // Standard Opus timestamp increment - let time = MediaTime::from_90khz(timestamp as u64); - - l.rtc.writer(mid).unwrap().write(pt, wallclock, time, data_a.clone())?; - - progress(&mut l, &mut r)?; - } - - info!("Sent 10 normal packets with regular timestamps"); - - // Store the last RTP timestamp we observed before the pause - let mut last_ts_before_pause: Option = None; - - // Get the last timestamp from received packets - for (_, event) in &r.events { - if let Event::RawPacket(raw_packet) = event { - if let RawPacket::RtpRx(header, _) = &**raw_packet { - last_ts_before_pause = Some(header.timestamp); - } - } - } - - info!("Last timestamp before pause: {:?}", last_ts_before_pause); - - // Now advance time by more than 1.5 seconds (default pause threshold) without sending any packets - // This will trigger the pause condition in the receiver - let pause_duration = Duration::from_millis(2000); - - // Advance time using timeouts instead of sleep - let pause_end = l.last + pause_duration; - while l.last < pause_end { - // Just handle timeouts without sending any packets - progress(&mut l, &mut r)?; - } - - info!("Advanced time by {} ms to trigger pause", pause_duration.as_millis()); - - // Wait to ensure we get a paused event - let mut seen_paused = false; - let pause_check_start = l.last; - let pause_check_timeout = Duration::from_millis(500); - - while !seen_paused && l.last < pause_check_start + pause_check_timeout { - progress(&mut l, &mut r)?; - - // Check for pause event - for (_, event) in &r.events { - if let Event::StreamPaused(stream_paused) = event { - if stream_paused.paused { - seen_paused = true; - info!("Confirmed stream is paused"); - break; - } - } - } - } - - assert!(seen_paused, "Stream did not enter paused state within timeout"); - - // Now send a packet with a timestamp that will trigger the bug - // We need timestamp > 2^31 + previous_timestamp to trigger the backwards condition - // Using the threshold from header.rs, HALF = 1 << 31 - let problematic_timestamp = (1u32 << 31) + base_timestamp + 10 * 960; - - info!("Sending packet with problematic timestamp: {}", problematic_timestamp); - - let wallclock = l.start + l.duration(); - let time = MediaTime::from_90khz(problematic_timestamp as u64); - - // Save the timestamp index for comparison BEFORE sending - let events_before_problematic = r.events.len(); - - l.rtc.writer(mid).unwrap().write(pt, wallclock, time, data_a.clone())?; - - // Process the packet and a few more cycles to ensure it's received - for _ in 0..10 { - progress(&mut l, &mut r)?; - } - - // We're looking for evidence that: - // 1. The stream unpaused (proving packet was received) - // 2. The timestamp value in the received packet - let mut problematic_ts: Option = None; - let mut stream_unpaused_after_problematic = false; - - // Only look at events that occurred after sending our problematic packet - for (_, (_, event)) in r.events.iter().enumerate().skip(events_before_problematic) { - match event { - Event::RawPacket(raw_packet) => { - if let RawPacket::RtpRx(header, _) = &**raw_packet { - info!("After pause - RTP timestamp: {}", header.timestamp); - problematic_ts = Some(header.timestamp); - } - } - Event::StreamPaused(stream_paused) if !stream_paused.paused => { - stream_unpaused_after_problematic = true; - info!("Stream unpaused after receiving problematic packet"); - } - _ => {} - } - } - - // The test succeeds if: - // 1. We confirmed the stream was paused - // 2. We received the packet with the problematic timestamp - // 3. The stream unpaused after receiving the problematic packet - // 4. The timestamps continue to move forward after the pause - - assert!(seen_paused, "Stream was never paused"); - assert!( - problematic_ts.is_some(), - "Did not receive packet with problematic timestamp" - ); - assert!( - stream_unpaused_after_problematic, - "Stream did not unpause after receiving problematic packet" - ); - - // Verify that time moves forward even after a pause with a problematic timestamp - // This is the core of the bugfix - ensuring that MediaTime never goes backwards - if let (Some(prev_ts), Some(new_ts)) = (last_ts_before_pause, problematic_ts) { - assert!( - new_ts > prev_ts, - "Time went backwards! Previous timestamp: {}, Current timestamp: {}", - prev_ts, - new_ts - ); - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs b/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs deleted file mode 100644 index 26a6547ea85..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! str0m's integration tests, run against the vendored module. - -#[path = "abs-capture-time.rs"] -mod abs_capture_time; -#[path = "amr-wb.rs"] -mod amr_wb; -#[path = "api-errors.rs"] -mod api_errors; -mod bidirectional; -#[path = "change-ssrc-reset-receive.rs"] -mod change_ssrc_reset_receive; -mod common; -#[path = "config-validation.rs"] -mod config_validation; -mod contiguous; -#[path = "crypto-compliance.rs"] -mod crypto_compliance; -mod dlrr; -#[path = "dtls-close.rs"] -mod dtls_close; -#[path = "dtls-error-readiness.rs"] -mod dtls_error_readiness; -#[path = "dtls-fingerprint.rs"] -mod dtls_fingerprint; -#[path = "dtls-retransmit.rs"] -mod dtls_retransmit; -#[path = "dtls-security.rs"] -mod dtls_security; -#[path = "early-rtx-padding.rs"] -mod early_rtx_padding; -#[path = "flappy-ice-state.rs"] -mod flappy_ice_state; -#[path = "ice-candidates.rs"] -mod ice_candidates; -#[path = "ice-lite-connectivity.rs"] -mod ice_lite_connectivity; -#[path = "ice-remote-binding-keepalive.rs"] -mod ice_remote_binding_keepalive; -#[path = "ice-restart.rs"] -mod ice_restart; -#[path = "idle-rtc.rs"] -mod idle_rtc; -#[path = "keyframe-requests.rs"] -mod keyframe_requests; -mod keyframes; -mod loss; -#[path = "malformed-packet-injection.rs"] -mod malformed_packet_injection; -#[path = "mediatime-backwards.rs"] -mod mediatime_backwards; -#[path = "mtu-compliance.rs"] -mod mtu_compliance; -mod nack; -#[path = "network-conditions.rs"] -mod network_conditions; -#[path = "no-local-media-added.rs"] -mod no_local_media_added; -#[path = "no-pre-ice-feedback.rs"] -mod no_pre_ice_feedback; -#[path = "pli-feedback.rs"] -mod pli_feedback; -#[path = "poll-scaling.rs"] -mod poll_scaling; -mod remb; -#[path = "remove-media-while-pacer-queued.rs"] -mod remove_media_while_pacer_queued; -mod repeated; -#[path = "rtcp-request-timeout.rs"] -mod rtcp_request_timeout; -#[path = "rtp-direct-csrc.rs"] -mod rtp_direct_csrc; -#[path = "rtp-direct-mid.rs"] -mod rtp_direct_mid; -#[path = "rtp-direct-mid-rid.rs"] -mod rtp_direct_mid_rid; -#[path = "rtp-direct-reset-ssrc.rs"] -mod rtp_direct_reset_ssrc; -#[path = "rtp-direct-ssrc.rs"] -mod rtp_direct_ssrc; -#[path = "rtp-direct-with-roc.rs"] -mod rtp_direct_with_roc; -#[path = "rtp-sequence.rs"] -mod rtp_sequence; -mod rtp_to_frame; -#[path = "rtx-cache-0.rs"] -mod rtx_cache_0; -#[path = "sdp-m-recycle.rs"] -mod sdp_m_recycle; -#[path = "sdp-negotiation.rs"] -mod sdp_negotiation; -#[path = "sdp-rtx-apt.rs"] -mod sdp_rtx_apt; -#[path = "sdp-unique-mids.rs"] -mod sdp_unique_mids; -#[path = "simulcast-rid-mapping.rs"] -mod simulcast_rid_mapping; -#[path = "srtp-replay-attack.rs"] -mod srtp_replay_attack; -mod ssrc_zero_feedback; -#[path = "stale-network-time-after-pause.rs"] -mod stale_network_time_after_pause; -#[path = "stream-lifecycle.rs"] -mod stream_lifecycle; -mod twcc; -mod unidirectional; -#[path = "unidirectional-r-create-media.rs"] -mod unidirectional_r_create_media; -#[path = "user-rtp-header-extension.rs"] -mod user_rtp_header_extension; -#[path = "writer-borrow.rs"] -mod writer_borrow; diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs b/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs deleted file mode 100644 index 23aeab22b16..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{DATAGRAM_MTU_TARGET_MAX, DATAGRAM_MTU_TARGET_MIN, Event, Rtc, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress_strict_mtu}; - -/// End-to-end MTU compliance: walk a full ICE/DTLS/SRTP session and -/// assert every outgoing datagram on either side has `len() <= mtu`. The -/// check fires inside the test pump via [`progress_strict_mtu`], so any -/// oversized datagram fails the test at the source. -fn run_mtu_compliance(mtu: usize) -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let l_rtc = Rtc::builder().set_mtu(mtu..=mtu).build(now); - let r_rtc = Rtc::builder().set_mtu(mtu..=mtu).build(now); - - let mut l = TestRtc::new_with_rtc(Peer::Left.span(), l_rtc); - let mut r = TestRtc::new_with_rtc(Peer::Right.span(), r_rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let audio_mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // ICE + DTLS handshake under strict MTU. - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress_strict_mtu(&mut l, &mut r, mtu)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Audio writes (Opus) at typical 20 ms cadence. - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - let audio_payload = vec![0xAAu8; 160]; - - let deadline = Duration::from_secs(2); - while l.duration() < deadline { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - if let Some(w) = l.writer(audio_mid) { - w.write(pt, wallclock, time, audio_payload.clone())?; - } - progress_strict_mtu(&mut l, &mut r, mtu)?; - } - - // Sanity: r received the audio. - let media_events = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - assert!( - media_events >= 1, - "expected at least one MediaData event at r, got {media_events}" - ); - - Ok(()) -} - -#[test] -fn mtu_compliance_min() -> Result<(), RtcError> { - run_mtu_compliance(DATAGRAM_MTU_TARGET_MIN) -} - -#[test] -fn mtu_compliance_mid() -> Result<(), RtcError> { - run_mtu_compliance((DATAGRAM_MTU_TARGET_MIN + DATAGRAM_MTU_TARGET_MAX) / 2) -} - -#[test] -fn mtu_compliance_max() -> Result<(), RtcError> { - run_mtu_compliance(DATAGRAM_MTU_TARGET_MAX) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/nack.rs b/rs/moq-webrtc/src/vendor/str0m/tests/nack.rs deleted file mode 100644 index 9b5030b4a6c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/nack.rs +++ /dev/null @@ -1,631 +0,0 @@ -use std::collections::VecDeque; -use std::time::{Duration, Instant}; - -use crate::vendor::netem::{Input as NetemInput, NetemConfig, Output as NetemOutput, Probability, RandomLoss}; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::net::Receive; -use crate::vendor::str0m::rtp::rtcp::Rtcp; -use crate::vendor::str0m::rtp::{ExtensionValues, RawPacket, RtpWrite, SeqNo, Ssrc}; -use crate::vendor::str0m::{Event, Input, Output, Reason, Rtc, RtcError}; - -use super::common; -use common::{connect_l_r, connect_l_r_with_rtc, init_crypto_default, init_log, progress}; - -#[test] -fn nack_receive_retransmits_without_another_timeout() -> Result<(), RtcError> { - init_crypto_default(); - let (mut l, mut r) = connect_l_r(); - let mid = "vid".into(); - let ssrc = 42.into(); - let rtx = 44.into(); - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, Some(rtx), mid, None); - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, Some(rtx), mid, None); - let pt = l.params_vp8().pt(); - let now = l.last.max(r.last); - l.last = now; - r.last = now; - - // Establish the stream and enough media traffic to permit a retransmission. - for seq in 47_000..47_020 { - let now = l.last; - l.direct_api() - .stream_tx(&ssrc) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), seq as u32 * 3000, now, [1, 2, 3, 4]).nackable(true)); - progress(&mut l, &mut r)?; - } - - // Hold feedback in the network while the receiver detects one lost packet. - l.set_netem(NetemConfig::new().latency(Duration::from_millis(100))); - for seq in 47_020..47_025 { - let loss = if seq == 47_020 { 1.0 } else { 0.0 }; - r.set_netem(NetemConfig::new().loss(RandomLoss::new(Probability::new(loss)))); - let now = l.last; - l.direct_api() - .stream_tx(&ssrc) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), seq as u32 * 3000, now, [1, 2, 3, 4]).nackable(true)); - progress(&mut l, &mut r)?; - } - let deadline = l.duration() + Duration::from_millis(50); - while !r.events.iter().any(|(_, event)| { - matches!(event.as_raw_packet(), Some(RawPacket::RtcpTx(Rtcp::Nack(n))) - if n.reports.iter().any(|entry| entry.pid == 47_020)) - }) { - assert!(l.duration() < deadline, "receiver must request the lost packet"); - progress(&mut l, &mut r)?; - } - - // Deliver queued feedback through the public API. Poll to the next timeout - // without providing Input::Timeout: receiving the NACK must ready the RTX queue. - for _ in 0..20 { - let now = l.pending.poll_timeout(); - l.pending.handle_input(NetemInput::Timeout(now)); - let Some(NetemOutput::Packet(packet)) = l.pending.poll_output() else { - panic!("expected queued feedback"); - }; - l.handle_input(Input::Receive( - now, - Receive { - proto: packet.proto, - source: packet.source, - destination: packet.destination, - contents: packet.contents.as_slice().try_into()?, - }, - ))?; - let mut nack = false; - let mut retransmitted = false; - let mut transmitted = false; - loop { - match l.poll_output()? { - Output::Timeout(_) => break, - Output::Transmit(_) => transmitted = true, - Output::Event(event) => { - nack |= matches!(event.as_raw_packet(), Some(RawPacket::RtcpRx(Rtcp::Nack(n))) - if n.reports.iter().any(|entry| entry.pid == 47_020)); - retransmitted |= matches!(event.as_raw_packet(), Some(RawPacket::RtpTx(h, _)) - if h.ssrc == rtx); - } - } - } - if nack { - assert!( - retransmitted && transmitted, - "NACK must send RTX before the next timeout" - ); - return Ok(()); - } - } - panic!("queued NACK was not received"); -} - -#[test] -pub fn loss_recovery() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - // Configure 5% random loss on R's incoming queue (L -> R has loss) - let loss_config = NetemConfig::new() - .loss(RandomLoss::new(Probability::new(0.05))) - .seed(42); - r.set_netem(loss_config); - - let mid = "vid".into(); - - // In this example we are using MID only (no RID) to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - let ssrc_rtx: Ssrc = 44.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - - l.direct_api().declare_stream_tx(ssrc_tx, Some(ssrc_rtx), mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - - r.direct_api().expect_stream_rx(ssrc_tx, Some(ssrc_rtx), mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - - let to_write = [0x1, 0x2, 0x3, 0x4]; - let num_packets: usize = 1000; - - // write all packets num_packets - for index in 0..num_packets { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let time = (index * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + index as u64).into(); - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, to_write).nackable(true)); - - // Disable loss near start and end to let retransmission algo stabilize - // (see MISORDER_DELAY in register.rs) - if !(10..=990).contains(&index) { - r.set_netem(NetemConfig::new()); // No loss - } - - progress(&mut l, &mut r)?; - - // Re-enable loss for middle packets - if index == 9 { - let loss_config = NetemConfig::new() - .loss(RandomLoss::new(Probability::new(0.05))) - .seed(42); - r.set_netem(loss_config); - } - } - - // let some time pass for retransmission to happen - let settle_time = l.duration() + Duration::from_secs(10); - loop { - progress(&mut l, &mut r)?; - - if l.duration() > settle_time { - break; - } - } - - // some nacks have been transmitted - let nacks_tx = r - .events - .iter() - .filter_map(|(_, e)| match e.as_raw_packet() { - Some(RawPacket::RtcpTx(Rtcp::Nack(p))) => Some(p), - _ => None, - }) - .collect::>(); - - assert!(!nacks_tx.is_empty()); - - // some nacks have been received - let nacks_rx = l - .events - .iter() - .filter_map(|(_, e)| match e.as_raw_packet() { - Some(RawPacket::RtcpRx(Rtcp::Nack(p))) => Some(p), - _ => None, - }) - .collect::>(); - - assert!(!nacks_rx.is_empty()); - - // all packets were received in the end - let mut packets_rx = r - .events - .iter() - .filter_map(|(_, e)| match e.as_raw_packet() { - Some(RawPacket::RtpRx(p, b)) => { - // - if p.payload_type == params.resend().unwrap() { - // read original seq no - let seq_no = u16::from_be_bytes(b.get(0..2)?.try_into().ok()?); - Some(seq_no) - } else { - Some(p.sequence_number) - } - } - - _ => None, - }) - .collect::>(); - - packets_rx.sort(); - - let discontinuities = packets_rx - .windows(2) - .filter_map(|slice| { - let a = slice.first()?; - let b = slice.get(1)?; - if a + 1 != *b { Some((*a, *b)) } else { None } - }) - .collect::>(); - - let min = packets_rx.first().unwrap(); - let max = packets_rx.last().unwrap(); - - // useful for debugging - println!( - "min: {}, max: {}, total_rx: {}, discontinuities: {:?}", - min, - max, - packets_rx.len(), - discontinuities - ); - - assert_eq!(*min, 47_000); - assert_eq!(*max, 47_999); - - assert_eq!(discontinuities.len(), 0); - assert_eq!(packets_rx.len(), num_packets); - - Ok(()) -} - -#[test] -pub fn nack_delay() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "vid".into(); - - // In this example we are using MID only (no RID) to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - let ssrc_rtx: Ssrc = 44.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - - l.direct_api().declare_stream_tx(ssrc_tx, Some(ssrc_rtx), mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - - r.direct_api().expect_stream_rx(ssrc_tx, Some(ssrc_rtx), mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - &[0x1, 0x2, 0x3, 0x4], - &[0x9, 0xa, 0xb, 0xc], - &[0x5, 0x6, 0x7, 0x8], - &[0x1, 0x2, 0x3, 0x4], - &[0x9, 0xa, 0xb, 0xc], - &[0x5, 0x6, 0x7, 0x8], - &[0x1, 0x2, 0x3, 0x4], - &[0x9, 0xa, 0xb, 0xc], - &[0x5, 0x6, 0x7, 0x8], - &[0x1, 0x2, 0x3, 0x4], - &[0x9, 0xa, 0xb, 0xc], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(5); - - let mut counts: Vec = vec![0, 1, 2, 4, 3, 5, 6, 7, 8, 9, 10]; - - let mut dropped = (Instant::now(), 0.into()); - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(5); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - if count == 5 { - // Drop a packet - dropped = (wallclock, seq_no); - continue; - } - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp( - RtpWrite::new(pt, seq_no, time, wallclock, packet) - .ext_vals(exts) - .nackable(true), - ); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let nacks_tx = r - .events - .iter() - .filter_map(|(t, e)| match e.as_raw_packet() { - Some(RawPacket::RtcpTx(Rtcp::Nack(p))) => { - if p.reports.iter().any(|r| SeqNo::from(r.pid as u64) == dropped.1) { - Some(*t - dropped.0) - } else { - None - } - } - _ => None, - }) - .collect::>(); - - let first_nack_tx = nacks_tx.first().expect("nack"); - - assert!(first_nack_tx < &Duration::from_millis(100)); - assert_eq!(nacks_tx.len(), 5); - assert!(nacks_tx.windows(2).all(|pair| { - let spacing = pair[1] - pair[0]; - spacing >= Duration::from_millis(105) && spacing <= Duration::from_millis(138) - })); - - let nacks_rx = l - .events - .iter() - .filter_map(|(t, e)| match e.as_raw_packet() { - Some(RawPacket::RtcpRx(Rtcp::Nack(p))) => { - if p.reports.iter().any(|r| SeqNo::from(r.pid as u64) == dropped.1) { - Some(*t - dropped.0) - } else { - None - } - } - _ => None, - }) - .collect::>(); - - let first_nack_rx = nacks_rx.first().expect("nack"); - - assert!(first_nack_rx < &Duration::from_millis(100)); - assert_eq!(nacks_rx.len(), nacks_tx.len()); - for (sent, received) in nacks_tx.iter().zip(&nacks_rx) { - assert!(received >= sent); - assert!(*received - *sent <= Duration::from_millis(10)); - } - - Ok(()) -} - -#[test] -pub fn nack_retries_follow_measured_rtt_in_both_receive_modes() -> Result<(), RtcError> { - init_crypto_default(); - - for rtp_mode in [true, false] { - let now = Instant::now(); - let rtc = |rtp_mode| { - Rtc::builder() - .set_rtp_mode(rtp_mode) - .enable_raw_packets(true) - .set_rtcp_report_interval_video(Duration::from_millis(100)) - .build(now) - }; - let (mut l, mut r) = connect_l_r_with_rtc(rtc(true), rtc(rtp_mode)); - l.set_netem(NetemConfig::new().latency(Duration::from_millis(100))); - r.set_netem(NetemConfig::new().latency(Duration::from_millis(100))); - - let mid = "vid".into(); - let ssrc = 42.into(); - let rtx = 44.into(); - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, Some(rtx), mid, None); - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, Some(rtx), mid, None); - let pt = l.params_vp8().pt(); - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let write = |l: &mut common::TestRtc, seq: u64| { - let now = l.last; - l.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new(pt, seq.into(), seq as u32 * 3000, now, [0x10, 0, 0]) - .marker(true) - .nackable(false), - ); - }; - - // Let RRTR/DLRR measure the 200 ms round trip before introducing loss. - for seq in 47_000..47_020 { - write(&mut l, seq); - progress(&mut l, &mut r)?; - } - let until = l.duration() + Duration::from_secs(2); - while l.duration() < until { - progress(&mut l, &mut r)?; - } - - // Never send 47020, so retries continue even though the sender has no repair. - write(&mut l, 47_021); - let until = l.duration() + Duration::from_secs(2); - while l.duration() < until { - progress(&mut l, &mut r)?; - } - let gap_detected = r - .events - .iter() - .find_map(|(at, event)| match event.as_raw_packet() { - Some(RawPacket::RtpRx(header, _)) if header.ssrc == ssrc && header.sequence_number == 47_021 => { - Some(*at) - } - _ => None, - }) - .expect("the packet exposing the gap should arrive"); - let nacks = r - .events - .iter() - .filter_map(|(at, event)| match event.as_raw_packet() { - Some(RawPacket::RtcpTx(Rtcp::Nack(nack))) if nack.reports.iter().any(|entry| entry.pid == 47_020) => { - Some(*at) - } - _ => None, - }) - .collect::>(); - assert_eq!(nacks.len(), 5); - assert!(nacks[0] - gap_detected <= Duration::from_millis(33)); - assert!( - nacks.windows(2).all(|pair| { - let spacing = pair[1] - pair[0]; - (Duration::from_millis(200)..=Duration::from_millis(250)).contains(&spacing) - }), - "retries must follow the measured RTT, not the default or the poll interval: {nacks:?}" - ); - } - - Ok(()) -} - -#[test] -pub fn nack_timer_stops_while_receive_paused() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "vid".into(); - let ssrc_tx: Ssrc = 42.into(); - let ssrc_rtx: Ssrc = 44.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc_tx, Some(ssrc_rtx), mid, None); - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc_tx, Some(ssrc_rtx), mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let pt = l.params_vp8().pt(); - - // Send media for a while and observe r's timeout reasons. - let write = |l: &mut common::TestRtc, index: usize| { - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc_tx).unwrap(); - let time = (index * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + index as u64).into(); - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, [0x1, 0x2, 0x3, 0x4]).nackable(true)); - }; - - let mut nack_while_receiving = 0; - for index in 0..100 { - write(&mut l, index); - progress(&mut l, &mut r)?; - if r.last_timeout_reason() == Reason::Nack { - nack_while_receiving += 1; - } - } - assert!(nack_while_receiving > 0, "NACK timer should be armed while receiving"); - - // Stop sending. Let the receive stream pass the (default 1.5s) pause threshold. - let paused_after = l.duration() + Duration::from_secs(3); - while l.duration() < paused_after { - progress(&mut l, &mut r)?; - } - - // While paused, r must never be woken for NACK. - let idle_until = l.duration() + Duration::from_secs(10); - let mut nack_while_paused = 0; - while l.duration() < idle_until { - progress(&mut l, &mut r)?; - if r.last_timeout_reason() == Reason::Nack { - nack_while_paused += 1; - } - } - assert_eq!( - nack_while_paused, 0, - "NACK timer must not be armed while all NACK streams are paused" - ); - - // Resume sending: the NACK timer comes back. - let mut nack_after_resume = 0; - for index in 100..200 { - write(&mut l, index); - progress(&mut l, &mut r)?; - if r.last_timeout_reason() == Reason::Nack { - nack_after_resume += 1; - } - } - assert!(nack_after_resume > 0, "NACK timer should be re-armed when RTP resumes"); - - Ok(()) -} - -#[test] -pub fn nack_timer_finishes_pending_retries_after_pause() -> Result<(), RtcError> { - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - let mid = "vid".into(); - let ssrc: Ssrc = 42.into(); - let rtx: Ssrc = 44.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, Some(rtx), mid, None); - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api() - .expect_stream_rx(ssrc, Some(rtx), mid, None) - .set_pause_threshold(Duration::from_millis(50)); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - let pt = l.params_vp8().pt(); - - // Leave a known gap and stop sending. Without a repair, all five NACK attempts - // must finish even though the receive stream is reported paused after 50ms. - for seq in [47_000_u64, 47_002] { - let wallclock = l.start + l.duration(); - l.direct_api() - .stream_tx(&ssrc) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), seq as u32 * 1000, wallclock, [1, 2, 3, 4]).nackable(false)); - progress(&mut l, &mut r)?; - } - - let until = l.duration() + Duration::from_secs(1); - while l.duration() < until { - progress(&mut l, &mut r)?; - } - - let paused_at = r - .events - .iter() - .find_map(|(at, event)| match event { - Event::StreamPaused(p) if p.ssrc == ssrc && p.paused => Some(*at), - _ => None, - }) - .expect("stream should be reported paused before retries finish"); - let nacks = r - .events - .iter() - .filter_map(|(at, event)| match event.as_raw_packet() { - Some(RawPacket::RtcpTx(Rtcp::Nack(n))) if n.reports.iter().any(|report| report.pid == 47_001) => Some(*at), - _ => None, - }) - .collect::>(); - assert_eq!(nacks.len(), 5, "pausing must not discard pending retries"); - assert!(nacks.iter().any(|at| *at > paused_at)); - - // Once the retry budget is exhausted, the paused stream must stop arming - // the NACK timer even though the packet remains missing. - let idle_until = l.duration() + Duration::from_millis(500); - while l.duration() < idle_until { - progress(&mut l, &mut r)?; - assert_ne!(r.last_timeout_reason(), Reason::Nack); - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/network-conditions.rs b/rs/moq-webrtc/src/vendor/str0m/tests/network-conditions.rs deleted file mode 100644 index 1bb4448dce4..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/network-conditions.rs +++ /dev/null @@ -1,377 +0,0 @@ -//! Tests for realistic network simulation conditions. - -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::netem::{NetemConfig, Probability, RandomLoss}; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// Test connection with high latency (500ms+). -#[test] -fn network_high_latency_500ms() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Apply high latency to both directions - l.set_netem(NetemConfig::new().latency(Duration::from_millis(500))); - r.set_netem(NetemConfig::new().latency(Duration::from_millis(500))); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - // Connection might take longer with high latency - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(30) { - panic!("Failed to connect with high latency"); - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Send and receive audio - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - let mut received_count = 0; - let send_until = l.duration() + Duration::from_secs(5); - - loop { - if l.duration() >= send_until { - break; - } - - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - - received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - } - - // Should still receive data despite high latency - assert!( - received_count > 10, - "Should receive data with high latency, got {}", - received_count - ); - - Ok(()) -} - -/// Test connection with packet loss. -#[test] -fn network_packet_loss() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(10) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Apply 10% packet loss to receiver - r.set_netem(NetemConfig::new().loss(RandomLoss::new(Probability::new(0.1))).seed(42)); - - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - let send_until = l.duration() + Duration::from_secs(5); - - loop { - if l.duration() >= send_until { - break; - } - - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - // Should still receive most data (90% with 10% loss) - assert!( - received_count > 50, - "Should receive most data with 10% loss, got {}", - received_count - ); - - Ok(()) -} - -/// Test recovery after network outage. -#[test] -fn network_recovery_from_outage() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - // Phase 1: Normal operation - let phase1_until = l.duration() + Duration::from_millis(500); - loop { - if l.duration() >= phase1_until { - break; - } - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Phase 2: Simulated outage (100% loss) - r.set_netem(NetemConfig::new().loss(RandomLoss::new(Probability::ONE))); - let phase2_until = l.duration() + Duration::from_millis(500); - loop { - if l.duration() >= phase2_until { - break; - } - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Phase 3: Recovery (restore network) - r.set_netem(NetemConfig::new()); - let phase3_until = l.duration() + Duration::from_secs(2); - loop { - if l.duration() >= phase3_until { - break; - } - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Should have received data in phases 1 and 3 - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!( - received_count > 20, - "Should recover and receive data after outage, got {}", - received_count - ); - - Ok(()) -} - -/// Test asymmetric latency (different in each direction). -#[test] -fn network_asymmetric_latency() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Different latency in each direction - l.set_netem(NetemConfig::new().latency(Duration::from_millis(50))); // L -> R: 50ms - r.set_netem(NetemConfig::new().latency(Duration::from_millis(200))); // R -> L: 200ms - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(15) { - panic!("Failed to connect with asymmetric latency"); - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - let send_until = l.duration() + Duration::from_secs(3); - - loop { - if l.duration() >= send_until { - break; - } - - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!( - received_count > 10, - "Should work with asymmetric latency, got {}", - received_count - ); - - Ok(()) -} - -/// Test moderate latency with some loss. -#[test] -fn network_latency_with_loss() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Moderate latency with some loss - l.set_netem( - NetemConfig::new() - .latency(Duration::from_millis(100)) - .loss(RandomLoss::new(Probability::new(0.02))) - .seed(42), - ); - r.set_netem( - NetemConfig::new() - .latency(Duration::from_millis(100)) - .loss(RandomLoss::new(Probability::new(0.02))) - .seed(43), - ); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(15) { - panic!("Failed to connect"); - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - let send_until = l.duration() + Duration::from_secs(5); - - loop { - if l.duration() >= send_until { - break; - } - - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - // Should receive most data (98%+ with 2% loss) - assert!( - received_count > 80, - "Should receive most data with latency and loss, got {}", - received_count - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/no-local-media-added.rs b/rs/moq-webrtc/src/vendor/str0m/tests/no-local-media-added.rs deleted file mode 100644 index aa3cf037901..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/no-local-media-added.rs +++ /dev/null @@ -1,81 +0,0 @@ -use std::net::Ipv4Addr; - -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::Ssrc; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn direct_declare_media_no_media_added_event() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - - // In this example we are using MID only (no RID) to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let found_local = l.events.iter().any(|(_, e)| matches!(e, Event::MediaAdded(_))); - - let found_remote = r.events.iter().any(|(_, e)| matches!(e, Event::MediaAdded(_))); - - assert!(!found_local, "declare_media with local MediaAdded"); - assert!(!found_remote, "declare_media found remote MediaAdded"); - - Ok(()) -} - -#[test] -pub fn sdp_no_media_added_event() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let found_local = l.events.iter().any(|(_, e)| matches!(e, Event::MediaAdded(_))); - - let found_remote = r.events.iter().any(|(_, e)| matches!(e, Event::MediaAdded(_))); - - assert!(!found_local, "declare_media with local MediaAdded"); - assert!(found_remote, "declare_media found remote MediaAdded"); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/no-pre-ice-feedback.rs b/rs/moq-webrtc/src/vendor/str0m/tests/no-pre-ice-feedback.rs deleted file mode 100644 index c9a15d6756e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/no-pre-ice-feedback.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::RawPacket; -use crate::vendor::str0m::{Rtc, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, negotiate, progress}; - -#[test] -pub fn no_pre_ice_feedback() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let l_rtc = Rtc::builder().enable_raw_packets(true).build(now); - let r_rtc = Rtc::builder().enable_raw_packets(true).build(now); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), l_rtc); - let mut r = TestRtc::new_with_rtc(info_span!("R"), r_rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None) - }); - - // Before ICE is established, introduce a large time delta that spans at least one sender/receiver report - // interval - let mut t = l.last; - l.handle_input(crate::vendor::str0m::Input::Timeout(t))?; - t += Duration::from_secs(10); - l.handle_input(crate::vendor::str0m::Input::Timeout(t))?; - - loop { - if l.is_connected() && r.is_connected() { - break; - } - - progress(&mut l, &mut r)?; - } - - for (_, event) in l.events.iter() { - if let Some(RawPacket::RtcpTx(tx)) = event.as_raw_packet() { - panic!( - "Sender should not have generated feedback before ICE, but it output {:?}", - tx - ); - } - } - - for (_, event) in r.events.iter() { - if let Some(RawPacket::RtcpRx(rx)) = event.as_raw_packet() { - panic!( - "Receiver should not have generated feedback before ICE, but it output {:?}", - rx - ); - } - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/pli-feedback.rs b/rs/moq-webrtc/src/vendor/str0m/tests/pli-feedback.rs deleted file mode 100644 index 9903c0d33c0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/pli-feedback.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::time::Duration; - -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::Ssrc; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -/// A PLI sent from one peer via [`DirectApi::send_pli_feedback`] is received by the -/// other peer as an `Event::KeyframeRequest`. -#[test] -pub fn pli_feedback_direct_api() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - // R sources a video stream (ssrc_r) that L receives; L will request a keyframe for it. - let mid = "vid".into(); - let ssrc_l: Ssrc = 100.into(); - let ssrc_r: Ssrc = 200.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc_l, None, mid, None); - l.direct_api().expect_stream_rx(ssrc_r, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().declare_stream_tx(ssrc_r, None, mid, None); - r.direct_api().expect_stream_rx(ssrc_l, None, mid, None); - - // Sync clocks - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // L requests a keyframe for R's stream, choosing L's SSRC as the feedback sender. - l.direct_api().send_pli_feedback(ssrc_l, ssrc_r); - - // Progress until R receives the keyframe request event. - let deadline = l.last + Duration::from_secs(5); - let mut received = false; - - loop { - if l.last > deadline || r.last > deadline { - break; - } - progress(&mut l, &mut r)?; - - for (_time, event) in r.events.drain(..) { - if let Event::KeyframeRequest(req) = event { - assert_eq!(req.mid, mid); - received = true; - } - } - - if received { - break; - } - } - - assert!(received, "R should have received a KeyframeRequest from L"); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/poll-scaling.rs b/rs/moq-webrtc/src/vendor/str0m/tests/poll-scaling.rs deleted file mode 100644 index 2c1ef3a093b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/poll-scaling.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! How much does one `poll_output()` cost, as a function of the number of -//! m-lines on the connection? -//! -//! This is the shape that matters for a server. A 1:1 call has 2 m-lines and the -//! cost is invisible. An SFU client in an N-person room has ~N m-lines (one per -//! other participant), and `poll_output` is called thousands of times per second -//! per connection - so any per-call linear scan over medias/streams is paid -//! O(N) times, O(N^2) per room. -//! -//! The number reported is the cost of a poll that finds NOTHING to do (returns -//! `Output::Timeout`). In a real SFU that is the majority of calls: every drain -//! ends with one, by construction. -//! -//! Ignored by default, since it is a measurement rather than an assertion and it -//! takes a while. Run with: -//! -//! cargo test --release --test poll-scaling -- --ignored --nocapture -//! -//! `--release` is essential; a debug build hides the effect entirely. -//! -//! Methodology note, because it cost us several wrong conclusions. Report the -//! MINIMUM of N trials, never the mean: CPU benchmark noise is additive, so the -//! fastest trial is the closest to the true cost. And never compare two numbers -//! measured minutes apart, because the machine drifts (thermal throttling, power -//! source). To compare two versions, prebuild both test binaries, run them back to -//! back alternating the order, and pair the results. - -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::media::{Direction, MediaKind, Mid}; -use crate::vendor::str0m::{Output, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// m-line counts to sweep. 2 = a 1:1 call. 30 = a mid-size conference. -const MLINES: &[usize] = &[2, 5, 10, 20, 30, 50]; - -/// Polls timed per trial. -const ITERATIONS: usize = 50_000; - -/// Trials per data point. We report the MINIMUM: a CPU benchmark's noise is -/// almost entirely additive (scheduling, interrupts, frequency dips), so the -/// fastest trial is the closest to the true cost. Reporting the mean instead -/// makes the numbers swing ~20% run to run and the comparison meaningless. -const TRIALS: usize = 7; - -#[test] -#[ignore = "measurement, not an assertion; run explicitly with --ignored"] -fn poll_output_cost_by_mline_count() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - println!(); - println!("cost of ONE poll_output() that returns Timeout (i.e. finds nothing to do)"); - println!(); - println!( - "{:>8} {:>12} {:>12} {:>10}", - "m-lines", "ns/poll", "vs 2 m-lines", "ns/m-line" - ); - println!("{:->8} {:->12} {:->12} {:->10}", "", "", "", ""); - - let mut baseline: Option = None; - - for &n in MLINES { - let ns = measure(n)?; - - let base = *baseline.get_or_insert(ns); - println!("{:>8} {:>12.0} {:>11.1}x {:>10.1}", n, ns, ns / base, ns / n as f64); - } - - println!(); - println!("A flat 'vs 2 m-lines' column means poll_output is O(1) in the number of"); - println!("m-lines. A column that tracks the m-line count means it is O(N), and an"); - println!("SFU pays that N times per iteration."); - println!(); - - Ok(()) -} - -/// Build a connection with `n` send-only m-lines (the SFU-to-viewer direction), -/// get media flowing on each so the StreamTx actually exist, then time a -/// `poll_output()` that has nothing left to produce. -fn measure(n: usize) -> Result { - let mut l = TestRtc::new(Peer::Left); // the "SFU" - let mut r = TestRtc::new(Peer::Right); // the viewer - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // One m-line per remote participant the viewer is subscribed to. - let mids: Vec = negotiate(&mut l, &mut r, |change| { - (0..n) - .map(|_| change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None)) - .collect() - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Write one packet on every m-line, so each has a live StreamTx. Without this - // the streams do not exist and the scan has nothing to scan. - let params = l.params_vp8(); - let pt = params.pt(); - for (i, mid) in mids.iter().enumerate() { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(*mid) - .unwrap() - .write(pt, wallclock, time, vec![1_u8, 2, 3, (i % 250) as u8])?; - progress(&mut l, &mut r)?; - } - - // Drain everything so the next poll is a pure "nothing to do" poll. - loop { - match l.rtc.poll_output()? { - Output::Timeout(_) => break, - Output::Transmit(_) | Output::Event(_) => continue, - } - } - - // Warm up: caches, branch predictors, CPU frequency. - for _ in 0..ITERATIONS { - std::hint::black_box(l.rtc.poll_output()?); - } - - // Time the empty poll. It is idempotent - it keeps returning Timeout - so we - // can call it repeatedly without changing the connection's state. - let mut best = f64::MAX; - for _ in 0..TRIALS { - let t0 = Instant::now(); - for _ in 0..ITERATIONS { - let out = l.rtc.poll_output()?; - debug_assert!(matches!(out, Output::Timeout(_))); - std::hint::black_box(&out); - } - let elapsed: Duration = t0.elapsed(); - let ns = elapsed.as_nanos() as f64 / ITERATIONS as f64; - if ns < best { - best = ns; - } - } - - Ok(best) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/remb.rs b/rs/moq-webrtc/src/vendor/str0m/tests/remb.rs deleted file mode 100644 index 0c90221c915..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/remb.rs +++ /dev/null @@ -1,79 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::bwe::{Bitrate, BweKind}; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, Rtc, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, negotiate, progress}; - -#[test] -pub fn remb() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let l_rtc = Rtc::builder().build(now); - let r_rtc = Rtc::builder().build(now); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), l_rtc); - let mut r = TestRtc::new_with_rtc(info_span!("R"), r_rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None) - }); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - //wait for srtp success - let settle_time = l.duration() + Duration::from_millis(20); - loop { - progress(&mut l, &mut r)?; - - if l.duration() > settle_time { - break; - } - } - - r.direct_api() - .stream_rx_by_mid(mid, None) - .expect("Should has rx") - .request_remb(Bitrate::bps(123456)); - - let settle_time = l.duration() + Duration::from_millis(20); - loop { - progress(&mut l, &mut r)?; - - if l.duration() > settle_time { - break; - } - } - - let l_remb: Vec<_> = l - .events - .iter() - .filter_map(|(_, e)| { - if let Event::EgressBitrateEstimate(event) = e { - Some(event) - } else { - None - } - }) - .collect(); - - let estimate = Bitrate::bps(123456); - let expected = BweKind::Remb { estimate, mid }; - assert_eq!(l_remb, vec![&expected]); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/remove-media-while-pacer-queued.rs b/rs/moq-webrtc/src/vendor/str0m/tests/remove-media-while-pacer-queued.rs deleted file mode 100644 index 34cecf9b37e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/remove-media-while-pacer-queued.rs +++ /dev/null @@ -1,80 +0,0 @@ -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Input, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log}; - -/// This test triggers the panic in `Session::poll_packet` where the pacer -/// holds a reference to a MidRid whose media has been removed. -/// -/// Sequence: -/// 1. Set up a connected pair with a media + stream via direct API -/// 2. Write an RTP packet so the stream's send queue is non-empty -/// 3. Call handle_input(Timeout) so session.handle_timeout populates the pacer -/// 4. Remove the media via direct_api().remove_media() - pacer still references the mid -/// 5. Call poll_output() - poll_packet asks pacer for next mid, finds it missing → panic -#[test] -pub fn remove_media_while_pacer_queued() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let ssrc_tx: Ssrc = 42.into(); - - // Declare media and stream on sender - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - - // Declare matching media on receiver - r.direct_api().declare_media(mid, MediaKind::Audio); - - // Sync time - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - // Write an RTP packet so the stream's send queue has data - let wallclock = l.start + l.duration(); - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc_tx).unwrap(); - - let exts = ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp( - RtpWrite::new(pt, 47_000.into(), 47_000_000, wallclock, [0x1, 0x2, 0x3, 0x4]) - .ext_vals(exts) - .nackable(true), - ); - } - - // Advance time slightly so the timeout fires - let now = l.last + Duration::from_millis(10); - l.last = now; - - // Trigger handle_timeout which calls update_queue_state → pacer captures the MidRid - l.handle_input(Input::Timeout(now))?; - - // Now remove the media - the pacer still holds a reference to mid "aud" - l.direct_api().remove_media(mid); - - // poll_output will call poll_packet → pacer.poll_queue() returns the stale MidRid → panic - // (The panic: "Pacer pointed to mid {} which doesn't exist") - let _output = l.poll_output()?; - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/repeated.rs b/rs/moq-webrtc/src/vendor/str0m/tests/repeated.rs deleted file mode 100644 index 8e1f654c61a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/repeated.rs +++ /dev/null @@ -1,104 +0,0 @@ -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn repeated() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - - // In this example we are not using RID to identify the stream, we are simply - // using SSRC 1 as knowledge shared between sending and receiving side. - let ssrc: Ssrc = 1.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let mut write_at = l.last + Duration::from_millis(300); - - // Repeat the 3 a bunch of times. - let mut counts: Vec = vec![0, 1, 2, 3, 2, 3, 3]; - - loop { - if l.start + l.duration() > write_at && !counts.is_empty() { - write_at = l.last + Duration::from_millis(300); - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, [0x01, 0x02, 0x03, 0x04]).ext_vals(exts)); - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(30) { - break; - } - } - - let packets: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| { - let Event::RtpPacket(v) = e else { - return None; - }; - Some(v) - }) - .collect(); - - // Should only be the 4 unique sequence numbers. - assert_eq!(packets.len(), 4); - - let h0 = packets[0].header.clone(); - let h1 = packets[1].header.clone(); - - assert_eq!(h0.sequence_number, 47000); - assert_eq!(h1.sequence_number, 47001); - - assert_eq!(h0.timestamp, 47_000_000); - assert_eq!(h1.timestamp, 47_001_000); - - assert_eq!(h0.ext_vals.audio_level, Some(-42)); - assert_eq!(h1.ext_vals.audio_level, Some(-43)); - - assert!(!h0.marker); - assert!(!h1.marker); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtcp-request-timeout.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtcp-request-timeout.rs deleted file mode 100644 index 9c940747a69..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtcp-request-timeout.rs +++ /dev/null @@ -1,151 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Instant; - -use crate::vendor::str0m::bwe::{Bitrate, BweKind}; -use crate::vendor::str0m::media::{Direction, KeyframeRequestKind, MediaKind, Mid}; -use crate::vendor::str0m::net::Receive; -use crate::vendor::str0m::{Event, Input, Output, RtcError}; - -use super::common; -use common::{Peer, PendingPacket, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// L sends video to a receive-only R whose stream has NACK suppressed. -fn setup() -> Result<(TestRtc, TestRtc, Mid, Instant), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None) - }); - - while !l.is_connected() || !r.is_connected() { - progress(&mut l, &mut r)?; - } - - // Without NACK, no 33ms NACK timer wakes the session. - r.direct_api() - .stream_rx_by_mid(mid, None) - .expect("stream rx") - .suppress_nack(true); - - let pt = l.params_vp8().pt(); - for i in 0..20 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid) - .unwrap() - .write(pt, wallclock, time, vec![0x10, 0x00, 0x00, i as u8])?; - progress(&mut l, &mut r)?; - } - - let now = l.last.max(r.last); - drain(&mut l, now)?; - drain(&mut r, now)?; - - Ok((l, r, mid, now)) -} - -/// Polls without handling any input. Returns transmits and the next timeout. -fn poll(rtc: &mut TestRtc) -> Result<(Vec, Instant), RtcError> { - let mut packets = Vec::new(); - - loop { - match rtc.rtc.poll_output()? { - Output::Timeout(t) => return Ok((packets, t)), - Output::Transmit(t) => packets.push(PendingPacket { - proto: t.proto, - source: t.source, - destination: t.destination, - contents: t.contents.to_vec(), - }), - Output::Event(e) => rtc.events.push((rtc.last, e)), - } - } -} - -fn drain(rtc: &mut TestRtc, now: Instant) -> Result<(Vec, Instant), RtcError> { - rtc.rtc.handle_input(Input::Timeout(now))?; - poll(rtc) -} - -fn deliver(rtc: &mut TestRtc, now: Instant, packets: Vec) -> Result<(), RtcError> { - for p in packets { - let input = Input::Receive( - now, - Receive { - proto: p.proto, - source: p.source, - destination: p.destination, - contents: (&p.contents[..]).try_into()?, - }, - ); - rtc.rtc.handle_input(input)?; - poll(rtc)?; - } - Ok(()) -} - -/// The request must go out on the next tick without time advancing, after which the -/// timeout is no longer immediate. -fn assert_sent_immediately( - request: impl FnOnce(&mut TestRtc, Mid), - received: impl Fn(&Event) -> bool, -) -> Result<(), RtcError> { - let (mut l, mut r, mid, now) = setup()?; - - request(&mut r, mid); - assert_eq!(poll(&mut r)?.1, now); - - let (packets, next) = drain(&mut r, now)?; - assert!(next > now); - - deliver(&mut l, now, packets)?; - assert!(l.events.iter().any(|(_, e)| received(e))); - - Ok(()) -} - -#[test] -fn keyframe_request_writer_is_immediate() -> Result<(), RtcError> { - assert_sent_immediately( - |r, mid| { - r.writer(mid) - .unwrap() - .request_keyframe(None, KeyframeRequestKind::Pli) - .unwrap() - }, - |e| matches!(e, Event::KeyframeRequest(r) if r.kind == KeyframeRequestKind::Pli), - ) -} - -#[test] -fn keyframe_request_direct_api_is_immediate() -> Result<(), RtcError> { - assert_sent_immediately( - |r, mid| { - r.direct_api() - .stream_rx_by_mid(mid, None) - .unwrap() - .request_keyframe(KeyframeRequestKind::Fir) - }, - |e| matches!(e, Event::KeyframeRequest(r) if r.kind == KeyframeRequestKind::Fir), - ) -} - -#[test] -fn remb_request_is_immediate() -> Result<(), RtcError> { - assert_sent_immediately( - |r, mid| { - r.direct_api() - .stream_rx_by_mid(mid, None) - .unwrap() - .request_remb(Bitrate::bps(123_456)) - }, - |e| matches!(e, Event::EgressBitrateEstimate(BweKind::Remb { .. })), - ) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-csrc.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-csrc.rs deleted file mode 100644 index 8b6a16e71f7..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-csrc.rs +++ /dev/null @@ -1,218 +0,0 @@ -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{MediaKind, Pt}; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc, Vp8Descriptor}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -const VP8_PAYLOAD: [u8; 6] = [0x90, 0xf0, 0x01, 0x02, 0xa3, 0x00]; -const VP8_REWRITTEN_PICTURE_ID_PAYLOAD: [u8; 6] = [0x90, 0xf0, 0x7e, 0x02, 0xa3, 0x00]; - -#[test] -pub fn rtp_direct_csrc_basic() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let ssrc: Ssrc = 1.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let csrc_values: [u32; 15] = [u32::MAX, 0x12_34_56_78, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - - let wallclock = l.start + l.duration(); - let exts = ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(false), - ..Default::default() - }; - - l.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new(pt, 47_000.into(), 47_000_000, wallclock, [0x1, 0x2, 0x3, 0x4]) - .ext_vals(exts) - .csrc(&csrc_values[..3]), - ); - - loop { - progress(&mut l, &mut r)?; - - let has_media_packet = r.events.iter().any(|(_, e)| matches!(e, Event::RtpPacket(_))); - - if has_media_packet || l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 1); - - let h = &media[0].header; - assert_eq!(h.csrc_count, 3); - assert_eq!(h.csrc[0], u32::MAX); - assert_eq!(h.csrc[1], 0x12_34_56_78); - assert_eq!(h.csrc[2], 1); - // Remaining slots should be zero - for i in 3..15 { - assert_eq!(h.csrc[i], 0, "csrc[{i}] should be 0"); - } - - Ok(()) -} - -#[test] -pub fn rtp_direct_csrc_max_entries() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let ssrc: Ssrc = 2.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - - let csrc_values: [u32; 15] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - - let wallclock = l.start + l.duration(); - l.direct_api() - .stream_tx(&ssrc) - .unwrap() - .write_rtp(RtpWrite::new(pt, 48_000.into(), 48_000_000, wallclock, [0xa, 0xb, 0xc, 0xd]).csrc(&csrc_values)); - - loop { - progress(&mut l, &mut r)?; - - let has_media_packet = r.events.iter().any(|(_, e)| matches!(e, Event::RtpPacket(_))); - - if has_media_packet || l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 1); - - let h = &media[0].header; - assert_eq!(h.csrc_count, 15); - for i in 0..15 { - assert_eq!(h.csrc[i], (i + 1) as u32, "csrc[{i}] mismatch"); - } - - Ok(()) -} - -#[test] -#[should_panic(expected = "CSRC count must be <= 15")] -pub fn rtp_direct_csrc_panics_on_too_many_entries() { - let csrc_values = [0; 16]; - RtpWrite::new( - Pt::new_with_value(96), - 47_000.into(), - 47_000_000, - std::time::Instant::now(), - [0], - ) - .csrc(&csrc_values); -} - -#[test] -pub fn rtp_direct_csrc_with_vp8_patch() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "vid".into(); - let ssrc: Ssrc = 3.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - let csrc_values = [0x12_34_56_78, 7]; - let wallclock = l.start + l.duration(); - let vp8_patch = Vp8Descriptor::parse(&VP8_PAYLOAD) - .expect("valid VP8 descriptor") - .patch() - .picture_id(0x7e) - .build() - .expect("valid VP8 patch"); - - l.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new(pt, 49_000.into(), 49_000_000, wallclock, VP8_PAYLOAD) - .csrc(&csrc_values) - .vp8_patch(vp8_patch), - ); - - loop { - progress(&mut l, &mut r)?; - - let has_media_packet = r.events.iter().any(|(_, e)| matches!(e, Event::RtpPacket(_))); - - if has_media_packet || l.duration() > Duration::from_secs(10) { - break; - } - } - - let mut media = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }); - - let packet = media.next().expect("one RTP packet"); - assert!(media.next().is_none()); - - assert_eq!(packet.payload.as_ref(), VP8_REWRITTEN_PICTURE_ID_PAYLOAD.as_slice()); - assert_eq!(packet.header.csrc_count, 2); - assert_eq!(packet.header.csrc[0], csrc_values[0]); - assert_eq!(packet.header.csrc[1], csrc_values[1]); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-mid-rid.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-mid-rid.rs deleted file mode 100644 index d9a170efb70..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-mid-rid.rs +++ /dev/null @@ -1,106 +0,0 @@ -use std::collections::VecDeque; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn rtp_direct_mid_rid() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let rid = "hi".into(); - - // In this example we are using MID and RID to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, Some(rid)); - - r.direct_api().declare_media(mid, MediaKind::Audio).expect_rid_rx(rid); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - // 1 - &[0x1, 0x2, 0x3, 0x4], - // 3 - &[0x9, 0xa, 0xb, 0xc], - // 2 - &[0x5, 0x6, 0x7, 0x8], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(300); - - let mut counts: Vec = vec![0, 3, 1]; - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 3); - - assert!(l.media(mid).is_some()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_some()); - l.direct_api().remove_media(mid); - assert!(l.media(mid).is_none()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_none()); - - assert!(r.media(mid).is_some()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_some()); - r.direct_api().remove_media(mid); - assert!(r.media(mid).is_none()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_none()); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-mid.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-mid.rs deleted file mode 100644 index be77c3df591..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-mid.rs +++ /dev/null @@ -1,105 +0,0 @@ -use std::collections::VecDeque; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn rtp_direct_mid() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - - // In this example we are using MID only (no RID) to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - // 1 - &[0x1, 0x2, 0x3, 0x4], - // 3 - &[0x9, 0xa, 0xb, 0xc], - // 2 - &[0x5, 0x6, 0x7, 0x8], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(300); - - let mut counts: Vec = vec![0, 3, 1]; - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 3); - - assert!(l.media(mid).is_some()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_some()); - l.direct_api().remove_media(mid); - assert!(l.media(mid).is_none()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_none()); - - assert!(r.media(mid).is_some()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_some()); - r.direct_api().remove_media(mid); - assert!(r.media(mid).is_none()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_none()); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-reset-ssrc.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-reset-ssrc.rs deleted file mode 100644 index 2b650ce9000..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-reset-ssrc.rs +++ /dev/null @@ -1,260 +0,0 @@ -use std::collections::VecDeque; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn rtp_direct_reset_ssrc() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let rid = "hi".into(); - - // Initial SSRC - let ssrc_tx_initial: Ssrc = 42.into(); - // New SSRC to use after reset - let ssrc_tx_new: Ssrc = 84.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx_initial, None, mid, Some(rid)); - - r.direct_api().declare_media(mid, MediaKind::Audio).expect_rid_rx(rid); - - // Set initial timing - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, Some(rid)).unwrap().ssrc(); - assert_eq!(ssrc, ssrc_tx_initial, "Initial SSRC should match what we set"); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - // First batch of packets with initial SSRC - let first_batch: Vec<&[u8]> = vec![&[0x1, 0x2, 0x3, 0x4], &[0x5, 0x6, 0x7, 0x8]]; - - let mut first_batch: VecDeque<_> = first_batch.into(); - let mut first_counts: Vec = vec![0, 1]; - let mut write_at = l.last + Duration::from_millis(300); - - // Send first batch with initial SSRC - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = first_batch.pop_front() { - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx_by_mid(mid, Some(rid)).unwrap(); - - let count = first_counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if first_batch.is_empty() && first_counts.is_empty() { - break; - } - } - - // Run a bit longer to ensure first batch of packets arrive - for _ in 0..20 { - progress(&mut l, &mut r)?; - } - - // Try resetting to the same SSRC (should fail and return None) - let mut api = l.direct_api(); - let result = api.reset_stream_tx(mid, Some(rid), ssrc_tx_initial, None); - assert!(result.is_none(), "Resetting to the same SSRC should return None"); - - // Reset the SSRC with None for RTX since the stream doesn't use RTX - let mut api = l.direct_api(); - let result = api.reset_stream_tx(mid, Some(rid), ssrc_tx_new, None); - assert!(result.is_some(), "Reset should succeed with valid new SSRC"); - - // Verify the SSRC was changed - let updated_ssrc = l.direct_api().stream_tx_by_mid(mid, Some(rid)).unwrap().ssrc(); - assert_eq!(updated_ssrc, ssrc_tx_new, "SSRC should be updated to new value"); - - // Second batch of packets with new SSRC - let second_batch: Vec<&[u8]> = vec![&[0x9, 0xa, 0xb, 0xc], &[0xd, 0xe, 0xf, 0x10]]; - - let mut second_batch: VecDeque<_> = second_batch.into(); - let mut second_counts: Vec = vec![0, 1]; - write_at = l.last + Duration::from_millis(300); - - // Send second batch with new SSRC - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = second_batch.pop_front() { - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx_by_mid(mid, Some(rid)).unwrap(); - - let count = second_counts.remove(0); - let time = (count * 1000 + 48_000_000) as u32; - let seq_no = (48_000 + count).into(); // Different seq range to verify reset - - let exts = ExtensionValues { - audio_level: Some(-52 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if second_batch.is_empty() && second_counts.is_empty() { - // Run a bit longer to ensure packets arrive - for _ in 0..20 { - progress(&mut l, &mut r)?; - } - break; - } - } - - // Collect all received media packets - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - // Should have received all 4 packets - assert_eq!(media.len(), 4, "Should have received all 4 packets"); - - // Verify that we have packets with both SSRCs - let first_ssrc_packets: Vec<_> = media.iter().filter(|p| p.header.ssrc == ssrc_tx_initial).collect(); - let second_ssrc_packets: Vec<_> = media.iter().filter(|p| p.header.ssrc == ssrc_tx_new).collect(); - - assert_eq!(first_ssrc_packets.len(), 2, "Should have 2 packets with initial SSRC"); - assert_eq!(second_ssrc_packets.len(), 2, "Should have 2 packets with new SSRC"); - - // Verify specific packet properties - // First SSRC packets - let h0 = &first_ssrc_packets[0].header; - let h1 = &first_ssrc_packets[1].header; - - assert_eq!(h0.sequence_number, 47000); - assert_eq!(h1.sequence_number, 47001); - - assert_eq!(h0.timestamp, 47_000_000); - assert_eq!(h1.timestamp, 47_001_000); - - assert_eq!(h0.ext_vals.audio_level, Some(-42)); - assert_eq!(h1.ext_vals.audio_level, Some(-43)); - - // Second SSRC packets - sequence numbers should be reset - let h2 = &second_ssrc_packets[0].header; - let h3 = &second_ssrc_packets[1].header; - - assert_eq!(h2.sequence_number, 48000); - assert_eq!(h3.sequence_number, 48001); - - assert_eq!(h2.timestamp, 48_000_000); - assert_eq!(h3.timestamp, 48_001_000); - - assert_eq!(h2.ext_vals.audio_level, Some(-52)); - assert_eq!(h3.ext_vals.audio_level, Some(-53)); - - // Clean up - l.direct_api().remove_media(mid); - r.direct_api().remove_media(mid); - - Ok(()) -} - -#[test] -pub fn rtp_direct_reset_ssrc_with_rtx() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "vid".into(); - let rid = "hi".into(); - - // Initial SSRCs - let ssrc_tx_initial: Ssrc = 100.into(); - let ssrc_rtx_initial: Ssrc = 101.into(); - - // New SSRCs to use after reset - let ssrc_tx_new: Ssrc = 200.into(); - let ssrc_rtx_new: Ssrc = 201.into(); - - // Create media and stream with both main and RTX SSRCs - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api() - .declare_stream_tx(ssrc_tx_initial, Some(ssrc_rtx_initial), mid, Some(rid)); - - r.direct_api().declare_media(mid, MediaKind::Video).expect_rid_rx(rid); - - // Set initial timing - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Verify the initial SSRCs - { - let mut api = l.direct_api(); - let stream = api.stream_tx_by_mid(mid, Some(rid)).unwrap(); - assert_eq!(stream.ssrc(), ssrc_tx_initial, "Initial SSRC should match what we set"); - assert_eq!( - stream.rtx(), - Some(ssrc_rtx_initial), - "Initial RTX SSRC should match what we set" - ); - } - - // Try resetting with the same RTX SSRC (should fail) - let mut api = l.direct_api(); - let result = api.reset_stream_tx(mid, Some(rid), ssrc_tx_new, Some(ssrc_rtx_initial)); - assert!(result.is_none(), "Reset with same RTX SSRC should fail"); - - // Reset with new main and RTX SSRCs (should succeed) - let mut api = l.direct_api(); - let result = api.reset_stream_tx(mid, Some(rid), ssrc_tx_new, Some(ssrc_rtx_new)); - assert!(result.is_some(), "Reset with new main and RTX SSRCs should succeed"); - - // Verify the SSRCs were changed - { - let mut api = l.direct_api(); - let stream = api.stream_tx_by_mid(mid, Some(rid)).unwrap(); - assert_eq!(stream.ssrc(), ssrc_tx_new, "SSRC should be updated to new value"); - assert_eq!( - stream.rtx(), - Some(ssrc_rtx_new), - "RTX SSRC should be updated to new value" - ); - } - - // Clean up - l.direct_api().remove_media(mid); - r.direct_api().remove_media(mid); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-ssrc.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-ssrc.rs deleted file mode 100644 index 865254bd224..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-ssrc.rs +++ /dev/null @@ -1,326 +0,0 @@ -use std::collections::VecDeque; -use std::time::{Duration, Instant}; - -use crate::vendor::netem::{NetemConfig, Probability, RandomLoss}; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::media::Pt; -use crate::vendor::str0m::rtp::{ExtensionValues, RawPacket, RtpWrite, Ssrc, Vp8Descriptor, Vp8Patch}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -const VP8_PAYLOAD: [u8; 6] = [0x90, 0xf0, 0x01, 0x02, 0xa3, 0x00]; -const VP8_REWRITTEN_PAYLOAD: [u8; 6] = [0x90, 0xf0, 0x7e, 0x44, 0xbf, 0x00]; - -#[test] -pub fn rtp_direct_ssrc() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - - // In this example we are not using RID to identify the stream, we are simply - // using SSRC 1 as knowledge shared between sending and receiving side. - let ssrc: Ssrc = 1.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - // 1 - &[0x1, 0x2, 0x3, 0x4], - // 3 - &[0x9, 0xa, 0xb, 0xc], - // 2 - &[0x5, 0x6, 0x7, 0x8], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(300); - - let mut counts: Vec = vec![0, 3, 1]; - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 3); - - let h0 = media[0].header.clone(); - let h1 = media[1].header.clone(); - let h2 = media[2].header.clone(); - - assert_eq!(h0.sequence_number, 47000); - assert_eq!(h1.sequence_number, 47003); - assert_eq!(h2.sequence_number, 47001); - - assert_eq!(h0.timestamp, 47_000_000); - assert_eq!(h1.timestamp, 47_003_000); - assert_eq!(h2.timestamp, 47_001_000); - - assert_eq!(h0.ext_vals.audio_level, Some(-42)); - assert_eq!(h1.ext_vals.audio_level, Some(-45)); - assert_eq!(h2.ext_vals.audio_level, Some(-43)); - - assert!(!h0.marker); - assert!(!h1.marker); - assert!(!h2.marker); - - assert!(l.media(mid).is_some()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_some()); - l.direct_api().remove_media(mid); - assert!(l.media(mid).is_none()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_none()); - - assert!(r.media(mid).is_some()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_some()); - r.direct_api().remove_media(mid); - assert!(r.media(mid).is_none()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_none()); - - Ok(()) -} - -#[test] -pub fn rtp_direct_vp8_patch() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "vid".into(); - let ssrc: Ssrc = 1.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - let wallclock = l.start + l.duration(); - - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - stream.write_rtp(RtpWrite::new(pt, 47_000.into(), 47_000_000, wallclock, VP8_PAYLOAD).vp8_patch(vp8_patch())); - - stream.write_rtp(RtpWrite::new(pt, 47_001.into(), 47_001_000, wallclock, [20, 21, 22])); - } - - loop { - progress(&mut l, &mut r)?; - - let has_two_media_packets = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::RtpPacket(_))) - .take(2) - .count() == 2; - - if has_two_media_packets || l.duration() > Duration::from_secs(10) { - break; - } - } - - let mut media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - media.sort_by_key(|packet| packet.header.sequence_number); - - assert_eq!(media.len(), 2); - assert_eq!(media[0].header.sequence_number, 47_000); - assert_eq!(media[0].payload.as_ref(), VP8_REWRITTEN_PAYLOAD.as_slice()); - assert_eq!(media[1].header.sequence_number, 47_001); - assert_eq!(media[1].payload.as_ref(), &[20, 21, 22]); - - Ok(()) -} - -#[test] -pub fn rtp_direct_vp8_patch_survives_rtx() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "vid".into(); - let ssrc: Ssrc = 42.into(); - let ssrc_rtx: Ssrc = 44.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api() - .declare_stream_tx(ssrc, Some(ssrc_rtx), mid, None) - .set_rtx_cache(32, Duration::from_secs(3), None); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, Some(ssrc_rtx), mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - let rtx_pt = params.resend().unwrap(); - let rewritten_seq = 47_002_u64; - let original_seq_bytes = (rewritten_seq as u16).to_be_bytes(); - - for index in 0_u64..=1 { - let wallclock = l.start + l.duration(); - l.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new( - pt, - (47_000 + index).into(), - 47_000_000 + index as u32 * 1_000, - wallclock, - [index as u8], - ) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - } - - r.set_netem(NetemConfig::new().loss(RandomLoss::new(Probability::ONE))); - - let wallclock = l.start + l.duration(); - l.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new(pt, rewritten_seq.into(), 47_002_000, wallclock, VP8_PAYLOAD) - .nackable(true) - .vp8_patch(vp8_patch()), - ); - - progress(&mut l, &mut r)?; - r.set_netem(NetemConfig::new()); - - for index in 3_u64..=7 { - let wallclock = l.start + l.duration(); - l.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new( - pt, - (47_000 + index).into(), - 47_000_000 + index as u32 * 1_000, - wallclock, - [index as u8], - ) - .nackable(true), - ); - - progress(&mut l, &mut r)?; - } - - let rtx_payload = loop { - progress(&mut l, &mut r)?; - - if let Some(payload) = rtx_payload_for_seq(&r.events, rtx_pt, &original_seq_bytes) { - break payload; - } - - if l.duration() > Duration::from_secs(10) { - panic!("rewritten packet should be retransmitted over RTX"); - } - }; - - assert_eq!(rtx_payload.get(2..), Some(VP8_REWRITTEN_PAYLOAD.as_slice())); - - let recovered_packet = r.events.iter().find_map(|(_, event)| match event { - Event::RtpPacket(packet) if packet.header.sequence_number == rewritten_seq as u16 => Some(packet), - _ => None, - }); - - assert_eq!( - recovered_packet.map(|packet| packet.payload.as_ref()), - Some(VP8_REWRITTEN_PAYLOAD.as_slice()) - ); - - Ok(()) -} - -fn vp8_patch() -> Vp8Patch { - Vp8Descriptor::parse(&VP8_PAYLOAD) - .expect("valid VP8 descriptor") - .patch() - .picture_id(0x7e) - .tl0_pic_idx(0x44) - .key_idx(0x1f) - .build() - .expect("valid VP8 patch") -} - -fn rtx_payload_for_seq<'a>( - events: &'a [(Instant, Event)], - rtx_pt: Pt, - original_seq_bytes: &[u8; 2], -) -> Option<&'a [u8]> { - events.iter().find_map(|(_, event)| match event.as_raw_packet() { - Some(RawPacket::RtpRx(header, payload)) - if header.payload_type == rtx_pt && payload.starts_with(original_seq_bytes) => - { - Some(payload.as_slice()) - } - _ => None, - }) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-with-roc.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-with-roc.rs deleted file mode 100644 index c9e3c42fbe2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-direct-with-roc.rs +++ /dev/null @@ -1,118 +0,0 @@ -use std::collections::VecDeque; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::SeqNo; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn rtp_direct_with_roc() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - - // In this example we are using MID only (no RID) to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Audio); - - let mut d = r.direct_api(); - let rx = d.expect_stream_rx(ssrc_tx, None, mid, None); - - // Above 2^16, which means we have ROC:ed. - let seq_no_offset: SeqNo = 100_000.into(); - - // By telling the receiver side to start at a specific ROC, we can send first ever - // packet from a high sequence number. - rx.reset_roc(seq_no_offset.roc()); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - // 1 - &[0x1, 0x2, 0x3, 0x4], - // 3 - &[0x9, 0xa, 0xb, 0xc], - // 2 - &[0x5, 0x6, 0x7, 0x8], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(300); - - let mut counts: Vec = vec![0, 3, 1]; - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - - // this seqno is already past first ROC - let seq_no = (*seq_no_offset + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 3); - - assert!(l.media(mid).is_some()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_some()); - l.direct_api().remove_media(mid); - assert!(l.media(mid).is_none()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_none()); - - assert!(r.media(mid).is_some()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_some()); - r.direct_api().remove_media(mid); - assert!(r.media(mid).is_none()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_none()); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-sequence.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp-sequence.rs deleted file mode 100644 index f09168cf86e..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp-sequence.rs +++ /dev/null @@ -1,509 +0,0 @@ -//! Tests for RTP sequence number and timing edge cases. - -use std::net::Ipv4Addr; -use std::time::Instant; - -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::{RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, Rtc, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_log, negotiate, progress}; -use common::{connect_l_r_with_rtc, init_crypto_default}; - -/// Test handling of packets crossing the u16 sequence number boundary (65535 -> 0). -#[test] -fn rtp_sequence_number_near_boundary() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Use RTP mode to control sequence numbers directly - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).build(now); - let rtc2 = Rtc::builder().build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "audio".into(); - let ssrc_tx: Ssrc = 1337.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - - // Start sequence numbers near the u16 boundary (65535) - // Send packets: 65530, 65531, 65532, 65533, 65534, 65535, 0, 1, 2, 3, 4, 5 - let start_seq: u64 = 65530; - let packet_count = 12; - - for i in 0..packet_count { - let seq_no = start_seq + i; - let time = (i * 960) as u32; // Opus uses 48kHz, 20ms = 960 samples - let wallclock = l.start + l.duration(); - - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - stream.write_rtp(RtpWrite::new(pt, seq_no.into(), time, wallclock, [1_u8; 80])); - } - progress(&mut l, &mut r)?; - } - - // Final progress to deliver remaining packets - for _ in 0..50 { - progress(&mut l, &mut r)?; - } - - // Collect received sequence numbers from seq_range - let received_seqs: Vec = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::MediaData(data) = e { - // Get the start of the sequence range (SeqNo derefs to u64) - Some(**data.seq_range.start()) - } else { - None - } - }) - .collect(); - - // Verify we received packets across the boundary - assert!( - received_seqs.len() >= 10, - "Should receive most packets, got {}", - received_seqs.len() - ); - - // The library uses extended 64-bit sequence numbers internally. - // Wire seq 65535 -> internal 65535, wire seq 0 (after wrap) -> internal 65536 - // Verify sequence numbers before boundary (65530-65535) were received - let before_boundary: Vec<_> = received_seqs - .iter() - .filter(|&&s| (65530..=65535).contains(&s)) - .collect(); - assert!( - !before_boundary.is_empty(), - "Should receive packets before boundary (65530-65535), got seq_nos: {:?}", - received_seqs - ); - - // Verify sequence numbers after boundary (65536+ = wire 0+) were received - // Internal 65536 = wire seq 0, 65537 = wire seq 1, etc. - let after_boundary: Vec<_> = received_seqs.iter().filter(|&&s| s >= 65536).collect(); - assert!( - !after_boundary.is_empty(), - "Should receive packets after boundary (65536+ = wire 0+), got seq_nos: {:?}", - received_seqs - ); - - // Verify sequence numbers are monotonically increasing (no gaps from wrap-around) - for i in 1..received_seqs.len() { - assert!( - received_seqs[i] > received_seqs[i - 1], - "Sequence numbers should be monotonically increasing across boundary: {} should be > {}", - received_seqs[i], - received_seqs[i - 1] - ); - } - - Ok(()) -} - -/// Test reordering buffer with audio - send packets out of order and verify reordering. -#[test] -fn rtp_reordering_buffer_audio() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Sender uses RTP mode to control sequence numbers - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).build(now); - // Receiver has reordering buffer enabled (default is 15 for audio) - let rtc2 = Rtc::builder().set_reordering_size_audio(15).build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "audio".into(); - let ssrc_tx: Ssrc = 1337.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - - // Send packets OUT OF ORDER: 1, 3, 2, 5, 4, 7, 6, 9, 8, 10 - // The reordering buffer should fix this - let send_order = [1u64, 3, 2, 5, 4, 7, 6, 9, 8, 10]; - - for &seq in &send_order { - let time = (seq * 960) as u32; // Opus 48kHz, 20ms frames - let wallclock = l.start + l.duration(); - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - stream.write_rtp(RtpWrite::new(pt, seq.into(), time, wallclock, [seq as u8; 80])); - } - progress(&mut l, &mut r)?; - } - - // Final progress to flush reordering buffer - for _ in 0..50 { - progress(&mut l, &mut r)?; - } - - // Collect received sequence number ranges - let received_ranges: Vec<(u64, u64)> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::MediaData(data) = e { - Some((**data.seq_range.start(), **data.seq_range.end())) - } else { - None - } - }) - .collect(); - - assert!(!received_ranges.is_empty(), "Should receive some packets"); - - // Verify ranges are non-decreasing (reordering buffer should fix order) - // Each range's start should be >= previous range's start - for i in 1..received_ranges.len() { - assert!( - received_ranges[i].0 >= received_ranges[i - 1].0, - "Packets should be reordered: range {:?} should come after {:?}, all ranges: {:?}", - received_ranges[i], - received_ranges[i - 1], - received_ranges - ); - } - - // Verify we received packets spanning our sent range (1-10) - let min_received = received_ranges.iter().map(|r| r.0).min().unwrap(); - let max_received = received_ranges.iter().map(|r| r.1).max().unwrap(); - assert!( - min_received <= 2, - "Should receive early packets, min was {}", - min_received - ); - assert!( - max_received >= 9, - "Should receive late packets, max was {}", - max_received - ); - - Ok(()) -} - -/// Test reordering buffer with video - send packets out of order and verify reordering. -#[test] -fn rtp_reordering_buffer_video() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Sender uses RTP mode to control sequence numbers - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).build(now); - // Receiver has reordering buffer for video - let rtc2 = Rtc::builder().set_reordering_size_video(30).build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "video".into(); - let ssrc_tx: Ssrc = 1337.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Video); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - let pt = params.pt(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - - // Send video packets OUT OF ORDER: 1, 3, 2, 5, 4, 7, 6, 9, 8, 10 - let send_order = [1u64, 3, 2, 5, 4, 7, 6, 9, 8, 10]; - - for &seq in &send_order { - let time = (seq * 3000) as u32; // 90kHz video clock, ~33ms frames - let wallclock = l.start + l.duration(); - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - // VP8 keyframe header - stream - .write_rtp(RtpWrite::new(pt, seq.into(), time, wallclock, [0x10, 0x00, 0x00, seq as u8]).marker(true)); - } - progress(&mut l, &mut r)?; - } - - // Final progress to flush reordering buffer - for _ in 0..50 { - progress(&mut l, &mut r)?; - } - - // Collect received sequence number ranges - let received_ranges: Vec<(u64, u64)> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::MediaData(data) = e { - Some((**data.seq_range.start(), **data.seq_range.end())) - } else { - None - } - }) - .collect(); - - assert!(!received_ranges.is_empty(), "Should receive some video packets"); - - // Verify ranges are non-decreasing (reordering buffer should fix order) - for i in 1..received_ranges.len() { - assert!( - received_ranges[i].0 >= received_ranges[i - 1].0, - "Video packets should be reordered: {:?} should come after {:?}", - received_ranges[i], - received_ranges[i - 1] - ); - } - - Ok(()) -} - -/// Test custom reordering buffer size - small buffer handles small gaps. -#[test] -fn rtp_reordering_buffer_custom_size() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Sender uses RTP mode - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).build(now); - // Receiver has small reordering buffer (5 packets) - let rtc2 = Rtc::builder().set_reordering_size_audio(5).build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "audio".into(); - let ssrc_tx: Ssrc = 1337.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - - // Send packets with small gaps (within buffer size of 5) - // Order: 1, 3, 2, 4, 6, 5, 7, 9, 8, 10 (max gap of 2) - let send_order = [1u64, 3, 2, 4, 6, 5, 7, 9, 8, 10]; - - for &seq in &send_order { - let time = (seq * 960) as u32; - let wallclock = l.start + l.duration(); - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - stream.write_rtp(RtpWrite::new(pt, seq.into(), time, wallclock, [seq as u8; 80])); - } - progress(&mut l, &mut r)?; - } - - for _ in 0..50 { - progress(&mut l, &mut r)?; - } - - let received_ranges: Vec<(u64, u64)> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::MediaData(data) = e { - Some((**data.seq_range.start(), **data.seq_range.end())) - } else { - None - } - }) - .collect(); - - assert!( - !received_ranges.is_empty(), - "Should receive packets with small reordering buffer" - ); - - // Verify ordering is correct - for i in 1..received_ranges.len() { - assert!( - received_ranges[i].0 >= received_ranges[i - 1].0, - "Packets should be reordered with small buffer" - ); - } - - Ok(()) -} - -/// Test media time increases correctly. -#[test] -fn rtp_media_time_increasing() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - // Send packets with increasing timestamps - for _ in 0..50 { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Verify we received packets (media time handling worked) - let received_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!( - received_count > 20, - "Should receive packets with increasing timestamps, got {}", - received_count - ); - - Ok(()) -} - -/// Test large reordering buffer - handles larger out-of-order gaps. -#[test] -fn rtp_reordering_buffer_large() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // Sender uses RTP mode - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).build(now); - // Receiver has large reordering buffer (50 packets) - let rtc2 = Rtc::builder().set_reordering_size_audio(50).build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "audio".into(); - let ssrc_tx: Ssrc = 1337.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - - // Send packets with larger gaps that require big buffer - // Send 1, 10, 2, 11, 3, 12, 4, 13... (interleaved with gap of ~9) - // Shuffle to create out-of-order: 1, 11, 2, 12, 3, 13... - let mut send_order = Vec::new(); - for i in 0_u64..10 { - send_order.push(1 + i); - send_order.push(11 + i); - } - - for seq in send_order { - let time = (seq * 960) as u32; - let wallclock = l.start + l.duration(); - { - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - stream.write_rtp(RtpWrite::new(pt, seq.into(), time, wallclock, [seq as u8; 80])); - } - progress(&mut l, &mut r)?; - } - - for _ in 0..50 { - progress(&mut l, &mut r)?; - } - - let received_ranges: Vec<(u64, u64)> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::MediaData(data) = e { - Some((**data.seq_range.start(), **data.seq_range.end())) - } else { - None - } - }) - .collect(); - - assert!( - !received_ranges.is_empty(), - "Should receive packets with large reordering buffer" - ); - - // Verify ordering is correct despite large gaps - for i in 1..received_ranges.len() { - assert!( - received_ranges[i].0 >= received_ranges[i - 1].0, - "Packets should be reordered with large buffer: {:?} vs {:?}", - received_ranges[i], - received_ranges[i - 1] - ); - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtp_to_frame.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtp_to_frame.rs deleted file mode 100644 index 2c07dfcf4cf..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtp_to_frame.rs +++ /dev/null @@ -1,893 +0,0 @@ -use std::collections::VecDeque; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::{Codec, CodecExtra}; -use crate::vendor::str0m::media::{MediaKind, Mid, Pt}; -use crate::vendor::str0m::net::Receive; -use crate::vendor::str0m::rtp::rtcp::Rtcp; -use crate::vendor::str0m::rtp::{ExtensionValues, RawPacket, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, Input, Output, Reason, Rtc, RtcConfig, RtcError}; - -use super::common; -use common::{PendingPacket, connect_l_r_with_rtc, init_crypto_default, init_log, progress}; - -struct VideoTest { - sender: common::TestRtc, - receiver: common::TestRtc, - now: Instant, - pt: Pt, - repair_pt: Option, - drop_original: Option, - dropped: usize, - defer_rtx: bool, - deferred_rtx: Vec, -} - -/// Exercises receive-side frame assembly with a packet-mode sender and configurable receiver. -/// Routes datagrams in memory and advances time explicitly to test exact deadlines. -/// Can drop original RTP packets or delay RTX while still exchanging feedback. -impl VideoTest { - fn new(receiver_config: RtcConfig, rtx: bool) -> Result { - Self::with_codec(receiver_config, rtx, Codec::Vp8) - } - - fn with_codec(receiver_config: RtcConfig, rtx: bool, codec: Codec) -> Result { - init_crypto_default(); - let now = Instant::now(); - let sender_config = Rtc::builder().set_rtp_mode(true).enable_raw_packets(true); - let (mut sender, mut receiver) = connect_l_r_with_rtc( - sender_config.build(now), - receiver_config.enable_raw_packets(true).build(now), - ); - for _ in 0..1000 { - if sender.is_connected() && receiver.is_connected() { - break; - } - progress(&mut sender, &mut receiver)?; - } - assert!(sender.is_connected() && receiver.is_connected()); - let now = sender.last.max(receiver.last); - let params = sender.codec_config().find(|p| p.spec().codec == codec).unwrap(); - let pt = params.pt(); - let repair_pt = params.resend(); - let mut test = Self { - sender, - receiver, - now, - pt, - repair_pt, - drop_original: None, - dropped: 0, - defer_rtx: false, - deferred_rtx: Vec::new(), - }; - test.add_video("video".into(), 1337.into(), rtx); - test.tick(now)?; - test.sender.events.clear(); - test.receiver.events.clear(); - Ok(test) - } - - fn add_video(&mut self, mid: Mid, ssrc: Ssrc, rtx: bool) { - let repair = rtx.then(|| (*ssrc + 1).into()); - self.sender.direct_api().declare_media(mid, MediaKind::Video); - self.sender.direct_api().declare_stream_tx(ssrc, repair, mid, None); - self.sender.direct_api().stream_tx(&ssrc).unwrap().set_rtx_cache( - if rtx { 32 } else { 0 }, - Duration::from_secs(3), - None, - ); - self.receiver.direct_api().declare_media(mid, MediaKind::Video); - self.receiver - .direct_api() - .expect_stream_rx(ssrc, repair, mid, None) - .suppress_nack(!rtx); - } - - fn drain( - rtc: &mut common::TestRtc, - now: Instant, - is_sender: bool, - packets: &mut VecDeque<(bool, PendingPacket)>, - ) -> Result<(), RtcError> { - for _ in 0..1000 { - match rtc.poll_output()? { - Output::Timeout(at) => { - rtc.last = at; - return Ok(()); - } - Output::Event(event) => rtc.events.push((now, event)), - Output::Transmit(v) => packets.push_back(( - is_sender, - PendingPacket { - proto: v.proto, - source: v.source, - destination: v.destination, - contents: v.contents.to_vec(), - }, - )), - } - } - panic!("output polling did not quiesce"); - } - - // Route all traffic, including NACK/RTX, without the common harness's forced ticks. - fn flush(&mut self) -> Result<(), RtcError> { - let mut packets = VecDeque::new(); - Self::drain(&mut self.sender, self.now, true, &mut packets)?; - Self::drain(&mut self.receiver, self.now, false, &mut packets)?; - for _ in 0..10000 { - let Some((from_sender, packet)) = packets.pop_front() else { - return Ok(()); - }; - let bytes = &packet.contents; - // The fixed RTP header is unencrypted; match only the original stream. - if from_sender - && bytes.len() >= 12 - && bytes[0] >> 6 == 2 - && bytes[1] & 0x7f == *self.pt - && u32::from_be_bytes(bytes[8..12].try_into().unwrap()) == 1337 - && self.drop_original == Some(u16::from_be_bytes([bytes[2], bytes[3]])) - { - self.drop_original = None; - self.dropped += 1; - continue; - } - if from_sender - && self.defer_rtx - && bytes.len() >= 12 - && bytes[0] >> 6 == 2 - && Some(bytes[1] & 0x7f) == self.repair_pt.map(|pt| *pt) - && u32::from_be_bytes(bytes[8..12].try_into().unwrap()) == 1338 - { - self.deferred_rtx.push(packet); - continue; - } - let to = if from_sender { - &mut self.receiver - } else { - &mut self.sender - }; - to.handle_input(Input::Receive( - self.now, - Receive { - proto: packet.proto, - source: packet.source, - destination: packet.destination, - contents: bytes.as_slice().try_into()?, - }, - ))?; - // Drain the destination before delivering another packet to that peer. - Self::drain(to, self.now, !from_sender, &mut packets)?; - } - panic!("datagram exchange did not quiesce"); - } - - fn tick(&mut self, now: Instant) -> Result<(), RtcError> { - assert!(now >= self.now); - self.now = now; - self.sender.handle_input(Input::Timeout(now))?; - self.flush()?; - self.receiver.handle_input(Input::Timeout(now))?; - self.flush() - } - - fn advance_to(&mut self, target: Instant) -> Result<(), RtcError> { - assert!(target >= self.now); - let mut same_time = 0; - for _ in 0..10000 { - let next = self.sender.last.min(self.receiver.last); - if next > target { - return self.tick(target); - } - assert!(next >= self.now); - same_time = if next == self.now { same_time + 1 } else { 0 }; - assert!( - same_time < 8, - "expired timeout was rearmed: sender {:?}, receiver {:?}", - self.sender.last_timeout_reason(), - self.receiver.last_timeout_reason() - ); - self.tick(next)?; - } - panic!("too many timer wakeups"); - } - - fn write(&mut self, ssrc: Ssrc, seq: u64, timestamp: u32, data: &[u8], marker: bool) -> Result<(), RtcError> { - self.sender.direct_api().stream_tx(&ssrc).unwrap().write_rtp( - RtpWrite::new(self.pt, seq.into(), timestamp, self.now, data.to_vec()) - .marker(marker) - .nackable(true), - ); - self.flush()?; - self.sender.handle_input(Input::Timeout(self.now))?; - self.flush() - } - - fn send_vp8_frame(&mut self, seq: u64) -> Result<(), RtcError> { - self.write( - 1337.into(), - seq, - 47_000_000 + (seq as u32 - 47_000) * 18_000, - &[0x10, 0x00, 0x00, seq as u8], - true, - ) - } - - fn received_frames(&self) -> Vec<(u64, u64, bool)> { - self.receiver - .events - .iter() - .filter_map(|(_, event)| match event { - Event::MediaData(data) => Some((**data.seq_range.start(), **data.seq_range.end(), data.contiguous)), - _ => None, - }) - .collect() - } -} - -#[test] -pub fn audio_start_of_talk_spurt() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).build(now); - let rtc2 = Rtc::builder().set_reordering_size_audio(0).build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "audio".into(); - let ssrc_tx: Ssrc = 1337.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - // 1 - &[0x1, 0x2, 0x3, 0x4], - // 3 - &[0x9, 0xa, 0xb, 0xc], - // 2 - &[0x5, 0x6, 0x7, 0x8], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(300); - - let mut counts: Vec = vec![0, 3, 1]; - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp( - RtpWrite::new(pt, seq_no, time, wallclock, packet) - .marker(*seq_no % 2 == 0) - .ext_vals(exts), - ); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(v) = e { Some(v) } else { None }) - .collect(); - - for m in media { - assert!(m.audio_start_of_talk_spurt == (**m.seq_range.start() % 2 == 0)); - } - - Ok(()) -} - -/// Test permanent packet loss releases video at the deadline and reports the gap. -#[test] -pub fn video_reorder_timeout_permanent_loss() -> Result<(), RtcError> { - let timeout = Duration::from_millis(300); - for cadence in [Duration::from_millis(200), Duration::from_secs(1)] { - let mut t = VideoTest::new(Rtc::builder(), false)?; - t.send_vp8_frame(47_000)?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - t.advance_to(t.now + cadence)?; - t.send_vp8_frame(47_002)?; // 47001 is never cached, so loss is permanent. - let deadline = t.now + timeout; - t.advance_to(deadline - Duration::from_nanos(1))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - assert_eq!(t.receiver.last, deadline); - assert_eq!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - t.tick(t.receiver.last)?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true), (47_002, 47_002, false)]); - t.send_vp8_frame(47_003)?; - assert_eq!( - t.received_frames(), - [(47_000, 47_000, true), (47_002, 47_002, false), (47_003, 47_003, true)] - ); - } - Ok(()) -} - -/// Test timeout expiry preserves VP8/VP9 temporal-layer dependency checks. -#[test] -fn video_reorder_timeout_temporal_dependencies() -> Result<(), RtcError> { - let timeout = Duration::from_millis(300); - for codec in [Codec::Vp8, Codec::Vp9] { - let mut t = VideoTest::with_codec(Rtc::builder(), false, codec)?; - // Parser-valid synthetic payloads, not complete encoded video bitstreams. - let payload = |picture: u8, tl0: u8, layer: u8, keyframe: bool| match codec { - // X/S, I/L/T, PictureID, TL0PICIDX, TID/Y, payload header. - Codec::Vp8 => vec![0x90, 0xe0, picture, tl0, layer << 6, u8::from(!keyframe), 0, 0], - // I/P/L/B/E, PictureID, TID (SID=0), TL0PICIDX; non-flexible mode. - Codec::Vp9 => vec![ - if keyframe { 0xac } else { 0xec }, - picture, - layer << 5, - tl0, - if keyframe { 0x80 } else { 0x84 }, - ], - _ => unreachable!(), - }; - t.write(1337.into(), 47_000, 1000, &payload(1, 1, 0, true), true)?; - t.write(1337.into(), 47_001, 2000, &payload(2, 1, 1, false), true)?; - let initial = [(47_000, 47_000, true), (47_001, 47_001, true)]; - assert_eq!(t.received_frames(), initial); - t.advance_to(t.now + Duration::from_millis(100))?; - // Base picture 3 (sequence 47002, TL0PICIDX=2) is permanently missing. - // Enhancement picture 4 depends on that missing base. - t.write(1337.into(), 47_003, 4000, &payload(4, 2, 1, false), true)?; - t.write(1337.into(), 47_004, 5000, &payload(5, 3, 0, true), true)?; - let deadline = t.now + timeout; - t.advance_to(deadline - Duration::from_nanos(1))?; - assert_eq!(t.received_frames(), initial); - assert_eq!(t.receiver.last, deadline); - assert_eq!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - // A rejected candidate requires Session to compute the following candidate's deadline. - t.advance_to(deadline)?; - assert_eq!( - t.received_frames(), - [(47_000, 47_000, true), (47_001, 47_001, true), (47_004, 47_004, false)], - "{codec:?}: reject the enhancement and drain the following due base" - ); - assert!(t.receiver.last > deadline, "no stale deadline after codec rejection"); - t.write(1337.into(), 47_005, 6000, &payload(6, 3, 1, false), true)?; - assert_eq!(t.received_frames().last(), Some(&(47_005, 47_005, true))); - let layers: Vec<_> = t - .receiver - .events - .iter() - .filter_map(|(_, event)| match event { - Event::MediaData(data) => Some(match data.codec_extra { - CodecExtra::Vp8(e) => ( - e.picture_id.unwrap(), - e.tl0_picture_id.unwrap(), - e.layer_index, - e.is_keyframe, - ), - CodecExtra::Vp9(e) => ( - e.picture_id.unwrap(), - e.tl0_picture_id.unwrap(), - e.tid.unwrap(), - e.is_keyframe, - ), - _ => panic!("expected parsed temporal-layer metadata"), - }), - _ => None, - }) - .collect(); - assert_eq!( - layers, - [(1, 1, 0, true), (2, 1, 1, false), (5, 3, 0, true), (6, 3, 1, false)] - ); - t.advance_to(deadline + Duration::from_millis(100))?; - assert_eq!(t.received_frames().len(), 4); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - } - Ok(()) -} - -/// Test H264 FU-A reassembly waits for completion and uses the first fragment's receipt time. -#[test] -fn video_reorder_timeout_h264_fragments() -> Result<(), RtcError> { - let timeout = Duration::from_millis(300); - let mut t = VideoTest::with_codec(Rtc::builder(), false, Codec::H264)?; - // Synthetic NAL/FU-A payloads exercise reassembly, not video decoding. - t.write(1337.into(), 47_000, 1000, &[0x65, 0xaa], true)?; - t.advance_to(t.now + Duration::from_millis(100))?; - t.write(1337.into(), 47_002, 2000, &[0x7c, 0x85, 0x11], false)?; - let deadline = t.now + timeout; - t.write(1337.into(), 47_003, 2000, &[0x7c, 0x05, 0x22], false)?; - t.advance_to(t.now + Duration::from_millis(100))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - t.write(1337.into(), 47_004, 2000, &[0x7c, 0x45, 0x33], true)?; - t.advance_to(deadline - Duration::from_nanos(1))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - assert_eq!(t.receiver.last, deadline); - assert_eq!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - t.tick(deadline)?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true), (47_002, 47_004, false)]); - let data = t - .receiver - .events - .iter() - .find_map(|(_, event)| match event { - Event::MediaData(data) if **data.seq_range.start() == 47_002 => Some(data), - _ => None, - }) - .unwrap(); - assert_eq!(data.data.as_ref(), &[0, 0, 0, 1, 0x65, 0x11, 0x22, 0x33]); - assert_eq!(data.network_time, deadline - timeout); - assert!(matches!(data.codec_extra, CodecExtra::H264(e) if e.is_keyframe)); - t.write(1337.into(), 47_005, 3000, &[0x61, 0x44], true)?; - t.advance_to(t.now + Duration::from_millis(100))?; - assert_eq!(t.received_frames().last(), Some(&(47_005, 47_005, true))); - assert_eq!(t.received_frames().len(), 3); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - Ok(()) -} - -/// A slow H264 frame survives until it completes when no complete successor exists. -#[test] -fn video_reorder_timeout_h264_slow_frame_completes() -> Result<(), RtcError> { - let mut t = VideoTest::with_codec(Rtc::builder(), false, Codec::H264)?; - t.write(1337.into(), 47_000, 1000, &[0x65, 0xaa], true)?; - t.write(1337.into(), 47_002, 2000, &[0x7c, 0x85, 0x11], false)?; - t.advance_to(t.now + Duration::from_secs(5))?; - t.write(1337.into(), 47_003, 2000, &[0x7c, 0x45, 0x33], true)?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true), (47_002, 47_003, false)]); - t.write(1337.into(), 47_004, 3000, &[0x61, 0x44], true)?; - t.advance_to(t.now + Duration::from_millis(600))?; - assert_eq!( - t.received_frames(), - [(47_000, 47_000, true), (47_002, 47_003, false), (47_004, 47_004, true)] - ); - Ok(()) -} - -/// Test H264 can release a later NAL after earlier fragments of the same picture are lost. -#[test] -fn video_reorder_timeout_h264_same_timestamp_gap() -> Result<(), RtcError> { - let timeout = Duration::from_millis(300); - let mut t = VideoTest::with_codec(Rtc::builder(), false, Codec::H264)?; - t.write(1337.into(), 47_000, 1000, &[0x65, 0xaa], true)?; - t.write(1337.into(), 47_001, 2000, &[0x7c, 0x81, 0x11], false)?; - // Missing FU-A fragment 47002; another NAL in the same picture is a new head. - t.write(1337.into(), 47_003, 2000, &[0x7c, 0x41, 0x33], false)?; - t.write(1337.into(), 47_004, 2000, &[0x61, 0x44], true)?; - let deadline = t.now + timeout; - t.advance_to(deadline - Duration::from_nanos(1))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - assert_eq!(t.receiver.last, deadline); - t.tick(deadline)?; - // The existing assembler can emit the later NAL despite missing earlier fragments. - assert_eq!(t.received_frames(), [(47_000, 47_000, true), (47_004, 47_004, false)]); - let data = t - .receiver - .events - .iter() - .find_map(|(_, event)| match event { - Event::MediaData(data) if **data.seq_range.start() == 47_004 => Some(data), - _ => None, - }) - .unwrap(); - assert_eq!(data.data.as_ref(), &[0, 0, 0, 1, 0x61, 0x44]); - t.advance_to(deadline + Duration::from_millis(100))?; - assert_eq!(t.received_frames().len(), 2); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - Ok(()) -} - -/// Test NACK/RTX recovery fills the gap before expiry and preserves frame continuity. -#[test] -fn video_reorder_timeout_rtx_recovers() -> Result<(), RtcError> { - let timeout = Duration::from_millis(300); - let mut t = VideoTest::new(Rtc::builder(), true)?; - t.send_vp8_frame(47_000)?; - t.advance_to(t.now + Duration::from_millis(100))?; - t.drop_original = Some(47_001); - t.send_vp8_frame(47_001)?; - assert_eq!(t.dropped, 1); - t.advance_to(t.now + Duration::from_millis(100))?; - t.send_vp8_frame(47_002)?; - let deadline = t.now + timeout; - t.advance_to(deadline - Duration::from_millis(1))?; - assert_eq!( - t.received_frames(), - [(47_000, 47_000, true), (47_001, 47_001, true), (47_002, 47_002, true)] - ); - assert!(t.receiver.events.iter().any(|(_, e)| matches!(e.as_raw_packet(), - Some(RawPacket::RtcpTx(Rtcp::Nack(n))) if n.reports.iter().any(|r| r.pid == 47_001)))); - assert!(t.sender.events.iter().any(|(_, e)| matches!(e.as_raw_packet(), - Some(RawPacket::RtcpRx(Rtcp::Nack(n))) if n.reports.iter().any(|r| r.pid == 47_001)))); - let repair_pt = t.sender.params_vp8().resend().unwrap(); - assert!(t.receiver.events.iter().any(|(_, e)| matches!(e.as_raw_packet(), - Some(RawPacket::RtpRx(header, payload)) if header.payload_type == repair_pt - && payload.get(..2) == Some(&47_001u16.to_be_bytes()[..])))); - t.advance_to(deadline + Duration::from_millis(100))?; - assert_eq!(t.received_frames().len(), 3); - Ok(()) -} - -/// RTX received in a later reporting interval can make that interval's loss negative. -#[test] -fn video_receiver_report_loss_after_delayed_rtx() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder().set_rtp_mode(true), true)?; - t.defer_rtx = true; - - // Receive 118 of 120 packets and hold the sender's repairs until after the RR. - for seq in 47_000..47_120 { - if [47_110, 47_111].contains(&seq) { - t.drop_original = Some(seq as u16); - } - t.send_vp8_frame(seq)?; - } - assert_eq!(t.dropped, 2); - - // Inspect the RR received by the sender, exercising RTCP serialization too. - let next_report = |t: &mut VideoTest| -> Result<_, RtcError> { - let deadline = t.now + Duration::from_secs(5); - loop { - t.advance_to(t.now + Duration::from_millis(10))?; - if let Some(report) = t - .sender - .events - .iter() - .find_map(|(_, event)| match event.as_raw_packet() { - Some(RawPacket::RtcpRx(Rtcp::ReceiverReport(rr))) => { - rr.reports.iter().find(|r| *r.ssrc == 1337).copied() - } - _ => None, - }) { - return Ok(report); - } - assert!(t.now < deadline, "sender did not receive a receiver report"); - } - }; - - let first = next_report(&mut t)?; - assert_eq!(first.max_seq, 47_119); - assert_eq!(first.packets_lost, 2); - assert_eq!(first.fraction_lost, 4); - assert!(!t.deferred_rtx.is_empty(), "sender must retransmit via RTX"); - t.sender.events.clear(); - - t.defer_rtx = false; - for packet in std::mem::take(&mut t.deferred_rtx) { - t.receiver.handle_input(Input::Receive( - t.now, - Receive { - proto: packet.proto, - source: packet.source, - destination: packet.destination, - contents: packet.contents.as_slice().try_into()?, - }, - ))?; - t.flush()?; - } - - // The two repairs plus 120 new packets mean 122 received versus 120 expected. - for seq in 47_120..47_240 { - t.send_vp8_frame(seq)?; - } - let mut received: Vec<_> = t - .receiver - .events - .iter() - .filter_map(|(_, event)| match event { - Event::RtpPacket(packet) => Some(*packet.seq_no), - _ => None, - }) - .collect(); - received.sort_unstable(); - assert_eq!(received, (47_000..47_240).collect::>()); - - let second = next_report(&mut t)?; - assert_eq!(second.max_seq, 47_239); - assert_eq!(second.packets_lost, 0); - assert_eq!(second.fraction_lost, 0, "negative interval loss must be zero"); - Ok(()) -} - -/// Test RTX arriving after timeout release cannot resurrect an older frame. -#[test] -fn video_reorder_timeout_rtx_after_release() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder(), true)?; - t.defer_rtx = true; - t.send_vp8_frame(47_000)?; - t.advance_to(t.now + Duration::from_millis(100))?; - t.drop_original = Some(47_001); - t.send_vp8_frame(47_001)?; - assert_eq!(t.dropped, 1); - t.advance_to(t.now + Duration::from_millis(100))?; - t.send_vp8_frame(47_002)?; - let mut last_nack = None; - for _ in 0..200 { - let requests: Vec<_> = t - .receiver - .events - .iter() - .filter_map(|(at, e)| { - matches!(e.as_raw_packet(), Some(RawPacket::RtcpTx(Rtcp::Nack(n))) - if n.reports.iter().any(|r| r.pid == 47_001)) - .then_some(*at) - }) - .collect(); - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - if requests.len() == 5 { - last_nack = requests.last().copied(); - break; - } - assert!(requests.len() < 5); - t.advance_to(t.now + Duration::from_millis(10))?; - } - let deadline = last_nack.expect("five NACK attempts") + Duration::from_millis(300); - t.advance_to(deadline - Duration::from_nanos(1))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - assert!(!t.deferred_rtx.is_empty(), "hold genuine sender-generated RTX"); - assert!(t.receiver.events.iter().any(|(_, e)| matches!(e.as_raw_packet(), - Some(RawPacket::RtcpTx(Rtcp::Nack(n))) if n.reports.iter().any(|r| r.pid == 47_001)))); - assert!(t.sender.events.iter().any(|(_, e)| matches!(e.as_raw_packet(), - Some(RawPacket::RtcpRx(Rtcp::Nack(n))) if n.reports.iter().any(|r| r.pid == 47_001)))); - let repair_pt = t.repair_pt.unwrap(); - let is_repair = |e: &Event| { - matches!(e.as_raw_packet(), - Some(RawPacket::RtpRx(header, payload)) if header.payload_type == repair_pt - && *header.ssrc == 1338 - && payload.get(..2) == Some(&47_001u16.to_be_bytes()[..])) - }; - assert!(!t.receiver.events.iter().any(|(_, e)| is_repair(e))); - assert_eq!(t.receiver.last, deadline); - assert_eq!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - t.tick(deadline)?; - let released = [(47_000, 47_000, true), (47_002, 47_002, false)]; - assert_eq!(t.received_frames(), released); - - t.advance_to(deadline + Duration::from_millis(50))?; - t.defer_rtx = false; - for packet in std::mem::take(&mut t.deferred_rtx) { - t.receiver.handle_input(Input::Receive( - t.now, - Receive { - proto: packet.proto, - source: packet.source, - destination: packet.destination, - contents: packet.contents.as_slice().try_into()?, - }, - ))?; - } - t.flush()?; - assert!(t.receiver.events.iter().any(|(at, e)| *at > deadline && is_repair(e))); - assert_eq!(t.received_frames(), released, "late RTX must not resurrect 47001"); - t.send_vp8_frame(47_003)?; - t.advance_to(deadline + Duration::from_millis(100))?; - assert_eq!( - t.received_frames(), - [(47_000, 47_000, true), (47_002, 47_002, false), (47_003, 47_003, true)] - ); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - Ok(()) -} - -/// Audio's timeout cannot disable or change automatic video recovery. -#[test] -fn video_recovery_is_independent_of_audio_timeout() -> Result<(), RtcError> { - for timeout in [None, Some(Duration::ZERO), Some(Duration::from_secs(5))] { - let mut t = VideoTest::new(Rtc::builder().set_reordering_timeout_audio(timeout), false)?; - t.send_vp8_frame(47_000)?; - t.advance_to(t.now + Duration::from_millis(100))?; - t.write(1337.into(), 47_001, 100, &[0x10, 0, 0], false)?; - t.write(1337.into(), 47_003, 200, &[0x10, 0, 0], false)?; - let deadline = t.now + Duration::from_millis(300); - t.advance_to(t.now + Duration::from_millis(100))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - t.write(1337.into(), 47_004, 200, &[0x00, 0], true)?; - t.advance_to(deadline - Duration::from_nanos(1))?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - t.advance_to(deadline)?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true), (47_003, 47_004, false)]); - } - Ok(()) -} - -/// Test the earliest video deadline wins across media, regardless of iteration order. -#[test] -fn video_reorder_timeout_earliest_across_media() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder(), false)?; - t.add_video("other".into(), 2337.into(), false); - t.send_vp8_frame(47_000)?; - t.write(2337.into(), 48_000, 1000, &[0x10, 0, 0], true)?; - let base = t.now; - t.advance_to(base + Duration::from_millis(100))?; - // The second media has the earlier deadline, independent of iteration order. - t.write(2337.into(), 48_002, 2000, &[0x10, 0, 0], true)?; - t.advance_to(base + Duration::from_millis(150))?; - t.send_vp8_frame(47_002)?; - t.advance_to(base + Duration::from_millis(399))?; - assert_eq!(t.received_frames().len(), 2); - assert_eq!(t.receiver.last, base + Duration::from_millis(400)); - t.tick(t.receiver.last)?; - assert_eq!(t.received_frames().last(), Some(&(48_002, 48_002, false))); - t.advance_to(base + Duration::from_millis(449))?; - assert_eq!(t.receiver.last, base + Duration::from_millis(450)); - t.tick(t.receiver.last)?; - assert_eq!(t.received_frames().last(), Some(&(47_002, 47_002, false))); - assert_eq!(t.received_frames().len(), 4); - Ok(()) -} - -/// A frame can start before a stream pause and finish after its resume. -#[test] -fn video_frame_completes_across_pause() -> Result<(), RtcError> { - for pause_ms in [100, 500] { - let mut t = VideoTest::new( - Rtc::builder().set_pause_threshold(Duration::from_millis(pause_ms)), - false, - )?; - t.write(1337.into(), 47_000, 1000, &[0x10, 0, 0], false)?; - assert!(t.received_frames().is_empty()); - t.advance_to(t.now + Duration::from_millis(650))?; - assert!( - t.receiver - .events - .iter() - .any(|(_, event)| { matches!(event, Event::StreamPaused(paused) if paused.paused) }) - ); - t.write(1337.into(), 47_001, 1000, &[0x00, 0], true)?; - assert_eq!(t.received_frames(), [(47_000, 47_001, true)]); - assert!( - t.receiver - .events - .iter() - .any(|(_, event)| { matches!(event, Event::StreamPaused(paused) if !paused.paused) }) - ); - } - Ok(()) -} - -/// A lost tail must not keep a fresh frame hidden for an entire reordering window -/// after the receiver has reported a pause. -#[test] -fn video_new_frame_after_paused_incomplete_frame_makes_progress() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder().set_pause_threshold(Duration::from_millis(500)), false)?; - t.write(1337.into(), 46_999, 500, &[0x10, 0, 0], true)?; - assert_eq!(t.received_frames(), [(46_999, 46_999, true)]); - t.write(1337.into(), 47_000, 1000, &[0x10, 0, 0], false)?; - t.advance_to(t.now + Duration::from_millis(650))?; - assert!( - t.receiver - .events - .iter() - .any(|(_, event)| { matches!(event, Event::StreamPaused(paused) if paused.paused) }) - ); - - // Packet 47_001 (the old frame's tail) was lost. The sender resumes - // with a complete new frame, which should be delivered as noncontiguous - // within a bounded interval even if no more packets arrive. - t.write(1337.into(), 47_002, 2000, &[0x10, 0, 0], true)?; - t.advance_to(t.now + Duration::from_millis(2500))?; - assert_eq!(t.received_frames(), [(46_999, 46_999, true), (47_002, 47_002, false)]); - Ok(()) -} - -/// A new frame after a pause must not implicitly complete the old frame's missing tail. -#[test] -fn video_new_frame_start_drops_paused_incomplete_frame() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder().set_pause_threshold(Duration::from_millis(500)), false)?; - t.write(1337.into(), 46_999, 500, &[0x10, 0, 0], true)?; - t.write(1337.into(), 47_000, 1000, &[0x10, 0, 0], false)?; - t.advance_to(t.now + Duration::from_millis(650))?; - - // Same SSRC and consecutive sequence numbers, but a new VP8 frame starts. - t.write(1337.into(), 47_001, 2000, &[0x10, 0, 0], false)?; - assert_eq!(t.received_frames(), [(46_999, 46_999, true)]); - t.write(1337.into(), 47_002, 2000, &[0x00, 0], true)?; - t.advance_to(t.now + Duration::from_millis(2200))?; - assert_eq!(t.received_frames(), [(46_999, 46_999, true), (47_001, 47_002, false)]); - Ok(()) -} - -/// A restarted sender can keep its SSRC while starting its picture IDs over. -#[test] -fn video_same_ssrc_restart_after_pause_accepts_new_keyframe() -> Result<(), RtcError> { - for previous_picture_id in [40, 1] { - let mut t = VideoTest::new(Rtc::builder().set_pause_threshold(Duration::from_millis(500)), false)?; - let vp8_keyframe = |picture_id: u8| [0x90, 0xe0, picture_id, picture_id, 0, 0, 0, 0]; - t.write(1337.into(), 47_000, 1000, &vp8_keyframe(previous_picture_id), true)?; - assert_eq!(t.received_frames(), [(47_000, 47_000, true)]); - t.advance_to(t.now + Duration::from_millis(650))?; - assert!( - t.receiver - .events - .iter() - .any(|(_, event)| matches!(event, Event::StreamPaused(p) if p.paused)) - ); - - t.write(1337.into(), 47_001, 2000, &vp8_keyframe(1), true)?; - assert_eq!( - t.received_frames(), - [(47_000, 47_000, true), (47_001, 47_001, false)], - "keyframe after PictureID {previous_picture_id} was not emitted" - ); - } - Ok(()) -} - -/// Video recovery leaves RTP-mode packet delivery unchanged. -#[test] -fn video_reorder_timeout_does_not_change_rtp_mode() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder().set_rtp_mode(true), false)?; - t.send_vp8_frame(47_000)?; - t.send_vp8_frame(47_002)?; - assert!(t.received_frames().is_empty()); - let seqs: Vec<_> = t - .receiver - .events - .iter() - .filter_map(|(_, e)| match e { - Event::RtpPacket(p) => Some(*p.seq_no), - _ => None, - }) - .collect(); - assert_eq!(seqs, [47_000, 47_002]); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - Ok(()) -} - -/// Video recovery does not change audio's separate timeout. -#[test] -fn video_reorder_timeout_does_not_change_audio() -> Result<(), RtcError> { - let mut t = VideoTest::new(Rtc::builder(), false)?; - let mid = "audio".into(); - let ssrc = 3337.into(); - let pt = t.sender.params_opus().pt(); - t.sender.direct_api().declare_media(mid, MediaKind::Audio); - t.sender.direct_api().declare_stream_tx(ssrc, None, mid, None); - t.receiver.direct_api().declare_media(mid, MediaKind::Audio); - t.receiver.direct_api().expect_stream_rx(ssrc, None, mid, None); - for seq in [100u64, 102] { - t.sender - .direct_api() - .stream_tx(&ssrc) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), seq as u32 * 960, t.now, [0xf8, 0xff, 0xfe]).marker(true)); - t.tick(t.now)?; - } - t.advance_to(t.now + Duration::from_millis(500))?; - assert_eq!(t.received_frames(), [(100, 100, true)]); - assert_ne!(t.receiver.last_timeout_reason(), Reason::ReceiveReorder); - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/rtx-cache-0.rs b/rs/moq-webrtc/src/vendor/str0m/tests/rtx-cache-0.rs deleted file mode 100644 index ac2374049fc..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/rtx-cache-0.rs +++ /dev/null @@ -1,110 +0,0 @@ -use std::collections::VecDeque; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::rtp::{ExtensionValues, RtpWrite, Ssrc}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{connect_l_r, init_crypto_default, init_log, progress}; - -#[test] -pub fn rtx_cache_0() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - - let mid = "aud".into(); - let rid = "hi".into(); - - // In this example we are using MID and RID to identify the incoming media. - let ssrc_tx: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Audio); - - l.direct_api() - .declare_stream_tx(ssrc_tx, None, mid, Some(rid)) - // - // disable RTX cache by setting 0 - .set_rtx_cache(0, Duration::ZERO, Some(0.15)); - - r.direct_api().declare_media(mid, MediaKind::Audio).expect_rid_rx(rid); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - - let to_write: Vec<&[u8]> = vec![ - // 1 - &[0x1, 0x2, 0x3, 0x4], - // 3 - &[0x9, 0xa, 0xb, 0xc], - // 2 - &[0x5, 0x6, 0x7, 0x8], - ]; - - let mut to_write: VecDeque<_> = to_write.into(); - - let mut write_at = l.last + Duration::from_millis(300); - - let mut counts: Vec = vec![0, 3, 1]; - - loop { - if l.start + l.duration() > write_at { - write_at = l.last + Duration::from_millis(300); - if let Some(packet) = to_write.pop_front() { - let wallclock = l.start + l.duration(); - - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - - let count = counts.remove(0); - let time = (count * 1000 + 47_000_000) as u32; - let seq_no = (47_000 + count).into(); - - let exts = ExtensionValues { - audio_level: Some(-42 - count as i8), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, packet).ext_vals(exts)); - } - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - - assert_eq!(media.len(), 3); - - assert!(l.media(mid).is_some()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_some()); - l.direct_api().remove_media(mid); - assert!(l.media(mid).is_none()); - assert!(l.direct_api().stream_tx_by_mid(mid, None).is_none()); - - assert!(r.media(mid).is_some()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_some()); - r.direct_api().remove_media(mid); - assert!(r.media(mid).is_none()); - assert!(r.direct_api().stream_rx_by_mid(mid, None).is_none()); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-m-recycle.rs b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-m-recycle.rs deleted file mode 100644 index 7e6d5d70e17..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-m-recycle.rs +++ /dev/null @@ -1,504 +0,0 @@ -use std::time::Instant; - -use super::common; -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::change::SdpOffer; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::format::CodecSpec; -use crate::vendor::str0m::format::FormatParams; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::media::Direction; -use crate::vendor::str0m::media::Frequency; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::media::Mid; -use crate::vendor::str0m::media::Pt; -use common::TestRtc; -use common::init_crypto_default; -use common::init_log; -use common::negotiate; -use tracing::Span; -use tracing::info_span; - -#[test] -pub fn stop_media_then_remote_recycles_slot() { - init_log(); - init_crypto_default(); - - // L stops its video m-line, then receives an offer that recycles the - // resulting port=0 slot with a new mid (RFC 8829 §5.2.2). - let (mut l, mut r) = with_params(info_span!("L"), &[vp8(100)], info_span!("R"), &[vp8(100)]); - - let old_mid = l._mids()[0]; - - negotiate(&mut l, &mut r, |change| { - change.stop_media(old_mid); - }); - - assert!(l.media(old_mid).unwrap().stopped()); - assert!(r.media(old_mid).unwrap().stopped()); - - // str0m's own SdpApi doesn't produce recycling offers, so take an - // offer from R (which appends a new m-line) and rewrite it so the - // new m-line lives at the index of the stopped one - what a browser - // would emit per RFC 8829 §5.2.2. - let offer_from_r = r - .span - .in_scope(|| { - let mut change = r.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("R has a change to apply"); - - let offer_sdp = offer_from_r.0.to_sdp_string(); - let recycled_offer_sdp = rewrite_offer_to_recycle_stopped_slot(&offer_sdp, old_mid); - - let recycled_offer = SdpOffer::from_sdp_string(&recycled_offer_sdp).expect("recycled offer parses"); - - let answer = l - .span - .in_scope(|| l.rtc.sdp_api().accept_offer(recycled_offer).expect("accept")); - - let answer_sdp = answer.to_sdp_string(); - - // RFC 3264 §6: the answer must have the same m-line count as the - // offer. Without recycling, str0m appends a second m-line and the - // answer is invalid. - let count_m_lines = |s: &str| s.lines().filter(|l| l.starts_with("m=")).count(); - let offer_m_lines = count_m_lines(&recycled_offer_sdp); - let answer_m_lines = count_m_lines(&answer_sdp); - assert_eq!( - answer_m_lines, offer_m_lines, - "answer m-line count ({answer_m_lines}) differs from offer m-line count ({offer_m_lines})\n\n\ - rewritten offer:\n{recycled_offer_sdp}\n\nanswer:\n{answer_sdp}", - ); -} - -#[test] -pub fn recycling_rejected_for_non_stopped_slot() { - init_log(); - init_crypto_default(); - - // L holds an active video m-line. An offer arrives that tries to - // recycle that active slot with a new mid (no prior stop). str0m must - // refuse rather than install a second Media at the same index. - let (mut l, mut r) = with_params(info_span!("L"), &[vp8(100)], info_span!("R"), &[vp8(100)]); - - let active_mid = l._mids()[0]; - - // Sanity: the mid is active, not stopped. - assert!(!l.media(active_mid).unwrap().stopped()); - assert!(!l.media(active_mid).unwrap().disabled()); - - // Take an ordinary offer from R adding a new m-line, then rewrite it - // so the new m-line squats the slot of L's active mid. - let offer_from_r = r - .span - .in_scope(|| { - let mut change = r.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("R has a change to apply"); - - let offer_sdp = offer_from_r.0.to_sdp_string(); - let bad_offer_sdp = rewrite_offer_to_recycle_stopped_slot(&offer_sdp, active_mid); - let bad_offer = SdpOffer::from_sdp_string(&bad_offer_sdp).expect("offer parses"); - - let result = l.span.in_scope(|| l.rtc.sdp_api().accept_offer(bad_offer)); - - assert!( - result.is_err(), - "accept_offer must reject a recycling attempt against a non-stopped slot, got Ok:\n{}", - bad_offer_sdp - ); -} - -#[test] -pub fn stop_media_recycled_slot_state() { - init_log(); - init_crypto_default(); - - // After a recycled offer is accepted, verify the post-recycle state - // of the surviving Media objects. The happy-path test only asserts - // answer m-line count; this pins down the full state. - let (mut l, mut r) = with_params(info_span!("L"), &[vp8(100)], info_span!("R"), &[vp8(100)]); - - let old_mid = l._mids()[0]; - - negotiate(&mut l, &mut r, |change| { - change.stop_media(old_mid); - }); - - let offer_from_r = r - .span - .in_scope(|| { - let mut change = r.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("R has a change to apply"); - - let recycled_offer_sdp = rewrite_offer_to_recycle_stopped_slot(&offer_from_r.0.to_sdp_string(), old_mid); - let recycled_offer = SdpOffer::from_sdp_string(&recycled_offer_sdp).expect("parses"); - - // The new mid is whichever mid in the recycled SDP isn't old_mid. - let new_mid = new_mid_in_sdp(&recycled_offer_sdp, old_mid); - - l.span.in_scope(|| { - l.rtc.sdp_api().accept_offer(recycled_offer).expect("accept"); - }); - - // L side: old mid is retired, new mid is live and not stopped. - assert!( - !l._mids().contains(&old_mid), - "retired mid {old_mid} must not appear in L's medias after recycle, got {:?}", - l._mids() - ); - assert!( - l._mids().contains(&new_mid), - "recycled mid {new_mid} must appear in L's medias, got {:?}", - l._mids() - ); - assert!(l.media(old_mid).is_none(), "old Media must be gone on L"); - - let new_media_l = l.media(new_mid).expect("new Media on L"); - assert!(!new_media_l.stopped(), "recycled Media must not be stopped"); - assert!(!new_media_l.disabled(), "recycled Media must not be disabled"); - assert_eq!( - new_media_l.kind(), - MediaKind::Video, - "recycled Media kind must match the offer" - ); - // R offered sendonly, so L's inverted direction is recvonly. - assert_eq!(new_media_l.direction(), Direction::RecvOnly); - assert_eq!( - new_media_l.remote_pts(), - &[Pt::new_with_value(100)], - "recycled Media must have remote_pts populated" - ); -} - -#[test] -pub fn stop_media_and_recycle_then_negotiate_again() { - init_log(); - init_crypto_default(); - - // After accepting a recycled offer, L must still be able to generate - // a valid subsequent offer of its own. This exercises that session - // state (medias, streams, index bookkeeping) is consistent for the - // side that processed the recycling. - // - // We don't round-trip R here: R sent a non-recycled offer that was - // rewritten out-of-band, so from R's own perspective the resulting - // answer is malformed. That's a synthetic-test artifact, not a - // real-world scenario (browsers always answer in-shape). - let (mut l, mut r) = with_params(info_span!("L"), &[vp8(100)], info_span!("R"), &[vp8(100)]); - - let old_mid = l._mids()[0]; - - negotiate(&mut l, &mut r, |change| { - change.stop_media(old_mid); - }); - - let offer_from_r = r - .span - .in_scope(|| { - let mut change = r.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("R has a change to apply"); - - let recycled_offer_sdp = rewrite_offer_to_recycle_stopped_slot(&offer_from_r.0.to_sdp_string(), old_mid); - let recycled_offer = SdpOffer::from_sdp_string(&recycled_offer_sdp).expect("parses"); - - l.span - .in_scope(|| l.rtc.sdp_api().accept_offer(recycled_offer).expect("accept")); - - // L must be able to create another offer cleanly. This would fail if - // `as_media_lines` disagrees with the post-recycle `medias` list. - let follow_up = l - .span - .in_scope(|| { - let mut change = l.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("L can produce a follow-up offer"); - - let follow_up_sdp = follow_up.0.to_sdp_string(); - - // Retired mid must not reappear in L's offer. - let old_mid_str = old_mid.to_string(); - assert!( - !follow_up_sdp - .lines() - .any(|l| l.strip_prefix("a=mid:").map(str::trim) == Some(old_mid_str.as_str())), - "retired mid resurfaced in L's follow-up offer:\n{}", - follow_up_sdp - ); - // The follow-up SDP must have exactly 2 m-lines (recycled + new). - let m_line_count = follow_up_sdp.lines().filter(|l| l.starts_with("m=")).count(); - assert_eq!( - m_line_count, 2, - "expected 2 m-lines in follow-up offer, got:\n{}", - follow_up_sdp - ); - assert!(!l._mids().contains(&old_mid)); -} - -#[test] -pub fn recycling_with_media_type_change() { - init_log(); - init_crypto_default(); - - // JSEP §5.2.2 allows a recycled slot to change media type. Stop an - // audio m-line and have the remote reoffer with a video m-line at - // the same slot. Both peers need audio *and* video codecs, so we - // construct them manually rather than via with_params. - let build = |span: Span| { - let mut b = Rtc::builder().clear_codecs(); - b.codec_config().add_config( - Pt::new_with_value(111), - None, - Codec::Opus, - Frequency::FORTY_EIGHT_KHZ, - Some(2), - FormatParams::default(), - ); - b.codec_config().add_config( - Pt::new_with_value(100), - None, - Codec::Vp8, - Frequency::NINETY_KHZ, - None, - FormatParams::default(), - ); - TestRtc::new_with_rtc(span, b.build(Instant::now())) - }; - let mut l = build(info_span!("L")); - let mut r = build(info_span!("R")); - - negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - }); - - let old_mid = l._mids()[0]; - assert_eq!(l.media(old_mid).unwrap().kind(), MediaKind::Audio); - - negotiate(&mut l, &mut r, |change| { - change.stop_media(old_mid); - }); - - let offer_from_r = r - .span - .in_scope(|| { - let mut change = r.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("R has a change to apply"); - - let recycled_sdp = rewrite_offer_to_recycle_stopped_slot(&offer_from_r.0.to_sdp_string(), old_mid); - let recycled_offer = SdpOffer::from_sdp_string(&recycled_sdp).expect("parses"); - let new_mid = new_mid_in_sdp(&recycled_sdp, old_mid); - - let result = l.span.in_scope(|| l.rtc.sdp_api().accept_offer(recycled_offer)); - assert!( - result.is_ok(), - "accepting a recycle that changes media type (audio->video) should succeed per JSEP §5.2.2: {:?}", - result.err() - ); - - let recycled = l.media(new_mid).expect("new Media present"); - assert_eq!( - recycled.kind(), - MediaKind::Video, - "recycled Media kind must reflect the new m-line type" - ); - assert!(!recycled.stopped()); -} - -#[test] -pub fn recycling_in_answer_produces_error() { - init_log(); - init_crypto_default(); - - // JSEP §5.2.2 only permits recycling in offers. An answer that - // introduces a new mid at the index of a stopped slot is malformed. - // str0m's `ensure_correct_answer` should reject it rather than - // silently retiring our Media. - let (mut l, mut r) = with_params(info_span!("L"), &[vp8(100)], info_span!("R"), &[vp8(100)]); - - let old_mid = l._mids()[0]; - - negotiate(&mut l, &mut r, |change| { - change.stop_media(old_mid); - }); - - // L initiates a fresh offer adding a new video m-line; R will answer. - let (offer_from_l, pending_l) = l - .span - .in_scope(|| { - let mut change = l.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - change.apply() - }) - .expect("L has a change to apply"); - - let answer_from_r = r - .span - .in_scope(|| r.rtc.sdp_api().accept_offer(offer_from_l).expect("accept")); - - // Rewrite R's answer so the new mid's m-line squats the old stopped - // slot. This is the malformed shape we want L to reject. - let malformed_answer_sdp = rewrite_offer_to_recycle_stopped_slot(&answer_from_r.to_sdp_string(), old_mid); - let malformed_answer = - crate::vendor::str0m::change::SdpAnswer::from_sdp_string(&malformed_answer_sdp).expect("parses"); - - let result = l - .span - .in_scope(|| l.rtc.sdp_api().accept_answer(pending_l, malformed_answer)); - - assert!( - result.is_err(), - "accept_answer must reject a recycled answer, got Ok:\n{}", - malformed_answer_sdp - ); -} - -// ------------------------------------------------------------------------- -// Helpers -// ------------------------------------------------------------------------- - -/// Moves the trailing (newly added) m-line into the slot occupied by the -/// m-line for `old_mid`, and updates the BUNDLE group accordingly. When -/// `old_mid` belongs to a stopped m-line (port=0) this produces the offer -/// shape a browser emits when recycling the slot per RFC 8829 §5.2.2. -fn rewrite_offer_to_recycle_stopped_slot(sdp: &str, old_mid: Mid) -> String { - // Split into sections, each starting with "m=". The first section is - // the session-level block before any m-line. - let mut sections: Vec = Vec::new(); - let mut current = String::new(); - for line in sdp.split_inclusive("\r\n") { - if line.starts_with("m=") && !current.is_empty() { - sections.push(std::mem::take(&mut current)); - } - current.push_str(line); - } - if !current.is_empty() { - sections.push(current); - } - - let session_block = sections.remove(0); - - // Find the stopped section and the trailing new section. - let old_mid_attr = format!("a=mid:{old_mid}\r\n"); - let stopped_idx = sections - .iter() - .position(|s| s.contains(&old_mid_attr)) - .expect("stopped section present"); - let new_section = sections.pop().expect("new section present"); - - sections[stopped_idx] = new_section; - - // Parse the new mid so we can rewrite the BUNDLE group. - let new_mid = sections[stopped_idx] - .lines() - .find_map(|l| l.strip_prefix("a=mid:")) - .expect("new section has a=mid:") - .trim() - .to_string(); - - let old_mid_str = old_mid.to_string(); - let session_block = session_block - .lines() - .map(|l| { - if let Some(rest) = l.strip_prefix("a=group:BUNDLE ") { - let mut mids: Vec<&str> = rest.split_whitespace().filter(|m| *m != old_mid_str).collect(); - if !mids.contains(&new_mid.as_str()) { - mids.push(new_mid.as_str()); - } - format!("a=group:BUNDLE {}", mids.join(" ")) - } else { - l.to_string() - } - }) - .collect::>() - .join("\r\n") - + "\r\n"; - - let mut out = session_block; - for s in sections { - out.push_str(&s); - } - out -} - -/// Find the mid in `sdp` that isn't `old_mid`. Panics if zero or more than one match. -fn new_mid_in_sdp(sdp: &str, old_mid: Mid) -> Mid { - let old_str = old_mid.to_string(); - let mut found: Option = None; - for line in sdp.lines() { - if let Some(rest) = line.strip_prefix("a=mid:") { - let m = rest.trim(); - if m == old_str { - continue; - } - assert!(found.is_none(), "more than one non-old mid in sdp:\n{}", sdp); - found = Some(m.into()); - } - } - found.expect("a new mid must be present in the recycled sdp") -} - -fn with_params( - span_l: Span, - params_l: &[PayloadParams], - span_r: Span, - params_r: &[PayloadParams], -) -> (TestRtc, TestRtc) { - let mut l = build_params(span_l, params_l); - let mut r = build_params(span_r, params_r); - - let kind = params_l - .first() - .map(|p| p.spec().codec.kind()) - .unwrap_or(MediaKind::Audio); - - negotiate(&mut l, &mut r, |change| { - change.add_media(kind, Direction::SendRecv, None, None, None); - }); - - (l, r) -} - -fn build_params(span: Span, params: &[PayloadParams]) -> TestRtc { - let mut b = Rtc::builder().clear_codecs(); - let config = b.codec_config(); - for p in params { - config.add_config( - p.pt(), - p.resend(), - p.spec().codec, - p.spec().clock_rate, - p.spec().channels, - p.spec().format, - ); - } - TestRtc::new_with_rtc(span, b.build(Instant::now())) -} - -fn vp8(pt: u8) -> PayloadParams { - PayloadParams::new( - pt.into(), - None, - CodecSpec { - codec: Codec::Vp8, - channels: None, - clock_rate: Frequency::NINETY_KHZ, - format: FormatParams::default(), - }, - ) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs deleted file mode 100644 index 15105c0a05d..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs +++ /dev/null @@ -1,906 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Instant; - -use super::common; -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::change::SdpAnswer; -use crate::vendor::str0m::change::SdpOffer; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::format::CodecSpec; -use crate::vendor::str0m::format::FormatParams; -use crate::vendor::str0m::format::PayloadParams; -use crate::vendor::str0m::media::Direction; -use crate::vendor::str0m::media::Frequency; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::media::Pt; -use crate::vendor::str0m::rtp::{Extension, ExtensionMap}; -use crate::vendor::str0m::{Event, RtcError}; -use common::TestRtc; -use common::init_crypto_default; -use common::init_log; -use common::negotiate; -use common::progress; -use tracing::Span; -use tracing::info_span; - -#[test] -pub fn change_default_pt() { - init_log(); - init_crypto_default(); - - // First proposed PT is 100, R side adjusts its default from 102 -> 100 - let (l, r) = with_params( - // - info_span!("L"), - &[opus(100)], - info_span!("R"), - &[opus(102)], - ); - - // Test left side. - assert_eq!(&[opus(100)], &**l.codec_config()); - assert!(l.codec_config()[0]._is_locked()); - - // Test right side. - assert_eq!(&[opus(100)], &**r.codec_config()); - assert!(r.codec_config()[0]._is_locked()); -} - -#[test] -pub fn answer_change_order() { - init_log(); - init_crypto_default(); - - // First proposed PT are 100/102, but R side has a different order. - let (l, r) = with_params( - // - info_span!("L"), - &[vp8(100), h264(102)], - info_span!("R"), - &[h264(96), vp8(98)], - ); - - let mid = l._mids()[0]; - - // Test left side. - assert_eq!(&[vp8(100), h264(102)], &**l.codec_config()); - assert!(l.codec_config().iter().all(|p| p._is_locked())); - assert_eq!( - l.media(mid).unwrap().remote_pts(), - // R side has expressed its preference order, but amended the PT to match the OFFER. - &[102.into(), 100.into()] - ); - - // Test right side. - assert_eq!(&[h264(102), vp8(100)], &**r.codec_config()); - assert!(r.codec_config().iter().all(|p| p._is_locked())); - assert_eq!( - r.media(mid).unwrap().remote_pts(), - // OFFER straight up. - &[100.into(), 102.into()] - ); -} - -#[test] -pub fn answer_narrow() { - init_log(); - init_crypto_default(); - - // First proposed PT are 100/102, the R side removes unsupported ones. - let (l, r) = with_params( - // - info_span!("L"), - &[vp8(100), h264(102)], - info_span!("R"), - &[h264(96)], - ); - - let mid = l._mids()[0]; - - // Test left side. - assert_eq!(&[vp8(100), h264(102)], &**l.codec_config()); - assert_eq!( - l.codec_config().iter().map(|p| p._is_locked()).collect::>(), - // VP8 is not locked, H264 is - vec![false, true] - ); - assert_eq!( - l.media(mid).unwrap().remote_pts(), - // R side has narrowed the remote_pts to only the supported. - &[102.into()] - ); - - // Test right side. The PT of h264 is updated with what L OFFERed. - assert_eq!(&[h264(102)], &**r.codec_config()); - assert!(r.codec_config().iter().all(|p| p._is_locked())); - assert_eq!( - r.media(mid).unwrap().remote_pts(), - // OFFER straight up. - &[102.into()] - ); -} - -#[test] -pub fn answer_no_match() { - init_log(); - init_crypto_default(); - - // L has one codec, and that is not matched by R. This should disable the m-line. - let mut l = build_params(info_span!("L"), &[vp8(100)]); - let mut r = build_params(info_span!("R"), &[h264(96)]); - - // Create offer from L - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - // R accepts the offer and generates an answer - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer).unwrap()); - - // Check that the answer SDP has port 0 for the rejected m-line - let answer_sdp = answer.to_sdp_string(); - assert!( - answer_sdp.contains("m=video 0 "), - "Expected rejected m-line with port 0, got:\n{}", - answer_sdp - ); - - // Rejected m-line should not be in the BUNDLE group - assert!( - !answer_sdp.contains("a=group:BUNDLE 0"), - "Rejected m-line should not be in BUNDLE group:\n{}", - answer_sdp - ); - - // L accepts the answer - l.span.in_scope(|| { - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - }); - - let mid = l._mids()[0]; - - // Test left side. Nothing has changed. The codec is not locked. - assert_eq!(&[vp8(100)], &**l.codec_config()); - assert!(!l.codec_config()[0]._is_locked()); - // No remote PTs. - assert_eq!(l.media(mid).unwrap().remote_pts(), &[]); - - // After receiving a rejected answer (port=0), direction should be Inactive. - assert_eq!( - l.media(mid).unwrap().direction(), - Direction::Inactive, - "Offerer's m-line should be Inactive after receiving rejected answer" - ); - - // Test right side. Nothing has changed. The codec is not locked. - assert_eq!(&[h264(96)], &**r.codec_config()); - assert!(!r.codec_config()[0]._is_locked()); - // No remote PTs. - assert_eq!(r.media(mid).unwrap().remote_pts(), &[]); -} - -#[test] -pub fn rejected_answer_is_accepted_as_text() { - init_log(); - init_crypto_default(); - - let mut l = build_params(info_span!("L"), &[vp8(100)]); - let mut r = build_params(info_span!("R"), &[h264(96)]); - - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer).unwrap()); - - let answer_sdp = answer.to_sdp_string(); - assert!( - answer_sdp.contains("m=video 0 UDP/TLS/RTP/SAVPF 0\r\n"), - "Expected a rejected m-line with a format, got:\n{}", - answer_sdp - ); - - let answer = SdpAnswer::from_sdp_string(&answer_sdp).unwrap(); - l.span.in_scope(|| { - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - }); - - let mid = l._mids()[0]; - assert!(l.media(mid).unwrap().disabled()); - assert_eq!(l.media(mid).unwrap().direction(), Direction::Inactive); -} - -#[test] -pub fn stop_media() { - init_log(); - init_crypto_default(); - - // L and R negotiate a video m-line, then L stops it. The next offer - // must emit port 0 and leave the m-line out of the BUNDLE group. - let (mut l, mut r) = with_params( - // - info_span!("L"), - &[vp8(100)], - info_span!("R"), - &[vp8(100)], - ); - - let mid = l._mids()[0]; - - assert!(!l.media(mid).unwrap().stopped()); - assert_eq!(l.media(mid).unwrap().direction(), Direction::SendRecv); - - // Stop and create a subsequent offer from L - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - change.stop_media(mid); - change.apply().unwrap() - }); - - // Stopping an already-stopped m-line is a no-op - l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - change.stop_media(mid); - assert!(change.apply().is_none()); - }); - - // Check that the offer SDP has port 0 and drops the mid from BUNDLE. - // The PT list is preserved so the m-line satisfies the SDP grammar - // (RFC 4566 §5.14 requires at least one fmt). - let offer_sdp = offer.to_sdp_string(); - assert!( - offer_sdp.contains("m=video 0 UDP/TLS/RTP/SAVPF 100\r\n"), - "Expected stopped m-line with port 0 and PT 100, got:\n{}", - offer_sdp - ); - assert!( - !offer_sdp.contains(&format!("a=group:BUNDLE {mid}")), - "Stopped m-line should not be in BUNDLE group:\n{}", - offer_sdp - ); - assert!( - !offer_sdp.contains("a=msid:"), - "Stopped m-line should not advertise an MSID:\n{offer_sdp}" - ); - assert!( - !offer_sdp.contains(" msid:"), - "Stopped m-line should not advertise an SSRC-level MSID:\n{offer_sdp}" - ); - - // Test left side. Stopped, direction Inactive, PTs preserved. - assert!(l.media(mid).unwrap().stopped()); - assert_eq!(l.media(mid).unwrap().direction(), Direction::Inactive); - assert_eq!(l.media(mid).unwrap().remote_pts(), &[Pt::new_with_value(100)]); - - // R accepts the offer and generates an answer - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer).unwrap()); - - // The answer also has port 0 (with preserved PT list) for the stopped m-line - let answer_sdp = answer.to_sdp_string(); - assert!( - answer_sdp.contains("m=video 0 UDP/TLS/RTP/SAVPF 100\r\n"), - "Expected stopped m-line with port 0 and PT 100 in answer, got:\n{}", - answer_sdp - ); - assert!( - !answer_sdp.contains("a=msid:"), - "Stopped m-line should not advertise an MSID in the answer:\n{answer_sdp}" - ); - assert!( - !answer_sdp.contains(" msid:"), - "Stopped m-line should not advertise an SSRC-level MSID in the answer:\n{answer_sdp}" - ); - - // L accepts the answer - l.span.in_scope(|| { - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - }); - - // Test right side. Same stopped state as L. - assert!(r.media(mid).unwrap().stopped()); - assert_eq!(r.media(mid).unwrap().direction(), Direction::Inactive); - assert_eq!(r.media(mid).unwrap().remote_pts(), &[Pt::new_with_value(100)]); -} - -#[test] -pub fn answer_different_pt_to_offer() { - init_log(); - init_crypto_default(); - - // This test case checks a scenario happening with Firefox. - // 1. SDP -> FF: OFFER to sendonly VP8 PT 96. - // 2. FF -> SDP: ANSWER to recvonly VP8 PT 96. (confirming the desired according to spec). - // 3. FF -> SDP: OFFER to sendonly VP8 PT 120. This is legal, since PT 120 is just a suggestion. - // 4. SDP -> FF: ANSWER we need to force PT 96 (and not remap to 120). - - // L has one codec, and that is not matched by R. This should disable the m-line. - let (mut l, mut r) = with_params( - // - info_span!("L"), - &[vp8(96)], - info_span!("R"), - &[vp8(120)], - ); - - // Both sides are 96. - assert_eq!(&[vp8(96)], &**l.codec_config()); - assert_eq!(&[vp8(96)], &**r.codec_config()); - - let mut change = r.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (offer, _pending) = change.apply().unwrap(); - - let sdp = offer.to_sdp_string(); - - let mut split = sdp.split("m=video 9 UDP/TLS/RTP/SAVPF 96"); - let prelude = split.next().unwrap(); - let mline_1 = split.next().unwrap(); - let mline_2 = split.next().unwrap(); - - // m=video 9 UDP/TLS/RTP/SAVPF 96 - - // a=rtpmap:96 VP8/90000 - // a=rtcp-fb:96 transport-cc - // a=rtcp-fb:96 ccm fir - // a=rtcp-fb:96 nack - // a=rtcp-fb:96 nack pli - - let mline_2 = mline_2.replace("a=rtpmap:96", "a=rtpmap:120"); - let mline_2 = mline_2.replace("a=rtcp-fb:96", "a=rtcp-fb:120"); - - let munged = format!( - "{}m=video 9 UDP/TLS/RTP/SAVPF 96{}m=video 9 UDP/TLS/RTP/SAVPF 120{}", - prelude, mline_1, mline_2 - ); - - let offer = SdpOffer::from_sdp_string(&munged).unwrap(); - - let answer = l.sdp_api().accept_offer(offer).unwrap(); - - // L remains 96. - assert_eq!(&[vp8(96)], &**l.codec_config()); - - let sdp = answer.to_sdp_string(); - - println!("{}", sdp); - - // All 3 m-lines should be with 96, ignoring the 120. - let mut split = sdp.split("m=video 9 UDP/TLS/RTP/SAVPF 96"); - split.next().expect("SDP answer prelude"); // prelude - split.next().expect("First m-line"); // m-line 1 - split.next().expect("Second m-line"); // m-line 2 -} - -#[test] -fn answer_remaps() { - init_log(); - init_crypto_default(); - - use Extension::*; - - let exts_l = ExtensionMap::standard(); - let mut exts_r = ExtensionMap::empty(); - - // Not same number as the default. - exts_r.set(14, TransportSequenceNumber); - exts_r.set(12, AudioLevel); - - // This negotiates a video track. - let (l, r) = with_exts(exts_l, exts_r); - - let v_l: Vec<_> = l._exts().iter_video().collect(); - let v_r: Vec<_> = r._exts().iter_video().collect(); - let a_l: Vec<_> = l._exts().iter_audio().collect(); - let a_r: Vec<_> = r._exts().iter_audio().collect(); - - // L locks 3 and changes it from 14 - // R keeps 3 and changes it from 14. - assert_eq!( - v_l, - vec![ - (2, &AbsoluteSendTime), - (3, &TransportSequenceNumber), - (4, &RtpMid), - (10, &RtpStreamId), - (11, &RepairedRtpStreamId), - (13, &VideoOrientation) - ] - ); - assert_eq!(v_r, vec![(3, &TransportSequenceNumber)]); - - // L audio exts are left untouched (the defaults), also ones shared with video. - // R audio exts are left untouched. - assert_eq!( - a_l, - vec![ - (1, &AudioLevel), - (2, &AbsoluteSendTime), - (3, &TransportSequenceNumber), - (4, &RtpMid), - (10, &RtpStreamId), - (11, &RepairedRtpStreamId) - ] - ); - assert_eq!(a_r, vec![(3, &TransportSequenceNumber), (12, &AudioLevel)]); -} - -#[test] -fn offers_unsupported_extension() { - init_log(); - init_crypto_default(); - - use Extension::*; - - let mut exts_l = ExtensionMap::empty(); - let mut exts_r = ExtensionMap::empty(); - - // They agree on VideoOrientation, but R has different number - // L has introduces an extension R doesn't support. - exts_l.set(3, VideoOrientation); - exts_l.set(8, ColorSpace); - - exts_r.set(5, VideoOrientation); - - // This negotiates a video track. - let (l, r) = with_exts(exts_l, exts_r); - - assert_eq!( - l._exts().iter_video().collect::>(), - vec![(3, &VideoOrientation), (8, &ColorSpace)] - ); - assert_eq!(r._exts().iter_video().collect::>(), vec![(3, &VideoOrientation)]); - - let mid = l._mids()[0]; - let m_l = l.media(mid).unwrap(); - let m_r = r.media(mid).unwrap(); - - // L media did not get R unsupported ext, despite that being configured on session. - assert_eq!( - m_l.remote_extmap().iter_video().collect::>(), - vec![(3, &VideoOrientation)] - ); - - // R media didn't get the unsupported ext. - assert_eq!( - m_r.remote_extmap().iter_video().collect::>(), - vec![(3, &VideoOrientation)] - ); -} - -#[test] -fn non_media_creator_cannot_change_inactive_to_recvonly() { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let (mut l, mut r) = ( - TestRtc::new_with_rtc( - info_span!("L"), - Rtc::builder().clear_codecs().enable_vp8(true).build(now), - ), - TestRtc::new_with_rtc( - info_span!("R"), - Rtc::builder().clear_codecs().enable_vp8(true).build(now), - ), - ); - - negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::Inactive, None, None, None); - }); - let mid = r._mids()[0]; - let m_r = r.media(mid).unwrap(); - assert_eq!(m_r.direction(), Direction::Inactive); - - negotiate(&mut r, &mut l, |change| { - change.set_direction(mid, Direction::RecvOnly); - }); - - // r didn't open the media and isn't allowed to change it from inactive to recvonly. - let m_r = r.media(mid).unwrap(); - assert_eq!(m_r.direction(), Direction::Inactive); - - let m_l = l.media(mid).unwrap(); - assert_eq!(m_l.direction(), Direction::Inactive); -} - -#[test] -fn media_creator_can_change_inactive_to_recvonly() { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let (mut l, mut r) = ( - TestRtc::new_with_rtc( - info_span!("L"), - Rtc::builder().clear_codecs().enable_vp8(true).build(now), - ), - TestRtc::new_with_rtc( - info_span!("R"), - Rtc::builder().clear_codecs().enable_vp8(true).build(now), - ), - ); - - negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::Inactive, None, None, None); - }); - let mid = r._mids()[0]; - let m_r = r.media(mid).unwrap(); - assert_eq!(m_r.direction(), Direction::Inactive); - - negotiate(&mut l, &mut r, |change| { - change.set_direction(mid, Direction::RecvOnly); - }); - - // r didn't open the media and isn't allowed to change it from inactive to recvonly. - let m_l = l.media(mid).unwrap(); - assert_eq!(m_l.direction(), Direction::RecvOnly); - - let m_r = r.media(mid).unwrap(); - assert_eq!(m_r.direction(), Direction::SendOnly); -} - -/// Test that max-bundle offers (where secondary m-lines have port=0) are handled correctly. -/// In max-bundle format (RFC 8843), m-lines after the first one use port=0 to indicate -/// they share transport with the first m-line. This is NOT a rejection. -#[test] -fn max_bundle_offer_accepted() { - init_log(); - init_crypto_default(); - - // Create an Rtc that supports both opus and VP8 - let mut r = TestRtc::new_with_rtc( - info_span!("R"), - Rtc::builder() - .clear_codecs() - .enable_opus(true) - .enable_vp8(true) - .build(Instant::now()), - ); - - // This is a max-bundle offer where the video m-line has port=0 - // to indicate it shares transport with the audio m-line. - let max_bundle_offer = "\ - v=0\r\n\ - o=- 123456789 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0 1\r\n\ - a=msid-semantic:WMS *\r\n\ - a=fingerprint:sha-256 00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00\r\n\ - a=ice-ufrag:testufrag\r\n\ - a=ice-pwd:testpassword12345678\r\n\ - a=setup:actpass\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:111 opus/48000/2\r\n\ - a=fmtp:111 minptime=10;useinbandfec=1\r\n\ - m=video 0 UDP/TLS/RTP/SAVPF 96\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:1\r\n\ - a=sendrecv\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:96 VP8/90000\r\n\ - "; - - // Parse and accept the max-bundle offer - let offer = SdpOffer::from_sdp_string(max_bundle_offer).expect("should parse"); - let answer = r.rtc.sdp_api().accept_offer(offer).expect("should accept"); - - // Verify the answer includes both m-lines in the BUNDLE group - let answer_sdp = answer.to_sdp_string(); - assert!( - answer_sdp.contains("a=group:BUNDLE 0 1"), - "Answer should have both MIDs in BUNDLE group, got:\n{}", - answer_sdp - ); - - // Both m-lines should be active (not rejected) - let mids = r._mids(); - assert_eq!(mids.len(), 2, "Should have 2 media lines"); - - let audio = r.media(mids[0]).unwrap(); - assert_eq!( - audio.direction(), - Direction::SendRecv, - "Audio should be SendRecv, not disabled" - ); - - let video = r.media(mids[1]).unwrap(); - assert_eq!( - video.direction(), - Direction::SendRecv, - "Video should be SendRecv even though offer had port=0 (max-bundle)" - ); -} - -/// A remote offer advertising a codec at a payload type outside the 7-bit RTP range must be -/// rejected, not panic. Before the fix the out-of-range PT was claimed against a 128-entry table -/// and indexed out of bounds; now the malformed `a=rtpmap` is ignored, leaving the m-line PT -/// without a codec, so the offer is rejected at parse instead. -#[test] -fn offer_with_out_of_range_pt_is_rejected() { - init_log(); - init_crypto_default(); - - let offer = "\ - v=0\r\n\ - o=- 123456789 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=msid-semantic:WMS *\r\n\ - a=fingerprint:sha-256 00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00\r\n\ - a=ice-ufrag:testufrag\r\n\ - a=ice-pwd:testpassword12345678\r\n\ - a=setup:actpass\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 200\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:200 opus/48000/2\r\n\ - "; - - // Before the fix this parsed and then panicked when the PT was claimed; now it is rejected. - let result = SdpOffer::from_sdp_string(offer); - assert!( - result.is_err(), - "offer with out-of-range PT must be rejected: {result:?}" - ); -} - -/// Regression test for issue #1015: an H.264 offer whose level exceeds the -/// locally configured level must still negotiate. RFC 6184 §8.2.2 makes the -/// level a negotiable (downgradable) parameter, so a remote `42e034` -/// (Constrained Baseline, level 5.2) must match local `42e01f` (level 3.1) -/// rather than reject the whole m-line; the Constrained High profile -/// (`640c34`) must also parse instead of dropping the payload. -#[test] -fn h264_offer_with_higher_level_negotiates() { - init_log(); - init_crypto_default(); - - // Only H.264 is enabled, so the video m-line survives *only* if an H.264 - // payload negotiates. str0m's default H.264 config is at level 3.1. - let mut r = TestRtc::new_with_rtc( - info_span!("R"), - Rtc::builder().clear_codecs().enable_h264(true).build(Instant::now()), - ); - - // A remote offer (taken verbatim from Safari/WebKit) advertising - // Constrained High (640c34) and Constrained Baseline (42e034), both at - // level 5.2, in packetization modes 1 and 0. - let remote_offer = "\ - v=0\r\n\ - o=- 123456789 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=msid-semantic:WMS *\r\n\ - a=fingerprint:sha-256 00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00\r\n\ - a=ice-ufrag:testufrag\r\n\ - a=ice-pwd:testpassword12345678\r\n\ - a=setup:actpass\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 96 98 100 102\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:96 H264/90000\r\n\ - a=fmtp:96 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c34\r\n\ - a=rtpmap:98 H264/90000\r\n\ - a=fmtp:98 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=640c34\r\n\ - a=rtpmap:100 H264/90000\r\n\ - a=fmtp:100 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e034\r\n\ - a=rtpmap:102 H264/90000\r\n\ - a=fmtp:102 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e034\r\n\ - "; - - let offer = SdpOffer::from_sdp_string(remote_offer).expect("offer should parse"); - let answer = r - .span - .in_scope(|| r.rtc.sdp_api().accept_offer(offer).expect("should accept")); - - let answer_sdp = answer.to_sdp_string(); - - // The video m-line must NOT be rejected (port 0). No local H.264 payload - // matches unless the level-5.2 offer is accepted against local level 3.1. - assert!( - !answer_sdp.contains("m=video 0 "), - "H.264 offer should negotiate, not reject the m-line:\n{answer_sdp}" - ); - - // The negotiated payload is str0m's Constrained Baseline (42e01f), matched - // against the remote's 42e034 with the level difference only penalizing the - // score per RFC 6184 §8.2.2. - assert!( - answer_sdp.contains("profile-level-id=42e01f"), - "Answer should negotiate Constrained Baseline (42e01f):\n{answer_sdp}" - ); - - // The answerer receives, so it adopts the remote's payload types. The - // Constrained Baseline packetization-mode=1 payload is PT 100 in the offer. - assert!( - answer_sdp.contains("a=rtpmap:100 H264/90000"), - "Answer should adopt the remote's Constrained Baseline PT 100:\n{answer_sdp}" - ); - - // The m-line stays active on the receiving side. - let mid = r._mids()[0]; - assert_eq!( - r.media(mid).unwrap().direction(), - Direction::SendRecv, - "Video should stay active after negotiating the H.264 offer" - ); -} - -/// RFC 8830 3.2.3: "The answer is generated in exactly the same manner as the -/// offer. `a=msid` values in the offer do not influence the answer." -/// -/// The offer here uses the `-` stream id, which RFC 8830 defines as "no -/// MediaStream". Reusing it would make the answer claim our own outgoing track -/// belongs to no stream, leaving a receiver nothing to bind it to. -#[test] -fn answer_msid_is_not_taken_from_the_offer() { - init_log(); - init_crypto_default(); - - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().build(Instant::now())); - - // An offer whose audio m-line is tagged with the "no MediaStream" id. - let remote_offer = "\ - v=0\r\n\ - o=- 123456789 2 IN IP4 127.0.0.1\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=msid-semantic:WMS *\r\n\ - a=fingerprint:sha-256 00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\ - :00:00:00:00:00:00:00:00:00\r\n\ - a=ice-ufrag:testufrag\r\n\ - a=ice-pwd:testpassword12345678\r\n\ - a=setup:actpass\r\n\ - m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a=mid:0\r\n\ - a=sendrecv\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:111 opus/48000/2\r\n\ - a=msid:- 4bdebdc4-2f42-4ca9-8326-d40bdbe30a8d\r\n\ - a=ssrc:1111 cname:remote\r\n\ - a=ssrc:1111 msid:- 4bdebdc4-2f42-4ca9-8326-d40bdbe30a8d\r\n\ - "; - - let offer = SdpOffer::from_sdp_string(remote_offer).expect("offer should parse"); - let answer = r - .span - .in_scope(|| r.rtc.sdp_api().accept_offer(offer).expect("should accept")); - - let answer_sdp = answer.to_sdp_string(); - - assert!( - !answer_sdp.contains("a=msid:- "), - "Answer must not adopt the offer's \"no MediaStream\" id:\n{answer_sdp}" - ); - assert!( - !answer_sdp.contains("4bdebdc4-2f42-4ca9-8326-d40bdbe30a8d"), - "Answer must not adopt the offer's track id:\n{answer_sdp}" - ); - assert!( - answer_sdp.contains("a=msid:"), - "Answer should still carry an msid of its own:\n{answer_sdp}" - ); -} - -fn with_params( - span_l: Span, - params_l: &[PayloadParams], - span_r: Span, - params_r: &[PayloadParams], -) -> (TestRtc, TestRtc) { - let mut l = build_params(span_l, params_l); - let mut r = build_params(span_r, params_r); - - let kind = params_l - .first() - .map(|p| p.spec().codec.kind()) - .unwrap_or(MediaKind::Audio); - - negotiate(&mut l, &mut r, |change| { - change.add_media(kind, Direction::SendRecv, None, None, None); - }); - - (l, r) -} - -fn with_exts(exts_l: ExtensionMap, exts_r: ExtensionMap) -> (TestRtc, TestRtc) { - let mut l = build_exts(info_span!("L"), exts_l); - let mut r = build_exts(info_span!("R"), exts_r); - - negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - }); - - (l, r) -} - -fn build_params(span: Span, params: &[PayloadParams]) -> TestRtc { - let mut b = Rtc::builder().clear_codecs(); - let config = b.codec_config(); - for p in params { - config.add_config( - p.pt(), - p.resend(), - p.spec().codec, - p.spec().clock_rate, - p.spec().channels, - p.spec().format, - ); - } - let rtc = b.build(Instant::now()); - - TestRtc::new_with_rtc(span, rtc) -} - -fn build_exts(span: Span, exts: ExtensionMap) -> TestRtc { - let mut b = Rtc::builder().clear_codecs(); - b = b.enable_vp8(true); - let e = b.extension_map(); - *e = exts; - let rtc = b.build(Instant::now()); - - TestRtc::new_with_rtc(span, rtc) -} - -fn opus(pt: u8) -> PayloadParams { - PayloadParams::new( - pt.into(), - None, - CodecSpec { - codec: Codec::Opus, - channels: Some(2), - clock_rate: Frequency::FORTY_EIGHT_KHZ, - format: FormatParams::default(), - }, - ) -} - -fn vp8(pt: u8) -> PayloadParams { - PayloadParams::new( - pt.into(), - None, - CodecSpec { - codec: Codec::Vp8, - channels: None, - clock_rate: Frequency::NINETY_KHZ, - format: FormatParams::default(), - }, - ) -} - -fn h264(pt: u8) -> PayloadParams { - PayloadParams::new( - pt.into(), - None, - CodecSpec { - codec: Codec::H264, - channels: None, - clock_rate: Frequency::NINETY_KHZ, - format: FormatParams::default(), - }, - ) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-rtx-apt.rs b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-rtx-apt.rs deleted file mode 100644 index 87cab72049b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-rtx-apt.rs +++ /dev/null @@ -1,135 +0,0 @@ -use std::time::Instant; - -use crate::vendor::str0m::change::{SdpAnswer, SdpOffer}; -use crate::vendor::str0m::error::SdpError; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Rtc, RtcError}; - -use super::common; -use common::init_crypto_default; - -fn offer_sdp(direction: &str, fmtp: &str) -> String { - format!( - "v=0\r\n\ - o=- 1 0 IN IP4 0.0.0.0\r\n\ - s=-\r\n\ - t=0 0\r\n\ - a=fingerprint: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\n\ - a=group:BUNDLE 0\r\n\ - m=video 9 UDP/TLS/RTP/SAVPF 120 121 125\r\n\ - c=IN IP4 0.0.0.0\r\n\ - a={direction}\r\n\ - a=mid:0\r\n\ - a=ice-ufrag:00000000\r\n\ - a=ice-pwd:00000000000000000000000000000000\r\n\ - a=setup:actpass\r\n\ - a=rtcp-mux\r\n\ - a=rtpmap:120 VP8/90000\r\n\ - a=rtpmap:121 VP9/90000\r\n\ - a=rtpmap:125 rtx/90000\r\n\ - {fmtp}" - ) -} - -fn assert_conflicting_apt(result: Result) { - let Err(RtcError::Sdp(SdpError::ParseError(message) | SdpError::Inconsistent(message))) = result else { - panic!("SDP with conflicting RTX apt values must be rejected: {result:?}"); - }; - assert!(message.contains("conflicting apt values"), "{message}"); -} - -#[test] -fn offer_with_conflicting_rtx_apt_is_rejected() { - init_crypto_default(); - - for direction in ["recvonly", "sendrecv", "sendonly", "inactive"] { - for fmtp in [ - "a=fmtp:125 apt=120\r\na=fmtp:125 apt=121\r\n", - "a=fmtp:125 apt=120;apt=121\r\n", - ] { - let mut rtc = Rtc::builder().build(Instant::now()); - let result = SdpOffer::from_sdp_string(&offer_sdp(direction, fmtp)) - .map_err(RtcError::from) - .and_then(|offer| rtc.sdp_api().accept_offer(offer)); - - assert_conflicting_apt(result); - assert!(rtc.media("0".into()).is_none()); - } - } -} - -#[test] -fn answer_with_conflicting_rtx_apt_is_rejected() { - init_crypto_default(); - - for same_line in [false, true] { - let mut local = Rtc::builder().build(Instant::now()); - let mut remote = Rtc::builder().build(Instant::now()); - let mut change = local.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = remote.sdp_api().accept_offer(offer).unwrap(); - - let params = remote.codec_config(); - let vp8 = params.iter().find(|p| p.spec().codec == Codec::Vp8).unwrap(); - let vp9 = params.iter().find(|p| p.spec().codec == Codec::Vp9).unwrap(); - let rtx = vp8.resend().unwrap(); - let original = format!("a=fmtp:{rtx} apt={}", vp8.pt()); - let extra = if same_line { - format!("{original};apt={}", vp9.pt()) - } else { - format!("{original}\r\na=fmtp:{rtx} apt={}", vp9.pt()) - }; - let sdp = answer.to_sdp_string(); - assert!(sdp.contains(&original)); - let result = SdpAnswer::from_sdp_string(&sdp.replace(&original, &extra)) - .map_err(RtcError::from) - .and_then(|answer| local.sdp_api().accept_answer(pending, answer)); - - assert_conflicting_apt(result); - assert!(local.media(mid).is_none()); - } -} - -#[test] -fn repeated_identical_rtx_apt_is_accepted() { - init_crypto_default(); - - for fmtp in [ - "a=fmtp:125 apt=120\r\na=fmtp:125 apt=120\r\n", - "a=fmtp:125 apt=120;apt=120\r\n", - ] { - let mut rtc = Rtc::builder().build(Instant::now()); - let offer = SdpOffer::from_sdp_string(&offer_sdp("recvonly", fmtp)).unwrap(); - let answer = rtc.sdp_api().accept_offer(offer).unwrap(); - - assert!(answer.to_sdp_string().contains("a=fmtp:125 apt=120\r\n")); - let vp8 = rtc - .codec_config() - .iter() - .find(|p| p.spec().codec == Codec::Vp8) - .unwrap(); - assert_eq!(vp8.resend(), Some(125.into())); - } -} - -#[test] -fn distinct_rtx_payload_types_are_accepted() { - init_crypto_default(); - - let mut rtc = Rtc::builder().build(Instant::now()); - let sdp = offer_sdp( - "recvonly", - "a=fmtp:125 apt=120\r\na=rtpmap:126 rtx/90000\r\na=fmtp:126 apt=121\r\n", - ) - .replace("SAVPF 120 121 125", "SAVPF 120 121 125 126"); - let offer = SdpOffer::from_sdp_string(&sdp).unwrap(); - rtc.sdp_api().accept_offer(offer).unwrap(); - - for (codec, rtx) in [(Codec::Vp8, 125), (Codec::Vp9, 126)] { - let params = rtc.codec_config().iter().find(|p| p.spec().codec == codec).unwrap(); - assert_eq!(params.resend(), Some(rtx.into())); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs deleted file mode 100644 index 4d3deed2030..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs +++ /dev/null @@ -1,123 +0,0 @@ -use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::change::{SdpAnswer, SdpApi, SdpOffer}; -use crate::vendor::str0m::error::SdpError; -use crate::vendor::str0m::media::{Direction, MediaKind, Mid}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate}; - -fn repeat_next_mid() -> Mid { - fastrand::seed(1); - let mid = Mid::new(); - fastrand::seed(1); - mid -} - -fn offer(l: &mut TestRtc, r: &mut TestRtc, do_change: impl FnOnce(&mut SdpApi)) -> Vec { - let mut change = l.rtc.sdp_api(); - do_change(&mut change); - let (offer, pending) = change.apply().unwrap(); - - let mids = offer - .to_sdp_string() - .lines() - .filter_map(|l| l.strip_prefix("a=mid:")) - .map(|m| m.trim().to_string()) - .collect(); - - let answer = r.rtc.sdp_api().accept_offer(offer).unwrap(); - l.rtc.sdp_api().accept_answer(pending, answer).unwrap(); - - mids -} - -fn add_audio(change: &mut SdpApi) -> Mid { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) -} - -#[test] -pub fn two_media_in_one_offer_get_distinct_mids() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - let mut added = vec![]; - let mids = offer(&mut l, &mut r, |change| { - let expected = repeat_next_mid(); - added.push(add_audio(change)); - assert_eq!(added[0], expected); - repeat_next_mid(); - added.push(add_audio(change)); - }); - - assert_ne!(added[0], added[1]); - assert_eq!(mids, [added[0].to_string(), added[1].to_string()]); - assert!(r.rtc.media(added[1]).is_some()); -} - -fn share_first_mid(sdp: &str) -> (String, String) { - let mids: Vec<&str> = sdp - .lines() - .filter_map(|l| l.strip_prefix("a=mid:")) - .map(str::trim) - .collect(); - assert_eq!(mids.len(), 2); - let shared = sdp - .replace(&format!("a=mid:{}", mids[1]), &format!("a=mid:{}", mids[0])) - .replace( - &format!("a=group:BUNDLE {} {}", mids[0], mids[1]), - &format!("a=group:BUNDLE {} {}", mids[0], mids[0]), - ); - (shared, mids[0].to_string()) -} - -fn assert_inconsistent_mid(result: Result, mid: &str) { - let Err(RtcError::Sdp(SdpError::Inconsistent(message))) = result else { - panic!("SDP with a duplicate mid must be rejected: {result:?}"); - }; - assert_eq!(message, format!("Mid {mid} is used by more than one m-line")); -} - -#[test] -pub fn offer_with_duplicate_mids_is_rejected() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - let mut change = l.rtc.sdp_api(); - add_audio(&mut change); - add_audio(&mut change); - let (offer, _pending) = change.apply().unwrap(); - - let (sdp, mid) = share_first_mid(&offer.to_sdp_string()); - let offer = SdpOffer::from_sdp_string(&sdp).unwrap(); - - assert_inconsistent_mid(r.rtc.sdp_api().accept_offer(offer), &mid); - assert!(r.rtc.media(mid.as_str().into()).is_none()); -} - -#[test] -pub fn answer_with_duplicate_mids_is_rejected() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - let mut change = l.rtc.sdp_api(); - let audio = add_audio(&mut change); - add_audio(&mut change); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer).unwrap(); - - let (sdp, mid) = share_first_mid(&answer.to_sdp_string()); - assert_eq!(mid, audio.to_string()); - let answer = SdpAnswer::from_sdp_string(&sdp).unwrap(); - - assert_inconsistent_mid(l.rtc.sdp_api().accept_answer(pending, answer), &mid); - assert!(l.rtc.media(audio).is_none()); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs b/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs deleted file mode 100644 index f8d653009c0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs +++ /dev/null @@ -1,457 +0,0 @@ -//! Receiver-side mapping of simulcast SSRCs to their RID between two str0m peers. -//! -//! The receiver learns which SSRC carries which simulcast layer from the RID header -//! extension, which it only accepts for rids the SDP declares. The sender only attaches -//! that extension until a receiver report for the SSRC comes back, so every layer must be -//! bound before the extension disappears, and every SDP describing the sender's track -//! must keep declaring the rids. - -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::netem::{GilbertElliot, NetemConfig, Probability, RandomLoss}; -use crate::vendor::str0m::change::{SdpAnswer, SdpOffer}; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, Frequency, MediaKind, MediaTime, Mid, Rid}; -use crate::vendor::str0m::media::{Simulcast, SimulcastLayer}; -use crate::vendor::str0m::{Event, RtcConfig, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -/// Layer rids with the frame size sent on each. -const LAYERS: [(&str, usize); 3] = [("l", 300), ("m", 1_500), ("h", 6_000)]; - -/// Whether RTX is negotiated. -const PEER_CONFIGS: [bool; 2] = [true, false]; - -const SIGNALLING: [Signalling; 3] = [ - Signalling::MediaInFirstOffer, - Signalling::Renegotiated { glare: false }, - Signalling::Renegotiated { glare: true }, -]; - -/// How the simulcast media reaches the receiver. -#[derive(Debug, Clone, Copy)] -enum Signalling { - /// The first offer carries the media. - MediaInFirstOffer, - /// The first offer is data-channel only and the media follows in a re-offer after - /// connecting. With `glare`, the receiver has its own offer outstanding and drops it - /// to accept the sender's. - Renegotiated { glare: bool }, -} - -/// Which peer offers the renegotiation that follows the simulcast negotiation. -#[derive(Debug, Clone, Copy)] -enum Reoffer { - /// The sender answers, as when an SFU offers it another peer's media. - FromReceiver, - FromSender, -} - -#[test] -fn simulcast_survives_answering_reoffer_before_media() -> Result<(), RtcError> { - let all = all_rids(); - assert_simulcast_survives_reoffer(Reoffer::FromReceiver, Duration::ZERO, &all) -} - -#[test] -fn simulcast_survives_answering_reoffer_after_media() -> Result<(), RtcError> { - let all = all_rids(); - assert_simulcast_survives_reoffer(Reoffer::FromReceiver, Duration::from_secs(1), &all) -} - -#[test] -fn simulcast_survives_sender_reoffer_before_media() -> Result<(), RtcError> { - let all = all_rids(); - assert_simulcast_survives_reoffer(Reoffer::FromSender, Duration::ZERO, &all) -} - -#[test] -fn simulcast_survives_sender_reoffer_after_media() -> Result<(), RtcError> { - let all = all_rids(); - assert_simulcast_survives_reoffer(Reoffer::FromSender, Duration::from_secs(1), &all) -} - -#[test] -fn simulcast_partially_accepted_survives_answering_reoffer() -> Result<(), RtcError> { - let accepted = ["l", "m"]; - assert_simulcast_survives_reoffer(Reoffer::FromReceiver, Duration::from_secs(1), &accepted) -} - -#[test] -fn simulcast_partially_accepted_survives_sender_reoffer() -> Result<(), RtcError> { - let accepted = ["l", "m"]; - assert_simulcast_survives_reoffer(Reoffer::FromSender, Duration::from_secs(1), &accepted) -} - -#[test] -fn simulcast_rejected_stays_rejected_after_answering_reoffer() -> Result<(), RtcError> { - assert_simulcast_survives_reoffer(Reoffer::FromReceiver, Duration::ZERO, &[]) -} - -#[test] -fn simulcast_rejected_stays_rejected_after_sender_reoffer() -> Result<(), RtcError> { - assert_simulcast_survives_reoffer(Reoffer::FromSender, Duration::ZERO, &[]) -} - -/// The receiver asks for simulcast in the first offer and the sender answers. -#[test] -fn simulcast_send_as_answerer() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let all = all_rids(); - let mut simulcast = Simulcast::new(); - for rid in &all { - simulcast.add_recv_layer(SimulcastLayer::new(rid)); - } - - let mut change = r.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::RecvOnly, None, None, Some(simulcast)); - let (offer, pending) = change.apply().unwrap(); - let answer = l.rtc.sdp_api().accept_offer(offer)?; - assert_declares_send_simulcast(&answer.to_sdp_string(), mid, &all); - r.rtc.sdp_api().accept_answer(pending, answer)?; - - connect(&mut l, &mut r)?; - send_frames(&mut l, &mut r, mid, &all, Duration::from_secs(2))?; - assert_rids_delivered(&mut r, mid, &all, 0, "sender answered"); - - Ok(()) -} - -#[test] -fn simulcast_rid_mapping_loopback() -> Result<(), RtcError> { - for rtx in PEER_CONFIGS { - for signalling in SIGNALLING { - assert_all_rids_mapped(Duration::ZERO, NetemConfig::new(), rtx, signalling)?; - } - } - Ok(()) -} - -#[test] -fn simulcast_rid_mapping_latency() -> Result<(), RtcError> { - for rtx in PEER_CONFIGS { - for signalling in SIGNALLING { - let latency = Duration::from_millis(25); - assert_all_rids_mapped(latency, NetemConfig::new(), rtx, signalling)?; - } - } - Ok(()) -} - -#[test] -fn simulcast_rid_mapping_sweep() -> Result<(), RtcError> { - for seed in 0..10 { - for rtx in PEER_CONFIGS { - for signalling in SIGNALLING { - let impairments = [ - NetemConfig::new().jitter(Duration::from_millis(10)).seed(seed), - NetemConfig::new() - .loss(RandomLoss::new(Probability::new(0.1))) - .seed(seed), - NetemConfig::new() - .jitter(Duration::from_millis(15)) - .loss(GilbertElliot::congested()) - .duplicate(Probability::new(0.02)) - .reorder_gap(5) - .seed(seed), - ]; - for impairment in impairments { - let latency = Duration::from_millis(30); - assert_all_rids_mapped(latency, impairment, rtx, signalling)?; - } - } - } - } - Ok(()) -} - -/// Negotiates simulcast with the receiver's answer restricted to `accepted` (none -/// rejects simulcast), renegotiates after `send_before` of media, and checks that the SDP -/// describing the sender's track keeps declaring exactly the accepted layers, and that -/// every accepted layer keeps arriving with its rid. -fn assert_simulcast_survives_reoffer( - reoffer: Reoffer, - send_before: Duration, - accepted: &[&str], -) -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = offer_simulcast(&mut l, &mut r, false, accepted)?; - connect(&mut l, &mut r)?; - send_frames(&mut l, &mut r, mid, accepted, send_before)?; - - // An unrelated media makes the renegotiation re-describe the simulcast track. - let sdp = match reoffer { - Reoffer::FromReceiver => { - let mut change = r.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let offer = SdpOffer::from_sdp_string(&restrict_sdp(&offer.to_sdp_string(), accepted)) - .expect("restricted offer to parse"); - let answer = l.rtc.sdp_api().accept_offer(offer)?; - let sdp = answer.to_sdp_string(); - r.rtc.sdp_api().accept_answer(pending, answer)?; - sdp - } - Reoffer::FromSender => { - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let sdp = offer.to_sdp_string(); - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - sdp - } - }; - assert_declares_send_simulcast(&sdp, mid, accepted); - - if !accepted.is_empty() { - let events_before = r.events.len(); - send_frames(&mut l, &mut r, mid, accepted, Duration::from_secs(2))?; - let context = format!("{reoffer:?}"); - assert_rids_delivered(&mut r, mid, accepted, events_before, &context); - } - - Ok(()) -} - -/// `impairment` applies on top of `latency` once the sender is connected. -fn assert_all_rids_mapped( - latency: Duration, - impairment: NetemConfig, - rtx: bool, - signalling: Signalling, -) -> Result<(), RtcError> { - let netem = impairment.latency(latency); - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new_with_config(Peer::Left, |c| vp8_only(c, rtx)); - let mut r = TestRtc::new_with_config(Peer::Right, |c| vp8_only(c, rtx)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The handshake does not survive the harsher configs; the latency alone keeps the - // relative timing of the two peers' connection realistic. - let latency_only = NetemConfig::new().latency(latency); - l.set_netem(latency_only); - r.set_netem(latency_only); - - let all = all_rids(); - let mid = match signalling { - Signalling::MediaInFirstOffer => { - let mid = offer_simulcast(&mut l, &mut r, false, &all)?; - connect(&mut l, &mut r)?; - mid - } - Signalling::Renegotiated { glare } => { - let mut change = l.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - connect(&mut l, &mut r)?; - offer_simulcast(&mut l, &mut r, glare, &all)? - } - }; - - l.set_netem(netem); - r.set_netem(netem); - - send_frames(&mut l, &mut r, mid, &all, Duration::from_secs(5))?; - - let context = format!("rtx: {rtx}, {signalling:?}, netem: {netem:?}"); - assert_rids_delivered(&mut r, mid, &all, 0, &context); - - Ok(()) -} - -/// Offers every layer and restricts the receiver's answer to the `accepted` rids. -fn offer_simulcast(l: &mut TestRtc, r: &mut TestRtc, glare: bool, accepted: &[&str]) -> Result { - let all = all_rids(); - let mut simulcast = Simulcast::new(); - for rid in &all { - simulcast.add_send_layer(SimulcastLayer::new(rid)); - } - - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Video, Direction::SendOnly, None, None, Some(simulcast)); - let (offer, pending) = change.apply().unwrap(); - assert_declares_send_simulcast(&offer.to_sdp_string(), mid, &all); - - if glare { - let mut change = r.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); - let (_ignored_offer, _dropped_pending) = change.apply().unwrap(); - } - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - let answer = SdpAnswer::from_sdp_string(&restrict_sdp(&answer.to_sdp_string(), accepted)) - .expect("restricted answer to parse"); - l.rtc.sdp_api().accept_answer(pending, answer)?; - Ok(mid) -} - -/// Progresses until the sender is connected. Applications start sending as soon as their -/// own side is connected, which can be well before the remote side is. -fn connect(l: &mut TestRtc, r: &mut TestRtc) -> Result<(), RtcError> { - while !l.is_connected() { - if l.duration() > Duration::from_secs(10) { - panic!("Failed to connect"); - } - progress(l, r)?; - } - Ok(()) -} - -/// Writes 30fps on each of `rids` for `duration`. -fn send_frames(l: &mut TestRtc, r: &mut TestRtc, mid: Mid, rids: &[&str], duration: Duration) -> Result<(), RtcError> { - let pt = l.params_vp8().pt(); - let start = l.last; - - let mut frame = 0_u32; - while l.last - start < duration { - let now = l.last; - let rtp_time = MediaTime::new(frame as u64 * 3_000, Frequency::NINETY_KHZ); - for rid in rids { - l.writer(mid) - .unwrap() - .rid((*rid).into()) - .write(pt, now, rtp_time, vec![frame as u8; frame_size(rid)])?; - } - frame += 1; - - let frame_end = now + Duration::from_millis(33); - while l.last < frame_end { - progress(l, r)?; - } - } - Ok(()) -} - -/// Asserts each of `rids` is bound on the receiver, and that the `MediaData` from -/// `events_from` onwards covers each of them and carries no other rid, or none. -fn assert_rids_delivered(r: &mut TestRtc, mid: Mid, rids: &[&str], events_from: usize, context: &str) { - let rids: Vec = rids.iter().map(|rid| (*rid).into()).collect(); - let unmapped: Vec = rids - .iter() - .copied() - .filter(|rid| r.direct_api().stream_rx_by_mid(mid, Some(*rid)).is_none()) - .collect(); - - let received: Vec> = r.events[events_from..] - .iter() - .filter_map(|(_, e)| match e { - Event::MediaData(d) => Some(d.rid), - _ => None, - }) - .collect(); - let without_rid = received.iter().filter(|r| r.is_none()).count(); - let unexpected: Vec = received - .iter() - .flatten() - .copied() - .filter(|rid| !rids.contains(rid)) - .collect(); - let per_rid: Vec<(Rid, usize)> = rids - .iter() - .map(|rid| (*rid, received.iter().filter(|r| **r == Some(*rid)).count())) - .collect(); - - let context = format!("{context}, MediaData per rid: {per_rid:?}"); - assert!(unmapped.is_empty(), "Unmapped rids {unmapped:?}; {context}"); - assert_eq!(without_rid, 0, "MediaData without rid; {context}"); - assert!( - unexpected.is_empty(), - "MediaData for unexpected rids {unexpected:?}; {context}" - ); - assert!(per_rid.iter().all(|(_, n)| *n > 0), "Rid with no MediaData; {context}"); -} - -/// Asserts the m-section for `mid` in `sdp` declares exactly `rids` as send rids, and -/// no simulcast at all when `rids` is empty. -fn assert_declares_send_simulcast(sdp: &str, mid: Mid, rids: &[&str]) { - let mid_line = format!("a=mid:{mid}"); - let section = sdp - .split("m=") - .find(|s| s.lines().any(|l| l == mid_line)) - .unwrap_or_else(|| panic!("No m-section for {mid} in:\n{sdp}")); - - let mut expected: Vec = rids.iter().map(|rid| format!("a=rid:{rid} send")).collect(); - if !rids.is_empty() { - expected.push(format!("a=simulcast:send {}", rids.join(";"))); - } - - let declared: Vec<&str> = section - .lines() - .filter(|l| l.starts_with("a=rid:") || l.starts_with("a=simulcast:")) - .collect(); - - assert_eq!( - declared, expected, - "Unexpected simulcast declaration for {mid} in:\nm={section}" - ); -} - -/// Removes the rids not in `accepted` from the receiver's `sdp`, and the simulcast -/// declaration when none is accepted, as a receiver narrowing or rejecting the offered -/// layers would describe them in each of its offers and answers. -fn restrict_sdp(sdp: &str, accepted: &[&str]) -> String { - let restricted: Vec = sdp - .split("\r\n") - .filter_map(|line| { - if let Some(rest) = line.strip_prefix("a=rid:") { - let rid = rest.split(' ').next().unwrap_or_default(); - accepted.contains(&rid).then(|| line.to_string()) - } else if line.starts_with("a=simulcast:") { - (!accepted.is_empty()).then(|| format!("a=simulcast:recv {}", accepted.join(";"))) - } else { - Some(line.to_string()) - } - }) - .collect(); - - restricted.join("\r\n") -} - -fn all_rids() -> Vec<&'static str> { - LAYERS.iter().map(|(rid, _)| *rid).collect() -} - -fn frame_size(rid: &str) -> usize { - LAYERS - .iter() - .find(|(layer, _)| *layer == rid) - .map(|(_, size)| *size) - .expect("layer for rid") -} - -fn vp8_only(config: RtcConfig, rtx: bool) -> RtcConfig { - let mut config = config.clear_codecs(); - config.codec_config().add_config( - 96.into(), - rtx.then(|| 97.into()), - Codec::Vp8, - Frequency::NINETY_KHZ, - None, - Default::default(), - ); - config -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/srtp-replay-attack.rs b/rs/moq-webrtc/src/vendor/str0m/tests/srtp-replay-attack.rs deleted file mode 100644 index bde014b9167..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/srtp-replay-attack.rs +++ /dev/null @@ -1,212 +0,0 @@ -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::net::Receive; -use crate::vendor::str0m::rtp::{ExtensionValues, RawPacket, RtpWrite, SeqNo, Ssrc}; -use crate::vendor::str0m::{Event, Input, Output, Rtc, RtcError}; - -use super::common; -use common::{TestRtc, connect_l_r, connect_l_r_with_rtc, init_crypto_default, init_log}; - -const EXPECTED_PACKETS: usize = 50; -const REPLAY_PER_PACKET: usize = 5; - -#[test] -pub fn srtp_replay_attack_rtp_mode() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - let mid = "aud".into(); - - let ssrc_tx: Ssrc = 42.into(); - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - let mut write_at = l.last + Duration::from_millis(20); - let mut seq_no: SeqNo = 0_u64.into(); - let mut time = 0; - let mut send_count = 0; - const TIME_INTERVAL: u32 = 960; - - // Process the DTLS Handshake, before we start duplicating SRTP packets - progress_with_replay(&mut l, &mut r, 1)?; - - loop { - if l.start + l.duration() > write_at && send_count < EXPECTED_PACKETS { - seq_no.inc(); - time += TIME_INTERVAL; - write_at = l.last + Duration::from_millis(20); - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - let exts = ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, [1, 3, 3, 7]).ext_vals(exts)); - send_count += 1; - } - - progress_with_replay(&mut l, &mut r, REPLAY_PER_PACKET)?; - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let rtp_raw_rx: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Some(RawPacket::RtpRx(header, payload)) = e.as_raw_packet() { - Some((header, payload)) - } else { - None - } - }) - .collect(); - assert_eq!(rtp_raw_rx.len(), EXPECTED_PACKETS); - - let rtp: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::RtpPacket(v) = e { Some(v) } else { None }) - .collect(); - assert_eq!(rtp.len(), EXPECTED_PACKETS); - Ok(()) -} - -#[test] -pub fn srtp_replay_attack_frame_mode() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let rtc1 = Rtc::builder().set_rtp_mode(true).enable_raw_packets(true).build(now); - let rtc2 = Rtc::builder() - .enable_raw_packets(true) - // release packet straight away - .set_reordering_size_audio(0) - .build(now); - - let (mut l, mut r) = connect_l_r_with_rtc(rtc1, rtc2); - - let mid = "aud".into(); - - let ssrc_tx: Ssrc = 42.into(); - l.direct_api().declare_media(mid, MediaKind::Audio); - l.direct_api().declare_stream_tx(ssrc_tx, None, mid, None); - r.direct_api().declare_media(mid, MediaKind::Audio); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let ssrc = l.direct_api().stream_tx_by_mid(mid, None).unwrap().ssrc(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - let mut write_at = l.last + Duration::from_millis(20); - let mut seq_no: SeqNo = 0_u64.into(); - let mut time = 0; - let mut send_count = 0; - const TIME_INTERVAL: u32 = 960; - - // Process the DTLS Handshake, before we start duplicating SRTP packets - progress_with_replay(&mut l, &mut r, 1)?; - - loop { - if l.start + l.duration() > write_at && send_count < EXPECTED_PACKETS { - seq_no.inc(); - time += TIME_INTERVAL; - write_at = l.last + Duration::from_millis(20); - let wallclock = l.start + l.duration(); - let mut direct = l.direct_api(); - let stream = direct.stream_tx(&ssrc).unwrap(); - let exts = ExtensionValues { - audio_level: Some(-42), - voice_activity: Some(false), - ..Default::default() - }; - - stream.write_rtp(RtpWrite::new(pt, seq_no, time, wallclock, [1, 3, 3, 7]).ext_vals(exts)); - send_count += 1; - } - - progress_with_replay(&mut l, &mut r, REPLAY_PER_PACKET)?; - - if l.duration() > Duration::from_secs(5) { - break; - } - } - - let rtp_raw_rx: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Some(RawPacket::RtpRx(header, payload)) = e.as_raw_packet() { - Some((header, payload)) - } else { - None - } - }) - .collect(); - assert_eq!(rtp_raw_rx.len(), EXPECTED_PACKETS); - - let media: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(v) = e { Some(v) } else { None }) - .collect(); - assert_eq!(media.len(), EXPECTED_PACKETS); - Ok(()) -} - -pub fn progress_with_replay(l: &mut TestRtc, r: &mut TestRtc, replay: usize) -> Result<(), RtcError> { - let (f, t) = if l.last < r.last { (l, r) } else { (r, l) }; - - loop { - f.span.in_scope(|| f.rtc.handle_input(Input::Timeout(f.last)))?; - - match f.span.in_scope(|| f.rtc.poll_output())? { - Output::Timeout(v) => { - let tick = f.last + Duration::from_millis(10); - f.last = if v == f.last { tick } else { tick.min(v) }; - break; - } - Output::Transmit(v) => { - let data = v.contents; - for _ in 0..replay { - let input = Input::Receive( - f.last, - Receive { - proto: v.proto, - source: v.source, - destination: v.destination, - contents: (&*data).try_into().unwrap(), - }, - ); - t.span.in_scope(|| t.rtc.handle_input(input)).unwrap(); - } - } - Output::Event(v) => { - f.events.push((f.last, v)); - } - } - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ssrc_zero_feedback.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ssrc_zero_feedback.rs deleted file mode 100644 index f31c6953bad..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ssrc_zero_feedback.rs +++ /dev/null @@ -1,64 +0,0 @@ -use crate::vendor::str0m::media::{MediaKind, Mid}; -use crate::vendor::str0m::{Input, Output, Reason, Rtc, RtcConfig}; -use std::time::{Duration, Instant}; - -fn next_timeout(rtc: &mut Rtc) -> (Instant, Reason) { - for _ in 0..32 { - if let Output::Timeout(deadline) = rtc.poll_output().unwrap() { - return (deadline, rtc.last_timeout_reason()); - } - } - panic!("str0m did not finish draining outputs within 32 polls"); -} - -fn receiver(ssrc: u32, now: Instant) -> Rtc { - let mut rtc = RtcConfig::new() - .set_rtp_mode(true) - .set_rtcp_report_interval_audio(Duration::from_secs(1)) - .set_rtcp_report_interval_video(Duration::from_secs(1)) - .build(now); - - let mid: Mid = "audio".into(); - let mut direct = rtc.direct_api(); - direct.declare_media(mid, MediaKind::Audio); - direct - .expect_stream_rx(ssrc.into(), None, mid, None) - .suppress_nack(true); - rtc -} - -#[test] -fn ordinary_receiver_advances_feedback_deadline() { - let now = Instant::now(); - let mut rtc = receiver(1234, now); - let expected = now + Duration::from_secs(1); - let mut timeout = now; - for _ in 0..32 { - rtc.handle_input(Input::Timeout(timeout)).unwrap(); - let (deadline, reason) = next_timeout(&mut rtc); - if reason == Reason::Feedback { - assert_eq!(deadline, expected); - return; - } - assert!(deadline <= expected, "feedback was not the next deadline"); - timeout = deadline; - } - panic!("ordinary receiver did not schedule feedback within 32 timeouts"); -} - -#[test] -fn ssrc_zero_probe_does_not_rearm_immediate_feedback_forever() { - let now = Instant::now(); - let mut rtc = receiver(0, now); - let mut due_timeouts = Vec::new(); - for _ in 0..3 { - rtc.handle_input(Input::Timeout(now)).unwrap(); - let (deadline, reason) = next_timeout(&mut rtc); - if deadline > now { - return; - } - due_timeouts.push((deadline, reason)); - } - - panic!("SSRC 0 never advances its timer after three timeout deliveries: {due_timeouts:?}"); -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs b/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs deleted file mode 100644 index 7c85f5b6da6..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs +++ /dev/null @@ -1,505 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::MediaKind; -use crate::vendor::str0m::net::Receive; -use crate::vendor::str0m::rtp::{RtpWrite, Ssrc}; -use crate::vendor::str0m::{Candidate, Event, Input, Output, Rtc, RtcError}; - -use super::common; -use common::{Peer, PendingPacket, TestRtc, init_crypto_default, init_log, progress}; - -fn connect_direct() -> Result<(TestRtc, TestRtc), RtcError> { - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(Peer::Left.span(), Rtc::new(now)); - // These tests hold a fragment across long pauses before completing it. - let mut r = TestRtc::new_with_rtc( - Peer::Right.span(), - Rtc::builder().set_reordering_size_video(10).build(now), - ); - - let host1 = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp")?.clone(); - let host2 = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp")?.clone(); - l.add_local_candidate(host1.clone()); - l.add_remote_candidate(host2.clone()); - r.add_local_candidate(host2); - r.add_remote_candidate(host1); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - l.direct_api().start_dtls(true)?; - r.direct_api().start_dtls(false)?; - - while !l.is_connected() || !r.is_connected() { - progress(&mut l, &mut r)?; - } - - Ok((l, r)) -} - -fn flush_transmits(rtc: &mut TestRtc, time: Instant) -> Result, RtcError> { - let mut packets = Vec::new(); - - rtc.rtc.handle_input(Input::Timeout(time))?; - - loop { - match rtc.rtc.poll_output()? { - Output::Timeout(v) => { - let tick = rtc.last + rtc.forced_time_advance; - rtc.last = if v == rtc.last { tick } else { tick.min(v) }; - break; - } - Output::Transmit(v) => { - packets.push(PendingPacket { - proto: v.proto, - source: v.source, - destination: v.destination, - contents: v.contents.to_vec(), - }); - } - Output::Event(v) => rtc.events.push((time, v)), - } - } - - Ok(packets) -} - -fn wait_for_transmits( - rtc: &mut TestRtc, - earliest: Instant, - max_wait: Duration, -) -> Result<(Instant, Vec), RtcError> { - let deadline = earliest + max_wait; - - loop { - let time = rtc.last.max(earliest); - let packets = flush_transmits(rtc, time)?; - - if !packets.is_empty() { - return Ok((time, packets)); - } - - assert!( - time < deadline, - "expected at least one packet by {:?}, but sender emitted none", - deadline.saturating_duration_since(earliest) - ); - } -} - -fn deliver_packet(rtc: &mut TestRtc, time: Instant, packet: PendingPacket) -> Result<(), RtcError> { - let input = Input::Receive( - time, - Receive { - proto: packet.proto, - source: packet.source, - destination: packet.destination, - contents: (&packet.contents[..]).try_into()?, - }, - ); - - rtc.rtc.handle_input(input)?; - - loop { - match rtc.rtc.poll_output()? { - Output::Timeout(v) => { - let tick = rtc.last + rtc.forced_time_advance; - rtc.last = if v == rtc.last { tick } else { tick.min(v) }; - break; - } - Output::Transmit(_) => {} - Output::Event(v) => rtc.events.push((time, v)), - } - } - - Ok(()) -} - -fn measure_fresh_age_after_pause(pause_duration: Duration) -> Result { - let (mut l, mut r) = connect_direct()?; - - let mid = "vid".into(); - let ssrc: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let pt = l.params_vp8().pt(); - assert_eq!(l.params_vp8().spec().codec, Codec::Vp8); - - let frame_timestamp = 90_000u32; - let first_write_at = l.last + Duration::from_millis(20); - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - 10_000u64.into(), - frame_timestamp, - first_write_at, - [0x10, 0x00, 0xAA, 0xBB], - ) - .nackable(true), - ); - } - let (first_emit_at, mut first_packets) = wait_for_transmits(&mut l, first_write_at, Duration::from_millis(50))?; - assert_eq!(first_packets.len(), 1, "expected one first-fragment packet"); - deliver_packet(&mut r, first_emit_at, first_packets.remove(0))?; - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - 10_001u64.into(), - frame_timestamp, - first_write_at + Duration::from_millis(5), - [0x00, 0xCC, 0xDD], - ) - .marker(true) - .nackable(true), - ); - } - let (_, delayed_packets) = wait_for_transmits( - &mut l, - first_write_at + Duration::from_millis(5), - Duration::from_millis(50), - )?; - assert!( - !delayed_packets.is_empty(), - "expected at least one packet when flushing delayed tail" - ); - - let pause_end = l.last + pause_duration; - while l.last < pause_end || r.last < pause_end { - progress(&mut l, &mut r)?; - } - - assert!( - r.events - .iter() - .any(|(_, e)| matches!(e, Event::StreamPaused(p) if p.paused)), - "receiver never entered paused state" - ); - - let before_tail_event_count = r.events.len(); - let delivery_time = pause_end + Duration::from_millis(20); - for packet in delayed_packets { - deliver_packet(&mut r, delivery_time, packet)?; - } - - let resumed = r.events[before_tail_event_count..] - .iter() - .find_map(|(_, event)| match event { - Event::MediaData(frame) => Some(frame), - _ => None, - }) - .expect("expected the frame spanning the pause to complete"); - assert_eq!(*resumed.seq_range.start(), 10_000u64.into()); - assert_eq!(*resumed.seq_range.end(), 10_001u64.into()); - - let fresh_first_at = delivery_time + Duration::from_millis(20); - let fresh_frame_timestamp = frame_timestamp + 3_000; - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - 10_002u64.into(), - fresh_frame_timestamp, - fresh_first_at, - [0x10, 0x00, 0x11, 0x22], - ) - .nackable(true), - ); - } - let (fresh_first_emit_at, mut fresh_first_packets) = - wait_for_transmits(&mut l, fresh_first_at, Duration::from_millis(50))?; - assert_eq!(fresh_first_packets.len(), 1, "expected one fresh first-fragment packet"); - deliver_packet(&mut r, fresh_first_emit_at, fresh_first_packets.remove(0))?; - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - 10_003u64.into(), - fresh_frame_timestamp, - fresh_first_at + Duration::from_millis(5), - [0x00, 0x33, 0x44], - ) - .marker(true) - .nackable(true), - ); - } - let (fresh_tail_emit_at, fresh_tail_packets) = wait_for_transmits( - &mut l, - fresh_first_at + Duration::from_millis(5), - Duration::from_millis(50), - )?; - let before_fresh_event_count = r.events.len(); - for packet in fresh_tail_packets { - deliver_packet(&mut r, fresh_tail_emit_at, packet)?; - } - - let media = r.events[before_fresh_event_count..] - .iter() - .find_map(|(event_time, e)| match e { - Event::MediaData(data) => Some((*event_time, data)), - _ => None, - }) - .expect("expected MediaData from the fresh post-pause frame"); - - let age = media.0.saturating_duration_since(media.1.network_time); - - assert_eq!(*media.1.seq_range.start(), 10_002u64.into()); - assert_eq!(*media.1.seq_range.end(), 10_003u64.into()); - - Ok(age) -} - -fn collect_fresh_ages_after_repeated_pauses(pause_durations: &[Duration]) -> Result, RtcError> { - let (mut l, mut r) = connect_direct()?; - - let mid = "vid".into(); - let ssrc: Ssrc = 42.into(); - - l.direct_api().declare_media(mid, MediaKind::Video); - l.direct_api().declare_stream_tx(ssrc, None, mid, None); - - r.direct_api().declare_media(mid, MediaKind::Video); - r.direct_api().expect_stream_rx(ssrc, None, mid, None); - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let pt = l.params_vp8().pt(); - assert_eq!(l.params_vp8().spec().codec, Codec::Vp8); - - let mut fresh_ages = Vec::new(); - - for (i, pause_duration) in pause_durations.iter().copied().enumerate() { - let seq = 20_000u64 + (i as u64) * 4; - let frame_timestamp = 90_000u32 + (i as u32) * 3_000; - let first_write_at = l.last + Duration::from_millis(20); - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - seq.into(), - frame_timestamp, - first_write_at, - [0x10, 0x00, 0xAA, 0xBB, i as u8], - ) - .nackable(true), - ); - } - let (first_emit_at, mut first_packets) = wait_for_transmits(&mut l, first_write_at, Duration::from_millis(50))?; - assert_eq!(first_packets.len(), 1, "expected one first-fragment packet"); - deliver_packet(&mut r, first_emit_at, first_packets.remove(0))?; - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - (seq + 1).into(), - frame_timestamp, - first_write_at + Duration::from_millis(5), - [0x00, 0xCC, 0xDD, i as u8], - ) - .marker(true) - .nackable(true), - ); - } - let (_, packets) = wait_for_transmits( - &mut l, - first_write_at + Duration::from_millis(5), - Duration::from_millis(50), - )?; - assert!( - !packets.is_empty(), - "expected at least one packet when flushing delayed tail" - ); - let pause_end = l.last + pause_duration; - while l.last < pause_end || r.last < pause_end { - progress(&mut l, &mut r)?; - } - - assert!( - r.events - .iter() - .any(|(_, e)| matches!(e, Event::StreamPaused(p) if p.paused)), - "receiver never entered paused state" - ); - - let before_tail_event_count = r.events.len(); - let delivery_time = pause_end + Duration::from_millis(20); - for packet in packets { - deliver_packet(&mut r, delivery_time, packet)?; - } - - let resumed = r.events[before_tail_event_count..] - .iter() - .find_map(|(_, event)| match event { - Event::MediaData(frame) => Some(frame), - _ => None, - }) - .expect("expected the frame spanning the pause to complete"); - assert_eq!(*resumed.seq_range.start(), seq.into()); - assert_eq!(*resumed.seq_range.end(), (seq + 1).into()); - - let fresh_first_at = delivery_time + Duration::from_millis(20); - let fresh_frame_timestamp = frame_timestamp + 3_000; - let fresh_seq = seq + 2; - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - fresh_seq.into(), - fresh_frame_timestamp, - fresh_first_at, - [0x10, 0x00, 0x55, 0x66, i as u8], - ) - .nackable(true), - ); - } - let (fresh_first_emit_at, mut fresh_first_packets) = - wait_for_transmits(&mut l, fresh_first_at, Duration::from_millis(50))?; - assert_eq!(fresh_first_packets.len(), 1, "expected one fresh first-fragment packet"); - deliver_packet(&mut r, fresh_first_emit_at, fresh_first_packets.remove(0))?; - - { - let mut direct = l.direct_api(); - let tx = direct.stream_tx_by_mid(mid, None).unwrap(); - tx.write_rtp( - RtpWrite::new( - pt, - (fresh_seq + 1).into(), - fresh_frame_timestamp, - fresh_first_at + Duration::from_millis(5), - [0x00, 0x77, 0x88, i as u8], - ) - .marker(true) - .nackable(true), - ); - } - let (fresh_tail_emit_at, fresh_tail_packets) = wait_for_transmits( - &mut l, - fresh_first_at + Duration::from_millis(5), - Duration::from_millis(50), - )?; - let before_fresh_event_count = r.events.len(); - for packet in fresh_tail_packets { - deliver_packet(&mut r, fresh_tail_emit_at, packet)?; - } - - let (event_time, media) = r.events[before_fresh_event_count..] - .iter() - .find_map(|(event_time, e)| match e { - Event::MediaData(data) => Some((*event_time, data)), - _ => None, - }) - .expect("expected MediaData from the fresh post-pause frame"); - - assert_eq!(*media.seq_range.start(), fresh_seq.into()); - assert_eq!(*media.seq_range.end(), (fresh_seq + 1).into()); - fresh_ages.push(event_time.saturating_duration_since(media.network_time)); - } - - Ok(fresh_ages) -} - -#[test] -fn delayed_vp8_tail_packet_after_pause_completes_frame() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let age = measure_fresh_age_after_pause(Duration::from_millis(2200))?; - - assert!( - age < Duration::from_millis(200), - "expected fresh MediaData after pause recovery, got age {:?}", - age - ); - - Ok(()) -} - -#[test] -fn longer_pauses_still_recover_with_fresh_media() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let pause_durations = [ - Duration::from_millis(2200), - Duration::from_millis(4200), - Duration::from_millis(8200), - ]; - - let observed_ages: Vec<_> = pause_durations - .into_iter() - .map(measure_fresh_age_after_pause) - .collect::>()?; - - assert!( - observed_ages.iter().all(|age| *age < Duration::from_millis(200)), - "expected fresh recovery after long pauses, got {:?}", - observed_ages - ); - - Ok(()) -} - -#[test] -fn repeated_pause_cycles_recover_without_stale_media() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let ages = collect_fresh_ages_after_repeated_pauses(&[ - Duration::from_millis(2200), - Duration::from_millis(4200), - Duration::from_millis(6200), - ])?; - - assert!( - ages.iter().all(|age| *age < Duration::from_millis(200)), - "expected fresh media after each pause cycle, got {:?}", - ages - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/stream-lifecycle.rs b/rs/moq-webrtc/src/vendor/str0m/tests/stream-lifecycle.rs deleted file mode 100644 index c28da6c5f1c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/stream-lifecycle.rs +++ /dev/null @@ -1,495 +0,0 @@ -//! Tests for stream pause/resume and lifecycle events. - -use std::net::Ipv4Addr; -use std::time::Duration; -use std::time::Instant; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::RtpWrite; -use crate::vendor::str0m::{Event, Rtc, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress}; - -/// Test that StreamPaused event is emitted after no packets for ~1.5 seconds. -#[test] -fn stream_pause_detection_timeout() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - // Send packets for 500ms - let send_until = l.duration() + Duration::from_millis(500); - loop { - if l.duration() >= send_until { - break; - } - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Stop sending and wait for pause detection (>1.5 seconds) - let pause_wait = l.duration() + Duration::from_secs(3); - loop { - if l.duration() >= pause_wait { - break; - } - progress(&mut l, &mut r)?; - } - - // Check for StreamPaused event on receiver - let paused_events: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::StreamPaused(p) = e { Some(p) } else { None }) - .collect(); - - assert!( - paused_events.iter().any(|p| p.paused && p.mid == mid), - "Expected StreamPaused event with paused=true for mid {:?}", - mid - ); - - Ok(()) -} - -/// Test pause detection followed by resume when packets arrive again. -#[test] -fn stream_pause_resume_cycle() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - let pt = params.pt(); - let data = vec![1_u8; 80]; - - // Phase 1: Send packets - let send_until = l.duration() + Duration::from_millis(500); - loop { - if l.duration() >= send_until { - break; - } - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Phase 2: Stop sending and wait for pause - let pause_wait = l.duration() + Duration::from_secs(2); - loop { - if l.duration() >= pause_wait { - break; - } - progress(&mut l, &mut r)?; - } - - // Phase 3: Resume sending - let resume_until = l.duration() + Duration::from_millis(500); - loop { - if l.duration() >= resume_until { - break; - } - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data.clone())?; - progress(&mut l, &mut r)?; - } - - // Check for both pause and resume events - let paused_states: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Event::StreamPaused(p) = e { - if p.mid == mid { Some(p.paused) } else { None } - } else { - None - } - }) - .collect(); - - assert!( - paused_states.contains(&true), - "Expected StreamPaused event with paused=true" - ); - assert!( - paused_states.contains(&false), - "Expected StreamPaused event with paused=false (resume)" - ); - - Ok(()) -} - -#[test] -fn pause_preserves_video_contiguity_history() -> Result<(), RtcError> { - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new_with_config(Peer::Right, |config| { - config - .set_pause_threshold(Duration::from_millis(500)) - .set_reordering_size_video(1) - }); - assert_eq!(Rtc::builder().pause_threshold(), Duration::from_millis(1500)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None) - }); - while !l.is_connected() || !r.is_connected() { - progress(&mut l, &mut r)?; - } - let max = l.last.max(r.last); - l.last = max; - r.last = max; - let pt = l.params_vp8().pt(); - - // A one-packet frame establishes the sequence and codec history. - send_vp8(&mut l, &mut r, mid, pt, 10, 90_000)?; - assert_frame_contiguity(&r, 10, true); - - // An idle interval longer than the configured threshold is a pause, but - // the next packet can still be the immediate successor. - advance_both(&mut l, &mut r, Duration::from_millis(200))?; - assert!( - !r.events - .iter() - .any(|(_, event)| { matches!(event, Event::StreamPaused(p) if p.paused && p.mid == mid) }) - ); - advance_both(&mut l, &mut r, Duration::from_millis(450))?; - assert!( - r.events - .iter() - .any(|(_, event)| { matches!(event, Event::StreamPaused(p) if p.paused && p.mid == mid) }) - ); - send_vp8(&mut l, &mut r, mid, pt, 11, 180_000)?; - assert_frame_contiguity(&r, 11, true); - - // After another pause, packet 12 is lost. The first resumed delta frame - // must report the gap even though the stream was reported paused. - advance_both(&mut l, &mut r, Duration::from_millis(650))?; - send_vp8(&mut l, &mut r, mid, pt, 13, 360_000)?; - assert_frame_contiguity(&r, 13, false); - - Ok(()) -} - -#[test] -fn sparse_audio_resumes_after_packet_loss() -> Result<(), RtcError> { - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None) - }); - while !l.is_connected() || !r.is_connected() { - progress(&mut l, &mut r)?; - } - let max = l.last.max(r.last); - l.last = max; - r.last = max; - let pt = l.params_opus().pt(); - - let send = |l: &mut TestRtc, r: &mut TestRtc, seq: u64| -> Result<(), RtcError> { - let at = l.last.max(r.last) + Duration::from_millis(10); - l.direct_api() - .stream_tx_by_mid(mid, None) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), seq as u32 * 960, at, [0xf8, 0xff, 0xfe])); - advance_until(l, r, at + Duration::from_millis(100)) - }; - - send(&mut l, &mut r, 10)?; - assert_frame_contiguity(&r, 10, true); - advance_both(&mut l, &mut r, Duration::from_secs(2))?; - assert!( - r.events - .iter() - .any(|(_, event)| { matches!(event, Event::StreamPaused(p) if p.paused && p.mid == mid) }) - ); - - // Sequence 11 is lost. A sparse sender may send only one packet on resume. - send(&mut l, &mut r, 12)?; - advance_both(&mut l, &mut r, Duration::from_millis(1200))?; - assert_frame_contiguity(&r, 12, false); - Ok(()) -} - -fn send_vp8( - l: &mut TestRtc, - r: &mut TestRtc, - mid: crate::vendor::str0m::media::Mid, - pt: crate::vendor::str0m::media::Pt, - seq: u64, - timestamp: u32, -) -> Result<(), RtcError> { - let at = l.last.max(r.last) + Duration::from_millis(10); - l.direct_api() - .stream_tx_by_mid(mid, None) - .unwrap() - .write_rtp(RtpWrite::new(pt, seq.into(), timestamp, at, [0x10, 0x01, 0xaa]).marker(true)); - advance_until(l, r, at + Duration::from_millis(200)) -} - -fn advance_both(l: &mut TestRtc, r: &mut TestRtc, duration: Duration) -> Result<(), RtcError> { - let until = l.last.max(r.last) + duration; - advance_until(l, r, until) -} - -fn advance_until(l: &mut TestRtc, r: &mut TestRtc, until: Instant) -> Result<(), RtcError> { - while l.last < until || r.last < until { - progress(l, r)?; - } - Ok(()) -} - -fn assert_frame_contiguity(r: &TestRtc, seq: u64, expected: bool) { - let frame = r.events.iter().find_map(|(_, event)| match event { - Event::MediaData(frame) if frame.seq_range.contains(&seq.into()) => Some(frame), - _ => None, - }); - assert_eq!(frame.map(|frame| frame.contiguous), Some(expected), "frame {seq}"); -} - -/// Test changing media direction to SendOnly. -#[test] -fn stream_direction_change_sendonly() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Initial negotiation with SendRecv - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - assert_eq!(l.media(mid).unwrap().direction(), Direction::SendRecv); - assert_eq!(r.media(mid).unwrap().direction(), Direction::SendRecv); - - // Change L to SendOnly - negotiate(&mut l, &mut r, |change| { - change.set_direction(mid, Direction::SendOnly); - }); - - assert_eq!( - l.media(mid).unwrap().direction(), - Direction::SendOnly, - "L should be SendOnly" - ); - assert_eq!( - r.media(mid).unwrap().direction(), - Direction::RecvOnly, - "R should be RecvOnly (opposite of L's SendOnly)" - ); - - Ok(()) -} - -/// Test changing media direction to RecvOnly. -#[test] -fn stream_direction_change_recvonly() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - assert_eq!(l.media(mid).unwrap().direction(), Direction::SendRecv); - assert_eq!(r.media(mid).unwrap().direction(), Direction::SendRecv); - - // Change L to RecvOnly - negotiate(&mut l, &mut r, |change| { - change.set_direction(mid, Direction::RecvOnly); - }); - - assert_eq!( - l.media(mid).unwrap().direction(), - Direction::RecvOnly, - "L should be RecvOnly" - ); - assert_eq!( - r.media(mid).unwrap().direction(), - Direction::SendOnly, - "R should be SendOnly (opposite of L's RecvOnly)" - ); - - Ok(()) -} - -/// Test changing media direction to Inactive. -#[test] -fn stream_direction_change_inactive() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - assert_eq!(l.media(mid).unwrap().direction(), Direction::SendRecv); - assert_eq!(r.media(mid).unwrap().direction(), Direction::SendRecv); - - // Change L to Inactive - negotiate(&mut l, &mut r, |change| { - change.set_direction(mid, Direction::Inactive); - }); - - assert_eq!( - l.media(mid).unwrap().direction(), - Direction::Inactive, - "L should be Inactive" - ); - assert_eq!( - r.media(mid).unwrap().direction(), - Direction::Inactive, - "R should be Inactive (both sides inactive)" - ); - - Ok(()) -} - -/// Test MediaChanged event is generated on direction change. -#[test] -fn stream_media_changed_event() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) - }); - - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // Clear previous events - l.events.clear(); - r.events.clear(); - - // Change direction - negotiate(&mut l, &mut r, |change| { - change.set_direction(mid, Direction::SendOnly); - }); - - // Progress to process events - for _ in 0..20 { - progress(&mut l, &mut r)?; - } - - // Check for MediaChanged event - let changed_events: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaChanged(c) = e { Some(c) } else { None }) - .collect(); - - assert!( - changed_events.iter().any(|c| c.mid == mid), - "Expected MediaChanged event for mid {:?}", - mid - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/twcc.rs b/rs/moq-webrtc/src/vendor/str0m/tests/twcc.rs deleted file mode 100644 index 085a299bbad..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/twcc.rs +++ /dev/null @@ -1,120 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::rtcp::Twcc; -use crate::vendor::str0m::{Rtc, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, negotiate, progress}; - -#[test] -pub fn twcc() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let l_rtc = Rtc::builder().enable_raw_packets(true).build(now); - let r_rtc = Rtc::builder().enable_raw_packets(true).build(now); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), l_rtc); - let mut r = TestRtc::new_with_rtc(info_span!("R"), r_rtc); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mid = negotiate(&mut l, &mut r, |change| { - change.add_media(MediaKind::Video, Direction::SendOnly, None, None, None) - }); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_vp8(); - assert_eq!(params.spec().codec, Codec::Vp8); - let pt = params.pt(); - - let data_a = [1_u8; 80]; - - loop { - { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data_a)?; - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let (sent_twcc, received_twcc) = { - use crate::vendor::str0m::rtp::{RawPacket, rtcp::Rtcp}; - let r_twcc: Vec<_> = r - .events - .iter() - .filter_map(|(_, e)| { - if let Some(RawPacket::RtcpTx(Rtcp::Twcc(twcc))) = e.as_raw_packet() { - Some(twcc) - } else { - None - } - }) - .collect(); - - let l_twcc: Vec<_> = l - .events - .iter() - .filter_map(|(_, e)| { - if let Some(RawPacket::RtcpRx(Rtcp::Twcc(twcc))) = e.as_raw_packet() { - Some(twcc) - } else { - None - } - }) - .collect(); - (r_twcc, l_twcc) - }; - - assert!(!sent_twcc.is_empty(), "Should've sent TWCC"); - assert!( - sent_twcc.len() == received_twcc.len(), - "The number of TWCC packets received should match what was sent" - ); - assert!( - sent_twcc == received_twcc, - "The same TWCC packets that were sent should be received" - ); - - let sent_is_consecutive = sent_twcc - .iter() - .fold((true, None), |(consecutive, last), packet| { - let consecutive = consecutive - && last - .map(|l: &Twcc| l.feedback_count.wrapping_add(1) == packet.feedback_count) - .unwrap_or(true); - - (consecutive, Some(packet)) - }) - .0; - - assert!(!sent_twcc.is_empty(), "Should have sent some TWCC"); - assert!( - sent_is_consecutive, - "Sent TWCC packets should contain no gaps in terms of `feedback_count`" - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/unidirectional-r-create-media.rs b/rs/moq-webrtc/src/vendor/str0m/tests/unidirectional-r-create-media.rs deleted file mode 100644 index 316dfb60f40..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/unidirectional-r-create-media.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::change::SdpOffer; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn unidirectional_r_create_media() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the R (not sending side) with Direction::RecvOnly. - let mut change = r.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::RecvOnly, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - // str0m always produces a=ssrc lines, also for RecvOnly (since direction can change). - // We munge the a=ssrc lines away. - let mut offer = offer.to_string(); - let start = offer.find("a=ssrc").unwrap(); - offer.replace_range(start..offer.len(), ""); - - let offer = SdpOffer::from_sdp_string(&offer).unwrap(); - let answer = l.rtc.sdp_api().accept_offer(offer)?; - r.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data_a = vec![1_u8; 80]; - - loop { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid).unwrap().write(pt, wallclock, time, data_a.clone())?; - - progress(&mut l, &mut r)?; - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!(media_count > 80, "Not enough MediaData: {}", media_count); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/unidirectional.rs b/rs/moq-webrtc/src/vendor/str0m/tests/unidirectional.rs deleted file mode 100644 index 43468dcc8d2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/unidirectional.rs +++ /dev/null @@ -1,87 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::Duration; - -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::{Event, RtcError}; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn unidirectional() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.set_forced_time_advance(Duration::from_millis(1)); - r.set_forced_time_advance(Duration::from_millis(1)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data_a = vec![1_u8; 80]; - - let mut start_of_talk_spurt = true; - loop { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - l.writer(mid) - .unwrap() - .start_of_talkspurt(start_of_talk_spurt) - .write(pt, wallclock, time, data_a.clone())?; - start_of_talk_spurt = false; - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - let media_count = r - .events - .iter() - .filter(|(_, e)| matches!(e, Event::MediaData(_))) - .count(); - - assert!(media_count > 800, "Not enough MediaData: {}", media_count); - - assert!( - r.events - .iter() - .find_map(|(_, e)| match e { - Event::MediaData(m) => Some(m), - _ => None, - }) - .expect("no MediaData event found") - .audio_start_of_talk_spurt - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/user-rtp-header-extension.rs b/rs/moq-webrtc/src/vendor/str0m/tests/user-rtp-header-extension.rs deleted file mode 100644 index 9e5d4eb1dfe..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/user-rtp-header-extension.rs +++ /dev/null @@ -1,298 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::Rtc; -use crate::vendor::str0m::change::SdpOffer; -use crate::vendor::str0m::format::Codec; -use crate::vendor::str0m::media::{Direction, MediaKind}; -use crate::vendor::str0m::rtp::Extension; -use crate::vendor::str0m::rtp::ExtensionSerializer; -use crate::vendor::str0m::rtp::ExtensionValues; -use crate::vendor::str0m::{Event, RtcError}; -use tracing::info_span; - -use super::common; -use common::{TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn user_rtp_header_extension() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - #[derive(Debug, PartialEq, Eq)] - struct MyValue(u16); - - #[derive(Debug)] - struct MyValueSerializer; - - impl ExtensionSerializer for MyValueSerializer { - fn write_to(&self, buf: &mut [u8], ev: &ExtensionValues) -> usize { - // Does output have space? - if buf.len() < 2 { - return 0; - } - - // Is there a value set? - let Some(my_value) = ev.user_values.get::() else { - return 0; - }; - - // u16 is 2 bytes - buf[..2].copy_from_slice(&my_value.0.to_be_bytes()); - - 2 - } - - fn parse_value(&self, buf: &[u8], ev: &mut ExtensionValues) -> bool { - // Is buffer big enough to hold the value? - if buf.len() < 2 { - return false; - } - - let v = u16::from_be_bytes([buf[0], buf[1]]); - let my_value = MyValue(v); - - // Save parsed value - ev.user_values.set(my_value); - - true - } - - fn is_audio(&self) -> bool { - true - } - - fn is_video(&self) -> bool { - true - } - } - - let user_ext = Extension::with_serializer("http://my-special-extension", MyValueSerializer); - - // Both L and R must have the uri + serializer configured. - let now = Instant::now(); - let rtc_l = Rtc::builder() - // - .set_extension(12, user_ext.clone()) - .build(now); - let rtc_r = Rtc::builder() - // - .set_extension(12, user_ext) - .build(now); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc_l); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - let offer_str = offer.to_sdp_string(); - let offer_parsed = SdpOffer::from_sdp_string(&offer_str).expect("Should parse offer from string"); - let answer = r.rtc.sdp_api().accept_offer(offer_parsed)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Verify that the extension is negotiated. - let ext_l = l.media(mid).unwrap().remote_extmap(); - assert_eq!( - ext_l.lookup(12).map(|e| e.as_uri()), - Some("http://my-special-extension") - ); - - let ext_r = r.media(mid).unwrap().remote_extmap(); - assert_eq!( - ext_r.lookup(12).map(|e| e.as_uri()), - Some("http://my-special-extension") - ); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data_a = vec![1_u8; 80]; - - loop { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - - l.writer(mid) - .unwrap() - // Set my bespoke RTP header value. - .user_extension_value(MyValue(42)) - .write(pt, wallclock, time, data_a.clone())?; - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(3) { - break; - } - } - - let iter = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - // Assert every media write got the value through. - for data in iter { - let v = data.ext_vals.user_values.get::(); - assert_eq!(v, Some(&MyValue(42))); - } - - Ok(()) -} - -#[test] -pub fn user_rtp_header_extension_two_byte_form() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - #[derive(Debug, PartialEq, Eq, Clone)] - struct MyValue(Vec); - - #[derive(Debug)] - struct MyValueSerializer; - - impl ExtensionSerializer for MyValueSerializer { - fn write_to(&self, buf: &mut [u8], ev: &ExtensionValues) -> usize { - let Some(my_value) = ev.user_values.get::() else { - return 0; - }; - - let my_len = my_value.0.len(); - if buf.len() < my_len { - return 0; - } - - // u16 is 2 bytes - buf[..my_len].copy_from_slice(&my_value.0); - - my_len - } - - fn parse_value(&self, buf: &[u8], ev: &mut ExtensionValues) -> bool { - let my_value = MyValue(buf.to_vec()); - - ev.user_values.set(my_value); - - true - } - - fn is_audio(&self) -> bool { - true - } - - fn is_video(&self) -> bool { - true - } - - fn requires_two_byte_form(&self, _ev: &ExtensionValues) -> bool { - true - } - } - - let user_ext = Extension::with_serializer("http://my-special-extension", MyValueSerializer); - - // Both L and R must have the uri + serializer configured. - let now = Instant::now(); - let rtc_l = Rtc::builder() - // - .set_extension(12, user_ext.clone()) - .build(now); - let rtc_r = Rtc::builder() - // - .set_extension(12, user_ext) - .build(now); - - let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc_l); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // The change is on the L (sending side) with Direction::SendRecv. - let mut change = l.sdp_api(); - let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Verify that the extension is negotiated. - let ext_l = l.media(mid).unwrap().remote_extmap(); - assert_eq!( - ext_l.lookup(12).map(|e| e.as_uri()), - Some("http://my-special-extension") - ); - - let ext_r = r.media(mid).unwrap().remote_extmap(); - assert_eq!( - ext_r.lookup(12).map(|e| e.as_uri()), - Some("http://my-special-extension") - ); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let params = l.params_opus(); - assert_eq!(params.spec().codec, Codec::Opus); - let pt = params.pt(); - - let data_a = vec![1_u8; 80]; - - let my_value = MyValue((0..100u8).collect()); - loop { - let wallclock = l.start + l.duration(); - let time = l.duration().into(); - - l.writer(mid) - .unwrap() - // Set my bespoke RTP header value. - .user_extension_value(my_value.clone()) - .write(pt, wallclock, time, data_a.clone())?; - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(3) { - break; - } - } - - let datas = r - .events - .iter() - .filter_map(|(_, e)| if let Event::MediaData(d) = e { Some(d) } else { None }); - - // Assert every media write got the value through. - let mut empty = true; - for data in datas { - empty = false; - let v = data.ext_vals.user_values.get::(); - assert_eq!(v, Some(&my_value)); - } - assert!(!empty); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/writer-borrow.rs b/rs/moq-webrtc/src/vendor/str0m/tests/writer-borrow.rs deleted file mode 100644 index 5d7001b0f88..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/writer-borrow.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! Keep named Writer handles compatible with non-lexical Rtc borrows. - -use std::time::Instant; - -use crate::vendor::str0m::media::{KeyframeRequestKind, MediaKind}; -use crate::vendor::str0m::{Input, Output, Rtc, RtcError}; - -use super::common; -use common::init_crypto_default; - -#[test] -fn named_writer_releases_rtc_after_keyframe_request() -> Result<(), RtcError> { - init_crypto_default(); - let now = Instant::now(); - let mut rtc = Rtc::new(now); - let mid = "video".into(); - rtc.direct_api().declare_media(mid, MediaKind::Video); - rtc.direct_api().expect_stream_rx(42.into(), None, mid, None); - rtc.handle_input(Input::Timeout(now))?; - while !matches!(rtc.poll_output()?, Output::Timeout(_)) {} - - let mut writer = rtc.writer(mid).unwrap(); - writer.request_keyframe(None, KeyframeRequestKind::Pli)?; - - // A named writer's last use ends its borrow, so callers can poll immediately - // without wrapping the request in a new scope or explicitly dropping it. - match rtc.poll_output()? { - Output::Timeout(deadline) => assert_eq!(deadline, now), - output => panic!("keyframe request must schedule an immediate timeout: {output:?}"), - } - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/util/bit_pattern.rs b/rs/moq-webrtc/src/vendor/str0m/util/bit_pattern.rs deleted file mode 100644 index 32bfa66f237..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/util/bit_pattern.rs +++ /dev/null @@ -1,107 +0,0 @@ -/// One byte bit pattern to allow matching against specific bits. -#[derive(Copy, Clone)] -pub(crate) struct BitPattern { - mask: u8, - masked_value: u8, -} - -impl BitPattern { - pub(crate) fn matches(&self, profile_iop: u8) -> bool { - ((profile_iop ^ self.masked_value) & self.mask) == 0x0 - } - - /// Create a bit pattern. Use `1` for bits that must be set, `0` for bits that must not be - /// set, and `x` for bits that can take any value. - /// - /// Panics if any other byte values than ASCII `1`, `0`, or `x` is used. - pub(crate) const fn new(pattern: [u8; 8]) -> Self { - const fn bit_to_mask_bit(pattern: [u8; 8], i: usize) -> u8 { - let bit = pattern[7 - i]; - match bit { - b'1' | b'0' => 0x1 << i, - b'x' => 0x0 << i, - _ => panic!("Invalid bit pattern in IOPPattern only ASCII 1, 0, and x are allowed"), - } - } - - const fn to_mask(pattern: [u8; 8]) -> u8 { - bit_to_mask_bit(pattern, 7) - | bit_to_mask_bit(pattern, 6) - | bit_to_mask_bit(pattern, 5) - | bit_to_mask_bit(pattern, 4) - | bit_to_mask_bit(pattern, 3) - | bit_to_mask_bit(pattern, 2) - | bit_to_mask_bit(pattern, 1) - | bit_to_mask_bit(pattern, 0) - } - - const fn bit_to_mask_value_bit(pattern: [u8; 8], i: usize) -> u8 { - let bit = pattern[7 - i]; - match bit { - b'1' => 0x1 << i, - b'x' | b'0' => 0x0 << i, - _ => panic!("Invalid bit pattern in IOPPattern only ASCII 1, 0, and x are allowed"), - } - } - - const fn to_mask_value(pattern: [u8; 8]) -> u8 { - bit_to_mask_value_bit(pattern, 7) - | bit_to_mask_value_bit(pattern, 6) - | bit_to_mask_value_bit(pattern, 5) - | bit_to_mask_value_bit(pattern, 4) - | bit_to_mask_value_bit(pattern, 3) - | bit_to_mask_value_bit(pattern, 2) - | bit_to_mask_value_bit(pattern, 1) - | bit_to_mask_value_bit(pattern, 0) - } - let mask = to_mask(pattern); - let masked_value = to_mask_value(pattern); - - Self { mask, masked_value } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_iop_pattern_matching() { - let all_any = BitPattern::new(*b"xxxxxxxx"); - for x in 0..255 { - assert!(all_any.matches(x)); - } - - let stripes = BitPattern::new(*b"10101010"); - assert!(stripes.matches(0b1010_1010)); - assert!(!stripes.matches(0b1011_1010)); - - let inverse_stripes = BitPattern::new(*b"01010101"); - assert!(inverse_stripes.matches(0b0101_0101)); - assert!(!inverse_stripes.matches(0b0111_0001)); - - let high_bits = BitPattern::new(*b"1101xxxx"); - assert!(high_bits.matches(0b1101_0101)); - assert!(!high_bits.matches(0b1001_0101)); - - let mid_bits = BitPattern::new(*b"xx0110xx"); - assert!(mid_bits.matches(0b0101_1001)); - assert!(!mid_bits.matches(0b1000_1001)); - - let only_ones = BitPattern::new(*b"11111111"); - assert!(only_ones.matches(0b1111_1111)); - assert!(!only_ones.matches(0b1110_1111)); - - let only_zeros = BitPattern::new(*b"00000000"); - assert!(only_zeros.matches(0b0000_0000)); - assert!(!only_zeros.matches(0b0000_0010)); - - let mixed_pattern = BitPattern::new(*b"1x0x1x01"); - assert!(mixed_pattern.matches(0b11011001)); - assert!(!mixed_pattern.matches(0b11011011)); - - let complex_pattern = BitPattern::new(*b"1xx01x0x"); - assert!(complex_pattern.matches(0b10001001)); - assert!(!complex_pattern.matches(0b10101010)); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/util/mod.rs b/rs/moq-webrtc/src/vendor/str0m/util/mod.rs deleted file mode 100644 index 757b695dd2c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/util/mod.rs +++ /dev/null @@ -1,84 +0,0 @@ -use std::time::{Duration, Instant}; - -mod bit_pattern; - -pub(crate) use bit_pattern::BitPattern; - -pub(crate) mod value_history; - -mod time_tricks; -pub(crate) use time_tricks::{InstantExt, SystemTimeExt, not_happening}; -pub(crate) use time_tricks::{already_happened, epoch_to_beginning}; - -pub(crate) trait Soonest { - fn soonest(self, other: Self) -> Self; -} - -impl Soonest for (Option, T) { - fn soonest(self, other: Self) -> Self { - match (self, other) { - ((Some(v1), s1), (Some(v2), s2)) => { - if v1 < v2 { - (Some(v1), s1) - } else { - (Some(v2), s2) - } - } - ((None, _), (None, _)) => (None, T::default()), - ((None, _), (v, s)) => (v, s), - ((v, s), (None, _)) => (v, s), - } - } -} - -/// Calculate the round trip time for a given peer as described in -/// [RFC3550 6.4.1](https://datatracker.ietf.org/doc/html/rfc3550#section-6.4.1). -/// -/// ## Params -/// - `ntp_time` the offset since 1900-01-01. -/// - `delay` the delay(`DLSR`) since last sender report expressed as fractions of a second in 32 bits. -/// - `last_report` the middle 32 bits of an NTP timestamp for the most recent sender report(LSR) -/// or Receiver Report(LRR). -pub(crate) fn calculate_rtt(ntp_time: Duration, delay: u32, last_report: u32) -> Option { - // [10 Nov 1995 11:33:25.125 UTC] [10 Nov 1995 11:33:36.5 UTC] - // n SR(n) A=b710:8000 (46864.500 s) - // ----------------------------------------------------------------> - // v ^ - // ntp_sec =0xb44db705 v ^ dlsr=0x0005:4000 ( 5.250s) - // ntp_frac=0x20000000 v ^ lsr =0xb705:2000 (46853.125s) - // (3024992005.125 s) v ^ - // r v ^ RR(n) - // ----------------------------------------------------------------> - // |<-DLSR->| - // (5.250 s) - // - // A 0xb710:8000 (46864.500 s) - // DLSR -0x0005:4000 ( 5.250 s) - // LSR -0xb705:2000 (46853.125 s) - // ------------------------------- - // delay 0x0006:2000 ( 6.125 s) - - // - we want the current middle 32 bits of an NTP timestamp for the current time. - // We treat the seconds separately to the fractions. - // [32 bit seconds].[32 bit fractions] - // [16 bit].[16 bit] - - // As per RFC delay is 0 in case no SR packet has been received yet. - if delay == 0 { - return None; - } - - let now_secs = ntp_time.as_secs(); - let now_fract_ns = ntp_time.subsec_nanos() as u64; - let now_fract = ((now_fract_ns * u32::MAX as u64) / 1_000_000_000) as u32; - - // Combine the final 2x16 bits together. - let now = (now_secs as u32) << 16 | (now_fract >> 16); - - let rtt = now.checked_sub(delay)?.checked_sub(last_report)?; - let rtt_seconds = rtt >> 16; - let rtt_fraction = (rtt & (u16::MAX as u32)) as f32 / (u16::MAX as u32) as f32; - - let nanos = (rtt_fraction * 1_000_000_000.0) as u32; - Some(Duration::new(rtt_seconds as u64, nanos)) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/util/time_tricks.rs b/rs/moq-webrtc/src/vendor/str0m/util/time_tricks.rs deleted file mode 100644 index bef2033250c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/util/time_tricks.rs +++ /dev/null @@ -1,208 +0,0 @@ -use std::backtrace::Backtrace; -use std::sync::LazyLock; -use std::time::{Duration, Instant, SystemTime}; -use tracing::warn; - -pub(crate) fn not_happening() -> Instant { - const YEARS_100: Duration = Duration::from_secs(60 * 60 * 24 * 365 * 100); - static FUTURE: LazyLock = LazyLock::new(|| Instant::now() + YEARS_100); - *FUTURE -} - -// The goal here is to make a constant "beginning of time" in both Instant and SystemTime -// that we can use as relative values for the rest of str0m. -// This is indeed a bit dodgy, but we want str0m's internal idea of time to be completely -// driven from the external API using `Instant`. What works against us is that Instant can't -// represent things like UNIX EPOCH (but SystemTime can). -static BEGINNING_OF_TIME: LazyLock<(Instant, SystemTime)> = LazyLock::new(|| { - // These two should be "frozen" the same instant. Hopefully they are not differing too much. - let now = Instant::now(); - let now_sys = SystemTime::now(); - - // Find an Instant in the past which is up to an hour back. - let beginning_of_time = { - let mut secs = 3600; - loop { - let dur = Duration::from_secs(secs); - if let Some(v) = now.checked_sub(dur) { - break v; - } - secs -= 1; - if secs == 0 { - panic!("Failed to find a beginning of time instant"); - } - } - }; - - // This might be less than 1 hour if the machine uptime is less. - let since_beginning_of_time = Instant::now() - beginning_of_time; - - let beginning_of_time_sys = now_sys - since_beginning_of_time; - - // This pair represents our "beginning of time" for the same moment. - (beginning_of_time, beginning_of_time_sys) -}); - -pub fn epoch_to_beginning() -> Duration { - BEGINNING_OF_TIME - .1 - .duration_since(SystemTime::UNIX_EPOCH) - .expect("beginning of time to be after epoch") -} - -pub(crate) fn already_happened() -> Instant { - BEGINNING_OF_TIME.0 -} - -pub trait InstantExt { - /// Convert an Instant to a Duration for unix time. - /// - /// First ever time must be "now". - /// - /// panics if `time` goes backwards, i.e. we use this for one Instant and then an earlier Instant. - fn to_unix_duration(&self) -> Duration; - - /// Convert an Instant to a Duration for ntp time. - fn to_ntp_duration(&self) -> Duration; - - /// Convert an Instant to a SystemTime for ntp time - fn to_system_time(&self) -> SystemTime; -} - -pub trait SystemTimeExt { - /// Convert an ntp_64 as seen in SR to a SystemTime. - fn from_ntp_64(v: u64) -> SystemTime; - - /// Convert a SystemTime to ntp_64. - fn as_ntp_64(&self) -> u64; -} - -// RTP spec "wallclock" uses NTP time, which starts at 1900-01-01. -// -// https://tools.ietf.org/html/rfc868 -// -// 365 days * 70 years + 17 leap year days -// (365 * 70 + 17) * 86400 = 2208988800 -const SECS_1900: u64 = 2_208_988_800; -const MICROS_1900: u64 = SECS_1900 * 1_000_000; - -/// 2^32 as float. -const F32: f64 = 4_294_967_296.0; - -impl InstantExt for Instant { - fn to_unix_duration(&self) -> Duration { - // This is a bit fishy. We "freeze" a moment in time for Instant and SystemTime, - // so we can make relative comparisons of Instant - Instant and translate that to - // SystemTime - unix epoch. Hopefully the error is quite small. - if *self < BEGINNING_OF_TIME.0 { - warn!("{}", Backtrace::force_capture()); - warn!("Time went backwards from beginning_of_time Instant"); - } - - let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0); - let system_time = BEGINNING_OF_TIME.1 + duration_since_time_0; - - system_time - .duration_since(SystemTime::UNIX_EPOCH) - .expect("clock to go forwards from unix epoch") - } - - fn to_ntp_duration(&self) -> Duration { - self.to_unix_duration() + Duration::from_micros(MICROS_1900) - } - - fn to_system_time(&self) -> SystemTime { - // This is a bit fishy. We "freeze" a moment in time for Instant and SystemTime, - // so we can make relative comparisons of Instant - Instant and translate that to - // SystemTime - unix epoch. Hopefully the error is quite small. - if *self < BEGINNING_OF_TIME.0 { - warn!("{}", Backtrace::force_capture()); - warn!("Time went backwards from beginning_of_time Instant"); - } - - let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0); - BEGINNING_OF_TIME.1 + duration_since_time_0 - } -} - -impl SystemTimeExt for SystemTime { - fn from_ntp_64(v: u64) -> SystemTime { - // https://tools.ietf.org/html/rfc3550#section-4 - // Wallclock time (absolute date and time) is represented using the - // timestamp format of the Network Time Protocol (NTP), which is in - // seconds relative to 0h UTC on 1 January 1900 [4]. The full - // resolution NTP timestamp is a 64-bit unsigned fixed-point number with - // the integer part in the first 32 bits and the fractional part in the - // last 32 bits. - let secs_ntp = (v as f64) / F32; - - // Shift to UNIX EPOCH - let secs_epoch = secs_ntp - SECS_1900 as f64; - - // Duration not allowed to be negative - let secs_dur = Duration::try_from_secs_f64(secs_epoch).unwrap_or(Duration::ZERO); - - // Time in SystemTime - SystemTime::UNIX_EPOCH + secs_dur - } - - fn as_ntp_64(&self) -> u64 { - let secs_epoch = if let Ok(value) = self.duration_since(SystemTime::UNIX_EPOCH) { - value.as_secs_f64() + SECS_1900 as f64 - } else { - 0.0 - }; - - (secs_epoch * F32) as u64 - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn not_happening_works() { - assert_eq!(not_happening(), not_happening()); - assert!(Instant::now() < not_happening()); - } - - #[test] - fn already_happened_works() { - assert_eq!(already_happened(), already_happened()); - assert!(Instant::now() > already_happened()); - } - - #[test] - fn already_happened_ne() { - assert_ne!(not_happening(), already_happened()) - } - - #[test] - fn ntp_64_from_to() { - let now = SystemTime::now(); - let ntp = now.as_ntp_64(); - let now2 = SystemTime::from_ntp_64(ntp); - let abs = if now > now2 { - now.duration_since(now2) - } else { - now2.duration_since(now) - }; - assert!(abs.unwrap() < Duration::from_millis(1)); - } - - #[test] - fn from_ntp_64_zero() { - let s = SystemTime::from_ntp_64(0); - assert_eq!(s.duration_since(SystemTime::UNIX_EPOCH).unwrap(), Duration::ZERO); - } - - #[test] - fn from_ntp_64_val1() { - let s = SystemTime::from_ntp_64((3971792775u64 << 32) | 4184015405u64); - match s.duration_since(SystemTime::UNIX_EPOCH) { - Ok(n) => assert_eq!(n.as_micros(), 1762803975974166), - Err(_) => panic!("Cannot calculate unix epoch"), - } - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/util/value_history.rs b/rs/moq-webrtc/src/vendor/str0m/util/value_history.rs deleted file mode 100644 index 8144ec50796..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/util/value_history.rs +++ /dev/null @@ -1,109 +0,0 @@ -use std::collections::VecDeque; -use std::iter::Sum; -use std::ops::{AddAssign, SubAssign}; -use std::time::{Duration, Instant}; - -/// Holds a history values of type T for up to a certain Duration, as well as the -/// cumulated (total) value. -#[derive(Debug)] -pub(crate) struct ValueHistory { - value: T, - history: VecDeque<(Instant, T)>, - max_time: Duration, -} - -const DEFAULT_VALUE_HISTORY_DURATION: Duration = Duration::from_secs(1); - -impl Default for ValueHistory { - fn default() -> Self { - Self { - value: Default::default(), - history: Default::default(), - max_time: DEFAULT_VALUE_HISTORY_DURATION, - } - } -} - -impl ValueHistory -where - T: Copy + AddAssign + SubAssign + Sum, -{ - /// Adds a timed value - /// Note: time should always monotonically increase in subsequent calls to add() - pub fn push(&mut self, t: Instant, v: T) { - self.value += v; - self.history.push_back((t, v)); - } - - /// Returns the sum of all values in the history up to max_time. Might - /// return stale value unless [`ValueHistory::purge_old`] is called before. - pub fn sum(&self) -> T { - self.value - } - - /// Recalculates sum purging values older than `now - max_time`. - pub fn purge_old(&mut self, now: Instant) { - while { - let Some(front_t) = self.history.front().map(|v| v.0) else { - return; - }; - now.duration_since(front_t) > self.max_time - } { - if let Some((_, v)) = self.history.pop_front() { - self.value -= v; - } - } - } -} - -#[allow(clippy::unchecked_time_subtraction)] -#[cfg(test)] -mod test { - use std::time::{Duration, Instant}; - - use super::ValueHistory; - - #[test] - fn with_value_test() { - let now = Instant::now(); - - let mut h = ValueHistory { - value: 11, - max_time: Duration::from_secs(1), - ..Default::default() - }; - - assert_eq!(h.sum(), 11); - h.purge_old(now); - assert_eq!(h.sum(), 11); - h.push(now - Duration::from_millis(1500), 22); - h.push(now - Duration::from_millis(500), 22); - assert_eq!(h.sum(), 11 + 22 + 22); - h.purge_old(now); - assert_eq!(h.sum(), 11 + 22); - h.push(now, 0); - assert_eq!(h.sum(), 11 + 22); - } - - #[test] - fn test() { - let now = Instant::now(); - let mut h = ValueHistory::default(); - - assert_eq!(h.sum(), 0); - h.push(now - Duration::from_millis(1500), 22); - assert_eq!(h.sum(), 22); - h.purge_old(now); - assert_eq!(h.sum(), 0); - h.push(now - Duration::from_millis(700), 22); - h.push(now - Duration::from_millis(500), 33); - assert_eq!(h.sum(), 22 + 33); - h.purge_old(now); - assert_eq!(h.sum(), 22 + 33); - - h.purge_old(now + Duration::from_millis(400)); - assert_eq!(h.sum(), 33); - h.purge_old(now + Duration::from_millis(600)); - assert_eq!(h.sum(), 0); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/bandwidth.rs b/rs/moq-webrtc/src/vendor/str0m_proto/bandwidth.rs deleted file mode 100644 index 63f270bf98a..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/bandwidth.rs +++ /dev/null @@ -1,450 +0,0 @@ -use std::fmt; -use std::iter::Sum; -use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; -use std::time::Duration; - -/// A data rate expressed as bits per second(bps). -/// -/// Internally the value is tracked as a floating point number for accuracy in the presence of -/// repeated calculations that can yield decimal values. -#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] -pub struct Bitrate(f64); - -impl Bitrate { - /// A bitrate of zero bit/s. - pub const ZERO: Self = Self::bps(0); - /// The maximum bitrate that can be represented. - pub const MAX: Self = Self::bps(u64::MAX); - /// Positive infinity, useful as an invalid value with comparison semantics - pub const INFINITY: Self = Self(f64::INFINITY); - /// Negative infinity, useful as an invalid value with comparison semantics - pub const NEG_INFINITY: Self = Self(f64::NEG_INFINITY); - - /// Create a bitrate of some bit per second(bps). - pub const fn bps(bps: u64) -> Self { - Bitrate(bps as f64) - } - - /// Create a bitrate of some **Kilobits** per second(kbps). - pub const fn kbps(kbps: u64) -> Self { - Self::bps(kbps * 10_u64.pow(3)) - } - - /// Create a bitrate of some **Megabits** per second(mbps). - pub const fn mbps(mbps: u64) -> Self { - Self::bps(mbps * 10_u64.pow(6)) - } - - /// Create a bitrate of some **Gigabits** per second(gbps). - pub const fn gbps(gbps: u64) -> Self { - Self::bps(gbps * 10_u64.pow(9)) - } - - /// The number of bits per second as f64. - pub fn as_f64(&self) -> f64 { - self.0 - } - - /// The number of bits per second rounded upwards as u64. - pub fn as_u64(&self) -> u64 { - self.0.ceil() as u64 - } - - /// Clamp the value between a min and a max. - pub fn clamp(&self, min: Self, max: Self) -> Self { - Self(self.0.clamp(min.0, max.0)) - } - - /// Return the minimum bitrate between `self` and `other`. - pub fn min(&self, other: Self) -> Self { - Self(self.0.min(other.0)) - } - - /// Return the maximum bitrate between `self` and `other`. - pub fn max(&self, other: Self) -> Self { - Self(self.0.max(other.0)) - } - - /// Whether this bitrate is valid - pub fn is_valid(&self) -> bool { - self.0.is_finite() - } - - /// Turn self into `Option` based on its validity - pub fn as_valid(&self) -> Option { - self.is_valid().then_some(*self) - } - - /// Whether this value is zero - pub fn is_zero(&self) -> bool { - *self == Bitrate::ZERO - } -} - -impl From for Bitrate { - fn from(value: u64) -> Self { - Self::bps(value) - } -} - -impl From for Bitrate { - fn from(value: f64) -> Self { - Self(value) - } -} - -impl Mul for Bitrate { - type Output = DataSize; - - fn mul(self, rhs: Duration) -> Self::Output { - let bits = self.0 * rhs.as_secs_f64(); - let bytes = bits / 8.0; - - DataSize::bytes(bytes.round() as i64) - } -} - -impl Mul for Bitrate { - type Output = Bitrate; - - fn mul(self, rhs: f64) -> Self::Output { - Bitrate(self.0 * rhs) - } -} - -impl Sub for Bitrate { - type Output = Bitrate; - - fn sub(self, rhs: Bitrate) -> Self::Output { - assert!( - self.0 >= rhs.0, - "Attempted to subtract Bitrates that would result in overflow. lhs={}, rhs={}", - self, - rhs - ); - - Self(self.0 - rhs.0) - } -} - -impl Add for Bitrate { - type Output = Bitrate; - - fn add(self, rhs: Bitrate) -> Self::Output { - Self(self.0 + rhs.0) - } -} - -impl fmt::Display for Bitrate { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let rate = self.0; - let log = rate.log10().floor() as u64; - - match log { - 0..=2 => write!(f, "{rate}bit/s"), - 3..=5 => write!(f, "{:.3}kbit/s", rate / 10.0_f64.powf(3.0)), - 6..=8 => write!(f, "{:.3}Mbit/s", rate / 10.0_f64.powf(6.0)), - 9..=11 => write!(f, "{:.3}Gbit/s", rate / 10.0_f64.powf(9.0)), - 12.. => write!(f, "{:.3}Tbit/s", rate / 10.0_f64.powf(12.0)), - } - } -} - -/// A data size expressed in bytes. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct DataSize(i64); - -impl DataSize { - /// A data size of zero bytes. - pub const ZERO: Self = DataSize::bytes(0); - - /// Create a data size of some bytes. - pub const fn bytes(bytes: i64) -> DataSize { - Self(bytes) - } - - /// Create a data size of some kilobytes. - pub const fn kbytes(kbytes: i64) -> DataSize { - Self(kbytes * 1024) - } - - /// Create a data size of some megabytes. - pub const fn mbytes(mbytes: i64) -> DataSize { - Self(mbytes * 1024 * 1024) - } - - /// Create a data size of some gigabytes. - pub const fn gbytes(gbytes: i64) -> DataSize { - Self(gbytes * 1024 * 1024 * 1024) - } - - /// The number of bytes as f64. - pub fn as_bytes_f64(&self) -> f64 { - self.0 as f64 - } - - /// The number of bytes as usize. - pub fn as_bytes_usize(&self) -> usize { - self.0.try_into().expect("DataSize i64 value must fit in usize") - } - - /// The number of bytes as i64. - pub fn as_bytes_i64(&self) -> i64 { - self.0 - } - - /// Subtract, saturating at zero. - pub fn saturating_sub(self, rhs: Self) -> Self { - Self((self.0 - rhs.0).max(0)) - } - - /// The number of kilobytes as f64. - pub fn as_kb(&self) -> f64 { - self.0 as f64 / 1000.0 - } -} - -impl From for DataSize { - fn from(value: usize) -> Self { - Self(value as i64) - } -} - -impl From for DataSize { - fn from(value: u8) -> Self { - Self(value as i64) - } -} - -impl Div for DataSize { - type Output = Bitrate; - - fn div(self, rhs: Duration) -> Self::Output { - let bytes = self.as_bytes_f64(); - let s = rhs.as_secs_f64(); - - if s == 0.0 { - return Bitrate::ZERO; - } - - let bps = (bytes * 8.0) / s; - - bps.into() - } -} - -impl Div for DataSize { - type Output = Duration; - - fn div(self, rhs: Bitrate) -> Self::Output { - let bits = self.as_bytes_f64() * 8.0; - let rhs = rhs.as_f64(); - - if rhs == 0.0 { - return Duration::ZERO; - } - - let seconds = bits / rhs; - - Duration::from_secs_f64(seconds) - } -} - -impl Mul for DataSize { - type Output = i64; - - fn mul(self, rhs: i64) -> Self::Output { - self.as_bytes_i64() * rhs - } -} - -impl Div for Bitrate { - type Output = Bitrate; - - fn div(self, rhs: f64) -> Self::Output { - if rhs == 0.0 { - return Self::ZERO; - } - - Self(self.0 / rhs) - } -} - -impl Mul for DataSize { - type Output = DataSize; - - fn mul(self, rhs: u64) -> Self::Output { - Self(self.0 * rhs as i64) - } -} - -impl AddAssign for DataSize { - fn add_assign(&mut self, rhs: DataSize) { - self.0 += rhs.0; - } -} - -impl Sub for DataSize { - type Output = DataSize; - - fn sub(self, rhs: DataSize) -> Self::Output { - Self(self.0 - rhs.0) - } -} - -impl SubAssign for DataSize { - fn sub_assign(&mut self, rhs: DataSize) { - self.0 -= rhs.0; - } -} - -impl Add for DataSize { - type Output = DataSize; - - fn add(self, rhs: DataSize) -> Self::Output { - Self(self.0 + rhs.0) - } -} - -impl Sum for DataSize { - fn sum>(iter: I) -> Self { - iter.fold(DataSize::ZERO, |acc, s| acc + s) - } -} - -impl fmt::Display for DataSize { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let size = self.0 as f64; - let log = (size as u64).ilog10(); - - match log { - 0..=2 => write!(f, "{size}B"), - 3..=5 => write!(f, "{:.3}kB", size / 10.0_f64.powf(3.0)), - 6..=8 => write!(f, "{:.3}MB", size / 10.0_f64.powf(6.0)), - 9..=11 => write!(f, "{:.3}GB", size / 10.0_f64.powf(9.0)), - 12.. => write!(f, "{:.3}TB", size / 10.0_f64.powf(12.0)), - } - } -} - -#[cfg(test)] -mod test { - use std::time::Duration; - - use super::{Bitrate, DataSize}; - - #[test] - fn test_bitrate_display() { - let rate = Bitrate::bps(1); - assert_eq!(rate.to_string(), "1bit/s"); - - let rate = Bitrate::bps(12); - assert_eq!(rate.to_string(), "12bit/s"); - - let rate = Bitrate::bps(123); - assert_eq!(rate.to_string(), "123bit/s"); - - let rate = Bitrate::bps(1234); - assert_eq!(rate.to_string(), "1.234kbit/s"); - - let rate = Bitrate::bps(12345); - assert_eq!(rate.to_string(), "12.345kbit/s"); - - let rate = Bitrate::bps(123456); - assert_eq!(rate.to_string(), "123.456kbit/s"); - - let rate = Bitrate::bps(1234567); - assert_eq!(rate.to_string(), "1.235Mbit/s"); - - let rate = Bitrate::bps(12345678); - assert_eq!(rate.to_string(), "12.346Mbit/s"); - - let rate = Bitrate::bps(123456789); - assert_eq!(rate.to_string(), "123.457Mbit/s"); - - let rate = Bitrate::bps(1234567898); - assert_eq!(rate.to_string(), "1.235Gbit/s"); - - let rate = Bitrate::bps(12345678987); - assert_eq!(rate.to_string(), "12.346Gbit/s"); - - let rate = Bitrate::bps(123456789876); - assert_eq!(rate.to_string(), "123.457Gbit/s"); - - let rate = Bitrate::bps(1234567898765); - assert_eq!(rate.to_string(), "1.235Tbit/s"); - } - - #[test] - fn test_data_size_div_duration() { - let size = DataSize::bytes(2_500_000); - let rate = size / Duration::from_secs(1); - - assert_eq!(rate.as_u64(), 20_000_000); - } - - #[test] - fn test_data_size_div_bitrate() { - let size = DataSize::bytes(12_500); - let rate = Bitrate::kbps(2_500); - let duration = size / rate; - - assert_eq!(duration.as_millis(), 40); - } - - #[test] - fn test_bitrate_div_f64() { - let rate = Bitrate::kbps(2_500); - let new_rate = rate / 2.0; - - assert_eq!(new_rate, Bitrate::kbps(1250)); - } - - #[test] - fn test_datasize_negative() { - let size = DataSize::bytes(-100); - assert_eq!(size.as_bytes_i64(), -100); - - // Test negative kilobytes - let size_kb = DataSize::kbytes(-5); - assert_eq!(size_kb.as_bytes_i64(), -5 * 1024); - - // Test that negative values work in comparisons - let positive = DataSize::bytes(50); - let negative = DataSize::bytes(-50); - assert!(negative < positive); - assert!(negative < DataSize::ZERO); - } - - #[test] - fn test_datasize_mul_negative() { - let size = DataSize::bytes(100); - - // Multiply by -1 to negate - let negated = size * -1i64; - assert_eq!(negated, -100); - - // Multiply by -2 - let doubled_neg = size * -2i64; - assert_eq!(doubled_neg, -200); - - // Negative size multiplied by -1 - let negative_size = DataSize::bytes(-50); - let positive_result = negative_size * -1i64; - assert_eq!(positive_result, 50); - } - - #[test] - fn test_datasize_arithmetic_with_negatives() { - let positive = DataSize::bytes(100); - let negative = DataSize::bytes(-50); - - // Add negative to positive - let result = positive + negative; - assert_eq!(result.as_bytes_i64(), 50); - - // Subtract negative from positive (should add) - let result2 = positive - negative; - assert_eq!(result2.as_bytes_i64(), 150); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/crypto/error.rs b/rs/moq-webrtc/src/vendor/str0m_proto/crypto/error.rs deleted file mode 100644 index 3d6deef7c8f..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/crypto/error.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::error::Error; -use std::fmt; -use std::io; - -use crate::vendor::str0m_proto::crypto::dtls::DtlsImplError; - -/// Errors that can arise in DTLS. -#[derive(Debug)] -pub enum CryptoError { - /// Error from DTLS implementation layer. - DtlsImpl(DtlsImplError), - - /// Other IO errors. - Io(io::Error), - - /// Other errors. - Other(String), -} - -impl fmt::Display for CryptoError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - CryptoError::Io(err) => write!(f, "{}", err), - CryptoError::DtlsImpl(err) => write!(f, "DTLS error: {}", err), - CryptoError::Other(err) => write!(f, "{}", err), - } - } -} - -impl Error for CryptoError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - CryptoError::Io(err) => Some(err), - CryptoError::DtlsImpl(err) => Some(err), - CryptoError::Other(_) => None, - } - } -} - -impl From for CryptoError { - fn from(err: io::Error) -> Self { - CryptoError::Io(err) - } -} - -impl From for CryptoError { - fn from(err: DtlsImplError) -> Self { - CryptoError::DtlsImpl(err) - } -} - -/// Errors that can arise in DTLS. -#[derive(Debug)] -pub enum DtlsError { - /// Error arising in the crypto - CryptoError(CryptoError), - - /// Other IO errors. - Io(io::Error), -} - -impl fmt::Display for DtlsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - DtlsError::CryptoError(err) => write!(f, "{}", err), - DtlsError::Io(err) => write!(f, "{}", err), - } - } -} - -impl Error for DtlsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - DtlsError::CryptoError(err) => Some(err), - DtlsError::Io(err) => Some(err), - } - } -} - -impl From for DtlsError { - fn from(err: io::Error) -> Self { - DtlsError::Io(err) - } -} - -impl From for DtlsError { - fn from(err: CryptoError) -> Self { - DtlsError::CryptoError(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/crypto/mod.rs b/rs/moq-webrtc/src/vendor/str0m_proto/crypto/mod.rs deleted file mode 100644 index cb73730b1c9..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/crypto/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -mod provider; -pub use provider::{AeadAes128Gcm, AeadAes128GcmCipher, AeadAes256Gcm, AeadAes256GcmCipher}; -pub use provider::{Aes128CmSha1_80, Aes128CmSha1_80Cipher, CryptoProvider, CryptoSafe}; -pub use provider::{Sha1HmacProvider, Sha1Provider, Sha256Provider}; -pub use provider::{SrtpProvider, SupportedAeadAes128Gcm}; -pub use provider::{SupportedAeadAes256Gcm, SupportedAes128CmSha1_80}; - -mod error; -pub use error::{CryptoError, DtlsError}; - -/// DTLS related types and traits. -pub mod dtls { - pub use super::provider::{DtlsInstance, DtlsProvider}; - - pub use crate::vendor::dimpl::CryptoError as DtlsCryptoError; - pub use crate::vendor::dimpl::CryptoOperation as DtlsCryptoOperation; - pub use crate::vendor::dimpl::DtlsCertificate as DtlsCert; - pub use crate::vendor::dimpl::KeyingMaterial; - pub use crate::vendor::dimpl::ProtocolVersion; - pub use crate::vendor::dimpl::SrtpProfile; - // Note: crate::vendor::dimpl::Error is renamed to DtlsImplError to avoid conflict with str0m's DtlsError - pub use crate::vendor::dimpl::{Error as DtlsImplError, Output as DtlsOutput}; -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/crypto/provider.rs b/rs/moq-webrtc/src/vendor/str0m_proto/crypto/provider.rs deleted file mode 100644 index dc7b2ed486b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/crypto/provider.rs +++ /dev/null @@ -1,439 +0,0 @@ -//! Cryptographic provider traits for pluggable crypto backends. -//! -//! This module defines the trait-based interface for cryptographic operations -//! in str0m, allowing users to provide custom crypto implementations for SRTP, -//! SHA-1 and SHA-256 hashing, SHA1 HMAC (for STUN), and DTLS. -//! -//! Implementors of a crypto provider only need to depend on this module. - -use std::fmt; -use std::fmt::Debug; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::sync::OnceLock; -use std::time::Instant; - -use subtle::ConstantTimeEq; - -use crate::vendor::str0m_proto::crypto::dtls::*; -use crate::vendor::str0m_proto::crypto::error::CryptoError; - -// ============================================================================ -// CryptoProvider -// ============================================================================ - -/// Cryptographic provider for SRTP, hashing, SHA1 HMAC, and DTLS operations. -/// -/// This struct holds references to all cryptographic components needed -/// for WebRTC operations. Users can provide custom implementations of each component -/// to replace the default OpenSSL-based provider. -/// -/// # Design -/// -/// The provider uses static trait object references (`&'static dyn Trait`) which -/// provides zero runtime overhead for trait dispatch. This design is inspired by -/// dimpl's CryptoProvider and ensures efficient crypto operations. -#[derive(Debug, Clone)] -pub struct CryptoProvider { - /// SRTP provider for creating cipher instances and key derivation. - pub srtp_provider: &'static dyn SrtpProvider, - /// SHA1 HMAC provider for STUN message integrity. - pub sha1_hmac_provider: &'static dyn Sha1HmacProvider, - /// SHA-1 hash provider for legacy certificate fingerprints. - pub sha1_provider: &'static dyn Sha1Provider, - /// SHA-256 hash provider. - pub sha256_provider: &'static dyn Sha256Provider, - /// DTLS provider for creating DTLS instances. - pub dtls_provider: &'static dyn DtlsProvider, -} - -/// CryptoProvider contains only static references to thread-safe traits, -/// so it's safe to use across panic boundaries. -impl UnwindSafe for CryptoProvider {} -impl RefUnwindSafe for CryptoProvider {} - -/// Static storage for the default crypto provider. -static DEFAULT: OnceLock = OnceLock::new(); - -impl CryptoProvider { - /// Install this provider as the process-wide default. - pub fn install_process_default(self) { - let _ = DEFAULT.set(self); - } - - /// Install a default crypto provider for the process. - /// - /// # Panics - /// - /// Panics if called more than once. - pub fn install_default(provider: CryptoProvider) { - DEFAULT - .set(provider) - .expect("CryptoProvider::install_default() called more than once"); - } - - /// Get the default crypto provider, if one has been installed. - pub fn get_default() -> Option<&'static CryptoProvider> { - DEFAULT.get() - } -} - -impl fmt::Display for CryptoProvider { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "CryptoProvider") - } -} - -// ============================================================================ -// Marker Trait -// ============================================================================ - -pub use crate::vendor::str0m_proto::{CryptoSafe, Sha1HmacProvider}; - -// ============================================================================ -// Main Provider Traits -// ============================================================================ - -/// SRTP provider for creating cipher instances and key derivation. -pub trait SrtpProvider: CryptoSafe { - /// Factory for AES-128-CM-SHA1-80 ciphers. - fn aes_128_cm_sha1_80(&self) -> &'static dyn SupportedAes128CmSha1_80; - - /// Factory for AEAD-AES-128-GCM ciphers. - fn aead_aes_128_gcm(&self) -> &'static dyn SupportedAeadAes128Gcm; - - /// Factory for AEAD-AES-256-GCM ciphers. - fn aead_aes_256_gcm(&self) -> &'static dyn SupportedAeadAes256Gcm; - - /// Perform AES-128-ECB round for key derivation. - fn srtp_aes_128_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]); - - /// Perform AES-256-ECB round for key derivation. - fn srtp_aes_256_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]); -} - -/// SHA-1 hash provider for legacy certificate fingerprints. -pub trait Sha1Provider: CryptoSafe { - /// Compute SHA-1 hash of the input data. - fn sha1(&self, data: &[u8]) -> [u8; 20]; -} - -/// SHA-256 hash provider. -pub trait Sha256Provider: CryptoSafe { - /// Compute SHA-256 hash of the input data. - fn sha256(&self, data: &[u8]) -> [u8; 32]; -} - -/// Factory for DTLS instances and certificates. -pub trait DtlsProvider: CryptoSafe { - /// Generate a new self-signed DTLS certificate. - /// - /// Returns `None` if this provider does not support certificate generation. - /// In that case, the user must supply a certificate via `RtcConfig::set_dtls_cert`. - fn generate_certificate(&self) -> Option; - - /// Create a new DTLS 1.2 instance with the given certificate. - /// - /// mtu: Backends that can size their record layer according to the provided MTU should do so; - /// backends that cannot ignore it. `None` means use the backend's default. - fn new_dtls(&self, cert: &DtlsCert, now: Instant, mtu: Option) - -> Result, CryptoError>; - - /// Whether the provider is used in a test context. - fn is_test(&self) -> bool { - cfg!(test) - } -} - -// ============================================================================ -// DTLS Instance Trait -// ============================================================================ - -/// DTLS instance operations (matches dimpl's Dtls API surface). -pub trait DtlsInstance: CryptoSafe { - /// Set whether this instance is active (client) or passive (server). - fn set_active(&mut self, active: bool); - - /// Handle an incoming DTLS packet. - fn handle_packet(&mut self, packet: &[u8]) -> Result<(), DtlsImplError>; - - /// Poll for output from the DTLS instance. - /// - /// The buffer must be large enough to hold the largest possible DTLS record. - fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a>; - - /// Handle a timeout event. - fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsImplError>; - - /// Send application data over DTLS. - /// - /// Returns the number of bytes accepted for buffering or transmission. - /// Accepts either the entire slice or none of it; retain unaccepted data - /// and retry after the handshake progresses. An empty slice returns zero - /// on success and does not indicate handshake readiness. - fn send_application_data(&mut self, data: &[u8]) -> Result; - - /// Return true if the instance is operating in the client role. - fn is_active(&self) -> bool; - - /// Return the negotiated DTLS protocol version. May return `None` before handshake completion. - fn protocol_version(&self) -> Option; - - /// Return true after close has started and while close output may still need polling. - fn is_closing(&self) -> bool { - false - } - - /// Return true once close output has drained and the instance is closed. - fn is_closed(&self) -> bool { - false - } - - /// Initiate graceful shutdown by sending a DTLS `close_notify` alert. - fn close(&mut self) -> Result<(), DtlsImplError>; -} - -// ============================================================================ -// SRTP Cipher Factory Traits -// ============================================================================ - -/// Factory for AES-128-CM-SHA1-80 cipher instances. -pub trait SupportedAes128CmSha1_80: CryptoSafe { - /// Create a cipher instance with the given key. - fn create_cipher(&self, key: [u8; 16], encrypt: bool) -> Box; -} - -/// Factory for AEAD-AES-128-GCM cipher instances. -pub trait SupportedAeadAes128Gcm: CryptoSafe { - /// Create a cipher instance with the given key. - fn create_cipher(&self, key: [u8; 16], encrypt: bool) -> Box; -} - -/// Factory for AEAD-AES-256-GCM cipher instances. -pub trait SupportedAeadAes256Gcm: CryptoSafe { - /// Create a cipher instance with the given key. - fn create_cipher(&self, key: [u8; 32], encrypt: bool) -> Box; -} - -// ============================================================================ -// SRTP Cipher Instance Traits -// ============================================================================ - -/// AES-128-CM-SHA1-80 cipher instance for SRTP encryption/decryption. -pub trait Aes128CmSha1_80Cipher: CryptoSafe { - /// Encrypt input with the given IV. - fn encrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError>; - - /// Decrypt input with the given IV. - fn decrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError>; -} - -/// AEAD-AES-128-GCM cipher instance for SRTP encryption/decryption. -pub trait AeadAes128GcmCipher: CryptoSafe { - /// Encrypt input with the given IV and AAD. - fn encrypt(&mut self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError>; - - /// Decrypt input with the given IV and AADs. - fn decrypt(&mut self, iv: &[u8; 12], aads: &[&[u8]], input: &[u8], output: &mut [u8]) - -> Result; -} - -/// AEAD-AES-256-GCM cipher instance for SRTP encryption/decryption. -pub trait AeadAes256GcmCipher: CryptoSafe { - /// Encrypt input with the given IV and AAD. - fn encrypt(&mut self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError>; - - /// Decrypt input with the given IV and AADs. - fn decrypt(&mut self, iv: &[u8; 12], aads: &[&[u8]], input: &[u8], output: &mut [u8]) - -> Result; -} - -// ============================================================================ -// SRTP Profile Definitions -// ============================================================================ - -/// AES-128-CM-SHA1-80 SRTP profile. -/// -/// This struct provides constants, types, and protocol functions for the -/// AES-128-CM-SHA1-80 SRTP protection profile (RFC 5764). -#[derive(Debug, Clone, Copy)] -pub struct Aes128CmSha1_80; - -impl Aes128CmSha1_80 { - /// Key length in bytes. - pub const KEY_LEN: usize = 16; - /// Salt length in bytes. - pub const SALT_LEN: usize = 14; - /// HMAC key length in bytes. - pub const HMAC_KEY_LEN: usize = 20; - /// HMAC tag length in bytes. - pub const HMAC_TAG_LEN: usize = 10; - - /// Compute and append RTP HMAC tag. - pub fn rtp_hmac( - sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20], - key: &[u8], - buf: &mut [u8], - srtp_index: u64, - hmac_start: usize, - ) { - let roc = (srtp_index >> 16) as u32; - let tag = sha1_hmac(key, &[&buf[..hmac_start], &roc.to_be_bytes()]); - buf[hmac_start..(hmac_start + Self::HMAC_TAG_LEN)].copy_from_slice(&tag[0..Self::HMAC_TAG_LEN]); - } - - /// Verify RTP HMAC tag. - pub fn rtp_verify( - sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20], - key: &[u8], - buf: &[u8], - srtp_index: u64, - cmp: &[u8], - ) -> bool { - let roc = (srtp_index >> 16) as u32; - let tag = sha1_hmac(key, &[buf, &roc.to_be_bytes()]); - tag[0..Self::HMAC_TAG_LEN].ct_eq(cmp).into() - } - - /// Compute RTP IV. - pub fn rtp_iv(salt: [u8; 14], ssrc: u32, srtp_index: u64) -> [u8; 16] { - let mut iv = [0; 16]; - let ssrc_be = ssrc.to_be_bytes(); - let srtp_be = srtp_index.to_be_bytes(); - iv[4..8].copy_from_slice(&ssrc_be); - for i in 0..8 { - iv[i + 6] ^= srtp_be[i]; - } - for i in 0..14 { - iv[i] ^= salt[i]; - } - iv - } - - /// Compute and append RTCP HMAC tag. - pub fn rtcp_hmac(sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20], key: &[u8], buf: &mut [u8], hmac_index: usize) { - let tag = sha1_hmac(key, &[&buf[0..hmac_index]]); - buf[hmac_index..(hmac_index + Self::HMAC_TAG_LEN)].copy_from_slice(&tag[0..Self::HMAC_TAG_LEN]); - } - - /// Verify RTCP HMAC tag. - pub fn rtcp_verify(sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20], key: &[u8], buf: &[u8], cmp: &[u8]) -> bool { - let tag = sha1_hmac(key, &[buf]); - tag[0..Self::HMAC_TAG_LEN].ct_eq(cmp).into() - } -} - -/// AEAD-AES-128-GCM SRTP profile. -/// -/// This struct provides constants, types, and protocol functions for the -/// AEAD-AES-128-GCM SRTP protection profile (RFC 7714). -#[derive(Debug, Clone, Copy)] -pub struct AeadAes128Gcm; - -impl AeadAes128Gcm { - /// Key length in bytes. - pub const KEY_LEN: usize = 16; - /// Salt length in bytes. - pub const SALT_LEN: usize = 12; - /// RTCP AAD length in bytes. - pub const RTCP_AAD_LEN: usize = 12; - /// Authentication tag length in bytes. - pub const TAG_LEN: usize = 16; - /// IV length in bytes. - pub const IV_LEN: usize = 12; - - /// Compute RTP IV. - pub fn rtp_iv(salt: [u8; 12], ssrc: u32, roc: u32, seq: u16) -> [u8; 12] { - // See: https://www.rfc-editor.org/rfc/rfc7714#section-8.1 - let mut iv = [0; 12]; - - let ssrc_be = ssrc.to_be_bytes(); - let roc_be = roc.to_be_bytes(); - let seq_be = seq.to_be_bytes(); - - iv[2..6].copy_from_slice(&ssrc_be); - iv[6..10].copy_from_slice(&roc_be); - iv[10..12].copy_from_slice(&seq_be); - - for i in 0..12 { - iv[i] ^= salt[i]; - } - - iv - } - - /// Compute RTCP IV. - pub fn rtcp_iv(salt: [u8; 12], ssrc: u32, srtp_index: u32) -> [u8; 12] { - // See: https://www.rfc-editor.org/rfc/rfc7714#section-9.1 - let mut iv = [0; 12]; - - let ssrc_be = ssrc.to_be_bytes(); - let srtp_be = srtp_index.to_be_bytes(); - - iv[2..6].copy_from_slice(&ssrc_be); - iv[8..12].copy_from_slice(&srtp_be); - - for i in 0..12 { - iv[i] ^= salt[i]; - } - - iv - } -} - -/// AEAD-AES-256-GCM SRTP profile. -/// -/// This struct provides constants, types, and protocol functions for the -/// AEAD-AES-256-GCM SRTP protection profile (RFC 7714). -#[derive(Debug, Clone, Copy)] -pub struct AeadAes256Gcm; - -impl AeadAes256Gcm { - /// Key length in bytes. - pub const KEY_LEN: usize = 32; - /// Salt length in bytes. - pub const SALT_LEN: usize = 12; - /// RTCP AAD length in bytes. - pub const RTCP_AAD_LEN: usize = 12; - /// Authentication tag length in bytes. - pub const TAG_LEN: usize = 16; - /// IV length in bytes. - pub const IV_LEN: usize = 12; - - /// Compute RTP IV. - pub fn rtp_iv(salt: [u8; 12], ssrc: u32, roc: u32, seq: u16) -> [u8; 12] { - // See: https://www.rfc-editor.org/rfc/rfc7714#section-8.1 - let mut iv = [0; 12]; - - let ssrc_be = ssrc.to_be_bytes(); - let roc_be = roc.to_be_bytes(); - let seq_be = seq.to_be_bytes(); - - iv[2..6].copy_from_slice(&ssrc_be); - iv[6..10].copy_from_slice(&roc_be); - iv[10..12].copy_from_slice(&seq_be); - - for i in 0..12 { - iv[i] ^= salt[i]; - } - - iv - } - - /// Compute RTCP IV. - pub fn rtcp_iv(salt: [u8; 12], ssrc: u32, srtp_index: u32) -> [u8; 12] { - // See: https://www.rfc-editor.org/rfc/rfc7714#section-9.1 - let mut iv = [0; 12]; - - let ssrc_be = ssrc.to_be_bytes(); - let srtp_be = srtp_index.to_be_bytes(); - - iv[2..6].copy_from_slice(&ssrc_be); - iv[8..12].copy_from_slice(&srtp_be); - - for i in 0..12 { - iv[i] ^= salt[i]; - } - - iv - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/id.rs b/rs/moq-webrtc/src/vendor/str0m_proto/id.rs deleted file mode 100644 index ee56dbab5b2..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/id.rs +++ /dev/null @@ -1,38 +0,0 @@ -use std::fmt; -use std::str::from_utf8; - -use crate::vendor::str0m_proto::NonCryptographicRng; - -// deliberate subset of ice-char, etc that are "safe" -const CHARS: &[u8] = b"abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789"; - -pub struct Id([u8; L]); - -impl Id { - pub fn random() -> Id { - let mut x = [0; L]; - for val in x.iter_mut().take(L) { - let y: f32 = NonCryptographicRng::f32(); - let idx = (CHARS.len() as f32 * y).floor() as usize; - *val = CHARS[idx]; - } - Id(x) - } - - pub fn into_array(self) -> [u8; L] { - self.0 - } -} - -impl Default for Id { - fn default() -> Self { - Id::random() - } -} - -impl fmt::Display for Id { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = from_utf8(&self.0).expect("ascii characters"); - write!(f, "{s}") - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/lib.rs b/rs/moq-webrtc/src/vendor/str0m_proto/lib.rs deleted file mode 100644 index 91b459bd0e0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/lib.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Shared protocol types and traits for str0m. - -// Avoid rewriting existing code: nested conditions are often more readable than long if-chains. -#![allow(clippy::collapsible_if)] - -/// Default target MTU when no MTU is explicitly configured via [`RtcConfig::set_mtu`]. -pub const DATAGRAM_MTU_TARGET: usize = 1150; - -/// Lower bound for the target MTU. -pub const DATAGRAM_MTU_TARGET_MIN: usize = 576; - -/// Upper bound for the target MTU. -pub const DATAGRAM_MTU_TARGET_MAX: usize = 1500; - -/// Default warning threshold for MTU when no warning threshold is configured via [`RtcConfig::set_mtu`]. -pub const DATAGRAM_MTU_WARN: usize = 1280; - -mod bandwidth; -pub use bandwidth::{Bitrate, DataSize}; - -mod rng; -pub use rng::NonCryptographicRng; - -mod pii; -pub use pii::Pii; - -mod id; -pub use id::Id; - -mod net; -pub use net::{DatagramSend, ParseTcpTypeError, Protocol, TcpType, Transmit}; - -mod sha1; -pub use sha1::{CryptoSafe, Sha1HmacProvider}; - -pub mod crypto; diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/net.rs b/rs/moq-webrtc/src/vendor/str0m_proto/net.rs deleted file mode 100644 index eacef7b3fa0..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/net.rs +++ /dev/null @@ -1,171 +0,0 @@ -use std::fmt; -use std::net::SocketAddr; -use std::ops::Deref; -use std::str::FromStr; - -use serde::{Deserialize, Serialize}; - -/// Type of protocol used in [`Transmit`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Protocol { - /// UDP - Udp, - /// TCP (See RFC 4571 for framing) - Tcp, - /// TCP with fixed SSL Hello Exchange - /// See AsyncSSLServerSocket implementation for exchange details: - /// - SslTcp, - /// TLS (only used via relay) - Tls, -} - -/// TCP connection role as defined by the `tcptype` SDP attribute. -/// -/// This enum corresponds to the TCP connection setup modes defined in -/// [RFC 6544 §4.5](https://datatracker.ietf.org/doc/html/rfc6544#section-4.5), -/// which specifies how endpoints establish TCP connections when TCP is used -/// as a transport for media streams. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum TcpType { - /// The endpoint actively initiates the TCP connection. - /// - /// In this mode, the endpoint performs an active open (i.e., sends a SYN) - /// to the remote peer. - Active, - - /// The endpoint passively waits for an incoming TCP connection. - /// - /// In this mode, the endpoint performs a passive open (i.e., listens) - /// and accepts a connection initiated by the remote peer. - Passive, - - /// Simultaneous open. - /// - /// Both endpoints attempt to actively open a TCP connection to each other - /// at the same time. This relies on TCP simultaneous open behavior. - So, -} - -impl fmt::Display for TcpType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let str = match self { - Self::Active => "active", - Self::Passive => "passive", - Self::So => "so", - }; - f.write_str(str) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ParseTcpTypeError; - -impl fmt::Display for ParseTcpTypeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("invalid TCP type (expected: active, passive, or so)") - } -} - -impl std::error::Error for ParseTcpTypeError {} - -impl FromStr for TcpType { - type Err = ParseTcpTypeError; - - fn from_str(s: &str) -> Result { - match s { - _ if s.eq_ignore_ascii_case("active") => Ok(Self::Active), - _ if s.eq_ignore_ascii_case("passive") => Ok(Self::Passive), - _ if s.eq_ignore_ascii_case("so") => Ok(Self::So), - _ => Err(ParseTcpTypeError), - } - } -} - -impl TryFrom<&str> for Protocol { - type Error = (); - - fn try_from(proto: &str) -> Result { - let proto = proto.to_lowercase(); - match proto.as_str() { - "udp" => Ok(Protocol::Udp), - "tcp" => Ok(Protocol::Tcp), - "ssltcp" => Ok(Protocol::SslTcp), - "tls" => Ok(Protocol::Tls), - _ => Err(()), - } - } -} - -impl From for &str { - fn from(proto: Protocol) -> Self { - match proto { - Protocol::Udp => "udp", - Protocol::Tcp => "tcp", - Protocol::SslTcp => "ssltcp", - Protocol::Tls => "tls", - } - } -} - -impl fmt::Display for Protocol { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let x: &str = (*self).into(); - write!(f, "{}", x) - } -} - -/// An instruction to send an outgoing packet. -#[derive(Serialize, Deserialize)] -pub struct Transmit { - /// Protocol the transmission should use. - pub proto: Protocol, - - /// The source IP this packet should be sent from. - /// - /// For ICE it's important to send outgoing packets from the correct IP address. - /// The IP could come from a local socket or relayed over a TURN server. Features like - /// hole-punching will only work if the packets are routed through the correct interfaces. - pub source: SocketAddr, - - /// The destination address this datagram should be sent to. - pub destination: SocketAddr, - - /// Contents of the datagram. - pub contents: DatagramSend, -} - -impl fmt::Debug for Transmit { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Transmit") - .field("proto", &self.proto) - .field("source", &self.source) - .field("destination", &self.destination) - .field("len", &self.contents.len()) - .finish() - } -} - -/// A wrapper for some payload that is to be sent. -#[derive(Debug, Serialize, Deserialize)] -pub struct DatagramSend(Vec); - -impl From> for DatagramSend { - fn from(value: Vec) -> Self { - DatagramSend(value) - } -} - -impl From for Vec { - fn from(value: DatagramSend) -> Self { - value.0 - } -} - -impl Deref for DatagramSend { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/pii.rs b/rs/moq-webrtc/src/vendor/str0m_proto/pii.rs deleted file mode 100644 index 7dab7b654a9..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/pii.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! PII-safe wrapper for sensitive values. -//! -//! The `Pii` type is a generic wrapper for any value that may contain -//! personally identifiable information (PII) or other sensitive data. -//! When the `pii` feature is enabled, any value wrapped in `Pii` will be -//! redacted (displayed as `REDACTED`) when formatted with `Display`. -//! Otherwise, the inner value is shown as normal. This helps prevent -//! accidental leakage of sensitive information in logs or user-facing -//! output. -//! -//! Logging or displaying sensitive data such as IP addresses, user IDs, or -//! authentication tokens can lead to privacy violations or security -//! incidents. -//! -//! This wrapper should be used for debug, info, warn, and error logs. -//! It is not intended for trace-level logs, as trace logs are typically -//! disabled in production environments. - -use core::fmt; -use core::ops::Deref; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Pii(pub T); - -impl fmt::Display for Pii { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -impl fmt::Debug for Pii { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self.0) - } -} - -impl Deref for Pii { - type Target = T; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - #[test] - fn socket_addr_display() { - let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); - let pii_addr = Pii(addr); - - assert_eq!(pii_addr.to_string(), "127.0.0.1:8080"); - } - - #[test] - fn string_display() { - let sensitive = String::from("sensitive data"); - let pii_string = Pii(sensitive); - - assert_eq!(pii_string.to_string(), "sensitive data"); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/rng.rs b/rs/moq-webrtc/src/vendor/str0m_proto/rng.rs deleted file mode 100644 index c085ee7b70c..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/rng.rs +++ /dev/null @@ -1,28 +0,0 @@ -pub struct NonCryptographicRng; - -impl NonCryptographicRng { - #[inline(always)] - pub fn u8() -> u8 { - fastrand::u8(..) - } - - #[inline(always)] - pub fn u16() -> u16 { - fastrand::u16(..) - } - - #[inline(always)] - pub fn u32() -> u32 { - fastrand::u32(..) - } - - #[inline(always)] - pub fn u64() -> u64 { - fastrand::u64(..) - } - - #[inline(always)] - pub fn f32() -> f32 { - fastrand::f32() - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_proto/sha1.rs b/rs/moq-webrtc/src/vendor/str0m_proto/sha1.rs deleted file mode 100644 index 2d67f0b888b..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_proto/sha1.rs +++ /dev/null @@ -1,20 +0,0 @@ -use std::fmt::Debug; - -/// Marker trait for types that are safe to use in crypto provider components. -/// -/// This trait combines the common bounds required for crypto provider trait objects: -/// - [`Send`] + [`Sync`]: Thread-safe -/// - [`Debug`]: Support debugging -/// -/// Note: We don't require `UnwindSafe` because some error types (like `crate::vendor::dimpl::Error`) -/// may not implement it, but they're still safe to use in our context. -pub trait CryptoSafe: Send + Sync + Debug {} - -/// Blanket implementation: any type satisfying the bounds implements [`CryptoSafe`]. -impl CryptoSafe for T {} - -/// SHA1 HMAC provider for STUN message integrity. -pub trait Sha1HmacProvider: CryptoSafe { - /// Compute HMAC-SHA1(key, payloads) and return the result. - fn sha1_hmac(&self, key: &[u8], payloads: &[&[u8]]) -> [u8; 20]; -} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/dtls.rs b/rs/moq-webrtc/src/vendor/str0m_rind/dtls.rs deleted file mode 100644 index 32c1fec62d8..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_rind/dtls.rs +++ /dev/null @@ -1,106 +0,0 @@ -use std::sync::Arc; -use std::time::Instant; - -use crate::vendor::dimpl; -use crate::vendor::str0m_proto::crypto::CryptoError; -use crate::vendor::str0m_proto::crypto::dtls::{ - DtlsCert, DtlsImplError, DtlsInstance, DtlsOutput, DtlsProvider, ProtocolVersion, -}; - -pub(super) static DTLS: RindDtls = RindDtls; - -#[derive(Debug)] -pub(super) struct RindDtls; - -impl DtlsProvider for RindDtls { - fn generate_certificate(&self) -> Option { - // Only a failing system random source fails it, on which str0m panics. - dimpl::certificate::generate_self_signed_certificate().ok() - } - - fn new_dtls( - &self, - cert: &DtlsCert, - now: Instant, - mtu: Option, - ) -> Result, CryptoError> { - let provider = dimpl::crypto::rind::default_provider().map_err(|e| CryptoError::Other(e.to_string()))?; - - // dimpl panics on an empty certificate or a key it cannot load, and - // `RtcConfig::set_dtls_cert` takes both from the caller. - if cert.certificate.is_empty() { - return Err(CryptoError::Other("empty DTLS certificate".into())); - } - provider - .key_provider - .load_private_key(&cert.private_key) - .map_err(|e| CryptoError::Other(format!("DTLS private key: {e}")))?; - - // ICE checks return routability before DTLS starts, so a server cookie - // adds a round trip without protecting anything. - let mut builder = dimpl::Config::builder() - .with_crypto_provider(provider) - .use_server_cookie(false); - if let Some(mtu) = mtu { - builder = builder.mtu(mtu); - } - if self.is_test() { - // Deterministic handshakes for the stack's own tests. - builder = builder.dangerously_set_rng_seed(42); - } - let config = Arc::new(builder.build().map_err(|e| CryptoError::Other(e.to_string()))?); - - Ok(Box::new(Dtls(dimpl::Dtls::new_12(config, cert.clone(), now)))) - } -} - -/// A dimpl connection, forwarded as is. -struct Dtls(dimpl::Dtls); - -impl std::fmt::Debug for Dtls { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Dtls").finish_non_exhaustive() - } -} - -impl DtlsInstance for Dtls { - fn set_active(&mut self, active: bool) { - self.0.set_active(active); - } - - fn handle_packet(&mut self, packet: &[u8]) -> Result<(), DtlsImplError> { - self.0.handle_packet(packet) - } - - fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a> { - self.0.poll_output(buf) - } - - fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsImplError> { - self.0.handle_timeout(now) - } - - fn send_application_data(&mut self, data: &[u8]) -> Result { - self.0.send_application_data(data) - } - - fn is_active(&self) -> bool { - self.0.is_active() - } - - fn protocol_version(&self) -> Option { - self.0.protocol_version() - } - - fn is_closing(&self) -> bool { - self.0.is_closing() - } - - fn is_closed(&self) -> bool { - self.0.is_closed() - } - - fn close(&mut self) -> Result<(), DtlsImplError> { - self.0.close() - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/hash.rs b/rs/moq-webrtc/src/vendor/str0m_rind/hash.rs deleted file mode 100644 index 554cb3353ad..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_rind/hash.rs +++ /dev/null @@ -1,39 +0,0 @@ -use rind::{digest, hmac}; - -use crate::vendor::str0m_proto::crypto::{Sha1HmacProvider, Sha1Provider, Sha256Provider}; - -pub(super) static SHA1_HMAC: RindSha1Hmac = RindSha1Hmac; -pub(super) static SHA1: RindSha1 = RindSha1; -pub(super) static SHA256: RindSha256 = RindSha256; - -#[derive(Debug)] -pub(super) struct RindSha1Hmac; - -impl Sha1HmacProvider for RindSha1Hmac { - fn sha1_hmac(&self, key: &[u8], payloads: &[&[u8]]) -> [u8; 20] { - let key = hmac::Key::new(&hmac::legacy::HMAC_SHA1, key); - let mut ctx = hmac::Context::with_key(&key); - for payload in payloads { - ctx.update(payload); - } - ctx.sign().as_ref().try_into().unwrap() - } -} - -#[derive(Debug)] -pub(super) struct RindSha1; - -impl Sha1Provider for RindSha1 { - fn sha1(&self, data: &[u8]) -> [u8; 20] { - digest::digest(&digest::legacy::SHA1, data).as_ref().try_into().unwrap() - } -} - -#[derive(Debug)] -pub(super) struct RindSha256; - -impl Sha256Provider for RindSha256 { - fn sha256(&self, data: &[u8]) -> [u8; 32] { - digest::digest(&digest::SHA256, data).as_ref().try_into().unwrap() - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/lib.rs b/rs/moq-webrtc/src/vendor/str0m_rind/lib.rs deleted file mode 100644 index cb1fcde689d..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_rind/lib.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! rind's cryptographic provider for str0m. -//! -//! Ported from kixel-ai/rind's `rind-str0m`, trimmed to DTLS 1.2, with its DTLS -//! on dimpl's rind provider. - -mod dtls; -mod hash; -mod srtp; - -use crate::vendor::str0m_proto::crypto::CryptoProvider; - -/// Returns a str0m [`CryptoProvider`] backed by rind, or the CPU feature rind -/// requires that this CPU lacks. -/// -/// It protects SRTP with AES-128-CM-HMAC-SHA1-80, AEAD-AES-128-GCM, and -/// AEAD-AES-256-GCM, signs STUN with HMAC-SHA1, hashes certificate -/// fingerprints with SHA-1 and SHA-256, and runs DTLS 1.2 through dimpl with a -/// self-signed ECDSA P-256 certificate. -pub fn default_provider() -> Result { - rind::cpu::check()?; - Ok(CryptoProvider { - srtp_provider: &srtp::SRTP, - sha1_hmac_provider: &hash::SHA1_HMAC, - sha1_provider: &hash::SHA1, - sha256_provider: &hash::SHA256, - dtls_provider: &dtls::DTLS, - }) -} diff --git a/rs/moq-webrtc/src/vendor/str0m_rind/srtp.rs b/rs/moq-webrtc/src/vendor/str0m_rind/srtp.rs deleted file mode 100644 index f381537ad08..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m_rind/srtp.rs +++ /dev/null @@ -1,199 +0,0 @@ -use std::fmt; - -use rind::aead::{self, Nonce, Tag}; -use rind::cipher::{self, Aes, AesCtr}; - -use crate::vendor::str0m_proto::crypto::{ - AeadAes128GcmCipher, AeadAes256GcmCipher, Aes128CmSha1_80Cipher, CryptoError, SrtpProvider, SupportedAeadAes128Gcm, - SupportedAeadAes256Gcm, SupportedAes128CmSha1_80, -}; - -const TAG_LEN: usize = 16; - -pub(super) static SRTP: RindSrtp = RindSrtp; - -#[derive(Debug)] -pub(super) struct RindSrtp; - -impl SrtpProvider for RindSrtp { - fn aes_128_cm_sha1_80(&self) -> &'static dyn SupportedAes128CmSha1_80 { - &RindSrtp - } - - fn aead_aes_128_gcm(&self) -> &'static dyn SupportedAeadAes128Gcm { - &RindSrtp - } - - fn aead_aes_256_gcm(&self) -> &'static dyn SupportedAeadAes256Gcm { - &RindSrtp - } - - /// Encrypts one SRTP key derivation block. - /// - /// Panics unless `key` is 16 bytes, `input` 16, and `output` at least 16: - /// the trait returns `()`, so there is no error to report. - fn srtp_aes_128_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]) { - ecb_round(&cipher::AES_128, key, input, output); - } - - /// Encrypts one SRTP key derivation block. - /// - /// Panics unless `key` is 32 bytes, `input` 16, and `output` at least 16: - /// the trait returns `()`, so there is no error to report. - fn srtp_aes_256_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]) { - ecb_round(&cipher::AES_256, key, input, output); - } -} - -// str0m sizes these from fixed arrays, never from a packet, so a mismatch is a -// str0m bug worth a panic. -fn ecb_round(algorithm: &'static cipher::Algorithm, key: &[u8], input: &[u8], output: &mut [u8]) { - let aes = Aes::new(algorithm, key).expect("SRTP master key length"); - let mut block: [u8; 16] = input.try_into().expect("SRTP key derivation block"); - aes.encrypt_block(&mut block); - output[..16].copy_from_slice(&block); -} - -impl SupportedAes128CmSha1_80 for RindSrtp { - fn create_cipher(&self, key: [u8; 16], _encrypt: bool) -> Box { - Box::new(Cm(AesCtr::new(&cipher::AES_128, &key, 16).unwrap())) - } -} - -impl SupportedAeadAes128Gcm for RindSrtp { - fn create_cipher(&self, key: [u8; 16], _encrypt: bool) -> Box { - Box::new(Gcm::new(&aead::AES_128_GCM, &key)) - } -} - -impl SupportedAeadAes256Gcm for RindSrtp { - fn create_cipher(&self, key: [u8; 32], _encrypt: bool) -> Box { - Box::new(Gcm::new(&aead::AES_256_GCM, &key)) - } -} - -/// AES counter mode, keyed for one SRTP or SRTCP direction. -struct Cm(AesCtr); - -impl fmt::Debug for Cm { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Cm").finish_non_exhaustive() - } -} - -impl Cm { - fn apply(&self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - let output = output - .get_mut(..input.len()) - .ok_or_else(|| CryptoError::Other("AES-CM output too short".into()))?; - output.copy_from_slice(input); - - // SRTP AES-CM counts over the IV's low 16 bits, which str0m leaves - // zero, so rind refuses a packet past 2^16 blocks rather than wrap. - self.0 - .apply_keystream(iv, output) - .map_err(|e| CryptoError::Other(format!("AES-CM failed: {e:?}"))) - } -} - -impl Aes128CmSha1_80Cipher for Cm { - fn encrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - self.apply(iv, input, output) - } - - fn decrypt(&mut self, iv: &[u8; 16], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - self.apply(iv, input, output) - } -} - -/// AES-GCM, keyed for one SRTP or SRTCP direction. -struct Gcm(aead::Key); - -impl fmt::Debug for Gcm { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Gcm").finish_non_exhaustive() - } -} - -impl Gcm { - /// str0m passes the profile's key length. - fn new(algorithm: &'static aead::Algorithm, key: &[u8]) -> Self { - Self(aead::Key::new(algorithm, key).unwrap()) - } - - /// Writes the ciphertext then the tag into `output`. - fn seal(&self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - let output = output - .get_mut(..input.len() + TAG_LEN) - .ok_or_else(|| CryptoError::Other("AES-GCM output too short".into()))?; - let (ciphertext, tag_out) = output.split_at_mut(input.len()); - ciphertext.copy_from_slice(input); - let tag = self - .0 - .seal_in_place_separate_tag(Nonce::assume_unique_for_key(*iv), aad, ciphertext) - .map_err(|e| CryptoError::Other(format!("AES-GCM failed: {e:?}")))?; - tag_out.copy_from_slice(tag.as_ref()); - Ok(()) - } - - /// Opens `input`, the ciphertext then the tag, and returns the plaintext length. - fn open(&self, iv: &[u8; 12], aads: &[&[u8]], input: &[u8], output: &mut [u8]) -> Result { - let ciphertext_len = input - .len() - .checked_sub(TAG_LEN) - .ok_or_else(|| CryptoError::Other("AES-GCM input shorter than its tag".into()))?; - let (ciphertext, tag) = input.split_at(ciphertext_len); - let tag = Tag::try_from(tag).expect("split at the tag length"); - let plaintext = output - .get_mut(..ciphertext.len()) - .ok_or_else(|| CryptoError::Other("AES-GCM output too short".into()))?; - plaintext.copy_from_slice(ciphertext); - - // str0m splits the AAD only for unencrypted SRTCP. - let joined; - let aad = match aads { - [aad] => aad, - _ => { - joined = aads.concat(); - joined.as_slice() - } - }; - - self.0 - .open_in_place_separate_tag(Nonce::assume_unique_for_key(*iv), aad, tag, plaintext) - .map_err(|e| CryptoError::Other(format!("AES-GCM failed: {e:?}")))?; - Ok(ciphertext.len()) - } -} - -impl AeadAes128GcmCipher for Gcm { - fn encrypt(&mut self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - self.seal(iv, aad, input, output) - } - - fn decrypt( - &mut self, - iv: &[u8; 12], - aads: &[&[u8]], - input: &[u8], - output: &mut [u8], - ) -> Result { - self.open(iv, aads, input, output) - } -} - -impl AeadAes256GcmCipher for Gcm { - fn encrypt(&mut self, iv: &[u8; 12], aad: &[u8], input: &[u8], output: &mut [u8]) -> Result<(), CryptoError> { - self.seal(iv, aad, input, output) - } - - fn decrypt( - &mut self, - iv: &[u8; 12], - aads: &[&[u8]], - input: &[u8], - output: &mut [u8], - ) -> Result { - self.open(iv, aads, input, output) - } -} diff --git a/rs/workspace-hack/Cargo.toml b/rs/workspace-hack/Cargo.toml index 18c148bd673..276c25bbc72 100644 --- a/rs/workspace-hack/Cargo.toml +++ b/rs/workspace-hack/Cargo.toml @@ -35,7 +35,7 @@ clap_builder = { version = "4", default-features = false, features = ["cargo", " const-oid = { version = "0.10", default-features = false, features = ["db"] } crossbeam-utils = { version = "0.8" } crypto-common = { version = "0.1", default-features = false, features = ["std"] } -der = { version = "0.8", default-features = false, features = ["derive", "flagset", "oid", "std", "zeroize"] } +der = { version = "0.8", default-features = false, features = ["derive", "flagset", "oid", "pem", "std"] } derive_more = { version = "2", features = ["debug", "display", "error", "from"] } digest-93f6ce9d446188ac = { package = "digest", version = "0.10", features = ["mac", "std"] } digest-a6292c17cd707f01 = { package = "digest", version = "0.11", features = ["alloc", "mac", "oid"] } @@ -68,6 +68,7 @@ num-traits = { version = "0.2", features = ["i128"] } object_store = { version = "0.14", default-features = false, features = ["aws-base", "azure-base", "fs", "gcp-base", "reqwest"] } once_cell = { version = "1" } percent-encoding = { version = "2" } +pkcs8 = { version = "0.11", default-features = false, features = ["pem"] } portable-atomic = { version = "1" } proptest = { version = "1", default-features = false, features = ["handle-panics"] } rcgen = { version = "0.14", default-features = false, features = ["pem"] } @@ -85,6 +86,7 @@ siphasher = { version = "1" } slab = { version = "0.4" } smallvec = { version = "1", default-features = false, features = ["const_new", "union", "write"] } socket2 = { version = "0.6", default-features = false, features = ["all"] } +spki = { version = "0.8", default-features = false, features = ["pem"] } subtle = { version = "2" } time = { version = "0.3", features = ["formatting", "local-offset", "macros", "parsing"] } tokio = { version = "1", features = ["full", "test-util"] } @@ -118,7 +120,7 @@ clap_builder = { version = "4", default-features = false, features = ["cargo", " const-oid = { version = "0.10", default-features = false, features = ["db"] } crossbeam-utils = { version = "0.8" } crypto-common = { version = "0.1", default-features = false, features = ["std"] } -der = { version = "0.8", default-features = false, features = ["derive", "flagset", "oid", "std", "zeroize"] } +der = { version = "0.8", default-features = false, features = ["derive", "flagset", "oid", "pem", "std"] } derive_more = { version = "2", features = ["debug", "display", "error", "from"] } derive_more-impl = { version = "2", features = ["debug", "display", "error", "from"] } digest-93f6ce9d446188ac = { package = "digest", version = "0.10", features = ["mac", "std"] } @@ -153,6 +155,7 @@ num-traits = { version = "0.2", features = ["i128"] } object_store = { version = "0.14", default-features = false, features = ["aws-base", "azure-base", "fs", "gcp-base", "reqwest"] } once_cell = { version = "1" } percent-encoding = { version = "2" } +pkcs8 = { version = "0.11", default-features = false, features = ["pem"] } portable-atomic = { version = "1" } proc-macro2 = { version = "1" } proptest = { version = "1", default-features = false, features = ["handle-panics"] } @@ -172,6 +175,7 @@ siphasher = { version = "1" } slab = { version = "0.4" } smallvec = { version = "1", default-features = false, features = ["const_new", "union", "write"] } socket2 = { version = "0.6", default-features = false, features = ["all"] } +spki = { version = "0.8", default-features = false, features = ["pem"] } subtle = { version = "2" } syn-7b89eefb6aaa9bf3 = { package = "syn", version = "3", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] } syn-f595c2ba2a3f28df = { package = "syn", version = "2", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }