mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
fix(webrtc): associate local RTP ICE and DTLS transports
This commit is contained in:
@@ -2,12 +2,14 @@
|
||||
|
||||
use moli_webapi::event_target::SIMPLE_EVENT_TARGET_LISTENERS_SLOT;
|
||||
use moli_webapi::rtc::peer_connection::{
|
||||
RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT, rtp_capabilities,
|
||||
RTC_PEER_CONNECTION_HAS_DATA_CHANNEL_SLOT, RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT, rtp_capabilities,
|
||||
complete_create_offer, complete_set_local_description,
|
||||
build_signaling_only_offer,
|
||||
};
|
||||
|
||||
mod operations;
|
||||
mod stats;
|
||||
mod transports;
|
||||
mod dtmf;
|
||||
mod data_channel;
|
||||
mod signaling;
|
||||
@@ -35,6 +37,9 @@ pub(super) fn install<'s>(
|
||||
if interface == "RTCStatsReport" {
|
||||
stats::install(scope, prototype);
|
||||
}
|
||||
if matches!(interface, "RTCIceTransport" | "RTCDtlsTransport") {
|
||||
transports::install(scope, prototype, interface);
|
||||
}
|
||||
if interface == "RTCDTMFSender" {
|
||||
dtmf::install(scope, prototype);
|
||||
}
|
||||
@@ -63,27 +68,19 @@ pub(super) fn install_runtime(scope: &mut v8::PinScope<'_, '_>) {
|
||||
moli_webapi::rtc::peer_connection::rtp_transceivers::RtpRuntime {
|
||||
initialize_pc,
|
||||
close: rtp_transceivers::close,
|
||||
create_offer,
|
||||
create_offer: rtp_transceivers::offer_sdp,
|
||||
apply_local_offer: rtp_transceivers::apply_local_offer,
|
||||
rollback_local_offer: rtp_transceivers::rollback_local_offer,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn create_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
data: bool,
|
||||
) -> Option<String> {
|
||||
rtp_transceivers::has_transceivers(scope, pc).then(|| {
|
||||
let sections = rtp_transceivers::offer_sections(scope, pc);
|
||||
rtp_offer::build(§ions, data)
|
||||
})
|
||||
}
|
||||
|
||||
fn initialize_pc<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) -> Option<()> {
|
||||
rtp_transceivers::initialize_pc(scope, pc);
|
||||
transports::initialize(scope, pc);
|
||||
let channels = v8::Set::new(scope);
|
||||
crate::util::set_private_value(scope, pc, data_channel::CHANNELS, channels.into());
|
||||
let owned = v8::Set::new(scope);
|
||||
@@ -96,4 +93,5 @@ fn initialize_pc<'s>(
|
||||
fn close_connection<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::Object>) {
|
||||
operations::close(scope, pc);
|
||||
data_channel::close_connection(scope, pc);
|
||||
transports::close(scope, pc);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Adapt the existing signaling-only SDP to local transceiver preferences.
|
||||
//! Payload identities and RTX dependencies come from the compatibility offer;
|
||||
//! this does not allocate ICE/DTLS transports or negotiate a remote description.
|
||||
//! transport credentials come from the native offer plan. Remote description
|
||||
//! negotiation still requires a WebRTC backend.
|
||||
|
||||
use super::rtp_parameters::Codec;
|
||||
use moli_webapi::rtc::peer_connection::{
|
||||
@@ -8,6 +9,9 @@ use moli_webapi::rtc::peer_connection::{
|
||||
};
|
||||
|
||||
pub(super) struct Section {
|
||||
pub mid: String,
|
||||
pub rejected: bool,
|
||||
pub transport_attributes: String,
|
||||
pub kind: String,
|
||||
pub direction: String,
|
||||
pub codecs: Vec<Codec>,
|
||||
@@ -70,7 +74,15 @@ fn formats<'a>(section: &'a str, kind: &str) -> Vec<Format<'a>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn media_section(kind: &str, direction: &str, codecs: &[Codec], mid: usize) -> String {
|
||||
fn media_section(section: &Section) -> String {
|
||||
let Section {
|
||||
kind,
|
||||
direction,
|
||||
codecs,
|
||||
mid,
|
||||
rejected,
|
||||
..
|
||||
} = section;
|
||||
let template = if kind == "audio" {
|
||||
RTC_AUDIO_OFFER_SECTION
|
||||
} else {
|
||||
@@ -97,8 +109,9 @@ fn media_section(kind: &str, direction: &str, codecs: &[Codec], mid: usize) -> S
|
||||
.collect();
|
||||
selected.retain(|format| format.apt.is_none_or(|apt| primary.contains(&apt)));
|
||||
let payloads: Vec<_> = selected.iter().map(|format| format.payload).collect();
|
||||
let port = if *rejected { 0 } else { 9 };
|
||||
let mut result = format!(
|
||||
"m={kind} 9 UDP/TLS/RTP/SAVPF {}\r\nc=IN IP4 0.0.0.0\r\na=mid:{mid}\r\na={direction}\r\na=rtcp-mux\r\na=rtcp-rsize\r\n",
|
||||
"m={kind} {port} UDP/TLS/RTP/SAVPF {}\r\nc=IN IP4 0.0.0.0\r\na=mid:{mid}\r\na={direction}\r\na=rtcp-mux\r\na=rtcp-rsize\r\n",
|
||||
payloads.join(" ")
|
||||
);
|
||||
for format in selected {
|
||||
@@ -110,32 +123,38 @@ fn media_section(kind: &str, direction: &str, codecs: &[Codec], mid: usize) -> S
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn build(sections: &[Section], data: bool) -> String {
|
||||
let count = sections.len() + usize::from(data);
|
||||
let mids: Vec<_> = (0..count).map(|mid| mid.to_string()).collect();
|
||||
let mids: Vec<_> = mids.iter().map(String::as_str).collect();
|
||||
let mut sdp = super::sdp::session_header(&mids);
|
||||
for (mid, section) in sections.iter().enumerate() {
|
||||
sdp.push_str(&media_section(
|
||||
§ion.kind,
|
||||
§ion.direction,
|
||||
§ion.codecs,
|
||||
mid,
|
||||
));
|
||||
pub(super) fn build(sections: &[Section], data: Option<(&str, &str)>) -> String {
|
||||
let mut media = Vec::new();
|
||||
for section in sections {
|
||||
let mut text = media_section(section);
|
||||
text.push_str(§ion.transport_attributes);
|
||||
if matches!(section.direction.as_str(), "sendrecv" | "sendonly") {
|
||||
if section.streams.is_empty() {
|
||||
sdp.push_str(&format!("a=msid:- {}\r\n", section.track));
|
||||
text.push_str(&format!("a=msid:- {}\r\n", section.track));
|
||||
} else {
|
||||
for stream in §ion.streams {
|
||||
sdp.push_str(&format!("a=msid:{stream} {}\r\n", section.track));
|
||||
text.push_str(&format!("a=msid:{stream} {}\r\n", section.track));
|
||||
}
|
||||
}
|
||||
}
|
||||
media.push((section.mid.as_str(), text, section.rejected));
|
||||
}
|
||||
if data {
|
||||
sdp.push_str(
|
||||
&RTC_DATA_OFFER_SECTION.replace("a=mid:2", &format!("a=mid:{}", sections.len())),
|
||||
);
|
||||
if let Some((mid, attributes)) = data {
|
||||
let mut text = RTC_DATA_OFFER_SECTION.replace("a=mid:2", &format!("a=mid:{mid}"));
|
||||
text.push_str(attributes);
|
||||
media.push((mid, text, false));
|
||||
}
|
||||
// Native, monotonically allocated MIDs preserve reservation order. A later
|
||||
// RTP transceiver must not displace an already offered application section.
|
||||
media.sort_by_key(|(mid, _, _)| mid.parse::<u32>().expect("locally reserved MID"));
|
||||
let mids: Vec<_> = media
|
||||
.iter()
|
||||
.filter(|(_, _, rejected)| !rejected)
|
||||
.map(|(mid, _, _)| *mid)
|
||||
.collect();
|
||||
let mut sdp = super::sdp::session_header(&mids);
|
||||
for (_, text, _) in media {
|
||||
sdp.push_str(&text);
|
||||
}
|
||||
sdp
|
||||
}
|
||||
@@ -159,6 +178,9 @@ mod tests {
|
||||
let sdp = build(
|
||||
&[
|
||||
Section {
|
||||
mid: "0".into(),
|
||||
rejected: false,
|
||||
transport_attributes: String::new(),
|
||||
kind: "video".into(),
|
||||
direction: "sendonly".into(),
|
||||
codecs: vec![h264.clone(), rtx],
|
||||
@@ -166,6 +188,9 @@ mod tests {
|
||||
track: "track".into(),
|
||||
},
|
||||
Section {
|
||||
mid: "1".into(),
|
||||
rejected: false,
|
||||
transport_attributes: String::new(),
|
||||
kind: "video".into(),
|
||||
direction: "inactive".into(),
|
||||
codecs: vec![h264],
|
||||
@@ -173,7 +198,7 @@ mod tests {
|
||||
track: "inactive".into(),
|
||||
},
|
||||
],
|
||||
true,
|
||||
Some(("2", "")),
|
||||
);
|
||||
assert!(sdp.contains("a=group:BUNDLE 0 1 2\r\n"));
|
||||
assert!(sdp.contains("m=video 9 UDP/TLS/RTP/SAVPF 103 104\r\n"));
|
||||
|
||||
@@ -54,6 +54,8 @@ struct SenderSlots<'s> {
|
||||
last_parameters: (),
|
||||
#[webapi(slot = DTMF)]
|
||||
dtmf: v8::Local<'s, v8::Value>,
|
||||
#[webapi(slot = super::transports::RTP_TRANSPORT, init = "null")]
|
||||
transport: (),
|
||||
}
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(plain)]
|
||||
@@ -218,11 +220,15 @@ fn track<'s>(
|
||||
rv.set(get_private_value(scope, sender, TRACK).expect("sender track"));
|
||||
}
|
||||
fn transport<'s>(
|
||||
_scope: &mut v8::PinScope<'s, '_>,
|
||||
_args: v8::FunctionCallbackArguments<'s>,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
rv.set_null();
|
||||
let sender = rtp_transceivers::target(scope, args.this());
|
||||
rv.set(
|
||||
get_private_value(scope, sender, super::transports::RTP_TRANSPORT)
|
||||
.expect("sender transport"),
|
||||
);
|
||||
}
|
||||
|
||||
fn dtmf<'s>(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Local RTP object relationships and offer preferences. Transport creation,
|
||||
//! SDP negotiation, encoding and reception still require a WebRTC backend.
|
||||
//! Local RTP object relationships, offer snapshots and transport association.
|
||||
//! Remote negotiation, encoding and reception still require a WebRTC backend.
|
||||
|
||||
use super::rtp_parameters::{Codec, Encoding, capabilities};
|
||||
use crate::{
|
||||
@@ -22,6 +22,13 @@ const TRACK: &str = "__moliRtpTrack";
|
||||
const DIRECTION: &str = "__moliRtpDirection";
|
||||
const CURRENT_DIRECTION: &str = "__moliRtpCurrentDirection";
|
||||
const MID: &str = "__moliRtpMid";
|
||||
const JSEP_MID: &str = "__moliRtpJsepMid";
|
||||
const NEXT_MID: &str = "__moliRtcNextMid";
|
||||
const PLANNED_TRANSPORT: &str = "__moliRtpPlannedTransport";
|
||||
const OFFER_SNAPSHOT: &str = "__moliRtcOfferSnapshot";
|
||||
const DATA_MID: &str = "__moliRtcDataMid";
|
||||
const DATA_TRANSPORT: &str = "__moliRtcDataTransport";
|
||||
const LEGACY_TRANSPORT: &str = "__moliRtcLegacyOfferTransport";
|
||||
const STOPPING: &str = "__moliRtpStopping";
|
||||
const STOPPED: &str = "__moliRtpStopped";
|
||||
const CODECS: &str = "__moliRtpPreferredCodecs";
|
||||
@@ -123,6 +130,10 @@ struct TransceiverSlots<'s> {
|
||||
current_direction: (),
|
||||
#[webapi(slot = MID, init = "null")]
|
||||
mid: (),
|
||||
#[webapi(slot = JSEP_MID, init = "null")]
|
||||
jsep_mid: (),
|
||||
#[webapi(slot = PLANNED_TRANSPORT, init = "null")]
|
||||
planned_transport: (),
|
||||
#[webapi(slot = STOPPING, init = false)]
|
||||
stopping: (),
|
||||
#[webapi(slot = STOPPED, init = false)]
|
||||
@@ -135,6 +146,19 @@ struct TransceiverSlots<'s> {
|
||||
struct ReceiverSlots<'s> {
|
||||
#[webapi(slot = TRACK)]
|
||||
track: v8::Local<'s, v8::Object>,
|
||||
#[webapi(slot = super::transports::RTP_TRANSPORT, init = "null")]
|
||||
transport: (),
|
||||
}
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(plain)]
|
||||
struct OfferAssociation<'s> {
|
||||
#[webapi(slot = TRANSCEIVERS)]
|
||||
transceiver: v8::Local<'s, v8::Value>,
|
||||
#[webapi(slot = MID)]
|
||||
mid: v8::Local<'s, v8::String>,
|
||||
#[webapi(slot = PLANNED_TRANSPORT)]
|
||||
transport: v8::Local<'s, v8::Object>,
|
||||
}
|
||||
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
@@ -204,6 +228,16 @@ pub(super) fn initialize_pc<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<
|
||||
set_private_value(scope, pc, TRANSCEIVERS, list.into());
|
||||
set_bool(scope, pc, NEGOTIATION_TASK, false);
|
||||
set_bool(scope, pc, NEGOTIATION_NEEDED, false);
|
||||
set_private_value(
|
||||
scope,
|
||||
pc,
|
||||
NEXT_MID,
|
||||
v8::Integer::new_from_unsigned(scope, 0).into(),
|
||||
);
|
||||
set_private_value(scope, pc, OFFER_SNAPSHOT, v8::Array::new(scope, 0).into());
|
||||
for slot in [DATA_MID, DATA_TRANSPORT, LEGACY_TRANSPORT] {
|
||||
set_private_value(scope, pc, slot, v8::null(scope).into());
|
||||
}
|
||||
}
|
||||
pub(super) fn has_transceivers<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
@@ -524,11 +558,15 @@ fn slot_getter<'s>(
|
||||
rv.set(get_private_value(scope, object, &slot).expect("RTP slot"));
|
||||
}
|
||||
fn transport_getter<'s>(
|
||||
_scope: &mut v8::PinScope<'s, '_>,
|
||||
_args: v8::FunctionCallbackArguments<'s>,
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
rv.set_null();
|
||||
let receiver = target(scope, args.this());
|
||||
rv.set(
|
||||
get_private_value(scope, receiver, super::transports::RTP_TRANSPORT)
|
||||
.expect("receiver transport"),
|
||||
);
|
||||
}
|
||||
fn direction_getter<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
@@ -702,6 +740,9 @@ pub(crate) fn apply_task<'s>(
|
||||
kind: RendererPageWebRtcTaskKind,
|
||||
) -> bool {
|
||||
let event_type = match kind {
|
||||
RendererPageWebRtcTaskKind::DtlsStateChange => {
|
||||
return super::transports::state_change_task(scope, object);
|
||||
}
|
||||
RendererPageWebRtcTaskKind::StartDataChannelClose
|
||||
| RendererPageWebRtcTaskKind::DataChannelClosed => {
|
||||
return super::data_channel::apply_close_task(scope, object, kind);
|
||||
@@ -755,41 +796,259 @@ pub(crate) fn apply_task<'s>(
|
||||
super::signaling::dispatch_event(scope, object, event_type)
|
||||
}
|
||||
|
||||
/// Read only private snapshots when building the signaling-only offer.
|
||||
pub(super) fn offer_sections<'s>(
|
||||
fn allocate_mid<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) -> Vec<super::rtp_offer::Section> {
|
||||
entries(scope, pc)
|
||||
.into_iter()
|
||||
.filter_map(|object| {
|
||||
if flag(scope, object, STOPPING) {
|
||||
return None;
|
||||
) -> Option<v8::Local<'s, v8::String>> {
|
||||
let next = get_private_value(scope, pc, NEXT_MID)?.uint32_value(scope)?;
|
||||
let Some(after) = next.checked_add(1) else {
|
||||
throw_dom_exception(
|
||||
scope,
|
||||
"OperationError",
|
||||
0,
|
||||
"No unused media identifiers remain.",
|
||||
);
|
||||
return None;
|
||||
};
|
||||
set_private_value(
|
||||
scope,
|
||||
pc,
|
||||
NEXT_MID,
|
||||
v8::Integer::new_from_unsigned(scope, after).into(),
|
||||
);
|
||||
v8_string(scope, &next.to_string())
|
||||
}
|
||||
|
||||
fn offer_snapshot<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) -> v8::Local<'s, v8::Array> {
|
||||
v8::Local::try_from(get_private_value(scope, pc, OFFER_SNAPSHOT).expect("offer snapshot"))
|
||||
.expect("native offer association array")
|
||||
}
|
||||
|
||||
/// Reserve MIDs and transport credentials at offer creation. Observable MIDs
|
||||
/// and endpoint transports change only when this exact snapshot is applied.
|
||||
pub(super) fn offer_sdp<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
audio: bool,
|
||||
video: bool,
|
||||
data: bool,
|
||||
) -> Option<String> {
|
||||
let mut snapshot = Vec::new();
|
||||
// Preserve the existing offerToReceive compatibility surface. It has no
|
||||
// native transceivers to associate, but still needs valid ICE credentials.
|
||||
if !has_transceivers(scope, pc) && (audio || video) {
|
||||
let existing = get_private_object(scope, pc, LEGACY_TRANSPORT);
|
||||
let transport = super::transports::plan(scope, pc, existing)?;
|
||||
set_private_value(scope, pc, LEGACY_TRANSPORT, transport.into());
|
||||
let next = get_private_value(scope, pc, NEXT_MID)?
|
||||
.uint32_value(scope)?
|
||||
.max(3);
|
||||
set_private_value(
|
||||
scope,
|
||||
pc,
|
||||
NEXT_MID,
|
||||
v8::Integer::new_from_unsigned(scope, next).into(),
|
||||
);
|
||||
snapshot.push(
|
||||
OfferAssociation::new(v8::null(scope).into(), v8str(scope, ""), transport)
|
||||
.bind(scope)
|
||||
.ok()?
|
||||
.into(),
|
||||
);
|
||||
if data {
|
||||
set_private_value(scope, pc, DATA_MID, v8str(scope, "2").into());
|
||||
set_private_value(scope, pc, DATA_TRANSPORT, transport.into());
|
||||
}
|
||||
let mut sdp = super::build_signaling_only_offer(audio, video, data);
|
||||
let at = sdp.find("m=").unwrap_or(sdp.len());
|
||||
sdp.insert_str(at, &super::transports::sdp_attributes(scope, transport));
|
||||
set_private_value(
|
||||
scope,
|
||||
pc,
|
||||
OFFER_SNAPSHOT,
|
||||
v8::Array::new_with_elements(scope, &snapshot).into(),
|
||||
);
|
||||
return Some(sdp);
|
||||
}
|
||||
let mut sections = Vec::new();
|
||||
for object in entries(scope, pc) {
|
||||
let stopped = flag(scope, object, STOPPING);
|
||||
if stopped && get_private_value(scope, object, MID)?.is_null() {
|
||||
continue;
|
||||
}
|
||||
let mid =
|
||||
match v8::Local::<v8::String>::try_from(get_private_value(scope, object, JSEP_MID)?) {
|
||||
Ok(mid) => mid,
|
||||
Err(_) => {
|
||||
let mid = allocate_mid(scope, pc)?;
|
||||
set_private_value(scope, object, JSEP_MID, mid.into());
|
||||
mid
|
||||
}
|
||||
};
|
||||
let existing = get_private_object(scope, object, PLANNED_TRANSPORT);
|
||||
let transport = super::transports::plan(scope, pc, existing)?;
|
||||
set_private_value(scope, object, PLANNED_TRANSPORT, transport.into());
|
||||
snapshot.push(
|
||||
OfferAssociation::new(object.into(), mid, transport)
|
||||
.bind(scope)
|
||||
.ok()?
|
||||
.into(),
|
||||
);
|
||||
let receiver = get_private_object(scope, object, RECEIVER).expect("RTP receiver");
|
||||
let track = get_private_object(scope, receiver, TRACK).expect("receiver track");
|
||||
let kind = media_streams::track_kind(scope, track);
|
||||
let direction = if stopped {
|
||||
"inactive".into()
|
||||
} else {
|
||||
get_private_value(scope, object, DIRECTION)
|
||||
.expect("direction")
|
||||
.to_rust_string_lossy(scope)
|
||||
};
|
||||
let codecs = get_private_value(scope, object, CODECS)
|
||||
.expect("codec snapshot")
|
||||
.to_rust_string_lossy(scope);
|
||||
let codecs: Vec<Codec> = serde_json::from_str(&codecs).expect("native codec snapshot");
|
||||
let sender = get_private_object(scope, object, SENDER).expect("RTP sender");
|
||||
let (streams, track) = super::rtp_sender::sdp_identity(scope, sender);
|
||||
sections.push(super::rtp_offer::Section {
|
||||
mid: mid.to_rust_string_lossy(scope),
|
||||
rejected: stopped,
|
||||
transport_attributes: super::transports::sdp_attributes(scope, transport),
|
||||
kind: kind.clone(),
|
||||
direction,
|
||||
codecs: if codecs.is_empty() {
|
||||
capabilities(&kind)
|
||||
} else {
|
||||
codecs
|
||||
},
|
||||
streams,
|
||||
track,
|
||||
});
|
||||
}
|
||||
let data_section = if data {
|
||||
let mid = match v8::Local::<v8::String>::try_from(get_private_value(scope, pc, DATA_MID)?) {
|
||||
Ok(mid) => mid,
|
||||
Err(_) => {
|
||||
let mid = allocate_mid(scope, pc)?;
|
||||
set_private_value(scope, pc, DATA_MID, mid.into());
|
||||
mid
|
||||
}
|
||||
};
|
||||
let existing = get_private_object(scope, pc, DATA_TRANSPORT);
|
||||
let transport = super::transports::plan(scope, pc, existing)?;
|
||||
set_private_value(scope, pc, DATA_TRANSPORT, transport.into());
|
||||
snapshot.push(
|
||||
OfferAssociation::new(v8::null(scope).into(), mid, transport)
|
||||
.bind(scope)
|
||||
.ok()?
|
||||
.into(),
|
||||
);
|
||||
Some((
|
||||
mid.to_rust_string_lossy(scope),
|
||||
super::transports::sdp_attributes(scope, transport),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
set_private_value(
|
||||
scope,
|
||||
pc,
|
||||
OFFER_SNAPSHOT,
|
||||
v8::Array::new_with_elements(scope, &snapshot).into(),
|
||||
);
|
||||
Some(super::rtp_offer::build(
|
||||
§ions,
|
||||
data_section
|
||||
.as_ref()
|
||||
.map(|(mid, attributes)| (mid.as_str(), attributes.as_str())),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn apply_local_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) -> Option<()> {
|
||||
let snapshot = offer_snapshot(scope, pc);
|
||||
let replacements = v8::Map::new(scope);
|
||||
// Stage allocations before mutating endpoint associations. A rollback may
|
||||
// have closed a previously generated offer's transport in the meantime.
|
||||
let mut associations = Vec::new();
|
||||
for index in 0..snapshot.length() {
|
||||
let association =
|
||||
v8::Local::<v8::Object>::try_from(snapshot.get_index(scope, index)?).ok()?;
|
||||
let planned = get_private_object(scope, association, PLANNED_TRANSPORT)?;
|
||||
let transport = if let Ok(transport) =
|
||||
v8::Local::<v8::Object>::try_from(replacements.get(scope, planned.into())?)
|
||||
{
|
||||
transport
|
||||
} else {
|
||||
let transport = super::transports::from_offer(scope, pc, planned)?;
|
||||
replacements.set(scope, planned.into(), transport.into())?;
|
||||
transport
|
||||
};
|
||||
associations.push((association, transport));
|
||||
}
|
||||
for (association, transport) in associations {
|
||||
super::transports::applied(scope, transport);
|
||||
super::transports::remember_bundle(scope, pc, transport);
|
||||
let mid = get_private_value(scope, association, MID)?;
|
||||
if let Some(transceiver) = get_private_object(scope, association, TRANSCEIVERS) {
|
||||
set_private_value(scope, transceiver, JSEP_MID, mid);
|
||||
set_private_value(scope, transceiver, MID, mid);
|
||||
set_private_value(scope, transceiver, PLANNED_TRANSPORT, transport.into());
|
||||
if !flag(scope, transceiver, STOPPED) {
|
||||
for endpoint in [SENDER, RECEIVER] {
|
||||
let endpoint = get_private_object(scope, transceiver, endpoint)?;
|
||||
set_private_value(
|
||||
scope,
|
||||
endpoint,
|
||||
super::transports::RTP_TRANSPORT,
|
||||
transport.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let receiver = get_private_object(scope, object, RECEIVER).expect("RTP receiver");
|
||||
let track = get_private_object(scope, receiver, TRACK).expect("receiver track");
|
||||
let kind = media_streams::track_kind(scope, track);
|
||||
let direction = get_private_value(scope, object, DIRECTION)
|
||||
.expect("direction")
|
||||
.to_rust_string_lossy(scope);
|
||||
let snapshot = get_private_value(scope, object, CODECS)
|
||||
.expect("codec snapshot")
|
||||
.to_rust_string_lossy(scope);
|
||||
let codecs: Vec<Codec> =
|
||||
serde_json::from_str(&snapshot).expect("native codec snapshot");
|
||||
let sender = get_private_object(scope, object, SENDER).expect("RTP sender");
|
||||
let (streams, track) = super::rtp_sender::sdp_identity(scope, sender);
|
||||
Some(super::rtp_offer::Section {
|
||||
kind: kind.clone(),
|
||||
direction,
|
||||
codecs: if codecs.is_empty() {
|
||||
capabilities(&kind)
|
||||
} else {
|
||||
codecs
|
||||
},
|
||||
streams,
|
||||
track,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
} else if mid.strict_equals(v8str(scope, "").into()) {
|
||||
set_private_value(scope, pc, LEGACY_TRANSPORT, transport.into());
|
||||
} else {
|
||||
set_private_value(scope, pc, DATA_MID, mid);
|
||||
set_private_value(scope, pc, DATA_TRANSPORT, transport.into());
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub(super) fn rollback_local_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
// The frontend has no remote/answer path yet, so every association is new
|
||||
// since the last stable state. Full negotiation must retain stable snapshots.
|
||||
for transceiver in entries(scope, pc) {
|
||||
if let Some(transport) = get_private_object(scope, transceiver, PLANNED_TRANSPORT) {
|
||||
super::transports::rollback(scope, transport);
|
||||
}
|
||||
for slot in [MID, JSEP_MID, PLANNED_TRANSPORT] {
|
||||
set_private_value(scope, transceiver, slot, v8::null(scope).into());
|
||||
}
|
||||
for endpoint in [SENDER, RECEIVER] {
|
||||
let endpoint = get_private_object(scope, transceiver, endpoint).expect("RTP endpoint");
|
||||
set_private_value(
|
||||
scope,
|
||||
endpoint,
|
||||
super::transports::RTP_TRANSPORT,
|
||||
v8::null(scope).into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
for slot in [DATA_TRANSPORT, LEGACY_TRANSPORT] {
|
||||
if let Some(transport) = get_private_object(scope, pc, slot) {
|
||||
super::transports::rollback(scope, transport);
|
||||
}
|
||||
set_private_value(scope, pc, slot, v8::null(scope).into());
|
||||
}
|
||||
set_private_value(scope, pc, DATA_MID, v8::null(scope).into());
|
||||
super::transports::clear_bundle(scope, pc);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ mod tests {
|
||||
assert_eq!(parsed.media.len(), (bits as u32).count_ones() as usize);
|
||||
assert_eq!(text.contains("a=group:BUNDLE"), bits != 0);
|
||||
}
|
||||
let text = super::super::rtp_offer::build(&[], false);
|
||||
let text = super::super::rtp_offer::build(&[], None);
|
||||
assert!(parse(&text).unwrap().media.is_empty());
|
||||
assert!(!text.contains("a=group:BUNDLE"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
//! Native local transports. Applying an offer exposes the planned ICE/DTLS
|
||||
//! objects; only a transport backend may supply candidates or advance them.
|
||||
|
||||
use super::{operations, rtp_transceivers, signaling, SIMPLE_EVENT_TARGET_LISTENERS_SLOT};
|
||||
use moli_webapi::rtc::peer_connection::{configuration, set_string_slot};
|
||||
use crate::{
|
||||
context_bootstrap::media_queries,
|
||||
util::{get_private_value, set_private_value, v8_string, v8str},
|
||||
web_api_interfaces,
|
||||
};
|
||||
use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
|
||||
use crate::page_task_queue::RendererPageWebRtcTaskKind;
|
||||
use crate::util::get_private_object;
|
||||
use base64::Engine as _;
|
||||
|
||||
pub(super) const RTP_TRANSPORT: &str = "__moliRtpTransport";
|
||||
const OWNED: &str = "__moliRtcOwnedTransports";
|
||||
const BUNDLED: &str = "__moliRtcBundledTransport";
|
||||
const OWNER: &str = "__moliRtcTransportOwner";
|
||||
const ICE: &str = "__moliRtcIceTransport";
|
||||
const STATE: &str = "__moliRtcTransportState";
|
||||
const APPLIED: &str = "__moliRtcIceLocalDescriptionApplied";
|
||||
const UFRAG: &str = "__moliRtcIceUsernameFragment";
|
||||
const PASSWORD: &str = "__moliRtcIcePassword";
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(interface = web_api_interfaces::RTCIceTransport, require_prototype)]
|
||||
struct IceTransport<'s> {
|
||||
#[webapi(slot = UFRAG)]
|
||||
username_fragment: v8::Local<'s, v8::String>,
|
||||
#[webapi(slot = PASSWORD)]
|
||||
password: v8::Local<'s, v8::String>,
|
||||
#[webapi(slot = STATE, init = string("new"))]
|
||||
state: (),
|
||||
#[webapi(slot = APPLIED, init = false)]
|
||||
applied: (),
|
||||
#[webapi(slot = SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")]
|
||||
event_target_slot: (),
|
||||
}
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(interface = web_api_interfaces::RTCDtlsTransport, require_prototype)]
|
||||
struct DtlsTransport<'s> {
|
||||
#[webapi(slot = OWNER)]
|
||||
owner: v8::Local<'s, v8::Object>,
|
||||
#[webapi(slot = ICE)]
|
||||
ice_transport: v8::Local<'s, v8::Object>,
|
||||
#[webapi(slot = STATE, init = string("new"))]
|
||||
state: (),
|
||||
#[webapi(slot = SIMPLE_EVENT_TARGET_LISTENERS_SLOT, init = "null_object")]
|
||||
event_target_slot: (),
|
||||
}
|
||||
|
||||
#[derive(WebApiObject)]
|
||||
#[webapi(plain)]
|
||||
struct IceParameters<'s> {
|
||||
#[webapi(data_property, enumerable)]
|
||||
username_fragment: v8::Local<'s, v8::String>,
|
||||
#[webapi(data_property, enumerable)]
|
||||
password: v8::Local<'s, v8::String>,
|
||||
}
|
||||
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
#[webapi(interface = web_api_interfaces::RTCIceTransport, enumerable)]
|
||||
struct IcePrototype {
|
||||
#[webapi(accessor_property, getter = constant, data = v8str(scope, "rtp"))]
|
||||
component: (),
|
||||
#[webapi(accessor_property, getter = constant, data = v8str(scope, "unknown"))]
|
||||
role: (),
|
||||
#[webapi(accessor_property, getter = value, data = v8str(scope, STATE))]
|
||||
state: (),
|
||||
#[webapi(accessor_property, getter = constant, data = v8str(scope, "new"))]
|
||||
gathering_state: (),
|
||||
#[webapi(accessor_property, getter = handler, setter = set_handler, data = v8str(scope, "gatheringstatechange"))]
|
||||
ongatheringstatechange: (),
|
||||
#[webapi(accessor_property, getter = handler, setter = set_handler, data = v8str(scope, "statechange"))]
|
||||
onstatechange: (),
|
||||
#[webapi(accessor_property, getter = handler, setter = set_handler, data = v8str(scope, "selectedcandidatepairchange"))]
|
||||
onselectedcandidatepairchange: (),
|
||||
#[webapi(method, length = 0, callback = empty_sequence)]
|
||||
get_local_candidates: (),
|
||||
#[webapi(method, length = 0, callback = empty_sequence)]
|
||||
get_remote_candidates: (),
|
||||
#[webapi(method, length = 0, callback = absent)]
|
||||
get_selected_candidate_pair: (),
|
||||
#[webapi(method, length = 0, callback = local_parameters)]
|
||||
get_local_parameters: (),
|
||||
#[webapi(method, length = 0, callback = absent)]
|
||||
get_remote_parameters: (),
|
||||
}
|
||||
|
||||
#[derive(WebApiFunctionTemplate)]
|
||||
#[webapi(interface = web_api_interfaces::RTCDtlsTransport, enumerable)]
|
||||
struct DtlsPrototype {
|
||||
#[webapi(accessor_property, getter = value, data = v8str(scope, ICE))]
|
||||
ice_transport: (),
|
||||
#[webapi(accessor_property, getter = value, data = v8str(scope, STATE))]
|
||||
state: (),
|
||||
#[webapi(method, length = 0, callback = empty_sequence)]
|
||||
get_remote_certificates: (),
|
||||
#[webapi(accessor_property, getter = handler, setter = set_handler, data = v8str(scope, "statechange"))]
|
||||
onstatechange: (),
|
||||
#[webapi(accessor_property, getter = handler, setter = set_handler, data = v8str(scope, "error"))]
|
||||
onerror: (),
|
||||
}
|
||||
|
||||
pub(super) fn install<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_, ()>,
|
||||
prototype: v8::Local<'s, v8::ObjectTemplate>,
|
||||
name: &str,
|
||||
) {
|
||||
match name {
|
||||
"RTCIceTransport" => IcePrototype::initialize_prototype_template(scope, prototype),
|
||||
"RTCDtlsTransport" => DtlsPrototype::initialize_prototype_template(scope, prototype),
|
||||
_ => unreachable!("local transport interface"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn initialize<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::Object>) {
|
||||
set_private_value(scope, pc, OWNED, v8::Set::new(scope).into());
|
||||
clear_bundle(scope, pc);
|
||||
}
|
||||
|
||||
fn owned<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) -> v8::Local<'s, v8::Set> {
|
||||
v8::Local::try_from(get_private_value(scope, pc, OWNED).expect("owned transports"))
|
||||
.expect("native transport Set")
|
||||
}
|
||||
|
||||
fn ice<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
dtls: v8::Local<'s, v8::Object>,
|
||||
) -> v8::Local<'s, v8::Object> {
|
||||
get_private_object(scope, dtls, ICE).expect("DTLS ICE transport")
|
||||
}
|
||||
|
||||
fn build<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
username_fragment: v8::Local<'s, v8::String>,
|
||||
password: v8::Local<'s, v8::String>,
|
||||
) -> Option<v8::Local<'s, v8::Object>> {
|
||||
// Transport objects belong to the connection, even when its methods were
|
||||
// borrowed from another realm. Never consult replaceable global constructors.
|
||||
let context = pc.get_creation_context(scope)?;
|
||||
let scope = &mut v8::ContextScope::new(scope, context);
|
||||
let ice = IceTransport::new(username_fragment, password)
|
||||
.bind(scope)
|
||||
.ok()?;
|
||||
let dtls = DtlsTransport::new(pc, ice).bind(scope).ok()?;
|
||||
owned(scope, pc).add(scope, dtls.into())?;
|
||||
Some(dtls)
|
||||
}
|
||||
|
||||
pub(super) fn plan<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
existing: Option<v8::Local<'s, v8::Object>>,
|
||||
) -> Option<v8::Local<'s, v8::Object>> {
|
||||
let bundled = configuration::max_bundle(scope, pc);
|
||||
if let Some(transport) = existing.or_else(|| {
|
||||
bundled
|
||||
.then(|| get_private_object(scope, pc, BUNDLED))
|
||||
.flatten()
|
||||
}) {
|
||||
return Some(transport);
|
||||
}
|
||||
// Independent ICE credentials for unbundled transports; each password has
|
||||
// 128 bits of entropy. Unpadded base64 uses RFC 8445's ice-char alphabet.
|
||||
let mut bytes = [0_u8; 32];
|
||||
if moli_crypto::fill_secure_random(&mut bytes).is_err() {
|
||||
crate::native_bridge::throw_dom_exception(
|
||||
scope,
|
||||
"UnknownError",
|
||||
0,
|
||||
"The ICE credentials could not be generated.",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let username_fragment = v8_string(
|
||||
scope,
|
||||
&base64::engine::general_purpose::STANDARD_NO_PAD.encode(&bytes[..16]),
|
||||
)?;
|
||||
let password = v8_string(
|
||||
scope,
|
||||
&base64::engine::general_purpose::STANDARD_NO_PAD.encode(&bytes[16..]),
|
||||
)?;
|
||||
let transport = build(scope, pc, username_fragment, password)?;
|
||||
if bundled {
|
||||
set_private_value(scope, pc, BUNDLED, transport.into());
|
||||
}
|
||||
Some(transport)
|
||||
}
|
||||
|
||||
/// An older locally generated offer remains applicable after rollback. Its
|
||||
/// credentials may be reused, but its closed observable transport may not.
|
||||
pub(super) fn from_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
planned: v8::Local<'s, v8::Object>,
|
||||
) -> Option<v8::Local<'s, v8::Object>> {
|
||||
if !get_private_value(scope, planned, STATE)?.strict_equals(v8str(scope, "closed").into()) {
|
||||
return Some(planned);
|
||||
}
|
||||
let ice = ice(scope, planned);
|
||||
let username_fragment = v8::Local::try_from(get_private_value(scope, ice, UFRAG)?).ok()?;
|
||||
let password = v8::Local::try_from(get_private_value(scope, ice, PASSWORD)?).ok()?;
|
||||
build(scope, pc, username_fragment, password)
|
||||
}
|
||||
|
||||
pub(super) fn sdp_attributes<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
transport: v8::Local<'s, v8::Object>,
|
||||
) -> String {
|
||||
let ice = ice(scope, transport);
|
||||
let ufrag = get_private_value(scope, ice, UFRAG)
|
||||
.expect("ICE ufrag")
|
||||
.to_rust_string_lossy(scope);
|
||||
let password = get_private_value(scope, ice, PASSWORD)
|
||||
.expect("ICE password")
|
||||
.to_rust_string_lossy(scope);
|
||||
format!("a=ice-ufrag:{ufrag}\r\na=ice-pwd:{password}\r\na=setup:actpass\r\n")
|
||||
}
|
||||
|
||||
pub(super) fn applied<'s>(scope: &mut v8::PinScope<'s, '_>, transport: v8::Local<'s, v8::Object>) {
|
||||
let ice = ice(scope, transport);
|
||||
set_private_value(scope, ice, APPLIED, v8::Boolean::new(scope, true).into());
|
||||
}
|
||||
|
||||
pub(super) fn clear_bundle<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::Object>) {
|
||||
set_private_value(scope, pc, BUNDLED, v8::null(scope).into());
|
||||
}
|
||||
|
||||
pub(super) fn remember_bundle<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
transport: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
if configuration::max_bundle(scope, pc) {
|
||||
set_private_value(scope, pc, BUNDLED, transport.into());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn rollback<'s>(scope: &mut v8::PinScope<'s, '_>, transport: v8::Local<'s, v8::Object>) {
|
||||
let ice = ice(scope, transport);
|
||||
set_private_value(scope, ice, APPLIED, v8::Boolean::new(scope, false).into());
|
||||
if !get_private_value(scope, transport, STATE)
|
||||
.expect("DTLS state")
|
||||
.strict_equals(v8str(scope, "closed").into())
|
||||
{
|
||||
set_string_slot(scope, transport, STATE, "closed");
|
||||
operations::queue(
|
||||
scope,
|
||||
transport,
|
||||
transport,
|
||||
RendererPageWebRtcTaskKind::DtlsStateChange,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn close<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::Object>) {
|
||||
let transports = owned(scope, pc).as_array(scope);
|
||||
for index in 0..transports.length() {
|
||||
let transport =
|
||||
v8::Local::try_from(transports.get_index(scope, index).expect("owned transport"))
|
||||
.expect("native DTLS transport");
|
||||
set_string_slot(scope, transport, STATE, "closed");
|
||||
let ice = ice(scope, transport);
|
||||
set_string_slot(scope, ice, STATE, "closed");
|
||||
}
|
||||
// PC.close() changes transport states synchronously without firing events.
|
||||
owned(scope, pc).clear();
|
||||
clear_bundle(scope, pc);
|
||||
}
|
||||
|
||||
pub(super) fn state_change_task<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
transport: v8::Local<'s, v8::Object>,
|
||||
) -> bool {
|
||||
let pc = get_private_object(scope, transport, OWNER).expect("DTLS owner");
|
||||
if rtp_transceivers::closed(scope, pc) {
|
||||
return false;
|
||||
}
|
||||
signaling::dispatch_event(scope, transport, "statechange")
|
||||
}
|
||||
|
||||
fn constant<'s>(
|
||||
_scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
rv.set(args.data());
|
||||
}
|
||||
|
||||
fn value<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let target = rtp_transceivers::target(scope, args.this());
|
||||
let slot = args.data().to_rust_string_lossy(scope);
|
||||
rv.set(get_private_value(scope, target, &slot).expect("transport slot"));
|
||||
}
|
||||
|
||||
fn empty_sequence<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
_args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
rv.set(v8::Array::new(scope, 0).into());
|
||||
}
|
||||
|
||||
fn absent<'s>(
|
||||
_scope: &mut v8::PinScope<'s, '_>,
|
||||
_args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
rv.set_null();
|
||||
}
|
||||
|
||||
fn local_parameters<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let ice = rtp_transceivers::target(scope, args.this());
|
||||
if !get_private_value(scope, ice, APPLIED)
|
||||
.expect("ICE local description flag")
|
||||
.boolean_value(scope)
|
||||
{
|
||||
rv.set_null();
|
||||
return;
|
||||
}
|
||||
let username_fragment =
|
||||
v8::Local::try_from(get_private_value(scope, ice, UFRAG).expect("ICE ufrag"))
|
||||
.expect("native ICE string");
|
||||
let password =
|
||||
v8::Local::try_from(get_private_value(scope, ice, PASSWORD).expect("ICE password"))
|
||||
.expect("native ICE string");
|
||||
if let Ok(parameters) = IceParameters::new(username_fragment, password).bind(scope) {
|
||||
rv.set(parameters.into());
|
||||
}
|
||||
}
|
||||
|
||||
fn handler_slot(event: &str) -> &'static str {
|
||||
match event {
|
||||
"statechange" => "__moliRtcTransportOnStateChange",
|
||||
"error" => "__moliRtcTransportOnError",
|
||||
"gatheringstatechange" => "__moliRtcTransportOnGatheringStateChange",
|
||||
"selectedcandidatepairchange" => "__moliRtcTransportOnSelectedCandidatePairChange",
|
||||
_ => unreachable!("transport event callback data"),
|
||||
}
|
||||
}
|
||||
|
||||
fn handler<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
mut rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let target = rtp_transceivers::target(scope, args.this());
|
||||
let event = args.data().to_rust_string_lossy(scope);
|
||||
rv.set(
|
||||
get_private_value(scope, target, handler_slot(&event))
|
||||
.unwrap_or_else(|| v8::null(scope).into()),
|
||||
);
|
||||
}
|
||||
|
||||
fn set_handler<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
_rv: v8::ReturnValue<'_, v8::Value>,
|
||||
) {
|
||||
let target = rtp_transceivers::target(scope, args.this());
|
||||
let event = args.data().to_rust_string_lossy(scope);
|
||||
let slot = handler_slot(&event);
|
||||
media_queries::simple_object_event_set_handler(
|
||||
scope,
|
||||
target,
|
||||
event.as_str(),
|
||||
slot,
|
||||
args.get(0),
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ pub(crate) enum RendererPageWebRtcTaskKind {
|
||||
GetStats,
|
||||
StartDataChannelClose,
|
||||
DataChannelClosed,
|
||||
DtlsStateChange,
|
||||
}
|
||||
pub(crate) type RendererPageWebRtcOwner = RendererPageWindowDocumentTaskOwner;
|
||||
pub(crate) type RendererPageWebRtcTask =
|
||||
|
||||
@@ -2492,6 +2492,7 @@ mod rtc_data_channel_init;
|
||||
mod rtc_data_channel_send;
|
||||
mod rtc_dtmf_sender;
|
||||
mod rtc_encoded_frames;
|
||||
mod rtc_local_transports;
|
||||
mod rtc_platform_values;
|
||||
mod rtc_stats;
|
||||
mod rtp_sender;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn rtc_local_transports_association_snapshots_brands_realms_rollback_and_close() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
for url in [
|
||||
"https://local-transports.test/",
|
||||
"http://local-transports.test/",
|
||||
"data:text/html,<body>",
|
||||
] {
|
||||
let mut vm = new_storage_page_task_executor_test_vm_with_loader(url, &loader);
|
||||
vm.eval("document.body.innerHTML='<iframe></iframe>'")
|
||||
.unwrap();
|
||||
vm.eval(include_str!(
|
||||
"../../../tests/fixtures/rtc-local-transports.js"
|
||||
))
|
||||
.unwrap();
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"String(globalThis.__uiEventResults?.complete)",
|
||||
"true",
|
||||
"local transport fixture must finish through the selected Page dispatcher",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__uiEventResults.checks.filter(row=>!row.passed))")
|
||||
.unwrap(),
|
||||
"[]",
|
||||
"{url}"
|
||||
);
|
||||
assert_eq!(vm.eval("__uiEventResults.total===54 && new Set(__uiEventResults.checks.map(row=>row.name)).size===54").unwrap(), "true");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn rtc_local_transports_registered_native_proxies_keep_native_identity_without_traps() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
|
||||
"https://local-transports.test/proxy",
|
||||
&loader,
|
||||
);
|
||||
vm.eval("globalThis.pc=new RTCPeerConnection();globalThis.t=pc.addTransceiver('audio');globalThis.ready=false;pc.setLocalDescription().then(()=>{globalThis.dtls=t.sender.transport;globalThis.ice=dtls.iceTransport;globalThis.ready=true;});globalThis.traps=0;globalThis.trap=()=>{traps++;throw Error('native Proxy trap')};").unwrap();
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"String(ready)",
|
||||
"true",
|
||||
"associate the native transports",
|
||||
)
|
||||
.await;
|
||||
let context_ptr = &vm.current_main_world().unwrap().context as *const _;
|
||||
vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
|
||||
let global = scope.get_current_context().global(scope);
|
||||
let trap_key = crate::util::v8_string(scope, "trap").unwrap();
|
||||
let trap = global.get(scope, trap_key.into()).unwrap();
|
||||
for (name, alias) in [("dtls", "nativeDtls"), ("ice", "nativeIce")] {
|
||||
let handler = crate::util::new_null_prototype_object(scope);
|
||||
let key = crate::util::v8_string(scope, "get").unwrap();
|
||||
assert_eq!(
|
||||
handler.create_data_property(scope, key.into(), trap),
|
||||
Some(true)
|
||||
);
|
||||
let key = crate::util::v8_string(scope, name).unwrap();
|
||||
let target =
|
||||
v8::Local::<v8::Object>::try_from(global.get(scope, key.into()).unwrap()).unwrap();
|
||||
let proxy = v8::Proxy::new(scope, target, handler).unwrap();
|
||||
moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
|
||||
let key = crate::util::v8_string(scope, alias).unwrap();
|
||||
assert_eq!(
|
||||
global.create_data_property(scope, key.into(), proxy.into()),
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(vm.eval(r#"(()=>{
|
||||
for(const [name,proxy,real] of [['RTCDtlsTransport',nativeDtls,dtls],['RTCIceTransport',nativeIce,ice]]){
|
||||
for(const key of Object.getOwnPropertyNames(globalThis[name].prototype)){
|
||||
if(key==='constructor')continue;const d=Object.getOwnPropertyDescriptor(globalThis[name].prototype,key);
|
||||
if(d.get){const value=d.get.call(proxy);if(value!==d.get.call(real))throw Error('native getter');if(d.set){const fn=()=>{};d.set.call(proxy,fn);if(d.get.call(real)!==fn)throw Error('native setter');d.set.call(real,null);}}
|
||||
else if(typeof d.value==='function'){const result=d.value.call(proxy);if(result!==null&&typeof result!=='object')throw Error('native method');}
|
||||
}
|
||||
EventTarget.prototype.addEventListener.call(proxy,'custom',()=>{});EventTarget.prototype.dispatchEvent.call(proxy,new Event('custom'));
|
||||
let error;try{Object.getOwnPropertyDescriptor(globalThis[name].prototype,'state').get.call(new Proxy(proxy,{}))}catch(e){error=e}if(!(error instanceof TypeError))throw Error('author Proxy');
|
||||
}
|
||||
pc.close();return dtls.state==='closed'&&ice.state==='closed'&&traps===0;
|
||||
})()"#).unwrap(),"true");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn rtc_local_transports_connection_close_suppresses_queued_rollback_statechange() {
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let mut vm = new_storage_page_task_executor_test_vm_with_loader(
|
||||
"https://local-transports.test/queued",
|
||||
&loader,
|
||||
);
|
||||
vm.eval("globalThis.pc=new RTCPeerConnection();globalThis.t=pc.addTransceiver('audio');globalThis.ready=false;pc.setLocalDescription().then(()=>{globalThis.dtls=t.sender.transport;globalThis.ice=dtls.iceTransport;globalThis.ready=true;});globalThis.trace=[];").unwrap();
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"String(ready)",
|
||||
"true",
|
||||
"associate the local transports",
|
||||
)
|
||||
.await;
|
||||
vm.eval("dtls.onstatechange=()=>trace.push('unexpected');ice.onstatechange=()=>trace.push('unexpected');pc.setLocalDescription({type:'rollback'}).then(()=>{trace.push('rolled back');pc.close();if(dtls.state!=='closed'||ice.state!=='closed')throw Error('synchronous transport shutdown');pc.getStats().then(()=>trace.push('stats'));});").unwrap();
|
||||
advance_page_task_executor_until_eval_equals(
|
||||
&mut vm,
|
||||
&loader,
|
||||
"trace.join('|')",
|
||||
"rolled back|stats",
|
||||
"closing the owner must suppress its queued DTLS event",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vm.eval("dtls.state==='closed' && ice.state==='closed' && t.sender.transport===null")
|
||||
.unwrap(),
|
||||
"true"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
(async()=>{
|
||||
const checks=[],child=document.querySelector('iframe').contentWindow;
|
||||
const assert=(ok,message='assertion failed')=>{if(!ok)throw Error(message);};
|
||||
const caught=body=>{try{body();}catch(error){return error;}};
|
||||
const tick=()=>new Promise(resolve=>setTimeout(resolve,40));
|
||||
const check=async(name,body)=>{try{await body();checks.push({name,passed:true});}catch(error){checks.push({name,passed:false,error:String(error),stack:error.stack});}};
|
||||
const parts=sdp=>sdp.split('m=').slice(1);
|
||||
const mids=sdp=>parts(sdp).map(part=>part.match(/a=mid:(\S+)/)[1]);
|
||||
const credentials=part=>({usernameFragment:part.match(/a=ice-ufrag:(\S+)/)[1],password:part.match(/a=ice-pwd:(\S+)/)[1]});
|
||||
const iceAttributes=['component','role','state','gatheringState','ongatheringstatechange','onstatechange','onselectedcandidatepairchange'];
|
||||
const iceMethods=['getLocalCandidates','getRemoteCandidates','getSelectedCandidatePair','getLocalParameters','getRemoteParameters'];
|
||||
const dtlsAttributes=['iceTransport','state','onstatechange','onerror'];
|
||||
const dtlsMethods=['getRemoteCertificates'];
|
||||
const ready=async pc=>{const transceiver=pc.addTransceiver('audio');await pc.setLocalDescription(await pc.createOffer());assert(transceiver.sender.transport,'missing DTLS association');return transceiver;};
|
||||
for(const [realm,w] of [['main',window],['iframe',child]]){
|
||||
const run=(name,body,config)=>check(`${realm}: ${name}`,async()=>{const pc=new w.RTCPeerConnection(config);try{await body(pc);}finally{w.RTCPeerConnection.prototype.close.call(pc);}});
|
||||
const get=(name,property,object)=>w.Object.getOwnPropertyDescriptor(w[name].prototype,property).get.call(object);
|
||||
await run('transport constructors are illegal and core declarations have native descriptors',pc=>{
|
||||
for(const [name,attributes,methods] of [['RTCIceTransport',iceAttributes,iceMethods],['RTCDtlsTransport',dtlsAttributes,dtlsMethods]]){
|
||||
assert(caught(()=>new w[name]()) instanceof w.TypeError);
|
||||
for(const property of attributes){const d=w.Object.getOwnPropertyDescriptor(w[name].prototype,property);assert(d&&d.enumerable&&d.configurable&&typeof d.get==='function');assert(d.get.name==='get '+property&&d.get.length===0);assert(property.startsWith('on')?typeof d.set==='function'&&d.set.length===1:d.set===undefined);}
|
||||
for(const method of methods){const d=w.Object.getOwnPropertyDescriptor(w[name].prototype,method);assert(d&&d.writable&&d.enumerable&&d.configurable&&d.value.name===method&&d.value.length===0);}
|
||||
}
|
||||
});
|
||||
await run('new transceivers have no MID or endpoint transport',pc=>{const t=pc.addTransceiver('audio');assert(t.mid===null&&t.sender.transport===null&&t.receiver.transport===null);});
|
||||
await run('offer creation reserves SDP credentials without exposing transport or MID',async pc=>{
|
||||
const t=pc.addTransceiver('audio'),offer=await pc.createOffer();assert(t.mid===null&&t.sender.transport===null&&t.receiver.transport===null);const c=credentials(parts(offer.sdp)[0]);assert(c.usernameFragment.length>=4&&c.password.length>=22&&parts(offer.sdp)[0].includes('a=setup:actpass'));
|
||||
});
|
||||
await run('local description associates sender and receiver with one native DTLS and ICE',async pc=>{
|
||||
const t=await ready(pc),dtls=t.sender.transport,ice=dtls.iceTransport;
|
||||
assert(dtls===t.receiver.transport&&dtls===t.sender.transport&&ice===dtls.iceTransport);
|
||||
assert(w.Object.getPrototypeOf(dtls)===w.RTCDtlsTransport.prototype&&w.Object.getPrototypeOf(ice)===w.RTCIceTransport.prototype);
|
||||
assert(dtls instanceof w.EventTarget&&ice instanceof w.EventTarget&&dtls.state==='new'&&ice.state==='new'&&t.mid===mids(pc.localDescription.sdp)[0]);
|
||||
});
|
||||
await run('ungathered ICE exposes the normative component and unknown role',async pc=>{
|
||||
const ice=(await ready(pc)).sender.transport.iceTransport;assert(ice.component==='rtp'&&ice.role==='unknown'&&ice.gatheringState==='new'&&ice.getSelectedCandidatePair()===null&&ice.getRemoteParameters()===null);
|
||||
});
|
||||
await run('candidate and certificate results are fresh sequences',async pc=>{
|
||||
const dtls=(await ready(pc)).sender.transport,ice=dtls.iceTransport;
|
||||
for(const [object,name] of [[ice,'getLocalCandidates'],[ice,'getRemoteCandidates'],[dtls,'getRemoteCertificates']]){const a=object[name](),b=object[name]();assert(w.Array.isArray(a)&&a!==b&&a.length===0&&b.length===0);a.push('author');assert(object[name]().length===0);}
|
||||
});
|
||||
await run('local parameters are fresh dictionaries matching the applied SDP',async pc=>{
|
||||
const t=await ready(pc),ice=t.sender.transport.iceTransport,a=ice.getLocalParameters(),b=ice.getLocalParameters(),c=credentials(parts(pc.localDescription.sdp)[0]);
|
||||
assert(a&&b&&a!==b&&w.Object.getPrototypeOf(a)===w.Object.prototype&&a.usernameFragment===c.usernameFragment&&a.password===c.password);
|
||||
a.usernameFragment='author';a.password='author';assert(ice.getLocalParameters().usernameFragment===c.usernameFragment&&ice.getLocalParameters().password===c.password);
|
||||
});
|
||||
for(const policy of ['balanced','max-compat','max-bundle'])await run(`${policy} shares only the prescribed local transport and credentials`,async pc=>{
|
||||
const ts=['audio','audio','video'].map(kind=>pc.addTransceiver(kind));pc.createDataChannel('data');await pc.setLocalDescription(await pc.createOffer());
|
||||
const transports=ts.map(t=>t.sender.transport);assert(transports.every((d,i)=>d&&d===ts[i].receiver.transport));
|
||||
const cs=parts(pc.localDescription.sdp).map(credentials),same=policy==='max-bundle';assert(new w.Set(transports).size===(same?1:3));
|
||||
assert(cs.every(c=>c.usernameFragment.length>=4&&c.password.length>=22));if(same)assert(new w.Set(cs.map(c=>c.usernameFragment)).size===1&&new w.Set(cs.map(c=>c.password)).size===1);
|
||||
},{bundlePolicy:policy});
|
||||
await run('repeated local offers retain associated MID and transport identities',async pc=>{
|
||||
const t=await ready(pc),dtls=t.sender.transport,ice=dtls.iceTransport,mid=t.mid;await pc.setLocalDescription(await pc.createOffer());assert(t.mid===mid&&t.sender.transport===dtls&&t.receiver.transport===dtls&&dtls.iceTransport===ice);
|
||||
});
|
||||
await run('applying an older offer does not associate a later transceiver',async pc=>{
|
||||
const a=pc.addTransceiver('audio'),offer=await pc.createOffer(),b=pc.addTransceiver('video');await pc.setLocalDescription(offer);
|
||||
assert(a.mid===mids(offer.sdp)[0]&&a.sender.transport&&b.mid===null&&b.sender.transport===null&&b.receiver.transport===null);
|
||||
await pc.setLocalDescription(await pc.createOffer());assert(b.mid!==null&&b.mid!==a.mid&&b.sender.transport);
|
||||
});
|
||||
await run('new transceivers preserve an already offered data media section index',async pc=>{
|
||||
pc.createDataChannel('first');const a=pc.addTransceiver('audio');await pc.setLocalDescription();const first=parts(pc.localDescription.sdp),old=mids(pc.localDescription.sdp);const b=pc.addTransceiver('video');await pc.setLocalDescription();
|
||||
const next=parts(pc.localDescription.sdp);assert(next.length===3&&next[0].split(' ')[0]===first[0].split(' ')[0]&&next[1].split(' ')[0]===first[1].split(' ')[0]&&mids(pc.localDescription.sdp).slice(0,2).join('|')===old.join('|')&&b.sender.transport&&a.sender.transport);
|
||||
});
|
||||
await run('stopping an unassociated transceiver does not consume an SDP section',async pc=>{
|
||||
const stopped=pc.addTransceiver('audio'),live=pc.addTransceiver('video');stopped.stop();const offer=await pc.createOffer();await pc.setLocalDescription(offer);
|
||||
assert(parts(offer.sdp).length===1&&stopped.mid===null&&stopped.sender.transport===null&&live.mid===mids(offer.sdp)[0]&&live.sender.transport);
|
||||
});
|
||||
await run('an associated stopped section keeps its MID and is rejected',async pc=>{
|
||||
const a=await ready(pc),old=a.mid,b=pc.addTransceiver('video');a.stop();const offer=await pc.createOffer();await pc.setLocalDescription(offer);
|
||||
const sections=parts(offer.sdp);assert(sections.length===2&§ions[0].startsWith('audio 0 ')&§ions[0].includes('a=inactive')&&a.mid===old&&b.mid!==old&&b.sender.transport);
|
||||
});
|
||||
await run('rollback detaches endpoints and closes only the old DTLS object',async pc=>{
|
||||
const t=await ready(pc),dtls=t.sender.transport,ice=dtls.iceTransport;await pc.setLocalDescription({type:'rollback'});
|
||||
assert(pc.localDescription===null&&t.mid===null&&t.sender.transport===null&&t.receiver.transport===null&&dtls.state==='closed'&&ice.state==='new'&&ice.getLocalParameters()===null);
|
||||
});
|
||||
await run('rollback emits one trusted DTLS statechange in listener order',async pc=>{
|
||||
const dtls=(await ready(pc)).sender.transport,ice=dtls.iceTransport,trace=[],events=[];let iceEvents=0;
|
||||
dtls.addEventListener('statechange',e=>{trace.push('first');events.push(e);assert(e.target===dtls&&e.currentTarget===dtls&&dtls.state==='closed');});
|
||||
dtls.onstatechange=()=>trace.push('handler');dtls.addEventListener('statechange',()=>trace.push('last'));ice.onstatechange=()=>iceEvents++;
|
||||
await pc.setLocalDescription({type:'rollback'});await tick();assert(trace.join('|')==='first|handler|last'&&events.length===1&&iceEvents===0);
|
||||
const e=events[0];assert(e instanceof w.Event&&w.Object.getPrototypeOf(e)===w.Event.prototype&&e.isTrusted&&!e.bubbles&&!e.cancelable&&!e.composed&&e.currentTarget===null);
|
||||
});
|
||||
await run('a new offer after rollback uses fresh transports and unused MIDs',async pc=>{
|
||||
const t=await ready(pc),old=t.sender.transport,mid=t.mid;await pc.setLocalDescription({type:'rollback'});await pc.setLocalDescription();
|
||||
assert(t.sender.transport&&t.sender.transport!==old&&t.sender.transport===t.receiver.transport&&t.mid!==mid&&old.state==='closed'&&old.iceTransport.state==='new');
|
||||
});
|
||||
await run('reapplying a saved generated offer creates a new association after rollback',async pc=>{
|
||||
const t=pc.addTransceiver('audio'),offer=await pc.createOffer();await pc.setLocalDescription(offer);const old=t.sender.transport;assert(old);await pc.setLocalDescription({type:'rollback'});await pc.setLocalDescription(offer);
|
||||
assert(t.mid===mids(offer.sdp)[0]&&t.sender.transport&&t.sender.transport!==old&&old.state==='closed');
|
||||
});
|
||||
await run('connection close closes both transports synchronously without state events',async pc=>{
|
||||
const t=await ready(pc),dtls=t.sender.transport,ice=dtls.iceTransport;let calls=0;dtls.onstatechange=()=>calls++;ice.onstatechange=()=>calls++;
|
||||
pc.close();assert(dtls.state==='closed'&&ice.state==='closed'&&t.sender.transport===dtls&&t.receiver.transport===dtls);await tick();assert(calls===0&&ice.getSelectedCandidatePair()===null);
|
||||
});
|
||||
await run('connection close also reaches ICE retained after rollback',async pc=>{
|
||||
const t=await ready(pc),old=t.sender.transport;await pc.setLocalDescription({type:'rollback'});await pc.setLocalDescription();const current=t.sender.transport;
|
||||
pc.close();assert(old.state==='closed'&&old.iceTransport.state==='closed'&¤t.state==='closed'&¤t.iceTransport.state==='closed');
|
||||
});
|
||||
await run('connection shutdown ignores author transport properties and methods',async pc=>{
|
||||
const dtls=(await ready(pc)).sender.transport,ice=dtls.iceTransport;let reads=0;
|
||||
for(const [object,properties] of [[dtls,['state','iceTransport','onstatechange']],[ice,['state','onstatechange']]])for(const name of properties)w.Object.defineProperty(object,name,{get(){reads++;throw Error('author getter');},configurable:true});
|
||||
ice.stop=()=>{reads++;throw Error('author method');};pc.close();assert(get('RTCDtlsTransport','state',dtls)==='closed'&&get('RTCIceTransport','state',ice)==='closed'&&reads===0);
|
||||
});
|
||||
await run('transport allocation and registries use intrinsic constructors and collections',async pc=>{
|
||||
const t=pc.addTransceiver('audio'),originals=w.Object.fromEntries(['RTCDtlsTransport','RTCIceTransport','Set','Map'].map(name=>[name,w[name]]));
|
||||
const methods=[];for(const name of ['Set','Map'])for(const key of ['add','set','get','has','clear','values'])if(typeof originals[name].prototype[key]==='function')methods.push([originals[name].prototype,key,originals[name].prototype[key]]);
|
||||
let calls=0;try{
|
||||
for(const name of w.Object.keys(originals))w[name]=function(){calls++;throw Error('author constructor');};for(const [prototype,key] of methods)prototype[key]=function(){calls++;throw Error('author collection');};
|
||||
await pc.setLocalDescription(await pc.createOffer());const dtls=t.sender.transport,ice=dtls.iceTransport;assert(w.Object.getPrototypeOf(dtls)===originals.RTCDtlsTransport.prototype&&w.Object.getPrototypeOf(ice)===originals.RTCIceTransport.prototype);pc.close();assert(calls===0&&dtls.state==='closed'&&ice.state==='closed');
|
||||
}finally{for(const [name,value] of w.Object.entries(originals))w[name]=value;for(const [prototype,key,value] of methods)prototype[key]=value;}
|
||||
});
|
||||
await run('transport EventHandlers retain objects and clear primitives without conversion',async pc=>{
|
||||
const dtls=(await ready(pc)).sender.transport,ice=dtls.iceTransport;let reads=0,calls=0;const object={get handleEvent(){reads++;throw Error('handleEvent');},toString(){reads++;throw Error('conversion');}};
|
||||
for(const [target,names] of [[dtls,['onstatechange','onerror']],[ice,['onstatechange','ongatheringstatechange','onselectedcandidatepairchange']]])for(const name of names){
|
||||
const fn=function(e){assert(this===target&&e.type===name.slice(2));calls++;};target[name]=fn;assert(target[name]===fn);target.dispatchEvent(new w.Event(name.slice(2)));target[name]=object;assert(target[name]===object);target.dispatchEvent(new w.Event(name.slice(2)));
|
||||
for(const value of [undefined,null,false,1,1n,'text',Symbol()]){target[name]=value;assert(target[name]===null);}
|
||||
}assert(calls===5&&reads===0);
|
||||
});
|
||||
await run('all transport bindings reject forged and author Proxy receivers before traps',async pc=>{
|
||||
const dtls=(await ready(pc)).sender.transport;let reads=0,conversions=0;const extra={toString(){conversions++;throw Error('conversion');}};
|
||||
for(const [name,real,attributes,methods] of [['RTCDtlsTransport',dtls,dtlsAttributes,dtlsMethods],['RTCIceTransport',dtls.iceTransport,iceAttributes,iceMethods]]){
|
||||
const proxy=new w.Proxy(real,{get(){reads++;throw Error('get');},getPrototypeOf(){reads++;throw Error('prototype');}}),revoked=w.Proxy.revocable(real,{});revoked.revoke();
|
||||
for(const receiver of [{},w.Object.create(w[name].prototype),w.Object.create(real),proxy,revoked.proxy,null,undefined]){
|
||||
for(const property of attributes){const d=w.Object.getOwnPropertyDescriptor(w[name].prototype,property);if(!d&&property==='component')continue;assert(caught(()=>d.get.call(receiver)) instanceof w.TypeError,`${name}.${property} getter brand`);if(d.set)assert(caught(()=>d.set.call(receiver,extra)) instanceof w.TypeError,`${name}.${property} setter brand`);}
|
||||
for(const method of methods)assert(caught(()=>w[name].prototype[method].call(receiver,extra)) instanceof w.TypeError);
|
||||
}
|
||||
}assert(reads===0&&conversions===0);
|
||||
});
|
||||
}
|
||||
for(const [name,callee,owner] of [['child callee',child,window],['main callee',window,child]]){
|
||||
await check(`${name}: borrowed local description creates transports in the connection realm`,async()=>{
|
||||
const pc=new owner.RTCPeerConnection(),t=pc.addTransceiver('audio');try{const offer=await callee.RTCPeerConnection.prototype.createOffer.call(pc);await callee.RTCPeerConnection.prototype.setLocalDescription.call(pc,offer);const dtls=t.sender.transport;assert(dtls&&owner.Object.getPrototypeOf(dtls)===owner.RTCDtlsTransport.prototype&&owner.Object.getPrototypeOf(dtls.iceTransport)===owner.RTCIceTransport.prototype);}finally{pc.close();}
|
||||
});
|
||||
await check(`${name}: borrowed transport accessors validate brands in the callee realm`,async()=>{
|
||||
const pc=new owner.RTCPeerConnection();try{const dtls=(await ready(pc)).sender.transport;
|
||||
for(const [name,real,properties,methods] of [['RTCDtlsTransport',dtls,dtlsAttributes,dtlsMethods],['RTCIceTransport',dtls.iceTransport,iceAttributes,iceMethods]]){
|
||||
for(const property of properties){const d=callee.Object.getOwnPropertyDescriptor(callee[name].prototype,property);if(!d&&property==='component')continue;assert(d.get.call(real)===owner.Object.getOwnPropertyDescriptor(owner[name].prototype,property).get.call(real));const error=caught(()=>d.get.call(new owner.Proxy(real,{})));assert(error instanceof callee.TypeError&&!(error instanceof owner.TypeError));}
|
||||
for(const method of methods){const fn=callee[name].prototype[method],error=caught(()=>fn.call(new owner.Proxy(real,{})));assert(error instanceof callee.TypeError&&!(error instanceof owner.TypeError));const result=fn.call(real);assert(result===null||typeof result==='object');}
|
||||
}
|
||||
}finally{pc.close();}
|
||||
});
|
||||
}
|
||||
globalThis.__uiEventResults={complete:true,passed:checks.filter(row=>row.passed).length,total:checks.length,checks};return checks.every(row=>row.passed);
|
||||
})()
|
||||
@@ -11,7 +11,7 @@ use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
|
||||
use moli_webidl::{self as webidl, WebIdlDictionarySerialize};
|
||||
|
||||
pub mod certificate;
|
||||
mod configuration;
|
||||
pub mod configuration;
|
||||
pub mod operations;
|
||||
mod peer_options;
|
||||
pub mod rtp_capabilities;
|
||||
@@ -228,12 +228,11 @@ fn offer_sdp<'s>(
|
||||
target: v8::Local<'s, v8::Object>,
|
||||
audio: bool,
|
||||
video: bool,
|
||||
) -> String {
|
||||
) -> Option<String> {
|
||||
let data = get_private_value(scope, target, RTC_PEER_CONNECTION_HAS_DATA_CHANNEL_SLOT)
|
||||
.expect("data channel flag")
|
||||
.boolean_value(scope);
|
||||
let mut sdp = rtp_transceivers::create_offer(scope, target, data)
|
||||
.unwrap_or_else(|| build_signaling_only_offer(audio, video, data));
|
||||
let mut sdp = rtp_transceivers::offer_sdp(scope, target, audio, video, data)?;
|
||||
let config = configuration::configuration(scope, target);
|
||||
let config = moli_webapi_declare::WebApiValue::to_v8_value(&config, scope)
|
||||
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
|
||||
@@ -242,7 +241,7 @@ fn offer_sdp<'s>(
|
||||
certificate::connection_fingerprints(scope, config, &mut fingerprints);
|
||||
let at = sdp.find("m=").unwrap_or(sdp.len());
|
||||
sdp.insert_str(at, &fingerprints);
|
||||
sdp
|
||||
Some(sdp)
|
||||
}
|
||||
pub fn complete_create_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
@@ -252,7 +251,9 @@ pub fn complete_create_offer<'s>(
|
||||
let options = operations::payload(scope, request)
|
||||
.int32_value(scope)
|
||||
.expect("native offer options");
|
||||
let sdp = offer_sdp(scope, pc, options & 1 != 0, options & 2 != 0);
|
||||
let Some(sdp) = offer_sdp(scope, pc, options & 1 != 0, options & 2 != 0) else {
|
||||
return false;
|
||||
};
|
||||
if let Err(error) = sdp::parse(&sdp) {
|
||||
return reject_sdp_error(scope, request, &error);
|
||||
}
|
||||
@@ -358,6 +359,7 @@ pub fn complete_set_local_description<'s>(
|
||||
return true;
|
||||
}
|
||||
if kind == "rollback" {
|
||||
rtp_transceivers::rollback_local_offer(scope, pc);
|
||||
set_private_value(scope, pc, signaling::PENDING_LOCAL, v8::null(scope).into());
|
||||
set_string_slot(
|
||||
scope,
|
||||
@@ -371,7 +373,9 @@ pub fn complete_set_local_description<'s>(
|
||||
.expect("last offer options")
|
||||
.int32_value(scope)
|
||||
.expect("offer option bits");
|
||||
let text = offer_sdp(scope, pc, options & 1 != 0, options & 2 != 0);
|
||||
let Some(text) = offer_sdp(scope, pc, options & 1 != 0, options & 2 != 0) else {
|
||||
return false;
|
||||
};
|
||||
let Some(value) = v8_string(scope, &text) else {
|
||||
return false;
|
||||
};
|
||||
@@ -387,6 +391,9 @@ pub fn complete_set_local_description<'s>(
|
||||
let Some(description) = session_description::from_parts(scope, kind, sdp) else {
|
||||
return false;
|
||||
};
|
||||
if rtp_transceivers::apply_local_offer(scope, pc).is_none() {
|
||||
return false;
|
||||
}
|
||||
set_private_value(scope, pc, signaling::PENDING_LOCAL, description.into());
|
||||
set_string_slot(
|
||||
scope,
|
||||
@@ -401,7 +408,7 @@ pub fn complete_set_local_description<'s>(
|
||||
if next != state && !signaling::dispatch_state_change(scope, pc) {
|
||||
return false;
|
||||
}
|
||||
// No ICE/DTLS transport or fabricated candidates are produced.
|
||||
// Local association does not fabricate gathering, candidates or a handshake.
|
||||
operations::resolve(scope, request, v8::undefined(scope).into());
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
//! Configuration dictionaries and snapshots, independent of an ICE transport.
|
||||
//! Argument conversion completes before inspecting or changing connection state.
|
||||
|
||||
use super::{
|
||||
RTC_PEER_CONNECTION_CONFIGURATION_SLOT,
|
||||
RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT,
|
||||
};
|
||||
use super::{RTC_PEER_CONNECTION_CONFIGURATION_SLOT, RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT};
|
||||
use crate::interfaces as web_api_interfaces;
|
||||
use moli_v8_util::{get_private_value, v8str};
|
||||
use moli_webapi_declare::WebApiValue;
|
||||
@@ -193,6 +190,18 @@ pub(super) fn configuration<'s>(
|
||||
.expect("native RTCConfiguration snapshot")
|
||||
}
|
||||
|
||||
pub fn max_bundle<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::Object>) -> bool {
|
||||
let config = configuration(scope, pc);
|
||||
let config = config
|
||||
.to_v8_value(scope)
|
||||
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
|
||||
.expect("configuration snapshot record");
|
||||
config
|
||||
.get(scope, v8str(scope, "bundlePolicy").into())
|
||||
.expect("copied bundle policy")
|
||||
.strict_equals(v8str(scope, "max-bundle").into())
|
||||
}
|
||||
|
||||
pub(super) fn get_configuration<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
args: v8::FunctionCallbackArguments<'s>,
|
||||
|
||||
@@ -2,16 +2,15 @@
|
||||
|
||||
pub const NEGOTIATION_HANDLER: &str = "__moliRtcOnNegotiationNeeded";
|
||||
|
||||
pub type ConnectionOperation = for<'s, 'p> fn(
|
||||
&mut v8::PinScope<'s, 'p>,
|
||||
v8::Local<'s, v8::Object>,
|
||||
);
|
||||
pub type ConnectionOperation = for<'s, 'p> fn(&mut v8::PinScope<'s, 'p>, v8::Local<'s, v8::Object>);
|
||||
pub type InitializeConnection =
|
||||
for<'s, 'p> fn(&mut v8::PinScope<'s, 'p>, v8::Local<'s, v8::Object>) -> Option<()>;
|
||||
pub type CreateOffer = for<'s, 'p> fn(
|
||||
&mut v8::PinScope<'s, 'p>,
|
||||
v8::Local<'s, v8::Object>,
|
||||
bool,
|
||||
bool,
|
||||
bool,
|
||||
) -> Option<String>;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -19,6 +18,8 @@ pub struct RtpRuntime {
|
||||
pub initialize_pc: InitializeConnection,
|
||||
pub close: ConnectionOperation,
|
||||
pub create_offer: CreateOffer,
|
||||
pub apply_local_offer: InitializeConnection,
|
||||
pub rollback_local_offer: ConnectionOperation,
|
||||
}
|
||||
|
||||
pub fn install_runtime(scope: &mut v8::PinScope<'_, '_>, runtime: RtpRuntime) {
|
||||
@@ -26,7 +27,9 @@ pub fn install_runtime(scope: &mut v8::PinScope<'_, '_>, runtime: RtpRuntime) {
|
||||
}
|
||||
|
||||
fn runtime(scope: &mut v8::PinScope<'_, '_>) -> RtpRuntime {
|
||||
*scope.get_current_context().get_slot::<RtpRuntime>()
|
||||
*scope
|
||||
.get_current_context()
|
||||
.get_slot::<RtpRuntime>()
|
||||
.expect("install the RTP runtime before invoking RTC bindings")
|
||||
}
|
||||
|
||||
@@ -41,20 +44,21 @@ pub(super) fn close<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::
|
||||
(runtime(scope).close)(scope, pc);
|
||||
}
|
||||
|
||||
pub(super) fn create_offer<'s>(
|
||||
pub(super) fn offer_sdp<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
audio: bool,
|
||||
video: bool,
|
||||
data: bool,
|
||||
) -> Option<String> {
|
||||
(runtime(scope).create_offer)(scope, pc, data)
|
||||
(runtime(scope).create_offer)(scope, pc, audio, video, data)
|
||||
}
|
||||
|
||||
pub(super) fn target<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
object: v8::Local<'s, v8::Object>,
|
||||
) -> v8::Local<'s, v8::Object> {
|
||||
moli_webapi_declare::web_api_object_target(scope, object)
|
||||
.expect("RTCPeerConnection receiver")
|
||||
moli_webapi_declare::web_api_object_target(scope, object).expect("RTCPeerConnection receiver")
|
||||
}
|
||||
|
||||
pub(super) fn closed<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8::Object>) -> bool {
|
||||
@@ -62,3 +66,17 @@ pub(super) fn closed<'s>(scope: &mut v8::PinScope<'s, '_>, pc: v8::Local<'s, v8:
|
||||
.expect("PC state")
|
||||
.strict_equals(moli_v8_util::v8str(scope, "closed").into())
|
||||
}
|
||||
|
||||
pub(super) fn apply_local_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) -> Option<()> {
|
||||
(runtime(scope).apply_local_offer)(scope, pc)
|
||||
}
|
||||
|
||||
pub(super) fn rollback_local_offer<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
pc: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
(runtime(scope).rollback_local_offer)(scope, pc);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user