Skip to content

Truly independent web browser

LibWeb+LibWebView+WebContent+WebWorker: Implement WebRTC

Ali Mohammad Pur194c6446961a
diff --git a/AK/Debug.h.in b/AK/Debug.h.in
index 7ebf8d043ec..3459b66cab7 100644
--- a/AK/Debug.h.in
+++ b/AK/Debug.h.in
@@ -274,6 +274,10 @@
# cmakedefine01 WEB_WORKER_DEBUG
#endif
+#ifndef WEBRTC_DEBUG
+# cmakedefine01 WEBRTC_DEBUG
+#endif
+
#ifndef XML_PARSER_DEBUG
# cmakedefine01 XML_PARSER_DEBUG
#endif
diff --git a/Libraries/LibAudio/Forward.h b/Libraries/LibAudio/Forward.h
index 47e433264cf..74512ad8af6 100644
--- a/Libraries/LibAudio/Forward.h
+++ b/Libraries/LibAudio/Forward.h
@@ -12,5 +12,6 @@ class ClientConnection;
class OutputSession;
class PlaybackStream;
class RecordStream;
+class SampleSpecification;
}
diff --git a/Libraries/LibMedia/Forward.h b/Libraries/LibMedia/Forward.h
index df85a6956b1..73b8f01dd47 100644
--- a/Libraries/LibMedia/Forward.h
+++ b/Libraries/LibMedia/Forward.h
@@ -37,3 +37,11 @@ class VideoPresentationServerConnection;
class VideoSink;
}
+
+namespace Media::FFmpeg {
+
+class FFmpegAudioConverter;
+class FFmpegAudioDecoder;
+class FFmpegAudioEncoder;
+
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index 0c30f70fdd6..c6ff07b8902 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -129,7 +129,7 @@ impl<'a, 'memory> SerializationWriter<'a, 'memory> {
object: &T,
for_storage: bool,
) -> WebIdlResult<()> {
- encode_serializable_object_header(self.serialized(), T::INTERFACE_NAME);
+ encode_serializable_object_header(self.serialized(), T::INTERFACE_NAME)?;
object.serialization_steps(cx, self, for_storage)
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
index a7d64e53c4f..394e90ff9b0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/cpp.rs
@@ -27,6 +27,7 @@ unsafe extern "C" {
count: usize,
);
fn web_structured_serialize_set_storage_record(record: *mut c_void, data: ak::Span<'_, u8>);
+ fn web_structured_serialize_is_ipc_interface(interface_name: u16) -> bool;
fn web_structured_serialize_interface_storage_identifier(
interface_name: u16,
identifier: &mut ak::Span<'static, u8>,
@@ -246,6 +247,12 @@ impl StorageSerializationRecord {
}
}
+/// Whether IPC records can contain this interface, including interfaces that cannot be stored.
+pub(crate) fn is_ipc_interface(interface_name: u16) -> bool {
+ // SAFETY: The call takes an interface identifier by value.
+ unsafe { web_structured_serialize_is_ipc_interface(interface_name) }
+}
+
/// The identifier of the serializable interface that a storage record holds, from LibWeb's registry of them, if the
/// Bindings::InterfaceName names one.
pub(crate) fn serializable_interface_storage_identifier(interface_name: u16) -> Option<&'static [u8]> {
@@ -465,6 +472,8 @@ pub(crate) enum SerializableSteps {
QuotaExceededError,
/// The steps of CryptoKey, which run in crate::crypto::crypto_key.
CryptoKey,
+ /// The steps of RTCEncodedAudioFrame, which run in crate::webrtc::rtc_encoded_audio_frame.
+ RTCEncodedAudioFrame,
}
pub(crate) fn serializable_steps(interface_name: u16) -> SerializableSteps {
@@ -474,6 +483,7 @@ pub(crate) fn serializable_steps(interface_name: u16) -> SerializableSteps {
1 => SerializableSteps::DOMException,
2 => SerializableSteps::QuotaExceededError,
3 => SerializableSteps::CryptoKey,
+ 4 => SerializableSteps::RTCEncodedAudioFrame,
steps => unreachable!("LibWeb names no serializable steps {steps}"),
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
index 4e24665a979..e34d2c71e71 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/mod.rs
@@ -39,9 +39,9 @@ use crate::html::structured_serialize::cpp::{
TransferDataHolder, create_transferred_platform_object, current_settings_object_agent_cluster,
current_settings_object_cross_origin_isolated_capability, data_clone_error_from_serialization_error,
deserialize_rust_platform_object, is_exposed, is_platform_object, is_transferable,
- is_transferable_interface_exposed, realm_agent_cluster, serializable_interface_name, serializable_payload_version,
- serializable_steps, serialization_steps, transfer_steps, transferable_is_detached, transferable_primary_interface,
- transferable_set_detached,
+ is_transferable_interface_exposed, realm_agent_cluster, serializable_interface_name,
+ serializable_interface_storage_identifier, serializable_payload_version, serializable_steps, serialization_steps,
+ transfer_steps, transferable_is_detached, transferable_primary_interface, transferable_set_detached,
};
use crate::html::structured_serialize::memory::{DeserializationMemory, SerializationMemory};
use crate::html::structured_serialize::message_record::MessageRecord;
@@ -747,7 +747,7 @@ impl<'memory> Serializer<'_, '_, 'memory> {
// 2. Let typeString be the identifier of the primary interface of value.
// 3. Set serialized to { [[Type]]: typeString }.
- encode_serializable_object_header(serialized, interface_name);
+ encode_serializable_object_header(serialized, interface_name)?;
// FIXME: 4. If value's primary interface is decorated with [SameAgentCluster], then set sameAgentCluster to true.
@@ -861,6 +861,13 @@ impl<'memory> Serializer<'_, '_, 'memory> {
quota_exceeded_error::serialization_steps(&QuotaExceededErrorFields::of(object), serialized);
}
SerializableSteps::CryptoKey => crypto_key::serialization_steps(object, serialized),
+ SerializableSteps::RTCEncodedAudioFrame => {
+ crate::webrtc::rtc_encoded_audio_frame::serialization_steps(
+ object,
+ &mut SerializationWriter::new(self),
+ self.for_storage,
+ )?;
+ }
SerializableSteps::Rust => {
let realm = self.realm.unwrap_or_else(|| object.shape().realm());
serialization_steps(
@@ -915,12 +922,21 @@ impl<'memory> Serializer<'_, '_, 'memory> {
}
}
-pub(crate) fn encode_serializable_object_header(serialized: &StructuredSerializeWriter, interface_name: u16) {
+pub(crate) fn encode_serializable_object_header(
+ serialized: &StructuredSerializeWriter,
+ interface_name: u16,
+) -> WebIdlResult<()> {
+ if serialized.serialization_type() == SerializationType::Storage
+ && serializable_interface_storage_identifier(interface_name).is_none()
+ {
+ return Err(data_clone_error("This interface cannot be serialized for storage"));
+ }
serialized.encode_u8(ValueTag::SerializableObject as u8);
serialized.encode_interface_name(interface_name);
if serialized.serialization_type() == SerializationType::Storage {
serialized.encode_u64(serializable_payload_version());
}
+ Ok(())
}
pub(crate) fn decode_serializable_object_header(
@@ -1424,7 +1440,7 @@ impl Deserializer<'_, '_, '_> {
// 3. Set value to a new instance of the interface identified by interfaceName, created in targetRealm.
// 4. Set deep to true.
// NB: The deserialization steps of an interface implemented in Rust, and those that run here for
- // DOMException, QuotaExceededError and CryptoKey, create the new instance from what they read, so
+ // C++ objects, create the new instance from what they read, so
// they run here, at the position in memory that the instance has, rather than in step 25.4.
let memory_index = self.memory.size();
self.memory.append(Value::UNDEFINED);
@@ -1440,6 +1456,12 @@ impl Deserializer<'_, '_, '_> {
SerializableSteps::CryptoKey => {
Value::from_object(crypto_key::deserialization_steps(realm, self.serialized)?)
}
+ SerializableSteps::RTCEncodedAudioFrame => {
+ Value::from_object(crate::webrtc::rtc_encoded_audio_frame::deserialization_steps(
+ realm,
+ &mut SerializationReader::new(self),
+ )?)
+ }
SerializableSteps::Rust => {
deserialize_rust_platform_object(interface_name, realm, &mut SerializationReader::new(self))?
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
index 18f5969dd6b..adf5275b5ad 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/structured_serialize/reader.rs
@@ -25,8 +25,8 @@ use libwebcommon_rust::html::serialization_records::{DecodeError, DecodedString,
use crate::bindings::WebIdlResult;
use crate::html::structured_serialize::cpp::{
- ReceivedIPCSerializationRecord, SharedBuffers, data_clone_error_from_serialization_error,
- serializable_interface_name_from_storage_identifier, serializable_interface_storage_identifier,
+ ReceivedIPCSerializationRecord, SharedBuffers, data_clone_error_from_serialization_error, is_ipc_interface,
+ serializable_interface_name_from_storage_identifier,
};
use crate::html::structured_serialize::message_record::MessageRecord;
@@ -172,7 +172,7 @@ impl<'a> StructuredSerializeReader<'a> {
let interface_name = match self.serialization_type() {
SerializationType::Ipc => {
let interface_name = self.decode_u16()?;
- serializable_interface_storage_identifier(interface_name).map(|_| interface_name)
+ is_ipc_interface(interface_name).then_some(interface_name)
}
SerializationType::Storage => match self.decode_utf16_string()?.as_units() {
ak::Utf16StringUnits::Ascii(identifier) => {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 59d14b4e2ba..d57aba4c099 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -153,6 +153,8 @@ pub(crate) mod web_assembly;
pub(crate) mod web_gl;
#[cfg(not(test))]
pub(crate) mod webidl;
+#[cfg(not(test))]
+pub(crate) mod webrtc;
// The generators of the build script, whose tests run with those of the crate.
#[cfg(test)]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/webrtc/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/webrtc/mod.rs
new file mode 100644
index 00000000000..847596979c4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/webrtc/mod.rs
@@ -0,0 +1,7 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+pub(crate) mod rtc_encoded_audio_frame;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/webrtc/rtc_encoded_audio_frame.rs b/Libraries/LibWeb/Bindings/Rust/src/webrtc/rtc_encoded_audio_frame.rs
new file mode 100644
index 00000000000..7f323cd5669
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/webrtc/rtc_encoded_audio_frame.rs
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{ArrayBuffer, Gc, Object, Realm, Value};
+
+use crate::bindings::structured_data::{SerializationReader, SerializationWriter};
+use crate::bindings::{Exception, WebIdlResult};
+
+#[repr(C)]
+#[derive(Default)]
+struct OptionalField<T> {
+ present: bool,
+ value: T,
+}
+
+impl<T: Default> From<Option<T>> for OptionalField<T> {
+ fn from(value: Option<T>) -> Self {
+ Self {
+ present: value.is_some(),
+ value: value.unwrap_or_default(),
+ }
+ }
+}
+
+// Matches RTCEncodedAudioFrameFields in WebRTC/RTCEncodedAudioFrame.cpp. Serialization takes ownership of
+// the string reference and borrows the span; deserialization lends both.
+#[repr(C)]
+struct RawFields<'a> {
+ synchronization_source: OptionalField<u32>,
+ payload_type: OptionalField<u8>,
+ contributing_sources: OptionalField<ak::Span<'a, u32>>,
+ rtp_timestamp: OptionalField<u32>,
+ receive_time: OptionalField<f64>,
+ capture_time: OptionalField<f64>,
+ sender_capture_time_offset: OptionalField<f64>,
+ mime_type: OptionalField<usize>,
+ sequence_number: OptionalField<i16>,
+ audio_level: OptionalField<f64>,
+}
+
+unsafe extern "C" {
+ fn web_rtc_encoded_audio_frame_with_fields(
+ frame: *mut c_void,
+ state: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *const RawFields<'_>),
+ ) -> *mut c_void;
+ fn web_rtc_encoded_audio_frame_create(realm: *mut c_void, fields: &RawFields<'_>, data: *mut c_void)
+ -> *mut c_void;
+}
+
+fn data_clone_error(message: &[u8]) -> Exception {
+ Exception::Dom("DataCloneError", Utf16String::from_ascii(message))
+}
+
+// https://w3c.github.io/webrtc-encoded-transform/#RTCEncodedAudioFrame-serialization
+pub(crate) fn serialization_steps(
+ frame: Gc<Object>,
+ serialized: &mut SerializationWriter,
+ for_storage: bool,
+) -> WebIdlResult<()> {
+ // 1. If forStorage is true, then throw a DataCloneError.
+ if for_storage {
+ return Err(data_clone_error(b"RTCEncodedAudioFrame is not storable"));
+ }
+
+ unsafe extern "C" fn write_metadata(state: *mut c_void, fields: *const RawFields<'_>) {
+ // SAFETY: The caller lends the writer and the frame's fields for this call.
+ let (serialized, fields) = unsafe { (&mut *state.cast::<SerializationWriter>(), &*fields) };
+ serialized.write_bool(fields.synchronization_source.present);
+ if fields.synchronization_source.present {
+ serialized.write_u32(fields.synchronization_source.value);
+ }
+ serialized.write_bool(fields.payload_type.present);
+ if fields.payload_type.present {
+ serialized.write_u8(fields.payload_type.value);
+ }
+ serialized.write_bool(fields.contributing_sources.present);
+ if fields.contributing_sources.present {
+ let sources = fields.contributing_sources.value.as_slice();
+ serialized.write_u64(sources.len() as u64);
+ for source in sources {
+ serialized.write_u32(*source);
+ }
+ }
+ serialized.write_bool(fields.rtp_timestamp.present);
+ if fields.rtp_timestamp.present {
+ serialized.write_u32(fields.rtp_timestamp.value);
+ }
+ serialized.write_bool(fields.receive_time.present);
+ if fields.receive_time.present {
+ serialized.write_f64(fields.receive_time.value);
+ }
+ serialized.write_bool(fields.capture_time.present);
+ if fields.capture_time.present {
+ serialized.write_f64(fields.capture_time.value);
+ }
+ serialized.write_bool(fields.sender_capture_time_offset.present);
+ if fields.sender_capture_time_offset.present {
+ serialized.write_f64(fields.sender_capture_time_offset.value);
+ }
+ serialized.write_bool(fields.mime_type.present);
+ if fields.mime_type.present {
+ // SAFETY: C++ hands over a reference to the string.
+ let mime_type = unsafe { Utf16String::from_raw_owned(fields.mime_type.value) };
+ serialized.write_utf16_string(&mime_type);
+ }
+ serialized.write_bool(fields.sequence_number.present);
+ if fields.sequence_number.present {
+ serialized.write_i32(i32::from(fields.sequence_number.value));
+ }
+ serialized.write_bool(fields.audio_level.present);
+ if fields.audio_level.present {
+ serialized.write_f64(fields.audio_level.value);
+ }
+ }
+
+ // 2. Set serialized.[[metadata]] to an internal representation of value's metadata.
+ // SAFETY: The frame is live, and the callback only writes its borrowed metadata.
+ let data = unsafe {
+ web_rtc_encoded_audio_frame_with_fields(
+ frame.as_ptr().cast(),
+ core::ptr::from_mut(serialized).cast(),
+ write_metadata,
+ )
+ };
+ // SAFETY: The frame owns the live ArrayBuffer returned by C++.
+ let data = unsafe { Gc::<Object>::from_non_null(NonNull::new(data.cast()).expect("a frame has data")) };
+ // 3. Set serialized.[[data]] to the sub-serialization of value.[[data]].
+ serialized.write_value(Value::from_object(data))
+}
+
+fn read_optional<T>(
+ serialized: &mut SerializationReader,
+ read: impl FnOnce(&mut SerializationReader) -> WebIdlResult<T>,
+) -> WebIdlResult<Option<T>> {
+ if serialized.read_bool()? {
+ Ok(Some(read(serialized)?))
+ } else {
+ Ok(None)
+ }
+}
+
+// https://w3c.github.io/webrtc-encoded-transform/#RTCEncodedAudioFrame-serialization
+pub(crate) fn deserialization_steps(
+ realm: Gc<Realm>,
+ serialized: &mut SerializationReader,
+) -> WebIdlResult<Gc<Object>> {
+ // 1. Set value's metadata to the platform object representation of serialized.[[metadata]].
+ let synchronization_source = read_optional(serialized, |s| s.read_u32())?;
+ let payload_type = read_optional(serialized, |s| s.read_u8())?;
+ let contributing_sources = read_optional(serialized, |serialized| {
+ let count = serialized.read_u64()?;
+ let mut sources = Vec::new();
+ for _ in 0..count {
+ sources.push(serialized.read_u32()?);
+ }
+ Ok(sources)
+ })?;
+ let rtp_timestamp = read_optional(serialized, |s| s.read_u32())?;
+ let receive_time = read_optional(serialized, |s| s.read_f64())?;
+ let capture_time = read_optional(serialized, |s| s.read_f64())?;
+ let sender_capture_time_offset = read_optional(serialized, |s| s.read_f64())?;
+ let mime_type = read_optional(serialized, |s| s.read_utf16_string())?;
+ let sequence_number = read_optional(serialized, |s| {
+ i16::try_from(s.read_i32()?).map_err(|_| data_clone_error(b"Invalid RTCEncodedAudioFrame sequence number"))
+ })?;
+ let audio_level = read_optional(serialized, |s| s.read_f64())?;
+ let fields = RawFields {
+ synchronization_source: synchronization_source.into(),
+ payload_type: payload_type.into(),
+ contributing_sources: contributing_sources.as_deref().map(ak::Span::new).into(),
+ rtp_timestamp: rtp_timestamp.into(),
+ receive_time: receive_time.into(),
+ capture_time: capture_time.into(),
+ sender_capture_time_offset: sender_capture_time_offset.into(),
+ mime_type: mime_type.as_ref().map(Utf16String::raw_identity).into(),
+ sequence_number: sequence_number.into(),
+ audio_level: audio_level.into(),
+ };
+
+ // 2. Set value.[[data]] to the sub-deserialization of serialized.[[data]].
+ let data = serialized.read_value()?;
+ let data = data
+ .is_object()
+ .then(|| data.as_object())
+ .and_then(|object| object.downcast::<ArrayBuffer>())
+ .ok_or_else(|| data_clone_error(b"RTCEncodedAudioFrame.[[data]] did not deserialize to an ArrayBuffer"))?;
+ // SAFETY: The realm and buffer are live; C++ borrows the metadata and copies it into the new frame.
+ let frame = unsafe { web_rtc_encoded_audio_frame_create(realm.as_ptr().cast(), &fields, data.as_ptr().cast()) };
+ // SAFETY: C++ returns the live wrapper of the new frame.
+ Ok(unsafe { Gc::from_non_null(NonNull::new(frame.cast()).expect("LibWeb creates the frame")) })
+}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index a50d0d1e3b3..a57cb7a4842 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1067,6 +1067,38 @@ set(SOURCES
WebIDL/OverloadTypes.cpp
WebIDL/Promise.cpp
WebIDL/QuotaExceededError.cpp
+ WebRTC/RTCCertificate.cpp
+ WebRTC/RTCDataChannel.cpp
+ WebRTC/RTCDataChannelEvent.cpp
+ WebRTC/RTCDtlsTransport.cpp
+ WebRTC/RTCDTMFSender.cpp
+ WebRTC/RTCDTMFToneChangeEvent.cpp
+ WebRTC/RTCEncodedAudioFrame.cpp
+ WebRTC/RTCEncodedVideoFrame.cpp
+ WebRTC/RTCError.cpp
+ WebRTC/RTCErrorEvent.cpp
+ WebRTC/RTCIceCandidate.cpp
+ WebRTC/RTCIceTransport.cpp
+ WebRTC/RTCPeerConnection.cpp
+ WebRTC/RTCPeerConnectionIceErrorEvent.cpp
+ WebRTC/RTCPeerConnectionIceEvent.cpp
+ WebRTC/RTCRtpReceiver.cpp
+ WebRTC/RTCRtpScriptTransform.cpp
+ WebRTC/RTCRtpScriptTransformer.cpp
+ WebRTC/RTCRtpSender.cpp
+ WebRTC/RTCRtpTransceiver.cpp
+ WebRTC/RTCSctpTransport.cpp
+ WebRTC/RTCSessionDescription.cpp
+ WebRTC/RTCSFrameReceiverTransform.cpp
+ WebRTC/RTCSFrameSenderTransform.cpp
+ WebRTC/RTCStatsReport.cpp
+ WebRTC/RTCTrackEvent.cpp
+ WebRTC/RTCTransformEvent.cpp
+ WebRTC/SFrameDecrypterStream.cpp
+ WebRTC/SFrameEncrypterStream.cpp
+ WebRTC/SFrameTransformErrorEvent.cpp
+ WebRTC/KeyFrameRequestEvent.cpp
+ WebRTC/WebRTCAgent.cpp
WebSockets/WebSocket.cpp
WebVTT/Parser.cpp
WebVTT/VTTCue.cpp
@@ -1132,7 +1164,7 @@ target_sources(LibWeb PRIVATE $<TARGET_OBJECTS:LibJSObjects>)
target_compile_definitions(LibWeb PRIVATE LibJS_EXPORTS)
target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon LibJSHeaders)
-target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
+target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibWebRTCClient LibXml2::LibXml2)
# LibWeb still includes ANGLE's GLES headers for WebGL constants and types, but
# the actual GL entry points live in the Compositor. Copy only ANGLE's compile
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index d10c6a3cc91..f583765054b 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -278,6 +278,7 @@
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/WebIDL/ObservableArray.h>
#include <LibWeb/WebIDL/Promise.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
#include <LibWeb/XHR/XMLHttpRequest.h>
#include <LibWeb/XPath/XPath.h>
#include <LibWebCommon/CSS/SystemColor.h>
@@ -6618,6 +6619,7 @@ void Document::run_unloading_cleanup_steps()
// opt not to follow the spec exactly in regards to this, instead letting the connection stay open until
// GC collects it. However, we need to be proactive about this when navigating for the sake of test-web.
window.close_all_idb_connections();
+ WebRTC::WebRTCAgent::the().close_connections_for_global(window.this_impl());
XHR::XMLHttpRequest::release_activity_roots_for_relevant_global_object(window.this_impl());
FileAPI::run_unloading_cleanup_steps(*this);
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 59439c4d691..f7dfa51b998 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -148,6 +148,42 @@ class MediaStreamTrack;
}
+namespace Web::WebRTC {
+
+class KeyFrameRequestEvent;
+class RTCCertificate;
+class RTCDataChannel;
+class RTCDataChannelEvent;
+class RTCDTMFSender;
+class RTCDTMFToneChangeEvent;
+class RTCDtlsTransport;
+class RTCEncodedAudioFrame;
+class RTCEncodedVideoFrame;
+class RTCError;
+class RTCErrorEvent;
+class RTCIceCandidate;
+class RTCIceTransport;
+class RTCPeerConnection;
+class RTCPeerConnectionIceErrorEvent;
+class RTCPeerConnectionIceEvent;
+class RTCRtpReceiver;
+class RTCRtpScriptTransform;
+class RTCRtpScriptTransformer;
+class RTCRtpSender;
+class RTCRtpTransceiver;
+class RTCSctpTransport;
+class RTCSessionDescription;
+class RTCSFrameReceiverTransform;
+class RTCSFrameSenderTransform;
+class RTCStatsReport;
+class RTCTrackEvent;
+class RTCTransformEvent;
+class SFrameDecrypterStream;
+class SFrameEncrypterStream;
+class SFrameTransformErrorEvent;
+
+}
+
namespace Web::Clipboard {
class Clipboard;
diff --git a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp
index c1b16ef053e..ebbc4c311d8 100644
--- a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp
@@ -224,4 +224,14 @@ WebIDL::CallbackType* DedicatedWorkerGlobalScope::onmessageerror()
return event_handler_attribute(EventNames::messageerror);
}
+WebIDL::CallbackType* DedicatedWorkerGlobalScope::onrtctransform()
+{
+ return event_handler_attribute(EventNames::rtctransform);
+}
+
+void DedicatedWorkerGlobalScope::set_onrtctransform(WebIDL::CallbackType* callback)
+{
+ set_event_handler_attribute(EventNames::rtctransform, callback);
+}
+
}
diff --git a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.h b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.h
index 7ab7a5c4f75..dda722f415e 100644
--- a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.h
+++ b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.h
@@ -49,6 +49,9 @@ public:
WebIDL::CallbackType* onmessageerror();
void set_onmessageerror(WebIDL::CallbackType* callback);
+ WebIDL::CallbackType* onrtctransform();
+ void set_onrtctransform(WebIDL::CallbackType* callback);
+
virtual void finalize() override;
private:
diff --git a/Libraries/LibWeb/HTML/EventNames.h b/Libraries/LibWeb/HTML/EventNames.h
index 0a0c31c92ff..b6f13ed2d9f 100644
--- a/Libraries/LibWeb/HTML/EventNames.h
+++ b/Libraries/LibWeb/HTML/EventNames.h
@@ -11,154 +11,169 @@
namespace Web::HTML::EventNames {
-#define ENUMERATE_HTML_EVENTS \
- __ENUMERATE_HTML_EVENT(abort) \
- __ENUMERATE_HTML_EVENT(addtrack) \
- __ENUMERATE_HTML_EVENT(afterprint) \
- __ENUMERATE_HTML_EVENT(animationcancel) \
- __ENUMERATE_HTML_EVENT(animationend) \
- __ENUMERATE_HTML_EVENT(animationiteration) \
- __ENUMERATE_HTML_EVENT(animationstart) \
- __ENUMERATE_HTML_EVENT(audioend) \
- __ENUMERATE_HTML_EVENT(audioprocess) \
- __ENUMERATE_HTML_EVENT(audiostart) \
- __ENUMERATE_HTML_EVENT(beginEvent) \
- __ENUMERATE_HTML_EVENT(beforeinput) \
- __ENUMERATE_HTML_EVENT(beforematch) \
- __ENUMERATE_HTML_EVENT(beforeprint) \
- __ENUMERATE_HTML_EVENT(beforetoggle) \
- __ENUMERATE_HTML_EVENT(beforeunload) \
- __ENUMERATE_HTML_EVENT(blocked) \
- __ENUMERATE_HTML_EVENT(blur) \
- __ENUMERATE_HTML_EVENT(boundary) \
- __ENUMERATE_HTML_EVENT(cancel) \
- __ENUMERATE_HTML_EVENT(canplay) \
- __ENUMERATE_HTML_EVENT(canplaythrough) \
- __ENUMERATE_HTML_EVENT(change) \
- __ENUMERATE_HTML_EVENT(click) \
- __ENUMERATE_HTML_EVENT(close) \
- __ENUMERATE_HTML_EVENT(command) \
- __ENUMERATE_HTML_EVENT(complete) \
- __ENUMERATE_HTML_EVENT(connect) \
- __ENUMERATE_HTML_EVENT(contextlost) \
- __ENUMERATE_HTML_EVENT(contextmenu) \
- __ENUMERATE_HTML_EVENT(contextrestored) \
- __ENUMERATE_HTML_EVENT(controllerchange) \
- __ENUMERATE_HTML_EVENT(copy) \
- __ENUMERATE_HTML_EVENT(cuechange) \
- __ENUMERATE_HTML_EVENT(currententrychange) \
- __ENUMERATE_HTML_EVENT(cut) \
- __ENUMERATE_HTML_EVENT(devicechange) \
- __ENUMERATE_HTML_EVENT(disconnect) \
- __ENUMERATE_HTML_EVENT(dispose) \
- __ENUMERATE_HTML_EVENT(DOMContentLoaded) \
- __ENUMERATE_HTML_EVENT(drag) \
- __ENUMERATE_HTML_EVENT(dragend) \
- __ENUMERATE_HTML_EVENT(dragenter) \
- __ENUMERATE_HTML_EVENT(dragleave) \
- __ENUMERATE_HTML_EVENT(dragover) \
- __ENUMERATE_HTML_EVENT(dragstart) \
- __ENUMERATE_HTML_EVENT(drop) \
- __ENUMERATE_HTML_EVENT(durationchange) \
- __ENUMERATE_HTML_EVENT(emptied) \
- __ENUMERATE_HTML_EVENT(end) \
- __ENUMERATE_HTML_EVENT(endEvent) \
- __ENUMERATE_HTML_EVENT(ended) \
- __ENUMERATE_HTML_EVENT(enter) \
- __ENUMERATE_HTML_EVENT(enterpictureinpicture) \
- __ENUMERATE_HTML_EVENT(error) \
- __ENUMERATE_HTML_EVENT(exit) \
- __ENUMERATE_HTML_EVENT(finish) \
- __ENUMERATE_HTML_EVENT(focus) \
- __ENUMERATE_HTML_EVENT(focusin) \
- __ENUMERATE_HTML_EVENT(focusout) \
- __ENUMERATE_HTML_EVENT(formdata) \
- __ENUMERATE_HTML_EVENT(fullscreenchange) \
- __ENUMERATE_HTML_EVENT(fullscreenerror) \
- __ENUMERATE_HTML_EVENT(hashchange) \
- __ENUMERATE_HTML_EVENT(input) \
- __ENUMERATE_HTML_EVENT(invalid) \
- __ENUMERATE_HTML_EVENT(languagechange) \
- __ENUMERATE_HTML_EVENT(leavepictureinpicture) \
- __ENUMERATE_HTML_EVENT(load) \
- __ENUMERATE_HTML_EVENT(loaded) \
- __ENUMERATE_HTML_EVENT(loadeddata) \
- __ENUMERATE_HTML_EVENT(loadedmetadata) \
- __ENUMERATE_HTML_EVENT(loadend) \
- __ENUMERATE_HTML_EVENT(loading) \
- __ENUMERATE_HTML_EVENT(loadingdone) \
- __ENUMERATE_HTML_EVENT(loadingerror) \
- __ENUMERATE_HTML_EVENT(loadstart) \
- __ENUMERATE_HTML_EVENT(mark) \
- __ENUMERATE_HTML_EVENT(message) \
- __ENUMERATE_HTML_EVENT(messageerror) \
- __ENUMERATE_HTML_EVENT(navigate) \
- __ENUMERATE_HTML_EVENT(navigateerror) \
- __ENUMERATE_HTML_EVENT(navigatesuccess) \
- __ENUMERATE_HTML_EVENT(nomatch) \
- __ENUMERATE_HTML_EVENT(offline) \
- __ENUMERATE_HTML_EVENT(online) \
- __ENUMERATE_HTML_EVENT(open) \
- __ENUMERATE_HTML_EVENT(pagehide) \
- __ENUMERATE_HTML_EVENT(pagereveal) \
- __ENUMERATE_HTML_EVENT(pageshow) \
- __ENUMERATE_HTML_EVENT(pageswap) \
- __ENUMERATE_HTML_EVENT(paste) \
- __ENUMERATE_HTML_EVENT(pause) \
- __ENUMERATE_HTML_EVENT(play) \
- __ENUMERATE_HTML_EVENT(playing) \
- __ENUMERATE_HTML_EVENT(popstate) \
- __ENUMERATE_HTML_EVENT(processorerror) \
- __ENUMERATE_HTML_EVENT(progress) \
- __ENUMERATE_HTML_EVENT(ratechange) \
- __ENUMERATE_HTML_EVENT(readystatechange) \
- __ENUMERATE_HTML_EVENT(rejectionhandled) \
- __ENUMERATE_HTML_EVENT(remove) \
- __ENUMERATE_HTML_EVENT(removetrack) \
- __ENUMERATE_HTML_EVENT(repeatEvent) \
- __ENUMERATE_HTML_EVENT(reset) \
- __ENUMERATE_HTML_EVENT(resize) \
- __ENUMERATE_HTML_EVENT(result) \
- __ENUMERATE_HTML_EVENT(resume) \
- __ENUMERATE_HTML_EVENT(scroll) \
- __ENUMERATE_HTML_EVENT(scrollend) \
- __ENUMERATE_HTML_EVENT(securitypolicyviolation) \
- __ENUMERATE_HTML_EVENT(seeked) \
- __ENUMERATE_HTML_EVENT(seeking) \
- __ENUMERATE_HTML_EVENT(select) \
- __ENUMERATE_HTML_EVENT(show) \
- __ENUMERATE_HTML_EVENT(selectionchange) \
- __ENUMERATE_HTML_EVENT(slotchange) \
- __ENUMERATE_HTML_EVENT(soundend) \
- __ENUMERATE_HTML_EVENT(soundstart) \
- __ENUMERATE_HTML_EVENT(speechend) \
- __ENUMERATE_HTML_EVENT(speechstart) \
- __ENUMERATE_HTML_EVENT(stalled) \
- __ENUMERATE_HTML_EVENT(start) \
- __ENUMERATE_HTML_EVENT(statechange) \
- __ENUMERATE_HTML_EVENT(storage) \
- __ENUMERATE_HTML_EVENT(submit) \
- __ENUMERATE_HTML_EVENT(success) \
- __ENUMERATE_HTML_EVENT(suspend) \
- __ENUMERATE_HTML_EVENT(timeupdate) \
- __ENUMERATE_HTML_EVENT(toggle) \
- __ENUMERATE_HTML_EVENT(transitioncancel) \
- __ENUMERATE_HTML_EVENT(transitionend) \
- __ENUMERATE_HTML_EVENT(transitionrun) \
- __ENUMERATE_HTML_EVENT(transitionstart) \
- __ENUMERATE_HTML_EVENT(unhandledrejection) \
- __ENUMERATE_HTML_EVENT(unload) \
- __ENUMERATE_HTML_EVENT(upgradeneeded) \
- __ENUMERATE_HTML_EVENT(versionchange) \
- __ENUMERATE_HTML_EVENT(visibilitychange) \
- __ENUMERATE_HTML_EVENT(voiceschanged) \
- __ENUMERATE_HTML_EVENT(volumechange) \
- __ENUMERATE_HTML_EVENT(waiting) \
- __ENUMERATE_HTML_EVENT(webkitAnimationEnd) \
- __ENUMERATE_HTML_EVENT(webkitAnimationIteration) \
- __ENUMERATE_HTML_EVENT(webkitAnimationStart) \
- __ENUMERATE_HTML_EVENT(webkitfullscreenchange) \
- __ENUMERATE_HTML_EVENT(webkitfullscreenerror) \
+#define ENUMERATE_HTML_EVENTS \
+ __ENUMERATE_HTML_EVENT(abort) \
+ __ENUMERATE_HTML_EVENT(addtrack) \
+ __ENUMERATE_HTML_EVENT(afterprint) \
+ __ENUMERATE_HTML_EVENT(animationcancel) \
+ __ENUMERATE_HTML_EVENT(animationend) \
+ __ENUMERATE_HTML_EVENT(animationiteration) \
+ __ENUMERATE_HTML_EVENT(animationstart) \
+ __ENUMERATE_HTML_EVENT(audioend) \
+ __ENUMERATE_HTML_EVENT(audioprocess) \
+ __ENUMERATE_HTML_EVENT(audiostart) \
+ __ENUMERATE_HTML_EVENT(beginEvent) \
+ __ENUMERATE_HTML_EVENT(beforeinput) \
+ __ENUMERATE_HTML_EVENT(beforematch) \
+ __ENUMERATE_HTML_EVENT(beforeprint) \
+ __ENUMERATE_HTML_EVENT(beforetoggle) \
+ __ENUMERATE_HTML_EVENT(beforeunload) \
+ __ENUMERATE_HTML_EVENT(blocked) \
+ __ENUMERATE_HTML_EVENT(blur) \
+ __ENUMERATE_HTML_EVENT(boundary) \
+ __ENUMERATE_HTML_EVENT(bufferedamountlow) \
+ __ENUMERATE_HTML_EVENT(cancel) \
+ __ENUMERATE_HTML_EVENT(canplay) \
+ __ENUMERATE_HTML_EVENT(canplaythrough) \
+ __ENUMERATE_HTML_EVENT(change) \
+ __ENUMERATE_HTML_EVENT(click) \
+ __ENUMERATE_HTML_EVENT(close) \
+ __ENUMERATE_HTML_EVENT(closing) \
+ __ENUMERATE_HTML_EVENT(command) \
+ __ENUMERATE_HTML_EVENT(complete) \
+ __ENUMERATE_HTML_EVENT(connect) \
+ __ENUMERATE_HTML_EVENT(connectionstatechange) \
+ __ENUMERATE_HTML_EVENT(contextlost) \
+ __ENUMERATE_HTML_EVENT(contextmenu) \
+ __ENUMERATE_HTML_EVENT(contextrestored) \
+ __ENUMERATE_HTML_EVENT(controllerchange) \
+ __ENUMERATE_HTML_EVENT(copy) \
+ __ENUMERATE_HTML_EVENT(cuechange) \
+ __ENUMERATE_HTML_EVENT(currententrychange) \
+ __ENUMERATE_HTML_EVENT(cut) \
+ __ENUMERATE_HTML_EVENT(datachannel) \
+ __ENUMERATE_HTML_EVENT(devicechange) \
+ __ENUMERATE_HTML_EVENT(disconnect) \
+ __ENUMERATE_HTML_EVENT(dispose) \
+ __ENUMERATE_HTML_EVENT(DOMContentLoaded) \
+ __ENUMERATE_HTML_EVENT(drag) \
+ __ENUMERATE_HTML_EVENT(dragend) \
+ __ENUMERATE_HTML_EVENT(dragenter) \
+ __ENUMERATE_HTML_EVENT(dragleave) \
+ __ENUMERATE_HTML_EVENT(dragover) \
+ __ENUMERATE_HTML_EVENT(dragstart) \
+ __ENUMERATE_HTML_EVENT(drop) \
+ __ENUMERATE_HTML_EVENT(durationchange) \
+ __ENUMERATE_HTML_EVENT(emptied) \
+ __ENUMERATE_HTML_EVENT(end) \
+ __ENUMERATE_HTML_EVENT(endEvent) \
+ __ENUMERATE_HTML_EVENT(ended) \
+ __ENUMERATE_HTML_EVENT(enter) \
+ __ENUMERATE_HTML_EVENT(enterpictureinpicture) \
+ __ENUMERATE_HTML_EVENT(error) \
+ __ENUMERATE_HTML_EVENT(exit) \
+ __ENUMERATE_HTML_EVENT(finish) \
+ __ENUMERATE_HTML_EVENT(focus) \
+ __ENUMERATE_HTML_EVENT(focusin) \
+ __ENUMERATE_HTML_EVENT(focusout) \
+ __ENUMERATE_HTML_EVENT(formdata) \
+ __ENUMERATE_HTML_EVENT(fullscreenchange) \
+ __ENUMERATE_HTML_EVENT(fullscreenerror) \
+ __ENUMERATE_HTML_EVENT(gatheringstatechange) \
+ __ENUMERATE_HTML_EVENT(hashchange) \
+ __ENUMERATE_HTML_EVENT(icecandidate) \
+ __ENUMERATE_HTML_EVENT(icecandidateerror) \
+ __ENUMERATE_HTML_EVENT(iceconnectionstatechange) \
+ __ENUMERATE_HTML_EVENT(icegatheringstatechange) \
+ __ENUMERATE_HTML_EVENT(input) \
+ __ENUMERATE_HTML_EVENT(invalid) \
+ __ENUMERATE_HTML_EVENT(languagechange) \
+ __ENUMERATE_HTML_EVENT(leavepictureinpicture) \
+ __ENUMERATE_HTML_EVENT(load) \
+ __ENUMERATE_HTML_EVENT(loaded) \
+ __ENUMERATE_HTML_EVENT(loadeddata) \
+ __ENUMERATE_HTML_EVENT(loadedmetadata) \
+ __ENUMERATE_HTML_EVENT(loadend) \
+ __ENUMERATE_HTML_EVENT(loading) \
+ __ENUMERATE_HTML_EVENT(loadingdone) \
+ __ENUMERATE_HTML_EVENT(loadingerror) \
+ __ENUMERATE_HTML_EVENT(loadstart) \
+ __ENUMERATE_HTML_EVENT(mark) \
+ __ENUMERATE_HTML_EVENT(message) \
+ __ENUMERATE_HTML_EVENT(messageerror) \
+ __ENUMERATE_HTML_EVENT(navigate) \
+ __ENUMERATE_HTML_EVENT(navigateerror) \
+ __ENUMERATE_HTML_EVENT(navigatesuccess) \
+ __ENUMERATE_HTML_EVENT(negotiationneeded) \
+ __ENUMERATE_HTML_EVENT(nomatch) \
+ __ENUMERATE_HTML_EVENT(offline) \
+ __ENUMERATE_HTML_EVENT(online) \
+ __ENUMERATE_HTML_EVENT(open) \
+ __ENUMERATE_HTML_EVENT(pagehide) \
+ __ENUMERATE_HTML_EVENT(pagereveal) \
+ __ENUMERATE_HTML_EVENT(pageshow) \
+ __ENUMERATE_HTML_EVENT(pageswap) \
+ __ENUMERATE_HTML_EVENT(paste) \
+ __ENUMERATE_HTML_EVENT(pause) \
+ __ENUMERATE_HTML_EVENT(play) \
+ __ENUMERATE_HTML_EVENT(playing) \
+ __ENUMERATE_HTML_EVENT(popstate) \
+ __ENUMERATE_HTML_EVENT(processorerror) \
+ __ENUMERATE_HTML_EVENT(progress) \
+ __ENUMERATE_HTML_EVENT(ratechange) \
+ __ENUMERATE_HTML_EVENT(readystatechange) \
+ __ENUMERATE_HTML_EVENT(rejectionhandled) \
+ __ENUMERATE_HTML_EVENT(remove) \
+ __ENUMERATE_HTML_EVENT(removetrack) \
+ __ENUMERATE_HTML_EVENT(repeatEvent) \
+ __ENUMERATE_HTML_EVENT(reset) \
+ __ENUMERATE_HTML_EVENT(resize) \
+ __ENUMERATE_HTML_EVENT(result) \
+ __ENUMERATE_HTML_EVENT(resume) \
+ __ENUMERATE_HTML_EVENT(scroll) \
+ __ENUMERATE_HTML_EVENT(scrollend) \
+ __ENUMERATE_HTML_EVENT(securitypolicyviolation) \
+ __ENUMERATE_HTML_EVENT(seeked) \
+ __ENUMERATE_HTML_EVENT(seeking) \
+ __ENUMERATE_HTML_EVENT(select) \
+ __ENUMERATE_HTML_EVENT(selectedcandidatepairchange) \
+ __ENUMERATE_HTML_EVENT(selectionchange) \
+ __ENUMERATE_HTML_EVENT(show) \
+ __ENUMERATE_HTML_EVENT(signalingstatechange) \
+ __ENUMERATE_HTML_EVENT(slotchange) \
+ __ENUMERATE_HTML_EVENT(soundend) \
+ __ENUMERATE_HTML_EVENT(soundstart) \
+ __ENUMERATE_HTML_EVENT(speechend) \
+ __ENUMERATE_HTML_EVENT(speechstart) \
+ __ENUMERATE_HTML_EVENT(stalled) \
+ __ENUMERATE_HTML_EVENT(start) \
+ __ENUMERATE_HTML_EVENT(statechange) \
+ __ENUMERATE_HTML_EVENT(storage) \
+ __ENUMERATE_HTML_EVENT(submit) \
+ __ENUMERATE_HTML_EVENT(success) \
+ __ENUMERATE_HTML_EVENT(suspend) \
+ __ENUMERATE_HTML_EVENT(timeupdate) \
+ __ENUMERATE_HTML_EVENT(toggle) \
+ __ENUMERATE_HTML_EVENT(tonechange) \
+ __ENUMERATE_HTML_EVENT(rtctransform) \
+ __ENUMERATE_HTML_EVENT(track) \
+ __ENUMERATE_HTML_EVENT(transitioncancel) \
+ __ENUMERATE_HTML_EVENT(transitionend) \
+ __ENUMERATE_HTML_EVENT(transitionrun) \
+ __ENUMERATE_HTML_EVENT(transitionstart) \
+ __ENUMERATE_HTML_EVENT(unhandledrejection) \
+ __ENUMERATE_HTML_EVENT(unload) \
+ __ENUMERATE_HTML_EVENT(upgradeneeded) \
+ __ENUMERATE_HTML_EVENT(versionchange) \
+ __ENUMERATE_HTML_EVENT(visibilitychange) \
+ __ENUMERATE_HTML_EVENT(voiceschanged) \
+ __ENUMERATE_HTML_EVENT(volumechange) \
+ __ENUMERATE_HTML_EVENT(waiting) \
+ __ENUMERATE_HTML_EVENT(webkitAnimationEnd) \
+ __ENUMERATE_HTML_EVENT(webkitAnimationIteration) \
+ __ENUMERATE_HTML_EVENT(webkitAnimationStart) \
+ __ENUMERATE_HTML_EVENT(webkitfullscreenchange) \
+ __ENUMERATE_HTML_EVENT(webkitfullscreenerror) \
__ENUMERATE_HTML_EVENT(webkitTransitionEnd)
#define __ENUMERATE_HTML_EVENT(name) extern WEB_API Utf16FlyString const& name;
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index 2e4a67bf10c..86fc67800b9 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -1887,8 +1887,8 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,
}
},
[&](GC::Ref<MediaCapture::MediaStream>) {
- // FIXME: Support MediaStream objects.
- failure_callback("MediaStream objects are not supported"_utf16);
+ // FIXME: Route MediaStream tracks into media-element playback.
+ // Accept srcObject assignments while RTC audio uses direct playback.
},
[&](GC::Ref<FileAPI::Blob>) {
// FIXME: Support File objects.
diff --git a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
index 1f6f8285e5f..57a27eb6d20 100644
--- a/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerializeRustIntegration.cpp
@@ -41,6 +41,7 @@ enum class SerializableSteps : u8 {
DOMException,
QuotaExceededError,
CryptoKey,
+ RTCEncodedAudioFrame,
};
extern "C" {
@@ -48,6 +49,7 @@ extern "C" {
void web_structured_serialize_set_ipc_record(IPCSerializationRecord*, ReadonlyBytes data, JSObject* const* shared_array_buffers, size_t count);
void web_structured_serialize_set_storage_record(StorageSerializationRecord*, ReadonlyBytes data);
bool web_structured_serialize_interface_storage_identifier(u16 interface_name, ReadonlyBytes* identifier);
+bool web_structured_serialize_is_ipc_interface(u16 interface_name);
bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyBytes identifier, u16* interface_name);
bool web_structured_serialize_shared_buffers_append_shared_memory(Vector<Core::AnonymousBuffer>*, JSObject* array_buffer, u32* index);
@@ -160,6 +162,15 @@ bool web_structured_serialize_interface_storage_identifier(u16 interface_name, R
return false;
}
+bool web_structured_serialize_is_ipc_interface(u16 interface_name)
+{
+ // Encoded audio frames can be cloned between agents, but cannot be stored.
+ if (static_cast<Bindings::InterfaceName>(interface_name) == Bindings::InterfaceName::RTCEncodedAudioFrame)
+ return true;
+ ReadonlyBytes identifier;
+ return web_structured_serialize_interface_storage_identifier(interface_name, &identifier);
+}
+
bool web_structured_serialize_interface_name_from_storage_identifier(ReadonlyBytes identifier, u16* interface_name)
{
for (auto const& entry : serializable_storage_registry()) {
@@ -293,6 +304,8 @@ u8 web_structured_serialize_serializable_steps(u16 interface_name)
return to_underlying(SerializableSteps::QuotaExceededError);
case Bindings::InterfaceName::CryptoKey:
return to_underlying(SerializableSteps::CryptoKey);
+ case Bindings::InterfaceName::RTCEncodedAudioFrame:
+ return to_underlying(SerializableSteps::RTCEncodedAudioFrame);
default:
VERIFY(Bindings::serializable_interface_is_implemented_in_rust(static_cast<Bindings::InterfaceName>(interface_name)));
return to_underlying(SerializableSteps::Rust);
diff --git a/Libraries/LibWeb/HTML/Worker.h b/Libraries/LibWeb/HTML/Worker.h
index 78dbb1a4424..bfcf6d57d41 100644
--- a/Libraries/LibWeb/HTML/Worker.h
+++ b/Libraries/LibWeb/HTML/Worker.h
@@ -55,6 +55,7 @@ public:
GC::Ptr<MessagePort> outside_message_port() { return m_outside_port; }
void set_agent(WorkerAgentParent& agent) { m_agent = agent; }
+ GC::Ptr<WorkerAgentParent> agent() { return m_agent; }
#undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name) \
diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
index 0ab246cf94a..7e3201dd28c 100644
--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
@@ -268,4 +268,45 @@ void WorkerAgentParent::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_worker_event_target);
}
+void WorkerAgentParent::rtc_transform_init(u64 transform_id, SerializedTransferRecord options_record)
+{
+ if (m_agent_id == 0)
+ return;
+ Bindings::principal_host_defined_page(m_outside_settings->realm()).client().rtc_transform_init(m_agent_id, transform_id, move(options_record));
+}
+
+void WorkerAgentParent::rtc_transform_teardown(u64 transform_id)
+{
+ m_transform_frame_callbacks.remove(transform_id);
+ if (m_agent_id == 0)
+ return;
+ Bindings::principal_host_defined_page(m_outside_settings->realm()).client().rtc_transform_teardown(m_agent_id, transform_id);
+}
+
+void WorkerAgentParent::rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ if (m_agent_id == 0)
+ return;
+ Bindings::principal_host_defined_page(m_outside_settings->realm()).client().rtc_transform_encoded_audio_frame(m_agent_id, transform_id, move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
+void WorkerAgentParent::register_transform_frame_callback(u64 transform_id, TransformFrameWrittenCallback callback)
+{
+ m_transform_frame_callbacks.set(transform_id, move(callback));
+}
+
+void WorkerAgentParent::unregister_transform_frame_callback(u64 transform_id)
+{
+ m_transform_frame_callbacks.remove(transform_id);
+}
+
+void WorkerAgentParent::did_write_rtc_transform_encoded_audio_frame(WorkerAgentOwnerToken owner_token, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ auto parent = worker_agent_parents().find(owner_token);
+ if (parent == worker_agent_parents().end())
+ return;
+ if (auto it = parent->value->m_transform_frame_callbacks.find(transform_id); it != parent->value->m_transform_frame_callbacks.end())
+ it->value(move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
}
diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.h b/Libraries/LibWeb/HTML/WorkerAgentParent.h
index 1c4ec60c660..5101eac8ed9 100644
--- a/Libraries/LibWeb/HTML/WorkerAgentParent.h
+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/HashMap.h>
#include <AK/Utf16String.h>
#include <LibURL/URL.h>
#include <LibWeb/Bindings/Worker.h>
@@ -31,6 +32,7 @@ public:
static WEB_API void did_report_content_security_policy_violation(WorkerAgentOwnerToken, u64 policy_index, String effective_directive, URL::URL resource);
static WEB_API void did_close_worker(WorkerAgentOwnerToken);
static WEB_API void did_worker_agent_die(WorkerAgentOwnerToken);
+ static WEB_API void did_write_rtc_transform_encoded_audio_frame(WorkerAgentOwnerToken, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number);
void terminate();
@@ -38,6 +40,15 @@ protected:
virtual void visit_edges(Cell::Visitor&) override;
virtual void finalize() override;
+public:
+ void rtc_transform_init(u64 transform_id, SerializedTransferRecord options_record);
+ void rtc_transform_teardown(u64 transform_id);
+ void rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number);
+
+ using TransformFrameWrittenCallback = AK::Function<void(ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)>;
+ void register_transform_frame_callback(u64 transform_id, TransformFrameWrittenCallback callback);
+ void unregister_transform_frame_callback(u64 transform_id);
+
private:
WorkerAgentParent(URL::URL, WorkerOptions const&, bool extended_lifetime, GC::Ptr<MessagePort> outside_port,
GC::Ref<EnvironmentSettingsObject> outside_settings, GC::Ref<DOM::EventTarget> worker_event_target,
@@ -62,6 +73,8 @@ private:
GC::Ptr<MessagePort> m_outside_port;
GC::Ref<EnvironmentSettingsObject> m_outside_settings;
GC::Ref<DOM::EventTarget> m_worker_event_target;
+
+ HashMap<u64, TransformFrameWrittenCallback> m_transform_frame_callbacks;
};
}
diff --git a/Libraries/LibWeb/HighResolutionTime/TimeOrigin.h b/Libraries/LibWeb/HighResolutionTime/TimeOrigin.h
index 472c99f112b..aa46e52e919 100644
--- a/Libraries/LibWeb/HighResolutionTime/TimeOrigin.h
+++ b/Libraries/LibWeb/HighResolutionTime/TimeOrigin.h
@@ -17,7 +17,7 @@ namespace Web::HighResolutionTime {
DOMHighResTimeStamp estimated_monotonic_time_of_the_unix_epoch();
DOMHighResTimeStamp get_time_origin_timestamp(JS::Object const&);
WEB_API DOMHighResTimeStamp coarsen_time(DOMHighResTimeStamp timestamp, HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability = HTML::CanUseCrossOriginIsolatedAPIs::No);
-DOMHighResTimeStamp current_high_resolution_time(JS::Object const&);
+WEB_API DOMHighResTimeStamp current_high_resolution_time(JS::Object const&);
DOMHighResTimeStamp relative_high_resolution_time(DOMHighResTimeStamp, JS::Object const&);
DOMHighResTimeStamp relative_high_resolution_coarsen_time(DOMHighResTimeStamp, JS::Object const&);
WEB_API DOMHighResTimeStamp coarsened_shared_current_time(HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability = HTML::CanUseCrossOriginIsolatedAPIs::No);
diff --git a/Libraries/LibWeb/MediaCapture/MediaStream.cpp b/Libraries/LibWeb/MediaCapture/MediaStream.cpp
index dfe63dd94ee..711c8364056 100644
--- a/Libraries/LibWeb/MediaCapture/MediaStream.cpp
+++ b/Libraries/LibWeb/MediaCapture/MediaStream.cpp
@@ -29,6 +29,15 @@ GC::Ref<MediaStream> MediaStream::create()
return stream;
}
+// Used when wrapping a remote stream-id from the WebRTC client (e.g. SFU-assigned msid)
+// so JS-side bookkeeping that maps stream.id -> user lines up with what the peer sent.
+GC::Ref<MediaStream> MediaStream::create_with_id(Utf16String id)
+{
+ auto stream = GC::Heap::the().allocate<MediaStream>();
+ stream->m_id = move(id);
+ return stream;
+}
+
// https://w3c.github.io/mediacapture-main/#mediastream
GC::Ref<MediaStream> MediaStream::create(ReadonlySpan<GC::Ref<MediaStreamTrack>> const& tracks)
{
diff --git a/Libraries/LibWeb/MediaCapture/MediaStream.h b/Libraries/LibWeb/MediaCapture/MediaStream.h
index e3d3c0dab8d..1f8a793c15c 100644
--- a/Libraries/LibWeb/MediaCapture/MediaStream.h
+++ b/Libraries/LibWeb/MediaCapture/MediaStream.h
@@ -23,6 +23,7 @@ public:
static GC::Ref<MediaStream> create();
static GC::Ref<MediaStream> create(ReadonlySpan<GC::Ref<MediaStreamTrack>> const&);
static GC::Ref<MediaStream> create(GC::RootVector<GC::Ref<MediaStreamTrack>> const&);
+ static GC::Ref<MediaStream> create_with_id(Utf16String id);
virtual ~MediaStream() override = default;
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index eeaf4dc3f1f..ca39e0dfdce 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -53,6 +53,7 @@
#include <LibWeb/HTML/SameDocumentNavigationEntry.h>
#include <LibWeb/HTML/Scripting/ScriptRegistry.h>
#include <LibWeb/HTML/SessionHistoryEntry.h>
+#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/TokenizedFeatures.h>
#include <LibWeb/HTML/UserNavigationInvolvement.h>
#include <LibWeb/HTML/WebViewHints.h>
@@ -973,6 +974,9 @@ public:
virtual HTML::WorkerAgentId start_worker_agent([[maybe_unused]] HTML::WorkerAgentStartRequest&& request) { return {}; }
virtual void close_worker_agent([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] HTML::WorkerAgentOwnerToken owner_token) { }
+ virtual void rtc_transform_init([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] u64 transform_id, [[maybe_unused]] HTML::SerializedTransferRecord options_record) { }
+ virtual void rtc_transform_teardown([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] u64 transform_id) { }
+ virtual void rtc_transform_encoded_audio_frame([[maybe_unused]] HTML::WorkerAgentId agent_id, [[maybe_unused]] u64 transform_id, [[maybe_unused]] ByteBuffer payload, [[maybe_unused]] u32 ssrc, [[maybe_unused]] u8 payload_type, [[maybe_unused]] u32 rtp_timestamp, [[maybe_unused]] u16 sequence_number) { }
virtual void page_did_mutate_dom([[maybe_unused]] Utf16FlyString const& type, [[maybe_unused]] DOM::Node const& target, [[maybe_unused]] DOM::NodeList& added_nodes, [[maybe_unused]] DOM::NodeList& removed_nodes, [[maybe_unused]] GC::Ptr<DOM::Node> previous_sibling, [[maybe_unused]] GC::Ptr<DOM::Node> next_sibling, [[maybe_unused]] Optional<Utf16FlyString> const& attribute_name) { }
virtual void flush_pending_dom_mutations() { }
diff --git a/Libraries/LibWeb/WebRTC/BindingsGlue.h b/Libraries/LibWeb/WebRTC/BindingsGlue.h
new file mode 100644
index 00000000000..719c3ed8aa6
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/BindingsGlue.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/Utf16View.h>
+#include <LibGC/Forward.h>
+#include <LibJS/Forward.h>
+#include <LibJS/Runtime/Value.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::WebRTC {
+
+class RTCStatsReport;
+
+}
+
+namespace Web::Bindings {
+
+WEB_API GC::Ref<JS::Map> map_entries(JS::Realm&, WebRTC::RTCStatsReport&);
+WEB_API Optional<JS::Value> map_get(JS::Realm&, WebRTC::RTCStatsReport&, Utf16View key);
+WEB_API bool map_has(WebRTC::RTCStatsReport&, Utf16View key);
+
+}
diff --git a/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.cpp b/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.cpp
new file mode 100644
index 00000000000..c3ba89790f9
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.cpp
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/KeyFrameRequestEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(KeyFrameRequestEvent);
+
+GC::Ref<KeyFrameRequestEvent> KeyFrameRequestEvent::create(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<KeyFrameRequestEvent>(event_name, time_stamp);
+}
+
+// FIXME: KeyFrameRequestEvent is a stub — store the rid once the attribute is implemented.
+GC::Ref<KeyFrameRequestEvent> KeyFrameRequestEvent::create_for_constructor(Utf16String const& type, Optional<Utf16String> const&, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return create(Utf16FlyString { type }, time_stamp);
+}
+KeyFrameRequestEvent::KeyFrameRequestEvent(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, time_stamp)
+{
+}
+KeyFrameRequestEvent::~KeyFrameRequestEvent() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.h b/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.h
new file mode 100644
index 00000000000..0c15ab3aa65
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+class KeyFrameRequestEvent final : public DOM::Event {
+ WEB_WRAPPABLE(KeyFrameRequestEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(KeyFrameRequestEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<KeyFrameRequestEvent> create(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp);
+ [[nodiscard]] static GC::Ref<KeyFrameRequestEvent> create_for_constructor(Utf16String const& type, Optional<Utf16String> const& rid, HighResolutionTime::DOMHighResTimeStamp);
+ virtual ~KeyFrameRequestEvent() override;
+
+private:
+ KeyFrameRequestEvent(Utf16FlyString const& event_name, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.idl b/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.idl
new file mode 100644
index 00000000000..2567e0054d1
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/KeyFrameRequestEvent.idl
@@ -0,0 +1,7 @@
+// https://w3c.github.io/webrtc-encoded-transform/#keyframerequestevent
+
+[Exposed=DedicatedWorker]
+interface KeyFrameRequestEvent : Event {
+ [FIXME] constructor(DOMString type, optional DOMString rid);
+ [FIXME] readonly attribute DOMString? rid;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCCertificate.cpp b/Libraries/LibWeb/WebRTC/RTCCertificate.cpp
new file mode 100644
index 00000000000..fe510366bdb
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCCertificate.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCCertificate.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCCertificate);
+
+GC::Ref<RTCCertificate> RTCCertificate::create() { return GC::Heap::the().allocate<RTCCertificate>(); }
+RTCCertificate::RTCCertificate() = default;
+RTCCertificate::~RTCCertificate() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCCertificate.h b/Libraries/LibWeb/WebRTC/RTCCertificate.h
new file mode 100644
index 00000000000..6f608d4a3c0
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCCertificate.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/Wrappable.h>
+
+namespace Web::WebRTC {
+
+class RTCCertificate final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCCertificate, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCCertificate);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCCertificate> create();
+ virtual ~RTCCertificate() override;
+
+private:
+ RTCCertificate();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCCertificate.idl b/Libraries/LibWeb/WebRTC/RTCCertificate.idl
new file mode 100644
index 00000000000..f3c31c34ad9
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCCertificate.idl
@@ -0,0 +1,16 @@
+// https://w3c.github.io/webrtc-pc/#rtccertificate-interface
+
+[Exposed=Window, Serializable]
+interface RTCCertificate {
+ [FIXME] readonly attribute EpochTimeStamp expires;
+ [FIXME] sequence<RTCDtlsFingerprint> getFingerprints();
+};
+
+dictionary RTCCertificateExpiration {
+ [EnforceRange] unsigned long long expires;
+};
+
+dictionary RTCDtlsFingerprint {
+ DOMString algorithm;
+ DOMString value;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCDTMFSender.cpp b/Libraries/LibWeb/WebRTC/RTCDTMFSender.cpp
new file mode 100644
index 00000000000..6e274e7a84b
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDTMFSender.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/WebRTC/RTCDTMFSender.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCDTMFSender);
+
+GC::Ref<RTCDTMFSender> RTCDTMFSender::create() { return GC::Heap::the().allocate<RTCDTMFSender>(); }
+RTCDTMFSender::RTCDTMFSender() = default;
+RTCDTMFSender::~RTCDTMFSender() = default;
+void RTCDTMFSender::set_ontonechange(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::tonechange, cb); }
+WebIDL::CallbackType* RTCDTMFSender::ontonechange() { return event_handler_attribute(HTML::EventNames::tonechange); }
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDTMFSender.h b/Libraries/LibWeb/WebRTC/RTCDTMFSender.h
new file mode 100644
index 00000000000..a3537730b8c
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDTMFSender.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/DOM/EventTarget.h>
+
+namespace Web::WebRTC {
+
+class RTCDTMFSender final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCDTMFSender, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCDTMFSender);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCDTMFSender> create();
+ virtual ~RTCDTMFSender() override;
+
+ void set_ontonechange(WebIDL::CallbackType*);
+ WebIDL::CallbackType* ontonechange();
+
+private:
+ RTCDTMFSender();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDTMFSender.idl b/Libraries/LibWeb/WebRTC/RTCDTMFSender.idl
new file mode 100644
index 00000000000..d5ae8e9bf5d
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDTMFSender.idl
@@ -0,0 +1,9 @@
+// https://w3c.github.io/webrtc-pc/#rtcdtmfsender
+
+[Exposed=Window]
+interface RTCDTMFSender : EventTarget {
+ [FIXME] undefined insertDTMF(DOMString tones, optional unsigned long duration = 100, optional unsigned long interToneGap = 70);
+ attribute EventHandler ontonechange;
+ [FIXME] readonly attribute boolean canInsertDTMF;
+ [FIXME] readonly attribute DOMString toneBuffer;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.cpp b/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.cpp
new file mode 100644
index 00000000000..bda52d9a14d
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.cpp
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCDTMFToneChangeEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCDTMFToneChangeEvent);
+
+GC::Ref<RTCDTMFToneChangeEvent> RTCDTMFToneChangeEvent::create(Utf16FlyString const& event_name, RTCDTMFToneChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCDTMFToneChangeEvent>(event_name, event_init, time_stamp);
+}
+
+// FIXME: RTCDTMFToneChangeEvent is a stub — store the tone once the attribute is implemented.
+RTCDTMFToneChangeEvent::RTCDTMFToneChangeEvent(Utf16FlyString const& event_name, RTCDTMFToneChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+{
+}
+
+RTCDTMFToneChangeEvent::~RTCDTMFToneChangeEvent() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.h b/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.h
new file mode 100644
index 00000000000..29e6b8e87ee
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCDTMFToneChangeEvent.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+using RTCDTMFToneChangeEventInit = Bindings::RTCDTMFToneChangeEventInit;
+
+class RTCDTMFToneChangeEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCDTMFToneChangeEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCDTMFToneChangeEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCDTMFToneChangeEvent> create(Utf16FlyString const& event_name, RTCDTMFToneChangeEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+ virtual ~RTCDTMFToneChangeEvent() override;
+
+private:
+ RTCDTMFToneChangeEvent(Utf16FlyString const& event_name, RTCDTMFToneChangeEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.idl b/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.idl
new file mode 100644
index 00000000000..577c42e9e80
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDTMFToneChangeEvent.idl
@@ -0,0 +1,11 @@
+// https://w3c.github.io/webrtc-pc/#rtcdtmftonechangeevent
+
+[Exposed=Window]
+interface RTCDTMFToneChangeEvent : Event {
+ [FIXME] constructor(DOMString type, optional RTCDTMFToneChangeEventInit eventInitDict = {});
+ [FIXME] readonly attribute DOMString tone;
+};
+
+dictionary RTCDTMFToneChangeEventInit : EventInit {
+ DOMString tone = "";
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCDataChannel.cpp b/Libraries/LibWeb/WebRTC/RTCDataChannel.cpp
new file mode 100644
index 00000000000..2f3072c8a40
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDataChannel.cpp
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ByteBuffer.h>
+#include <LibGC/Heap.h>
+#include <LibJS/Runtime/ArrayBuffer.h>
+#include <LibWeb/FileAPI/Blob.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/WebIDL/Buffers.h>
+#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebRTC/RTCDataChannel.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
+#include <LibWebRTCClient/Client.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCDataChannel);
+
+GC::Ref<RTCDataChannel> RTCDataChannel::create(GC::Ref<DOM::EventTarget> relevant_global_object)
+{
+ return GC::Heap::the().allocate<RTCDataChannel>(relevant_global_object);
+}
+
+RTCDataChannel::RTCDataChannel(GC::Ref<DOM::EventTarget> relevant_global_object)
+ : DOM::EventTarget()
+ , m_global_object(relevant_global_object)
+{
+}
+
+RTCDataChannel::~RTCDataChannel() = default;
+
+void RTCDataChannel::visit_edges(JS::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_global_object);
+}
+
+JS::Realm& RTCDataChannel::relevant_realm() const
+{
+ return HTML::relevant_realm(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+}
+
+JS::Object& RTCDataChannel::relevant_global_object() const
+{
+ return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+}
+
+void RTCDataChannel::set_onopen(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::open, cb); }
+WebIDL::CallbackType* RTCDataChannel::onopen() { return event_handler_attribute(HTML::EventNames::open); }
+void RTCDataChannel::set_onbufferedamountlow(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::bufferedamountlow, cb); }
+WebIDL::CallbackType* RTCDataChannel::onbufferedamountlow() { return event_handler_attribute(HTML::EventNames::bufferedamountlow); }
+void RTCDataChannel::set_onerror(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::error, cb); }
+WebIDL::CallbackType* RTCDataChannel::onerror() { return event_handler_attribute(HTML::EventNames::error); }
+void RTCDataChannel::set_onclosing(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::closing, cb); }
+WebIDL::CallbackType* RTCDataChannel::onclosing() { return event_handler_attribute(HTML::EventNames::closing); }
+void RTCDataChannel::set_onclose(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::close, cb); }
+WebIDL::CallbackType* RTCDataChannel::onclose() { return event_handler_attribute(HTML::EventNames::close); }
+void RTCDataChannel::set_onmessage(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::message, cb); }
+WebIDL::CallbackType* RTCDataChannel::onmessage() { return event_handler_attribute(HTML::EventNames::message); }
+
+void RTCDataChannel::close()
+{
+ if (m_ready_state == Bindings::RTCDataChannelState::Closing || m_ready_state == Bindings::RTCDataChannelState::Closed)
+ return;
+ m_ready_state = Bindings::RTCDataChannelState::Closing;
+ if (auto* client = WebRTCAgent::the().existing_client())
+ client->async_data_channel_close(m_channel_id);
+ else
+ m_ready_state = Bindings::RTCDataChannelState::Closed;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcdatachannel-send
+WebIDL::ExceptionOr<void> RTCDataChannel::send(RTCDataChannelSendData const& data)
+{
+ // 1. Let channel be the RTCDataChannel object on which data is to be sent.
+ // 2. Set channel.[[IsTransferable]] to false.
+ m_is_transferable = false;
+ // 3. If channel.[[ReadyState]] is not "open", throw an InvalidStateError.
+ if (m_ready_state != Bindings::RTCDataChannelState::Open)
+ return WebIDL::InvalidStateError::create("RTCDataChannel is not open"_utf16);
+
+ auto* client = WebRTCAgent::the().client();
+ size_t byte_size = 0;
+
+ // 4. Execute the sub step that corresponds to the type of the methods argument:
+ data.visit(
+ [&](Utf16String const& string) {
+ // string object: Let data be a byte buffer that represents the result of encoding the method's argument as UTF-8.
+ auto encoded_string = string.to_utf8();
+ byte_size = encoded_string.bytes().size();
+ // FIXME: 5. If the byte size of data exceeds the value of maxMessageSize on channel's associated RTCSctpTransport, throw a TypeError.
+ // 6. Queue data for transmission on channel's underlying data transport.
+ if (client)
+ client->async_data_channel_send_text(m_channel_id, encoded_string);
+ },
+ [&](GC::Ref<FileAPI::Blob> const& blob) {
+ // Blob object: Let data be the raw data represented by the Blob object.
+ auto bytes = blob->raw_bytes();
+ byte_size = bytes.size();
+ // FIXME: 5. If the byte size of data exceeds the value of maxMessageSize on channel's associated RTCSctpTransport, throw a TypeError.
+ // 6. Queue data for transmission on channel's underlying data transport.
+ if (client)
+ client->async_data_channel_send_binary(m_channel_id, bytes);
+ },
+ [&](auto const& view) {
+ // ArrayBuffer object: Let data be the data stored in the buffer described by the ArrayBuffer object.
+ // ArrayBufferView object: Let data be the data stored in the section of the buffer described by the ArrayBuffer object that the ArrayBufferView object references.
+ WebIDL::BufferSource source { WebIDL::BufferSourceVariant { view } };
+ ByteBuffer buffer_storage;
+ ReadonlyBytes bytes;
+ if (auto array_buffer = source.viewed_array_buffer(); array_buffer && !array_buffer->is_detached() && !source.is_out_of_bounds()) {
+ buffer_storage = MUST(ByteBuffer::create_uninitialized(source.byte_length()));
+ array_buffer->copy_to(source.byte_offset(), buffer_storage);
+ bytes = buffer_storage;
+ }
+ byte_size = bytes.size();
+ // FIXME: 5. If the byte size of data exceeds the value of maxMessageSize on channel's associated RTCSctpTransport, throw a TypeError.
+ // 6. Queue data for transmission on channel's underlying data transport.
+ if (client)
+ client->async_data_channel_send_binary(m_channel_id, bytes);
+ });
+ // FIXME: 6. ...If queuing data is not possible because not enough buffer space is available, throw an OperationError.
+ // 7. Increase the value of the [[BufferedAmount]] slot by the byte size of data.
+ m_buffered_amount += byte_size;
+ return {};
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDataChannel.h b/Libraries/LibWeb/WebRTC/RTCDataChannel.h
new file mode 100644
index 00000000000..e0fa75e2ade
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDataChannel.h
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Utf16String.h>
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCDataChannel.h>
+#include <LibWeb/Bindings/WebSocket.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/Buffers.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWebCommon/WebIDL/Types.h>
+
+namespace Web::WebRTC {
+
+// The IDL `(USVString or Blob or BufferSource)` union the bindings generator expands BufferSource
+// into each concrete ArrayBuffer/ArrayBufferView type, so the send() argument must match exactly.
+using RTCDataChannelSendData = Variant<
+ Utf16String,
+ GC::Ref<FileAPI::Blob>,
+ GC::Ref<JS::Int8Array>,
+ GC::Ref<JS::Int16Array>,
+ GC::Ref<JS::Int32Array>,
+ GC::Ref<JS::Uint8Array>,
+ GC::Ref<JS::Uint16Array>,
+ GC::Ref<JS::Uint32Array>,
+ GC::Ref<JS::Uint8ClampedArray>,
+ GC::Ref<JS::BigInt64Array>,
+ GC::Ref<JS::BigUint64Array>,
+ GC::Ref<JS::Float16Array>,
+ GC::Ref<JS::Float32Array>,
+ GC::Ref<JS::Float64Array>,
+ GC::Ref<JS::DataView>,
+ GC::Ref<JS::ArrayBuffer>>;
+
+using Bindings::RTCDataChannelInit;
+
+class RTCDataChannel final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCDataChannel, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCDataChannel);
+
+public:
+ static GC::Ref<RTCDataChannel> create(GC::Ref<DOM::EventTarget> relevant_global_object);
+ virtual ~RTCDataChannel() override;
+
+ JS::Realm& relevant_realm() const;
+ JS::Object& relevant_global_object() const;
+ virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override { return m_global_object; }
+
+ void set_label(Utf16String label) { m_label = move(label); }
+ void set_max_packet_life_time(Optional<u16> v) { m_max_packet_life_time = v; }
+ void set_max_retransmits(Optional<u16> v) { m_max_retransmits = v; }
+ void set_ordered(bool v) { m_ordered = v; }
+ void set_protocol(Utf16String v) { m_protocol = move(v); }
+ void set_negotiated(bool v) { m_negotiated = v; }
+ void set_id(Optional<u16> v) { m_id = v; }
+ void set_channel_id(u64 v) { m_channel_id = v; }
+ void set_ready_state(Bindings::RTCDataChannelState v) { m_ready_state = v; }
+
+ Utf16String const& label() const { return m_label; }
+ bool ordered() const { return m_ordered; }
+ Optional<u16> max_packet_life_time() const { return m_max_packet_life_time; }
+ Optional<u16> max_retransmits() const { return m_max_retransmits; }
+ Utf16String const& protocol() const { return m_protocol; }
+ bool negotiated() const { return m_negotiated; }
+ Optional<u16> id() const { return m_id; }
+ Bindings::BinaryType binary_type() const { return m_binary_type; }
+ void set_binary_type(Bindings::BinaryType type) { m_binary_type = move(type); }
+ void close();
+
+ Bindings::RTCDataChannelState ready_state() const { return m_ready_state; }
+ WebIDL::UnsignedLong buffered_amount() const { return m_buffered_amount; }
+ WebIDL::UnsignedLong buffered_amount_low_threshold() const { return m_buffered_amount_low_threshold; }
+ void set_buffered_amount_low_threshold(WebIDL::UnsignedLong v) { m_buffered_amount_low_threshold = v; }
+
+ WebIDL::ExceptionOr<void> send(RTCDataChannelSendData const&);
+
+ void set_onopen(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onopen();
+ void set_onbufferedamountlow(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onbufferedamountlow();
+ void set_onerror(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onerror();
+ void set_onclosing(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onclosing();
+ void set_onclose(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onclose();
+ void set_onmessage(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onmessage();
+
+private:
+ explicit RTCDataChannel(GC::Ref<DOM::EventTarget> relevant_global_object);
+ virtual void visit_edges(JS::Cell::Visitor&) override;
+
+ // The global this channel was created for; used to recover the realm when
+ // dispatching IPC-driven events.
+ GC::Ref<DOM::EventTarget> m_global_object;
+
+ // [[DataChannelLabel]]
+ Utf16String m_label;
+ // [[MaxPacketLifeTime]]
+ Optional<u16> m_max_packet_life_time;
+ // [[MaxRetransmits]]
+ Optional<u16> m_max_retransmits;
+ // [[Ordered]]
+ bool m_ordered { true };
+ // [[DataChannelProtocol]]
+ Utf16String m_protocol;
+ // [[Negotiated]]
+ bool m_negotiated { false };
+ // [[DataChannelId]]
+ Optional<u16> m_id;
+ // [[ReadyState]]
+ Bindings::RTCDataChannelState m_ready_state { Bindings::RTCDataChannelState::Connecting };
+ // [[BufferedAmount]]
+ WebIDL::UnsignedLong m_buffered_amount { 0 };
+ WebIDL::UnsignedLong m_buffered_amount_low_threshold { 0 };
+ // [[IsTransferable]]
+ bool m_is_transferable { true };
+ u64 m_channel_id { 0 };
+ Bindings::BinaryType m_binary_type { Bindings::BinaryType::Arraybuffer };
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDataChannel.idl b/Libraries/LibWeb/WebRTC/RTCDataChannel.idl
new file mode 100644
index 00000000000..3a224e33986
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDataChannel.idl
@@ -0,0 +1,38 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcdatachannel
+
+[Exposed=(Window,DedicatedWorker), Transferable]
+interface RTCDataChannel : EventTarget {
+ readonly attribute USVString label;
+ readonly attribute boolean ordered;
+ readonly attribute unsigned short? maxPacketLifeTime;
+ readonly attribute unsigned short? maxRetransmits;
+ readonly attribute USVString protocol;
+ readonly attribute boolean negotiated;
+ readonly attribute unsigned short? id;
+ readonly attribute RTCDataChannelState readyState;
+ readonly attribute unsigned long bufferedAmount;
+ [EnforceRange] attribute unsigned long bufferedAmountLowThreshold;
+ attribute EventHandler onopen;
+ attribute EventHandler onbufferedamountlow;
+ attribute EventHandler onerror;
+ attribute EventHandler onclosing;
+ attribute EventHandler onclose;
+ undefined close();
+ attribute EventHandler onmessage;
+ attribute BinaryType binaryType;
+ // FIXME: spec is 4 overloads (USVString / Blob / ArrayBuffer / ArrayBufferView). Codegen
+ // for typed overloads is fiddly; use the same union-arg shape as WebSocket.send.
+ undefined send((USVString or Blob or BufferSource) data);
+};
+
+dictionary RTCDataChannelInit {
+ boolean ordered = true;
+ [EnforceRange] unsigned short maxPacketLifeTime;
+ [EnforceRange] unsigned short maxRetransmits;
+ USVString protocol = "";
+ boolean negotiated = false;
+ [EnforceRange] unsigned short id;
+};
+
+enum RTCDataChannelState { "connecting", "open", "closing", "closed" };
diff --git a/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.cpp b/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.cpp
new file mode 100644
index 00000000000..75eeefc2211
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCDataChannel.h>
+#include <LibWeb/WebRTC/RTCDataChannelEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCDataChannelEvent);
+
+GC::Ref<RTCDataChannelEvent> RTCDataChannelEvent::create(Utf16FlyString const& event_name, RTCDataChannelEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCDataChannelEvent>(event_name, event_init, time_stamp);
+}
+
+RTCDataChannelEvent::RTCDataChannelEvent(Utf16FlyString const& event_name, RTCDataChannelEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+ , m_channel(event_init.channel)
+{
+}
+
+RTCDataChannelEvent::~RTCDataChannelEvent() = default;
+
+void RTCDataChannelEvent::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_channel);
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.h b/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.h
new file mode 100644
index 00000000000..cc62f8aca14
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCDataChannelEvent.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+using RTCDataChannelEventInit = Bindings::RTCDataChannelEventInit;
+
+class RTCDataChannelEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCDataChannelEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCDataChannelEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCDataChannelEvent> create(Utf16FlyString const& event_name, RTCDataChannelEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+ static GC::Ref<RTCDataChannelEvent> create_for_constructor(Utf16String const& type, RTCDataChannelEventInit const& init, HighResolutionTime::DOMHighResTimeStamp time_stamp) { return create(Utf16FlyString { type }, init, time_stamp); }
+ GC::Ref<RTCDataChannel> channel() const { return m_channel; }
+ virtual ~RTCDataChannelEvent() override;
+
+private:
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+ GC::Ref<RTCDataChannel> m_channel;
+ RTCDataChannelEvent(Utf16FlyString const& event_name, RTCDataChannelEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.idl b/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.idl
new file mode 100644
index 00000000000..149034cd88c
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDataChannelEvent.idl
@@ -0,0 +1,12 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcdatachannelevent
+
+[Exposed=Window]
+interface RTCDataChannelEvent : Event {
+ constructor(DOMString type, RTCDataChannelEventInit eventInitDict);
+ readonly attribute RTCDataChannel channel;
+};
+
+dictionary RTCDataChannelEventInit : EventInit {
+ required RTCDataChannel channel;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCDtlsTransport.cpp b/Libraries/LibWeb/WebRTC/RTCDtlsTransport.cpp
new file mode 100644
index 00000000000..700baa67128
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDtlsTransport.cpp
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/WebRTC/RTCDtlsTransport.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCDtlsTransport);
+
+GC::Ref<RTCDtlsTransport> RTCDtlsTransport::create() { return GC::Heap::the().allocate<RTCDtlsTransport>(); }
+RTCDtlsTransport::RTCDtlsTransport() = default;
+RTCDtlsTransport::~RTCDtlsTransport() = default;
+void RTCDtlsTransport::set_onstatechange(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::statechange, cb); }
+WebIDL::CallbackType* RTCDtlsTransport::onstatechange() { return event_handler_attribute(HTML::EventNames::statechange); }
+void RTCDtlsTransport::set_onerror(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::error, cb); }
+WebIDL::CallbackType* RTCDtlsTransport::onerror() { return event_handler_attribute(HTML::EventNames::error); }
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDtlsTransport.h b/Libraries/LibWeb/WebRTC/RTCDtlsTransport.h
new file mode 100644
index 00000000000..a9f2067602e
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDtlsTransport.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/DOM/EventTarget.h>
+
+namespace Web::WebRTC {
+
+class RTCDtlsTransport final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCDtlsTransport, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCDtlsTransport);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCDtlsTransport> create();
+ virtual ~RTCDtlsTransport() override;
+
+ void set_onstatechange(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onstatechange();
+ void set_onerror(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onerror();
+
+private:
+ RTCDtlsTransport();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCDtlsTransport.idl b/Libraries/LibWeb/WebRTC/RTCDtlsTransport.idl
new file mode 100644
index 00000000000..b974be54073
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCDtlsTransport.idl
@@ -0,0 +1,19 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcdtlstransport-interface
+
+[Exposed=Window]
+interface RTCDtlsTransport : EventTarget {
+ [FIXME, SameObject] readonly attribute RTCIceTransport iceTransport;
+ [FIXME] readonly attribute RTCDtlsTransportState state;
+ [FIXME] sequence<ArrayBuffer> getRemoteCertificates();
+ attribute EventHandler onstatechange;
+ attribute EventHandler onerror;
+};
+
+enum RTCDtlsTransportState {
+ "new",
+ "connecting",
+ "connected",
+ "closed",
+ "failed"
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.cpp b/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.cpp
new file mode 100644
index 00000000000..9f7a19d71ff
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.cpp
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/ArrayBuffer.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/PrincipalHostDefined.h>
+#include <LibWeb/Bindings/RTCEncodedAudioFrame.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/WebRTC/RTCEncodedAudioFrame.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCEncodedAudioFrame);
+
+GC::Ref<RTCEncodedAudioFrame> RTCEncodedAudioFrame::create()
+{
+ return GC::Heap::the().allocate<RTCEncodedAudioFrame>();
+}
+
+// https://w3c.github.io/webrtc-encoded-transform/#dom-rtcencodedaudioframe-rtcencodedaudioframe
+WebIDL::ExceptionOr<GC::Ref<RTCEncodedAudioFrame>> RTCEncodedAudioFrame::construct_impl(JS::Realm& realm, GC::Ref<RTCEncodedAudioFrame> original_frame, RTCEncodedAudioFrameOptions const& options)
+{
+ auto frame = create();
+
+ // 1. Let this.[[data]] be the result of CloneArrayBuffer(originalFrame.[[data]], 0,
+ // originalFrame.[[data]].[[ArrayBufferByteLength]]).
+ auto& original_data = *original_frame->m_data;
+ auto* cloned = TRY(JS::clone_array_buffer(realm.vm(), original_data, 0, original_data.byte_length()));
+ frame->m_data = cloned;
+
+ // 2. Let [[metadata]] represent the metadata associated with this newly constructed frame.
+ // 2.1. Copy each field of originalFrame's [[metadata]] into this.[[metadata]].
+ frame->m_metadata = original_frame->m_metadata;
+ // 2.2. For each field present in options.metadata, override this.[[metadata]] with a deep copy.
+ if (options.metadata.has_value()) {
+ auto const& source = options.metadata.value();
+ if (source.synchronization_source.has_value())
+ frame->m_metadata.synchronization_source = source.synchronization_source;
+ if (source.payload_type.has_value())
+ frame->m_metadata.payload_type = source.payload_type;
+ if (source.contributing_sources.has_value())
+ frame->m_metadata.contributing_sources = source.contributing_sources;
+ if (source.rtp_timestamp.has_value())
+ frame->m_metadata.rtp_timestamp = source.rtp_timestamp;
+ if (source.receive_time.has_value())
+ frame->m_metadata.receive_time = source.receive_time;
+ if (source.capture_time.has_value())
+ frame->m_metadata.capture_time = source.capture_time;
+ if (source.sender_capture_time_offset.has_value())
+ frame->m_metadata.sender_capture_time_offset = source.sender_capture_time_offset;
+ if (source.mime_type.has_value())
+ frame->m_metadata.mime_type = source.mime_type;
+ if (source.sequence_number.has_value())
+ frame->m_metadata.sequence_number = source.sequence_number;
+ if (source.audio_level.has_value())
+ frame->m_metadata.audio_level = source.audio_level;
+ }
+ return frame;
+}
+
+GC::Ref<RTCEncodedAudioFrame> RTCEncodedAudioFrame::create_from_packet(JS::Realm& realm, ByteBuffer payload,
+ u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ auto frame = create();
+ frame->m_data = JS::ArrayBuffer::create(realm, move(payload));
+ frame->m_metadata.synchronization_source = ssrc;
+ frame->m_metadata.payload_type = payload_type;
+ frame->m_metadata.rtp_timestamp = rtp_timestamp;
+ // sequenceNumber is signed 16-bit per spec — RTP seq is u16, just bit-cast.
+ frame->m_metadata.sequence_number = static_cast<i16>(sequence_number);
+ frame->m_metadata.mime_type = "audio/opus"_utf16;
+ return frame;
+}
+
+RTCEncodedAudioFrame::RTCEncodedAudioFrame() = default;
+
+RTCEncodedAudioFrame::~RTCEncodedAudioFrame() = default;
+
+void RTCEncodedAudioFrame::visit_edges(JS::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_data);
+}
+
+GC::Ref<JS::ArrayBuffer> RTCEncodedAudioFrame::data() const
+{
+ return *m_data;
+}
+
+WebIDL::ExceptionOr<void> RTCEncodedAudioFrame::set_data(GC::Ref<JS::ArrayBuffer> buffer)
+{
+ m_data = buffer;
+ return {};
+}
+
+GC::Ref<RTCEncodedAudioFrame> RTCEncodedAudioFrame::create(GC::Ref<JS::ArrayBuffer> data, RTCEncodedAudioFrameMetadata metadata)
+{
+ auto frame = create();
+ frame->m_data = data;
+ frame->m_metadata = move(metadata);
+ return frame;
+}
+
+// The Rust serialization steps borrow the spans and take ownership of the string reference.
+// Deserialization lends both to C++ for the duration of the call.
+template<typename T>
+struct OptionalFrameField {
+ bool present { false };
+ T value {};
+};
+
+struct RTCEncodedAudioFrameFields {
+ OptionalFrameField<u32> synchronization_source;
+ OptionalFrameField<u8> payload_type;
+ OptionalFrameField<ReadonlySpan<u32>> contributing_sources;
+ OptionalFrameField<u32> rtp_timestamp;
+ OptionalFrameField<double> receive_time;
+ OptionalFrameField<double> capture_time;
+ OptionalFrameField<double> sender_capture_time_offset;
+ OptionalFrameField<FlatPtr> mime_type;
+ OptionalFrameField<i16> sequence_number;
+ OptionalFrameField<double> audio_level;
+};
+
+extern "C" {
+JSObject* web_rtc_encoded_audio_frame_with_fields(JSObject*, void* state, void (*steps)(void*, RTCEncodedAudioFrameFields const*));
+JSObject* web_rtc_encoded_audio_frame_create(void* realm, RTCEncodedAudioFrameFields const*, JSObject* data);
+}
+
+JSObject* web_rtc_encoded_audio_frame_with_fields(JSObject* object, void* state, void (*steps)(void*, RTCEncodedAudioFrameFields const*))
+{
+ auto const& frame = Bindings::impl_from<RTCEncodedAudioFrame>(*JS::HostABI::object_from_abi(object));
+ auto metadata = frame.get_metadata();
+ RTCEncodedAudioFrameFields fields;
+ if (metadata.synchronization_source.has_value())
+ fields.synchronization_source = { true, metadata.synchronization_source.value() };
+ if (metadata.payload_type.has_value())
+ fields.payload_type = { true, metadata.payload_type.value() };
+ if (metadata.contributing_sources.has_value())
+ fields.contributing_sources = { true, metadata.contributing_sources.value().span() };
+ if (metadata.rtp_timestamp.has_value())
+ fields.rtp_timestamp = { true, metadata.rtp_timestamp.value() };
+ if (metadata.receive_time.has_value())
+ fields.receive_time = { true, metadata.receive_time.value() };
+ if (metadata.capture_time.has_value())
+ fields.capture_time = { true, metadata.capture_time.value() };
+ if (metadata.sender_capture_time_offset.has_value())
+ fields.sender_capture_time_offset = { true, metadata.sender_capture_time_offset.value() };
+ if (metadata.mime_type.has_value())
+ fields.mime_type = { true, metadata.mime_type.value().to_raw_leaked() };
+ if (metadata.sequence_number.has_value())
+ fields.sequence_number = { true, metadata.sequence_number.value() };
+ if (metadata.audio_level.has_value())
+ fields.audio_level = { true, metadata.audio_level.value() };
+ steps(state, &fields);
+ return JS::HostABI::object_to_abi(frame.data().ptr());
+}
+
+JSObject* web_rtc_encoded_audio_frame_create(void* realm, RTCEncodedAudioFrameFields const* fields, JSObject* data)
+{
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+ RTCEncodedAudioFrameMetadata metadata;
+ if (fields->synchronization_source.present)
+ metadata.synchronization_source = fields->synchronization_source.value;
+ if (fields->payload_type.present)
+ metadata.payload_type = fields->payload_type.value;
+ if (fields->contributing_sources.present)
+ metadata.contributing_sources = Vector<u32> { fields->contributing_sources.value };
+ if (fields->rtp_timestamp.present)
+ metadata.rtp_timestamp = fields->rtp_timestamp.value;
+ if (fields->receive_time.present)
+ metadata.receive_time = fields->receive_time.value;
+ if (fields->capture_time.present)
+ metadata.capture_time = fields->capture_time.value;
+ if (fields->sender_capture_time_offset.present)
+ metadata.sender_capture_time_offset = fields->sender_capture_time_offset.value;
+ if (fields->mime_type.present)
+ metadata.mime_type = Utf16String::from_raw(fields->mime_type.value);
+ if (fields->sequence_number.present)
+ metadata.sequence_number = fields->sequence_number.value;
+ if (fields->audio_level.present)
+ metadata.audio_level = fields->audio_level.value;
+ auto frame = RTCEncodedAudioFrame::create(as<JS::ArrayBuffer>(*JS::HostABI::object_from_abi(data)), move(metadata));
+ return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, frame).ptr());
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.h b/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.h
new file mode 100644
index 00000000000..940abd91b19
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/Vector.h>
+#include <LibJS/Runtime/ArrayBuffer.h>
+#include <LibWeb/Bindings/RTCEncodedAudioFrame.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+using Bindings::RTCEncodedAudioFrameMetadata;
+using Bindings::RTCEncodedAudioFrameOptions;
+using Bindings::RTCEncodedFrameMetadata;
+
+class WEB_API RTCEncodedAudioFrame final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCEncodedAudioFrame, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCEncodedAudioFrame);
+
+public:
+ static GC::Ref<RTCEncodedAudioFrame> create();
+ static GC::Ref<RTCEncodedAudioFrame> create(GC::Ref<JS::ArrayBuffer>, RTCEncodedAudioFrameMetadata);
+
+ static WebIDL::ExceptionOr<GC::Ref<RTCEncodedAudioFrame>> construct_impl(JS::Realm&, GC::Ref<RTCEncodedAudioFrame> original_frame, RTCEncodedAudioFrameOptions const& options = {});
+
+ static GC::Ref<RTCEncodedAudioFrame> create_from_packet(JS::Realm&, ByteBuffer payload,
+ u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number);
+
+ virtual ~RTCEncodedAudioFrame() override;
+
+ GC::Ref<JS::ArrayBuffer> data() const;
+ WebIDL::ExceptionOr<void> set_data(GC::Ref<JS::ArrayBuffer>);
+
+ RTCEncodedAudioFrameMetadata get_metadata() const { return m_metadata; }
+
+private:
+ explicit RTCEncodedAudioFrame();
+ virtual void visit_edges(JS::Cell::Visitor&) override;
+
+ // [[data]]
+ GC::Ptr<JS::ArrayBuffer> m_data;
+ // [[metadata]]
+ RTCEncodedAudioFrameMetadata m_metadata;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.idl b/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.idl
new file mode 100644
index 00000000000..648603e53ab
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCEncodedAudioFrame.idl
@@ -0,0 +1,17 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtcencodedaudioframe
+
+dictionary RTCEncodedAudioFrameMetadata : RTCEncodedFrameMetadata {
+ short sequenceNumber;
+ double audioLevel;
+};
+
+dictionary RTCEncodedAudioFrameOptions {
+ RTCEncodedAudioFrameMetadata metadata;
+};
+
+[Exposed=(Window,DedicatedWorker), Serializable]
+interface RTCEncodedAudioFrame {
+ constructor(RTCEncodedAudioFrame originalFrame, optional RTCEncodedAudioFrameOptions options = {});
+ attribute ArrayBuffer data;
+ RTCEncodedAudioFrameMetadata getMetadata();
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.cpp b/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.cpp
new file mode 100644
index 00000000000..4a443c09fab
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.cpp
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/RTCEncodedVideoFrame.h>
+#include <LibWeb/WebRTC/RTCEncodedVideoFrame.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCEncodedVideoFrame);
+
+GC::Ref<RTCEncodedVideoFrame> RTCEncodedVideoFrame::create() { return GC::Heap::the().allocate<RTCEncodedVideoFrame>(); }
+
+// FIXME: RTCEncodedVideoFrame is a stub — copy the original frame's data/metadata once they exist.
+WebIDL::ExceptionOr<GC::Ref<RTCEncodedVideoFrame>> RTCEncodedVideoFrame::construct_impl(GC::Ref<RTCEncodedVideoFrame>, Bindings::RTCEncodedVideoFrameOptions const&)
+{
+ return create();
+}
+
+RTCEncodedVideoFrame::RTCEncodedVideoFrame() = default;
+RTCEncodedVideoFrame::~RTCEncodedVideoFrame() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.h b/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.h
new file mode 100644
index 00000000000..3f68b56276a
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/RTCEncodedVideoFrame.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+class RTCEncodedVideoFrame final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCEncodedVideoFrame, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCEncodedVideoFrame);
+
+public:
+ static GC::Ref<RTCEncodedVideoFrame> create();
+ static WebIDL::ExceptionOr<GC::Ref<RTCEncodedVideoFrame>> construct_impl(GC::Ref<RTCEncodedVideoFrame> original_frame, Bindings::RTCEncodedVideoFrameOptions const& = {});
+ virtual ~RTCEncodedVideoFrame() override;
+
+private:
+ explicit RTCEncodedVideoFrame();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.idl b/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.idl
new file mode 100644
index 00000000000..02717ea3cb6
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCEncodedVideoFrame.idl
@@ -0,0 +1,34 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtcencodedvideoframe
+
+dictionary RTCEncodedFrameMetadata {
+ unsigned long synchronizationSource;
+ octet payloadType;
+ sequence<unsigned long> contributingSources;
+ unsigned long rtpTimestamp;
+ DOMHighResTimeStamp receiveTime;
+ DOMHighResTimeStamp captureTime;
+ DOMHighResTimeStamp senderCaptureTimeOffset;
+ DOMString mimeType;
+};
+
+dictionary RTCEncodedVideoFrameMetadata : RTCEncodedFrameMetadata {
+ unsigned long long frameId;
+ sequence<unsigned long long> dependencies;
+ unsigned short width;
+ unsigned short height;
+ unsigned long spatialIndex;
+ unsigned long temporalIndex;
+ long long timestamp;
+};
+
+dictionary RTCEncodedVideoFrameOptions {
+ RTCEncodedVideoFrameMetadata metadata;
+};
+
+// FIXME: spec has `readonly attribute EncodedVideoChunkType type;` — WebCodecs isn't implemented.
+[Exposed=(Window,DedicatedWorker), Serializable]
+interface RTCEncodedVideoFrame {
+ [FIXME] constructor(RTCEncodedVideoFrame originalFrame, optional RTCEncodedVideoFrameOptions options = {});
+ [FIXME] attribute ArrayBuffer data;
+ [FIXME] RTCEncodedVideoFrameMetadata getMetadata();
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCError.cpp b/Libraries/LibWeb/WebRTC/RTCError.cpp
new file mode 100644
index 00000000000..21c8d1a1286
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCError.cpp
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/WebRTC/RTCError.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCError);
+
+GC::Ref<RTCError> RTCError::create() { return GC::Heap::the().allocate<RTCError>(); }
+
+// FIXME: RTCError is a stub — populate errorDetail/sdpLineNumber/etc. from init and use the message.
+WebIDL::ExceptionOr<GC::Ref<RTCError>> RTCError::construct_impl(RTCErrorInit const&, Utf16String const&)
+{
+ return create();
+}
+RTCError::RTCError()
+ : WebIDL::DOMException("OperationError"_fly_string, {})
+{
+}
+RTCError::~RTCError() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCError.h b/Libraries/LibWeb/WebRTC/RTCError.h
new file mode 100644
index 00000000000..92c7853601a
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCError.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/RTCError.h>
+#include <LibWeb/WebIDL/DOMException.h>
+
+namespace Web::WebRTC {
+
+using RTCErrorInit = Bindings::RTCErrorInit;
+
+class RTCError final : public WebIDL::DOMException {
+ WEB_WRAPPABLE(RTCError, WebIDL::DOMException);
+ GC_DECLARE_ALLOCATOR(RTCError);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCError> create();
+ static WebIDL::ExceptionOr<GC::Ref<RTCError>> construct_impl(RTCErrorInit const&, Utf16String const& message);
+ virtual ~RTCError() override;
+
+private:
+ RTCError();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCError.idl b/Libraries/LibWeb/WebRTC/RTCError.idl
new file mode 100644
index 00000000000..a322f62d11b
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCError.idl
@@ -0,0 +1,29 @@
+// https://w3c.github.io/webrtc-pc/#rtcerror-interface
+
+[Exposed=Window]
+interface RTCError : DOMException {
+ [FIXME] constructor(RTCErrorInit init, optional DOMString message = "");
+ [FIXME] readonly attribute RTCErrorDetailType errorDetail;
+ [FIXME] readonly attribute long? sdpLineNumber;
+ [FIXME] readonly attribute long? sctpCauseCode;
+ [FIXME] readonly attribute unsigned long? receivedAlert;
+ [FIXME] readonly attribute unsigned long? sentAlert;
+};
+
+dictionary RTCErrorInit {
+ required RTCErrorDetailType errorDetail;
+ long sdpLineNumber;
+ long sctpCauseCode;
+ unsigned long receivedAlert;
+ unsigned long sentAlert;
+};
+
+enum RTCErrorDetailType {
+ "data-channel-failure",
+ "dtls-failure",
+ "fingerprint-failure",
+ "sctp-failure",
+ "sdp-syntax-error",
+ "hardware-encoder-not-available",
+ "hardware-encoder-error"
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCErrorEvent.cpp b/Libraries/LibWeb/WebRTC/RTCErrorEvent.cpp
new file mode 100644
index 00000000000..0ce78ddddba
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCErrorEvent.cpp
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCErrorEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCErrorEvent);
+
+GC::Ref<RTCErrorEvent> RTCErrorEvent::create(Utf16FlyString const& event_name, RTCErrorEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCErrorEvent>(event_name, event_init, time_stamp);
+}
+
+// FIXME: RTCErrorEvent is a stub — store the error once the attribute is implemented.
+RTCErrorEvent::RTCErrorEvent(Utf16FlyString const& event_name, RTCErrorEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+{
+}
+
+RTCErrorEvent::~RTCErrorEvent() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCErrorEvent.h b/Libraries/LibWeb/WebRTC/RTCErrorEvent.h
new file mode 100644
index 00000000000..04afd811f85
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCErrorEvent.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCErrorEvent.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+using RTCErrorEventInit = Bindings::RTCErrorEventInit;
+
+class RTCErrorEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCErrorEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCErrorEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCErrorEvent> create(Utf16FlyString const& event_name, RTCErrorEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+ virtual ~RTCErrorEvent() override;
+
+private:
+ RTCErrorEvent(Utf16FlyString const& event_name, RTCErrorEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCErrorEvent.idl b/Libraries/LibWeb/WebRTC/RTCErrorEvent.idl
new file mode 100644
index 00000000000..04c15382168
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCErrorEvent.idl
@@ -0,0 +1,13 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcerrorevent-interface
+
+[Exposed=Window]
+interface RTCErrorEvent : Event {
+ [FIXME] constructor(DOMString type, RTCErrorEventInit eventInitDict);
+ [FIXME, SameObject] readonly attribute RTCError error;
+};
+
+dictionary RTCErrorEventInit : EventInit {
+ // FIXME: spec has `required RTCError error`.
+ required object error;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCIceCandidate.cpp b/Libraries/LibWeb/WebRTC/RTCIceCandidate.cpp
new file mode 100644
index 00000000000..9161fd0dd6d
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCIceCandidate.cpp
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCIceCandidate.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCIceCandidate);
+
+GC::Ref<RTCIceCandidate> RTCIceCandidate::create(RTCIceCandidateInit const& init)
+{
+ return GC::Heap::the().allocate<RTCIceCandidate>(init);
+}
+
+WebIDL::ExceptionOr<GC::Ref<RTCIceCandidate>> RTCIceCandidate::construct_impl(RTCIceCandidateInit const& init)
+{
+ return create(init);
+}
+
+RTCIceCandidate::RTCIceCandidate(RTCIceCandidateInit init)
+ : m_init(move(init))
+{
+}
+
+RTCIceCandidate::~RTCIceCandidate() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCIceCandidate.h b/Libraries/LibWeb/WebRTC/RTCIceCandidate.h
new file mode 100644
index 00000000000..156181afad0
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCIceCandidate.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/RTCIceCandidate.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+using Bindings::RTCIceCandidateInit;
+
+class RTCIceCandidate final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCIceCandidate, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCIceCandidate);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCIceCandidate> create(RTCIceCandidateInit const& = {});
+ static WebIDL::ExceptionOr<GC::Ref<RTCIceCandidate>> construct_impl(RTCIceCandidateInit const& = {});
+
+ virtual ~RTCIceCandidate() override;
+
+ Utf16String const& candidate() const { return m_init.candidate; }
+ Optional<Utf16String> sdp_mid() const { return m_init.sdp_mid; }
+ Optional<u16> sdp_m_line_index() const { return m_init.sdp_m_line_index; }
+ Optional<Utf16String> username_fragment() const { return m_init.username_fragment; }
+ RTCIceCandidateInit to_json() const { return m_init; }
+ Optional<Utf16String> foundation() const { return {}; }
+ Optional<Bindings::RTCIceServerTransportProtocol> relay_protocol() const { return {}; }
+
+private:
+ explicit RTCIceCandidate(RTCIceCandidateInit);
+ RTCIceCandidateInit m_init;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCIceCandidate.idl b/Libraries/LibWeb/WebRTC/RTCIceCandidate.idl
new file mode 100644
index 00000000000..97e53810a89
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCIceCandidate.idl
@@ -0,0 +1,35 @@
+// https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
+
+[Exposed=Window]
+interface RTCIceCandidate {
+ constructor(optional RTCIceCandidateInit candidateInitDict = {});
+ readonly attribute DOMString candidate;
+ readonly attribute DOMString? sdpMid;
+ readonly attribute unsigned short? sdpMLineIndex;
+ readonly attribute DOMString? foundation;
+ [FIXME] readonly attribute RTCIceComponent? component;
+ [FIXME] readonly attribute unsigned long? priority;
+ [FIXME] readonly attribute DOMString? address;
+ [FIXME] readonly attribute RTCIceProtocol? protocol;
+ [FIXME] readonly attribute unsigned short? port;
+ [FIXME] readonly attribute RTCIceCandidateType? type;
+ [FIXME] readonly attribute RTCIceTcpCandidateType? tcpType;
+ [FIXME] readonly attribute DOMString? relatedAddress;
+ [FIXME] readonly attribute unsigned short? relatedPort;
+ readonly attribute DOMString? usernameFragment;
+ readonly attribute RTCIceServerTransportProtocol? relayProtocol;
+ [FIXME] readonly attribute DOMString? url;
+ RTCIceCandidateInit toJSON();
+};
+
+dictionary RTCIceCandidateInit {
+ DOMString candidate = "";
+ DOMString? sdpMid = null;
+ unsigned short? sdpMLineIndex = null;
+ DOMString? usernameFragment = null;
+};
+
+enum RTCIceProtocol { "udp", "tcp" };
+enum RTCIceTcpCandidateType { "active", "passive", "so" };
+enum RTCIceCandidateType { "host", "srflx", "prflx", "relay" };
+enum RTCIceServerTransportProtocol { "udp", "tcp", "tls" };
diff --git a/Libraries/LibWeb/WebRTC/RTCIceTransport.cpp b/Libraries/LibWeb/WebRTC/RTCIceTransport.cpp
new file mode 100644
index 00000000000..b3535714de2
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCIceTransport.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/WebRTC/RTCIceTransport.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCIceTransport);
+
+GC::Ref<RTCIceTransport> RTCIceTransport::create() { return GC::Heap::the().allocate<RTCIceTransport>(); }
+RTCIceTransport::RTCIceTransport() = default;
+RTCIceTransport::~RTCIceTransport() = default;
+void RTCIceTransport::set_onstatechange(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::statechange, cb); }
+WebIDL::CallbackType* RTCIceTransport::onstatechange() { return event_handler_attribute(HTML::EventNames::statechange); }
+void RTCIceTransport::set_ongatheringstatechange(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::gatheringstatechange, cb); }
+WebIDL::CallbackType* RTCIceTransport::ongatheringstatechange() { return event_handler_attribute(HTML::EventNames::gatheringstatechange); }
+void RTCIceTransport::set_onselectedcandidatepairchange(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::selectedcandidatepairchange, cb); }
+WebIDL::CallbackType* RTCIceTransport::onselectedcandidatepairchange() { return event_handler_attribute(HTML::EventNames::selectedcandidatepairchange); }
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCIceTransport.h b/Libraries/LibWeb/WebRTC/RTCIceTransport.h
new file mode 100644
index 00000000000..5d52d8e5603
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCIceTransport.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/DOM/EventTarget.h>
+
+namespace Web::WebRTC {
+
+class RTCIceTransport final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCIceTransport, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCIceTransport);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCIceTransport> create();
+ virtual ~RTCIceTransport() override;
+
+ void set_onstatechange(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onstatechange();
+ void set_ongatheringstatechange(WebIDL::CallbackType*);
+ WebIDL::CallbackType* ongatheringstatechange();
+ void set_onselectedcandidatepairchange(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onselectedcandidatepairchange();
+
+private:
+ RTCIceTransport();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCIceTransport.idl b/Libraries/LibWeb/WebRTC/RTCIceTransport.idl
new file mode 100644
index 00000000000..48ec2441955
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCIceTransport.idl
@@ -0,0 +1,38 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcicetransport-interface
+
+[Exposed=Window]
+interface RTCIceTransport : EventTarget {
+ [FIXME] readonly attribute RTCIceRole role;
+ [FIXME] readonly attribute RTCIceComponent component;
+ [FIXME] readonly attribute RTCIceTransportState state;
+ [FIXME] readonly attribute RTCIceGathererState gatheringState;
+ [FIXME] sequence<RTCIceCandidate> getLocalCandidates();
+ [FIXME] sequence<RTCIceCandidate> getRemoteCandidates();
+ [FIXME] RTCIceCandidatePair? getSelectedCandidatePair();
+ [FIXME] RTCIceParameters? getLocalParameters();
+ [FIXME] RTCIceParameters? getRemoteParameters();
+ attribute EventHandler onstatechange;
+ attribute EventHandler ongatheringstatechange;
+ attribute EventHandler onselectedcandidatepairchange;
+};
+
+dictionary RTCIceParameters {
+ DOMString usernameFragment;
+ DOMString password;
+};
+
+enum RTCIceGathererState { "new", "gathering", "complete" };
+
+enum RTCIceTransportState {
+ "closed",
+ "failed",
+ "disconnected",
+ "new",
+ "checking",
+ "completed",
+ "connected"
+};
+
+enum RTCIceRole { "unknown", "controlling", "controlled" };
+enum RTCIceComponent { "rtp", "rtcp" };
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp b/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp
new file mode 100644
index 00000000000..c37e7413cfd
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp
@@ -0,0 +1,1861 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Debug.h>
+#include <AK/JsonArray.h>
+#include <AK/JsonObject.h>
+#include <LibAudio/PlaybackStream.h>
+#include <LibCore/EventLoop.h>
+#include <LibGC/Heap.h>
+#include <LibJS/Runtime/Map.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibMedia/FFmpeg/FFmpegAudioConverter.h>
+#include <LibMedia/FFmpeg/FFmpegAudioDecoder.h>
+#include <LibMedia/FFmpeg/FFmpegAudioEncoder.h>
+#include <LibMediaCodecs/AudioBlock.h>
+#include <LibMediaCodecs/CodecID.h>
+#include <LibMediaCodecs/CodedFrame.h>
+#include <LibWeb/Bindings/RTCPeerConnection.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/DOM/Event.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/Infra/JSON.h>
+#include <LibWeb/MediaCapture/MediaStream.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+#include <LibWeb/PermissionsAPI/Permissions.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+#include <LibWeb/WebIDL/Promise.h>
+#include <LibWeb/WebRTC/RTCDataChannel.h>
+#include <LibWeb/WebRTC/RTCDataChannelEvent.h>
+#include <LibWeb/WebRTC/RTCEncodedAudioFrame.h>
+#include <LibWeb/WebRTC/RTCIceCandidate.h>
+#include <LibWeb/WebRTC/RTCPeerConnection.h>
+#include <LibWeb/WebRTC/RTCPeerConnectionIceEvent.h>
+#include <LibWeb/WebRTC/RTCRtpReceiver.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransform.h>
+#include <LibWeb/WebRTC/RTCRtpSender.h>
+#include <LibWeb/WebRTC/RTCRtpTransceiver.h>
+#include <LibWeb/WebRTC/RTCSctpTransport.h>
+#include <LibWeb/WebRTC/RTCSessionDescription.h>
+#include <LibWeb/WebRTC/RTCStatsReport.h>
+#include <LibWeb/WebRTC/RTCTrackEvent.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
+#include <LibWebRTCClient/Client.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCPeerConnection);
+
+WebIDL::ExceptionOr<GC::Ref<RTCPeerConnection>> RTCPeerConnection::create_for_constructor(JS::Object& relevant_global_object, RTCConfiguration const& configuration)
+{
+ if (!WebRTCAgent::the().is_ready())
+ return WebIDL::OperationError::create("Unable to start the WebRTC helper"_utf16);
+ auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(relevant_global_object);
+ VERIFY(global_scope);
+ auto connection = GC::Heap::the().allocate<RTCPeerConnection>(global_scope->this_impl(), configuration);
+ JsonArray servers;
+ for (auto const& server : configuration.ice_servers) {
+ JsonArray urls;
+ server.urls.visit(
+ [&](Utf16String const& url) { urls.must_append(url.to_utf8()); },
+ [&](auto const& entries) { for (auto const& url : entries) urls.must_append(url.to_utf8()); });
+ JsonObject entry;
+ entry.set("urls"sv, move(urls));
+ entry.set("username"sv, server.username.value_or(Utf16String {}).to_utf8());
+ entry.set("credential"sv, server.credential.value_or(Utf16String {}).to_utf8());
+ servers.must_append(move(entry));
+ }
+ JsonObject config;
+ config.set("ice_servers"sv, move(servers));
+ config.set("ice_transport_policy"sv, idl_enum_to_string(configuration.ice_transport_policy).to_utf8());
+ config.set("bundle_policy"sv, idl_enum_to_string(configuration.bundle_policy).to_utf8());
+ config.set("ice_candidate_pool_size"sv, configuration.ice_candidate_pool_size);
+ // Like other browsers, only reveal local addresses to pages that may capture audio, which could tell where the
+ // user is anyway. Everyone else gets mDNS names in their place.
+ // https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-mdns-ice-candidates#section-3.1
+ PermissionsAPI::PermissionDescriptor microphone_permission { "microphone"_utf16 };
+ auto may_capture = PermissionsAPI::permission_state(microphone_permission) == PermissionsAPI::PermissionState::Granted;
+ config.set("host_candidates"sv, may_capture ? "exposed"sv : "obfuscated"sv);
+ if (!configuration.certificates.is_empty())
+ return WebIDL::NotSupportedError::create("Custom RTC certificates are not supported"_utf16);
+ auto result = WebRTCAgent::the().client()->try_create_peer_connection(connection->m_pc_id, config.serialized());
+ if (result.is_error()) {
+ connection->m_is_closed = true;
+ return WebIDL::OperationError::create("WebRTC helper disconnected during construction"_utf16);
+ }
+ if (!result.value().is_empty()) {
+ connection->m_is_closed = true;
+ return WebIDL::OperationError::create(Utf16String::from_utf8(result.value()));
+ }
+ WebRTCAgent::the().register_peer_connection(connection->m_pc_id, connection);
+ return connection;
+}
+
+RTCPeerConnection::RTCPeerConnection(GC::Ref<DOM::EventTarget> relevant_global_object, RTCConfiguration configuration)
+ : DOM::EventTarget()
+ , m_global_object(relevant_global_object)
+ , m_configuration(move(configuration))
+{
+ auto& agent = WebRTCAgent::the();
+ m_pc_id = agent.next_pc_id();
+}
+
+void RTCPeerConnection::finalize()
+{
+ auto& agent = WebRTCAgent::the();
+ if (!m_is_closed) {
+ if (auto* client = agent.existing_client())
+ client->async_close_peer_connection(m_pc_id);
+ }
+ agent.unregister_peer_connection(m_pc_id);
+ Base::finalize();
+}
+
+JS::Realm& RTCPeerConnection::relevant_realm() const
+{
+ return HTML::relevant_realm(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+}
+
+JS::Object& RTCPeerConnection::relevant_global_object() const
+{
+ return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+}
+
+void RTCPeerConnection::visit_edges(JS::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_global_object);
+ visitor.visit(m_sctp);
+ visitor.visit(m_last_operation);
+ visitor.visit(m_transceivers);
+ visitor.visit(m_data_channels);
+ visitor.visit(m_data_channels_by_id);
+ visitor.visit(m_current_local_description);
+ visitor.visit(m_pending_local_description);
+ visitor.visit(m_current_remote_description);
+ visitor.visit(m_pending_remote_description);
+ visitor.visit(m_remote_streams);
+ visitor.visit(m_remote_receivers_by_id);
+ for (auto& [_, pipeline] : m_outgoing_audio_pipelines)
+ visitor.visit(pipeline->track);
+}
+
+GC::Ref<WebIDL::Promise> RTCPeerConnection::chain_operation(GC::Ref<WebIDL::ReactionSteps> operation)
+{
+ if (m_is_closed)
+ return WebIDL::create_rejected_promise(relevant_realm(), WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ auto previous = m_last_operation;
+ if (!previous)
+ previous = WebIDL::create_resolved_promise(relevant_realm(), JS::js_undefined());
+ m_last_operation = WebIDL::react_to_promise(*previous, operation, operation);
+ return *m_last_operation;
+}
+
+void RTCPeerConnection::on_helper_died()
+{
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ for (auto& [_, promise] : m_pending_void_requests)
+ WebIDL::reject_promise(relevant_realm(), *promise, WebIDL::OperationError::create("WebRTC helper disconnected"_utf16));
+ for (auto& [_, promise] : m_pending_description_requests)
+ WebIDL::reject_promise(relevant_realm(), *promise, WebIDL::OperationError::create("WebRTC helper disconnected"_utf16));
+ m_pending_void_requests.clear();
+ m_pending_description_requests.clear();
+ m_pending_description_payloads.clear();
+ m_held_ice_events.clear();
+ close();
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::connectionstatechange));
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close
+void RTCPeerConnection::close()
+{
+ // When the close method is invoked, the user agent MUST run the following steps:
+ // 1. Let connection be the RTCPeerConnection object on which the method was invoked.
+ // 2. close the connection with connection and the value false.
+ close_the_connection_algorithm(false);
+}
+
+void RTCPeerConnection::close_for_document_destruction()
+{
+ close_the_connection_algorithm(true);
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close
+void RTCPeerConnection::close_the_connection_algorithm(bool disappear)
+{
+ // The close the connection algorithm given a connection and a disappear boolean, is as follows:
+ // 1. If connection.[[IsClosed]] is true, abort these steps.
+ if (m_is_closed)
+ return;
+ // 2.Set connection.[[IsClosed]] to true.
+ m_is_closed = true;
+ // 3. Set connection.[[SignalingState]] to "closed". This does not fire any event.
+ m_signaling_state = Bindings::RTCSignalingState::Closed;
+ // 4. Let transceivers be the result of executing the CollectTransceivers algorithm...
+ auto transceivers = collect_transceivers();
+ // 4... For every RTCRtpTransceiver transceiver in transceivers, run the following steps:
+ for (auto& transceiver : transceivers) {
+ // 4.1. If transceiver.[[Stopped]] is true, abort these sub steps.
+ if (transceiver->is_stopped())
+ continue;
+ // 4.2. Stop the RTCRtpTransceiver with transceiver and disappear.
+ transceiver->stop(disappear);
+ }
+ auto& agent = WebRTCAgent::the();
+ if (auto* client = agent.existing_client())
+ client->async_close_peer_connection(m_pc_id);
+ for (auto& [id, channel] : m_data_channels_by_id) {
+ channel->set_ready_state(Bindings::RTCDataChannelState::Closed);
+ agent.unregister_data_channel(id);
+ }
+ for (auto& [_, pipeline] : m_outgoing_audio_pipelines) {
+ if (pipeline->track && pipeline->sink)
+ pipeline->track->remove_audio_sink(*pipeline->sink);
+ }
+ m_outgoing_audio_pipelines.clear();
+ m_last_operation = nullptr;
+ m_pending_void_requests.clear();
+ m_pending_description_requests.clear();
+ m_pending_description_payloads.clear();
+ m_held_ice_events.clear();
+ for (auto& [_, playback] : m_receiver_audio_playbacks) {
+ if (playback->playback_stream)
+ (void)playback->playback_stream->discard_buffer_and_suspend();
+ }
+ m_receiver_audio_playbacks.clear();
+ agent.unregister_peer_connection(m_pc_id);
+ // 6. If connection.[[SctpTransport]] is not null...
+ if (m_sctp) {
+ // TODO: 6. ...tear down the underlying SCTP association by sending an SCTP ABORT chunk and set the [[SctpTransportState]] to "closed".
+ }
+ // TODO: 7. Set the [[DtlsTransportState]] slot of each of connection's RTCDtlsTransports to "closed".
+ // TODO: 8. Destroy connection's ICE Agent, abruptly ending any active ICE processing and releasing any relevant resources (e.g. TURN permissions).
+ // TODO: 9. Set the [[IceTransportState]] slot of each of connection's RTCIceTransports to "closed".
+ // 10. Set connection.[[IceConnectionState]] to "closed". This does not fire any event.
+ m_ice_connection_state = Bindings::RTCIceConnectionState::Closed;
+ // 11. Set connection.[[ConnectionState]] to "closed". This does not fire any event.
+ m_connection_state = Bindings::RTCPeerConnectionState::Closed;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createoffer
+GC::Ref<WebIDL::Promise> RTCPeerConnection::create_offer(RTCOfferOptions const& options)
+{
+ return chain_operation(GC::create_function(heap(), [this, options](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
+ return create_offer_impl(options)->promise();
+ }));
+}
+
+GC::Ref<WebIDL::Promise> RTCPeerConnection::create_offer_impl(RTCOfferOptions const& options)
+{
+ // 1. Let connection be the RTCPeerConnection object on which the method was invoked.
+ auto& realm = relevant_realm();
+ // 2. If connection.[[IsClosed]] is true, return a promise rejected with a newly created InvalidStateError.
+ if (m_is_closed) {
+ auto promise = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ return promise;
+ }
+ // FIXME: 3. Return the result of chaining the result of creating an offer with connection to connection's operations chain.
+ m_restart_ice |= options.ice_restart;
+ return create_an_offer();
+}
+
+// https://www.w3.org/TR/webrtc/#create-an-offer
+GC::Ref<WebIDL::Promise> RTCPeerConnection::create_an_offer()
+{
+ auto& realm = relevant_realm();
+ // 1. If connection.[[SignalingState]] is neither "stable" nor "have-local-offer", return a promise rejected with a newly created InvalidStateError.
+ if (m_signaling_state != Bindings::RTCSignalingState::Stable && m_signaling_state != Bindings::RTCSignalingState::HaveLocalOffer) {
+ auto rejected = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, rejected, WebIDL::InvalidStateError::create("RTCPeerConnection is not in a state to create an offer"_utf16));
+ return rejected;
+ }
+ // 2. Let p be a new promise.
+ auto p = WebIDL::create_promise(realm);
+ // 3. In parallel, begin the in-parallel steps to create an offer given connection and p.
+ // Service-side equivalents (in parallel + the final-step queued task) are run by the rust
+ // WebRTCClient; result arrives via on_create_offer_result.
+ auto& agent = WebRTCAgent::the();
+ auto request_id = agent.next_request_id();
+ m_pending_description_requests.set(request_id, p);
+ if (auto* client = agent.client())
+ client->async_create_offer(m_pc_id, request_id, m_restart_ice);
+ // 4. Return p.
+ return p;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createanswer
+GC::Ref<WebIDL::Promise> RTCPeerConnection::create_answer(RTCAnswerOptions const& options)
+{
+ return chain_operation(GC::create_function(heap(), [this, options](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
+ return create_answer_impl(options)->promise();
+ }));
+}
+
+GC::Ref<WebIDL::Promise> RTCPeerConnection::create_answer_impl(RTCAnswerOptions const&)
+{
+ auto& realm = relevant_realm();
+ // 1. Let connection be the RTCPeerConnection object on which the method was invoked.
+ // 2. If connection.[[IsClosed]] is true, return a promise rejected with a newly created InvalidStateError.
+ if (m_is_closed) {
+ auto rejected = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, rejected, WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ return rejected;
+ }
+ // FIXME: 3. Return the result of chaining the result of creating an answer with connection to connection's operations chain.
+ return create_an_answer();
+}
+
+// https://www.w3.org/TR/webrtc/#create-an-answer
+GC::Ref<WebIDL::Promise> RTCPeerConnection::create_an_answer()
+{
+ auto& realm = relevant_realm();
+ // 1. If connection.[[SignalingState]] is neither "have-remote-offer" nor "have-local-pranswer", return a promise rejected with a newly created InvalidStateError.
+ if (m_signaling_state != Bindings::RTCSignalingState::HaveRemoteOffer && m_signaling_state != Bindings::RTCSignalingState::HaveLocalPranswer) {
+ auto rejected = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, rejected, WebIDL::InvalidStateError::create("RTCPeerConnection is not in a state to create an answer"_utf16));
+ return rejected;
+ }
+ // 2. Let p be a new promise.
+ auto p = WebIDL::create_promise(realm);
+ // 3. In parallel, begin the in-parallel steps to create an answer given connection and p.
+ // Service-side equivalents (in parallel + the final-step queued task) are run by the rust
+ // WebRTCClient; result arrives via on_create_answer_result.
+ auto& agent = WebRTCAgent::the();
+ auto request_id = agent.next_request_id();
+ m_pending_description_requests.set(request_id, p);
+ if (auto* client = agent.client())
+ client->async_create_answer(m_pc_id, request_id);
+ // 4. Return p.
+ return p;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setlocaldescription
+GC::Ref<WebIDL::Promise> RTCPeerConnection::set_local_description(RTCLocalSessionDescriptionInit const& description)
+{
+ return chain_operation(GC::create_function(heap(), [this, description](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
+ return set_local_description_impl(description)->promise();
+ }));
+}
+
+GC::Ref<WebIDL::Promise> RTCPeerConnection::set_local_description_impl(RTCLocalSessionDescriptionInit const& description)
+{
+ if (m_is_closed)
+ return WebIDL::create_rejected_promise(relevant_realm(), WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ auto& realm = relevant_realm();
+ // 1. Let description be the method's first argument.
+ // 2. Let connection be the RTCPeerConnection object on which the method was invoked.
+ // 3. Let sdp be description.sdp.
+ auto sdp = description.sdp;
+ // FIXME: 4. Return the result of chaining the following steps to connection's operations chain:
+ // 4.1. Let type be description.type if present, or "offer" if not present and connection.[[SignalingState]] is either "stable", "have-local-offer", or "have-remote-pranswer"; otherwise "answer".
+ Bindings::RTCSdpType type;
+ if (description.type.has_value()) {
+ type = *description.type;
+ } else if (m_signaling_state == Bindings::RTCSignalingState::Stable
+ || m_signaling_state == Bindings::RTCSignalingState::HaveLocalOffer
+ || m_signaling_state == Bindings::RTCSignalingState::HaveRemotePranswer) {
+ type = Bindings::RTCSdpType::Offer;
+ } else {
+ type = Bindings::RTCSdpType::Answer;
+ }
+ // 4.2. If type is "offer", and sdp is not the empty string and not equal to connection.[[LastCreatedOffer]], then return a promise rejected with a newly created InvalidModificationError and abort these steps.
+ if (type == Bindings::RTCSdpType::Offer && !sdp.is_empty() && sdp != m_last_created_offer) {
+ auto rejected = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, rejected, WebIDL::InvalidModificationError::create("Local description SDP does not match last created offer"_utf16));
+ return rejected;
+ }
+ // 4.3. If type is "answer" or "pranswer", and sdp is not the empty string and not equal to connection.[[LastCreatedAnswer]], then return a promise rejected with a newly created InvalidModificationError and abort these steps.
+ if ((type == Bindings::RTCSdpType::Answer || type == Bindings::RTCSdpType::Pranswer) && !sdp.is_empty() && sdp != m_last_created_answer) {
+ auto rejected = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, rejected, WebIDL::InvalidModificationError::create("Local description SDP does not match last created answer"_utf16));
+ return rejected;
+ }
+ if (sdp.is_empty() && type != Bindings::RTCSdpType::Rollback) {
+ auto generated = type == Bindings::RTCSdpType::Offer ? create_an_offer() : create_an_answer();
+ return WebIDL::react_to_promise(generated, GC::create_function(heap(), [this, type](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {
+ if (m_is_closed)
+ return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);
+ auto sdp_value = TRY(value.as_object().get("sdp"_utf16_fly_string));
+ auto generated_sdp = TRY(sdp_value.to_utf16_string(relevant_realm().vm()));
+ return set_a_local_description(type, generated_sdp)->promise();
+ }),
+ nullptr);
+ }
+ // 4.6. Return the result of setting the local session description indicated by {type, sdp}.
+ return set_a_local_description(type, sdp);
+}
+
+// FIXME: https://www.w3.org/TR/webrtc/#set-the-rtcsessiondescription (set the local session description)
+GC::Ref<WebIDL::Promise> RTCPeerConnection::set_a_local_description(Bindings::RTCSdpType type, Utf16String const& sdp)
+{
+ auto& realm = relevant_realm();
+ auto p = WebIDL::create_promise(realm);
+ auto& agent = WebRTCAgent::the();
+ auto request_id = agent.next_request_id();
+ m_pending_void_requests.set(request_id, p);
+ m_pending_description_payloads.set(request_id, PendingDescription { type, sdp, true });
+ if (auto* client = agent.client())
+ client->async_set_local_description(m_pc_id, request_id, idl_enum_to_string(type).to_well_formed_utf8(), sdp.to_well_formed_utf8());
+ return p;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setremotedescription
+GC::Ref<WebIDL::Promise> RTCPeerConnection::set_remote_description(RTCSessionDescriptionInit const& description)
+{
+ return chain_operation(GC::create_function(heap(), [this, description](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
+ return set_remote_description_impl(description)->promise();
+ }));
+}
+
+GC::Ref<WebIDL::Promise> RTCPeerConnection::set_remote_description_impl(RTCSessionDescriptionInit const& description)
+{
+ if (m_is_closed)
+ return WebIDL::create_rejected_promise(relevant_realm(), WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ // 1. Let description be the method's first argument.
+ // 2. Let connection be the RTCPeerConnection object on which the method was invoked.
+ // FIXME: 3. Return the result of chaining the following steps to connection's operations chain:
+ // FIXME: 3.1. If description.type is "offer" and is invalid for the current connection.[[SignalingState]] as described in [RFC9429] (section 5.5. and section 5.6.), then run the following sub steps:
+ // FIXME: 3.1.1. Let p be the result of setting the local session description indicated by {type: "rollback"}.
+ // FIXME: 3.1.2. Return the result of reacting to p with a fulfillment step that sets the remote session description description, and abort these steps.
+ // 3.2. Return the result of setting the remote session description description.
+ return set_a_remote_description(description);
+}
+
+// FIXME: https://www.w3.org/TR/webrtc/#set-description (set the remote session description)
+GC::Ref<WebIDL::Promise> RTCPeerConnection::set_a_remote_description(RTCSessionDescriptionInit const& description)
+{
+ auto& realm = relevant_realm();
+ auto p = WebIDL::create_promise(realm);
+ auto& agent = WebRTCAgent::the();
+ auto request_id = agent.next_request_id();
+ m_pending_void_requests.set(request_id, p);
+ m_pending_description_payloads.set(request_id, PendingDescription { description.type, description.sdp, false });
+ if (auto* client = agent.client())
+ client->async_set_remote_description(m_pc_id, request_id, idl_enum_to_string(description.type).to_well_formed_utf8(), description.sdp.to_well_formed_utf8());
+ return p;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-localdescription
+GC::Ptr<RTCSessionDescription> RTCPeerConnection::local_description() const
+{
+ // The localDescription attribute MUST return [[PendingLocalDescription]] if not null and otherwise [[CurrentLocalDescription]].
+ if (m_pending_local_description)
+ return m_pending_local_description;
+ return m_current_local_description;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-remotedescription
+GC::Ptr<RTCSessionDescription> RTCPeerConnection::remote_description() const
+{
+ // The remoteDescription attribute MUST return [[PendingRemoteDescription]] if not null and otherwise [[CurrentRemoteDescription]].
+ if (m_pending_remote_description)
+ return m_pending_remote_description;
+ return m_current_remote_description;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getreceivers
+GC::RootVector<GC::Ref<RTCRtpReceiver>> RTCPeerConnection::get_receivers() const
+{
+ // 1. Let transceivers be the result of executing the CollectTransceivers algorithm.
+ auto transceivers = collect_transceivers();
+ // 2. Let receivers be a new empty sequence.
+ GC::RootVector<GC::Ref<RTCRtpReceiver>> receivers;
+ // 3. For each transceiver in transceivers,
+ for (auto& transceiver : transceivers) {
+ // 3.1. If transceiver.[[Stopped]] is false, add transceiver.[[Receiver]] to receivers.
+ if (!transceiver->is_stopped())
+ receivers.append(transceiver->receiver());
+ }
+ // 4. Return receivers.
+ return receivers;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addicecandidate
+GC::Ref<WebIDL::Promise> RTCPeerConnection::add_ice_candidate(RTCIceCandidateInit const& candidate)
+{
+ return chain_operation(GC::create_function(heap(), [this, candidate](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
+ return add_ice_candidate_impl(candidate)->promise();
+ }));
+}
+
+GC::Ref<WebIDL::Promise> RTCPeerConnection::add_ice_candidate_impl(RTCIceCandidateInit const& candidate)
+{
+ if (m_is_closed)
+ return WebIDL::create_rejected_promise(relevant_realm(), WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ auto& realm = relevant_realm();
+ // 1. Let candidate be the method's argument.
+ // 2. Let connection be the RTCPeerConnection object on which the method was invoked.
+ // 3. If candidate.candidate is not an empty string and both candidate.sdpMid and candidate.sdpMLineIndex are null, return a promise rejected with a newly created TypeError.
+ if (!candidate.candidate.is_empty() && !candidate.sdp_mid.has_value() && !candidate.sdp_m_line_index.has_value()) {
+ auto rejected = WebIDL::create_promise(realm);
+ WebIDL::reject_promise(realm, rejected, JS::TypeError::create(realm, "addIceCandidate: sdpMid and sdpMLineIndex are both null"_utf16));
+ return rejected;
+ }
+ // FIXME: 4. Return the result of chaining the following steps to connection's operations chain:
+ auto p = WebIDL::create_promise(realm);
+ if (!remote_description()) {
+ WebIDL::reject_promise(realm, p, WebIDL::InvalidStateError::create("Remote description is not set"_utf16));
+ return p;
+ }
+ // FIXME: 4.2. If candidate.sdpMid is not null, run the following steps:
+ // FIXME: 4.2.1. If candidate.sdpMid is not equal to the mid of any media description in remoteDescription, return a promise rejected with a newly created OperationError.
+ // FIXME: 4.3. Else, if candidate.sdpMLineIndex is not null, run the following steps:
+ // FIXME: 4.3.1. If candidate.sdpMLineIndex is equal to or larger than the number of media descriptions in remoteDescription, return a promise rejected with a newly created OperationError.
+ // FIXME: 4.4. If either candidate.sdpMid or candidate.sdpMLineIndex indicate a media description in remoteDescription whose associated transceiver is stopped, return a promise resolved with undefined.
+ // FIXME: 4.5. If candidate.usernameFragment is not null, and is not equal to any username fragment present in the corresponding media description of an applied remote description, return a promise rejected with a newly created OperationError.
+ // 4.6. Let p be a new promise.
+ // 4.7. In parallel, if the candidate is not administratively prohibited, add the ICE candidate
+ // candidate as described in [RFC9429] (section 4.1.19.). The service runs the in-parallel
+ // branch and queues the result task; it lands here via on_add_ice_candidate_result.
+ auto& agent = WebRTCAgent::the();
+ auto request_id = agent.next_request_id();
+ m_pending_void_requests.set(request_id, p);
+ if (auto* client = agent.client()) {
+ client->async_add_ice_candidate(
+ m_pc_id,
+ request_id,
+ candidate.candidate.to_well_formed_utf8(),
+ candidate.sdp_mid.map([](Utf16String const& v) { return v.to_well_formed_utf8(); }),
+ candidate.sdp_m_line_index.map([](u16 v) { return static_cast<u32>(v); }),
+ candidate.username_fragment.map([](Utf16String const& v) { return v.to_well_formed_utf8(); }));
+ }
+ // 4.8. Return p.
+ return p;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtrack
+WebIDL::ExceptionOr<GC::Ref<RTCRtpSender>> RTCPeerConnection::add_track(GC::Ref<MediaCapture::MediaStreamTrack> track, GC::Ref<MediaCapture::MediaStream> stream)
+{
+ GC::RootVector<GC::Ref<MediaCapture::MediaStream>> streams;
+ streams.append(stream);
+ return add_track(track, streams);
+}
+
+WebIDL::ExceptionOr<GC::Ref<RTCRtpSender>> RTCPeerConnection::add_track(GC::Ref<MediaCapture::MediaStreamTrack> track, GC::RootVector<GC::Ref<MediaCapture::MediaStream>> const& streams)
+{
+ // 1. Let connection be the RTCPeerConnection object on which this method was invoked.
+ // 2. Let track be the MediaStreamTrack object indicated by the method's first argument.
+ // 3. Let kind be track.kind.
+ auto kind = track->track_kind();
+ // 4. Let streams be a list of MediaStream objects constructed from the method's remaining arguments, or an empty list if the method was called with a single argument.
+ // 5. If connection.[[IsClosed]] is true, throw an InvalidStateError.
+ if (m_is_closed)
+ return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);
+ // 6. Let senders be the result of executing the CollectSenders algorithm. If an RTCRtpSender for track already exists in senders, throw an InvalidAccessError.
+ auto senders = collect_senders();
+ for (auto const& existing : senders) {
+ if (existing->track() == track)
+ return WebIDL::InvalidAccessError::create("RTCRtpSender for track already exists"_utf16);
+ }
+ // 7. ...if any RTCRtpSender object in senders matches all the following criteria, let sender be that object, or null otherwise:
+ // - The sender's track is null.
+ // - The transceiver kind of the RTCRtpTransceiver, associated with the sender, matches kind.
+ // - The [[Stopping]] slot of the RTCRtpTransceiver associated with the sender is false.
+ // - The sender has never been used to send. More precisely, the [[CurrentDirection]] slot of the RTCRtpTransceiver associated with the sender has never had a value of "sendrecv" or "sendonly".
+ GC::Ptr<RTCRtpSender> sender;
+ GC::Ptr<RTCRtpTransceiver> matching_transceiver;
+ for (auto& transceiver : m_transceivers) {
+ if (transceiver->sender()->track() != nullptr)
+ continue;
+ if (transceiver->kind() != kind)
+ continue;
+ if (transceiver->is_stopping())
+ continue;
+ // FIXME: track [[CurrentDirection]] history; for now we approximate by checking the current value.
+ auto current = transceiver->current_direction();
+ if (current.has_value() && (*current == Bindings::RTCRtpTransceiverDirection::Sendrecv || *current == Bindings::RTCRtpTransceiverDirection::Sendonly))
+ continue;
+ sender = transceiver->sender();
+ matching_transceiver = transceiver;
+ break;
+ }
+ // 8. If sender is not null, run the following steps to use that sender:
+ if (sender) {
+ // 8.1. Set sender.[[SenderTrack]] to track.
+ sender->set_track(track);
+ // 8.2. Set sender.[[AssociatedMediaStreamIds]] to an empty set.
+ Vector<Utf16String> ids;
+ // 8.3. For each stream in streams, add stream.id to [[AssociatedMediaStreamIds]] if it's not already there.
+ for (auto const& stream : streams) {
+ auto id = stream->id();
+ if (!ids.contains_slow(id))
+ ids.append(move(id));
+ }
+ sender->set_associated_media_stream_ids(move(ids));
+ // 8.4. Let transceiver be the RTCRtpTransceiver associated with sender.
+ // 8.5. If transceiver.[[Direction]] is "recvonly", set transceiver.[[Direction]] to "sendrecv".
+ if (matching_transceiver->direction() == Bindings::RTCRtpTransceiverDirection::Recvonly)
+ matching_transceiver->set_direction(Bindings::RTCRtpTransceiverDirection::Sendrecv);
+ // 8.6. If transceiver.[[Direction]] is "inactive", set transceiver.[[Direction]] to "sendonly".
+ else if (matching_transceiver->direction() == Bindings::RTCRtpTransceiverDirection::Inactive)
+ matching_transceiver->set_direction(Bindings::RTCRtpTransceiverDirection::Sendonly);
+ }
+ auto& agent = WebRTCAgent::the();
+ // 9. If sender is null, run the following steps:
+ if (!sender) {
+ auto sender_id = agent.next_sender_id();
+ auto sender_ssrc = agent.next_ssrc();
+ // FIXME: 9.1. Create an RTCRtpSender with track, kind and streams, and let sender be the result.
+ sender = RTCRtpSender::create(*this, sender_id, sender_ssrc);
+ sender->set_track(track);
+ Vector<Utf16String> ids;
+ for (auto const& stream : streams) {
+ auto id = stream->id();
+ if (!ids.contains_slow(id))
+ ids.append(move(id));
+ }
+ sender->set_associated_media_stream_ids(move(ids));
+ // 9.2. Create an RTCRtpReceiver with kind, and let receiver be the result.
+ auto receiver = RTCRtpReceiver::create(kind);
+ // FIXME: 9.3. Create an RTCRtpTransceiver with sender, receiver and an RTCRtpTransceiverDirection value of "sendrecv", and let transceiver be the result.
+ auto transceiver = RTCRtpTransceiver::create(*this, *sender, receiver, Bindings::RTCRtpTransceiverDirection::Sendrecv, kind);
+ transceiver->set_transceiver_id(sender_id);
+ // 9.4. Add transceiver to connection's set of transceivers.
+ m_transceivers.append(transceiver);
+ }
+ // FIXME: 10. A track could have contents that are inaccessible to the application. ... Silence (audio), black frames (video) or equivalently absent content is sent in place of track content.
+ // 11. Update the negotiation-needed flag for connection.
+ update_negotiation_needed_flag();
+ // 12. Return sender.
+ return GC::Ref { *sender };
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtransceiver
+WebIDL::ExceptionOr<GC::Ref<RTCRtpTransceiver>> RTCPeerConnection::add_transceiver(Variant<GC::Ref<MediaCapture::MediaStreamTrack>, Utf16String> const& track_or_kind, RTCRtpTransceiverInit const& init)
+{
+ // 1. Let connection be the RTCPeerConnection object on which the method was invoked.
+ // 2. If connection.[[IsClosed]] is true, throw an InvalidStateError.
+ if (m_is_closed)
+ return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);
+ // 3. Let init be the method's second argument.
+ // 4. Let trackOrKind be the method's first argument.
+ // 5. If trackOrKind is a kind, then let kind be trackOrKind, and let track be null.
+ // Otherwise, let kind be trackOrKind.kind and let track be trackOrKind.
+ GC::Ptr<MediaCapture::MediaStreamTrack> track;
+ Bindings::MediaStreamTrackKind kind;
+ if (track_or_kind.has<Utf16String>()) {
+ auto const& kind_string = track_or_kind.get<Utf16String>();
+ // 6. If kind is not equal to "audio" or "video", throw a TypeError.
+ if (kind_string == "audio"sv) {
+ kind = Bindings::MediaStreamTrackKind::Audio;
+ } else if (kind_string == "video"sv) {
+ kind = Bindings::MediaStreamTrackKind::Video;
+ } else {
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "addTransceiver: kind must be \"audio\" or \"video\""_utf16 };
+ }
+ } else {
+ track = *track_or_kind.get<GC::Ref<MediaCapture::MediaStreamTrack>>();
+ kind = track->track_kind();
+ }
+ // FIXME: 7. Verify that each value in init.sendEncodings conforms to the set of "RTCRtpEncodingParameters dictionary" requirements provided in the send encodings parameters section. If one of the values does not meet these requirements, throw a RangeError.
+ // FIXME: 8. ...remaining sendEncodings normalization steps from the spec.
+ // 9. Let sendEncodings be the value of init.sendEncodings.
+ (void)init.send_encodings;
+ // 10. Let direction be the value of init.direction.
+ auto direction = init.direction;
+ // 11. Create an RTCRtpSender, sender, from track, kind, init.streams, and sendEncodings.
+ auto sender_id_for_new_sender = WebRTCAgent::the().next_sender_id();
+ auto sender_ssrc_for_new_sender = WebRTCAgent::the().next_ssrc();
+ auto sender = RTCRtpSender::create(*this, sender_id_for_new_sender, sender_ssrc_for_new_sender);
+ Vector<Utf16String> stream_ids;
+ for (auto const& stream : init.streams) {
+ auto id = stream->id();
+ if (!stream_ids.contains_slow(id))
+ stream_ids.append(move(id));
+ }
+ sender->set_associated_media_stream_ids(move(stream_ids));
+ // 12. Create an RTCRtpReceiver, receiver, from kind.
+ auto receiver = RTCRtpReceiver::create(kind);
+ // 13. Create an RTCRtpTransceiver, transceiver, from sender, receiver, and direction.
+ auto transceiver = RTCRtpTransceiver::create(*this, sender, receiver, direction, kind);
+ // 14. Add transceiver to connection's set of transceivers.
+ m_transceivers.append(transceiver);
+ auto& agent = WebRTCAgent::the();
+ auto transceiver_id = sender_id_for_new_sender;
+ transceiver->set_transceiver_id(transceiver_id);
+ if (auto* client = agent.client()) {
+ client->async_add_transceiver(
+ m_pc_id,
+ transceiver_id,
+ kind == Bindings::MediaStreamTrackKind::Audio ? "audio"_string : "video"_string,
+ idl_enum_to_string(direction).to_well_formed_utf8());
+ }
+ sender->set_track(track);
+ // 15. Update the negotiation-needed flag for connection.
+ update_negotiation_needed_flag();
+ // 16. Return transceiver.
+ return transceiver;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getsenders (CollectSenders)
+GC::RootVector<GC::Ref<RTCRtpSender>> RTCPeerConnection::collect_senders() const
+{
+ // 1. Let transceivers be the result of executing the CollectTransceivers algorithm.
+ auto transceivers = collect_transceivers();
+ // 2. Let senders be a new empty sequence.
+ GC::RootVector<GC::Ref<RTCRtpSender>> senders;
+ // 3. For each transceiver in transceivers,
+ for (auto& transceiver : transceivers) {
+ // 3.1. If transceiver.[[Stopped]] is false, add transceiver.[[Sender]] to senders.
+ if (!transceiver->is_stopped())
+ senders.append(transceiver->sender());
+ }
+ // 4. Return senders.
+ return senders;
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createdatachannel
+WebIDL::ExceptionOr<GC::Ref<RTCDataChannel>> RTCPeerConnection::create_data_channel(Utf16String const& label, RTCDataChannelInit const& options)
+{
+ // 1. Let connection be the RTCPeerConnection object on which the method is invoked.
+ // 2. If connection.[[IsClosed]] is true, throw an InvalidStateError.
+ if (m_is_closed)
+ return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);
+ // 3. Create an RTCDataChannel, channel.
+ auto channel = RTCDataChannel::create(m_global_object);
+ // 4. Initialize channel.[[DataChannelLabel]] to the value of the first argument.
+ channel->set_label(label);
+ // 5. If the UTF-8 representation of [[DataChannelLabel]] is longer than 65535 bytes, throw a TypeError.
+ auto label_utf8 = label.to_well_formed_utf8();
+ if (label_utf8.bytes().size() > 65535)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "RTCDataChannel label exceeds 65535 bytes"_utf16 };
+ // 6. Let options be the second argument.
+ // 7. Initialize channel.[[MaxPacketLifeTime]] to option.maxPacketLifeTime, if present, otherwise null.
+ channel->set_max_packet_life_time(options.max_packet_life_time);
+ // 8. Initialize channel.[[MaxRetransmits]] to option.maxRetransmits, if present, otherwise null.
+ channel->set_max_retransmits(options.max_retransmits);
+ // 9. Initialize channel.[[Ordered]] to option.ordered.
+ channel->set_ordered(options.ordered);
+ // 10. Initialize channel.[[DataChannelProtocol]] to option.protocol.
+ channel->set_protocol(options.protocol);
+ // 11. If the UTF-8 representation of [[DataChannelProtocol]] is longer than 65535 bytes, throw a TypeError.
+ auto protocol_utf8 = options.protocol.to_well_formed_utf8();
+ if (protocol_utf8.bytes().size() > 65535)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "RTCDataChannel protocol exceeds 65535 bytes"_utf16 };
+ // 12. Initialize channel.[[Negotiated]] to option.negotiated.
+ channel->set_negotiated(options.negotiated);
+ // 13. Initialize channel.[[DataChannelId]] to the value of option.id, if it is present and [[Negotiated]] is true, otherwise null.
+ if (options.id.has_value() && options.negotiated)
+ channel->set_id(options.id);
+ else
+ channel->set_id({});
+ // 14. If [[Negotiated]] is true and [[DataChannelId]] is null, throw a TypeError.
+ if (options.negotiated && !options.id.has_value())
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "RTCDataChannel: negotiated=true requires id"_utf16 };
+ // 15. If both [[MaxPacketLifeTime]] and [[MaxRetransmits]] attributes are set (not null), throw a TypeError.
+ if (options.max_packet_life_time.has_value() && options.max_retransmits.has_value())
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "RTCDataChannel: maxPacketLifeTime and maxRetransmits are mutually exclusive"_utf16 };
+ // FIXME: 16. If a setting, either [[MaxPacketLifeTime]] or [[MaxRetransmits]], has been set to indicate unreliable mode, and that value exceeds the maximum value supported by the user agent, the value MUST be set to the user agents maximum value.
+ // 17. If [[DataChannelId]] is equal to 65535, which is greater than the maximum allowed ID of 65534 but still qualifies as an unsigned short, throw a TypeError.
+ if (options.id.has_value() && *options.id == 65535)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "RTCDataChannel id 65535 is reserved"_utf16 };
+ // FIXME: 18. If the [[DataChannelId]] slot is null (due to no ID being passed into createDataChannel, or [[Negotiated]] being false), and the DTLS role of the SCTP transport has already been negotiated, then initialize [[DataChannelId]] to a value generated by the user agent, according to [RFC8832], and skip to the next step. If no available ID could be generated, or if the value of the [[DataChannelId]] slot is being used by an existing RTCDataChannel, throw an OperationError exception.
+ // FIXME: 19. Let transport be connection.[[SctpTransport]]. If the [[DataChannelId]] slot is not null, transport is in the "connected" state and [[DataChannelId]] is greater or equal to transport.[[MaxChannels]], throw an OperationError.
+ // 20. If channel is the first RTCDataChannel created on connection, update the negotiation-needed flag for connection.
+ if (m_data_channels.is_empty())
+ update_negotiation_needed_flag();
+ // 21. Append channel to connection.[[DataChannels]].
+ m_data_channels.append(channel);
+ // 22. Return channel and continue the following steps in parallel.
+ // 23. Create channel's associated underlying data transport and configure it according to the relevant properties of channel.
+ auto& agent = WebRTCAgent::the();
+ auto channel_id = agent.next_channel_id();
+ channel->set_channel_id(channel_id);
+ m_data_channels_by_id.set(channel_id, channel);
+ agent.register_data_channel(channel_id, channel);
+ if (auto* client = agent.client()) {
+ client->async_add_data_channel(
+ m_pc_id,
+ channel_id,
+ label_utf8,
+ options.ordered,
+ options.max_packet_life_time,
+ options.max_retransmits,
+ protocol_utf8,
+ options.negotiated,
+ options.id);
+ }
+ return channel;
+}
+
+// https://www.w3.org/TR/webrtc/#collect-transceivers
+GC::RootVector<GC::Ref<RTCRtpTransceiver>> RTCPeerConnection::collect_transceivers() const
+{
+ // 1. Let transceivers be a new sequence consisting of all RTCRtpTransceiver objects in this RTCPeerConnection object's set of transceivers, in insertion order.
+ // 2. Return transceivers.
+ return GC::RootVector { m_transceivers.span() };
+}
+
+// FIXME: https://www.w3.org/TR/webrtc/#update-the-negotiation-needed-flag
+void RTCPeerConnection::restart_ice()
+{
+ if (m_is_closed)
+ return;
+ m_restart_ice = true;
+ update_negotiation_needed_flag();
+}
+
+void RTCPeerConnection::update_negotiation_needed_flag()
+{
+ HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), [this] {
+ if (!m_is_closed && m_signaling_state == Bindings::RTCSignalingState::Stable)
+ on_negotiation_needed_received();
+ }));
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getstats
+GC::Ref<WebIDL::Promise> RTCPeerConnection::get_stats(GC::Ptr<MediaCapture::MediaStreamTrack> selector)
+{
+ auto promise = WebIDL::create_promise(relevant_realm());
+ if (selector) {
+ // The backend currently returns connection-wide reports. Do not silently
+ // return unrelated statistics when a caller requests a particular track.
+ WebIDL::reject_promise(relevant_realm(), promise, WebIDL::NotSupportedError::create("Track-scoped RTC statistics are not supported"_utf16));
+ return promise;
+ }
+ auto* client = WebRTCAgent::the().existing_client();
+ if (!client || m_is_closed) {
+ auto report = RTCStatsReport::create();
+ WebIDL::resolve_promise(relevant_realm(), promise, Bindings::wrap(Bindings::host_defined_wrapper_world(relevant_realm()), relevant_realm(), report));
+ return promise;
+ }
+ auto request_id = WebRTCAgent::the().next_request_id();
+ m_pending_description_requests.set(request_id, promise);
+ client->async_get_stats(m_pc_id, request_id);
+ return promise;
+}
+
+void RTCPeerConnection::on_stats_received(u64 request_id, String reports, String error)
+{
+ auto pending = m_pending_description_requests.take(request_id);
+ if (!pending.has_value())
+ return;
+ auto& realm = relevant_realm();
+ HTML::TemporaryExecutionContext context(realm);
+ if (!error.is_empty()) {
+ WebIDL::reject_promise(realm, **pending, WebIDL::OperationError::create(Utf16String::from_utf8(error)));
+ return;
+ }
+ auto parsed = Infra::parse_json_string_to_javascript_value(realm, Utf16String::from_utf8(reports));
+ if (parsed.is_exception() || !parsed.value().is_object()) {
+ WebIDL::reject_promise(realm, **pending, WebIDL::OperationError::create("Invalid RTC statistics report"_utf16));
+ return;
+ }
+ auto& object = parsed.value().as_object();
+ auto report = RTCStatsReport::create();
+ for (auto key : MUST(object.enumerable_own_property_names(JS::Object::PropertyKind::Key))) {
+ auto name = MUST(key.to_utf16_string(realm.vm()));
+ auto entry = MUST(object.get(name));
+ if (entry.is_object())
+ report->set_entry(move(name), entry.as_object());
+ }
+ WebIDL::resolve_promise(realm, **pending, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, report));
+}
+
+static Optional<Bindings::RTCSignalingState> parse_signaling_state(StringView s)
+{
+ if (s == "stable"sv)
+ return Bindings::RTCSignalingState::Stable;
+ if (s == "have-local-offer"sv || s == "havelocaloffer"sv)
+ return Bindings::RTCSignalingState::HaveLocalOffer;
+ if (s == "have-remote-offer"sv || s == "haveremoteoffer"sv)
+ return Bindings::RTCSignalingState::HaveRemoteOffer;
+ if (s == "have-local-pranswer"sv || s == "havelocalpranswer"sv)
+ return Bindings::RTCSignalingState::HaveLocalPranswer;
+ if (s == "have-remote-pranswer"sv || s == "haveremotepranswer"sv)
+ return Bindings::RTCSignalingState::HaveRemotePranswer;
+ if (s == "closed"sv)
+ return Bindings::RTCSignalingState::Closed;
+ return {};
+}
+
+static Optional<Bindings::RTCPeerConnectionState> parse_connection_state(StringView s)
+{
+ if (s == "new"sv)
+ return Bindings::RTCPeerConnectionState::New;
+ if (s == "connecting"sv)
+ return Bindings::RTCPeerConnectionState::Connecting;
+ if (s == "connected"sv)
+ return Bindings::RTCPeerConnectionState::Connected;
+ if (s == "disconnected"sv)
+ return Bindings::RTCPeerConnectionState::Disconnected;
+ if (s == "failed"sv)
+ return Bindings::RTCPeerConnectionState::Failed;
+ if (s == "closed"sv)
+ return Bindings::RTCPeerConnectionState::Closed;
+ return {};
+}
+
+static Optional<Bindings::RTCIceGatheringState> parse_ice_gathering(StringView s)
+{
+ if (s == "new"sv)
+ return Bindings::RTCIceGatheringState::New;
+ if (s == "gathering"sv)
+ return Bindings::RTCIceGatheringState::Gathering;
+ if (s == "complete"sv)
+ return Bindings::RTCIceGatheringState::Complete;
+ return {};
+}
+
+static Optional<Bindings::RTCIceConnectionState> parse_ice_connection(StringView s)
+{
+ if (s == "new"sv)
+ return Bindings::RTCIceConnectionState::New;
+ if (s == "checking"sv)
+ return Bindings::RTCIceConnectionState::Checking;
+ if (s == "connected"sv)
+ return Bindings::RTCIceConnectionState::Connected;
+ if (s == "completed"sv)
+ return Bindings::RTCIceConnectionState::Completed;
+ if (s == "disconnected"sv)
+ return Bindings::RTCIceConnectionState::Disconnected;
+ if (s == "failed"sv)
+ return Bindings::RTCIceConnectionState::Failed;
+ if (s == "closed"sv)
+ return Bindings::RTCIceConnectionState::Closed;
+ return {};
+}
+
+void RTCPeerConnection::on_signaling_state_event(String state)
+{
+ if (m_is_closed)
+ return;
+ if (auto parsed = parse_signaling_state(state); parsed.has_value()) {
+ m_signaling_state = *parsed;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::signalingstatechange));
+ }
+}
+
+void RTCPeerConnection::on_connection_state_event(String state)
+{
+ if (m_is_closed)
+ return;
+ if (auto parsed = parse_connection_state(state); parsed.has_value()) {
+ m_connection_state = *parsed;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::connectionstatechange));
+ }
+}
+
+void RTCPeerConnection::on_ice_gathering_state_event(String state)
+{
+ if (m_is_closed)
+ return;
+ // Gathering starts as the local description is set; see on_ice_candidate_received().
+ if (is_setting_local_description()) {
+ m_held_ice_events.append([this, state = move(state)]() mutable { on_ice_gathering_state_event(move(state)); });
+ return;
+ }
+ if (auto parsed = parse_ice_gathering(state); parsed.has_value()) {
+ m_ice_gathering_state = *parsed;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::icegatheringstatechange));
+ }
+}
+
+void RTCPeerConnection::on_ice_connection_state_event(String state)
+{
+ if (m_is_closed)
+ return;
+ if (auto parsed = parse_ice_connection(state); parsed.has_value()) {
+ m_ice_connection_state = *parsed;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::iceconnectionstatechange));
+ }
+}
+
+void RTCPeerConnection::on_ice_candidate_received(Optional<String> candidate, Optional<String> sdp_mid, Optional<u32> sdp_mline_index)
+{
+ if (m_is_closed)
+ return;
+ // webrtc-rs gathers while it sets the local description, so its candidates can reach us before the result. The
+ // page must only see them once setLocalDescription() has resolved, or it may have nowhere to send them yet: a
+ // peer without a remote description rejects them.
+ // https://w3c.github.io/webrtc-pc/#dom-peerconnection-setlocaldescription
+ if (is_setting_local_description()) {
+ m_held_ice_events.append([this, candidate = move(candidate), sdp_mid = move(sdp_mid), sdp_mline_index]() mutable {
+ on_ice_candidate_received(move(candidate), move(sdp_mid), sdp_mline_index);
+ });
+ return;
+ }
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ RTCPeerConnectionIceEventInit init;
+ if (candidate.has_value()) {
+ RTCIceCandidateInit candidate_init;
+ candidate_init.candidate = Utf16String::from_utf8(*candidate);
+ if (sdp_mid.has_value())
+ candidate_init.sdp_mid = Utf16String::from_utf8(*sdp_mid);
+ if (sdp_mline_index.has_value())
+ candidate_init.sdp_m_line_index = static_cast<u16>(*sdp_mline_index);
+ init.candidate = RTCIceCandidate::create(candidate_init);
+ }
+ dispatch_event(RTCPeerConnectionIceEvent::create(HTML::EventNames::icecandidate, init, HighResolutionTime::current_high_resolution_time(relevant_global_object())));
+}
+
+void RTCPeerConnection::on_ice_candidate_error_received(Optional<String>, Optional<u16>, String, u16, String)
+{
+ // FIXME: dispatch an RTCPeerConnectionIceErrorEvent with the right fields.
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::icecandidateerror));
+}
+
+void RTCPeerConnection::on_negotiation_needed_received()
+{
+ if (m_is_closed)
+ return;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ dispatch_event(DOM::Event::create(relevant_global_object(), HTML::EventNames::negotiationneeded));
+}
+
+namespace {
+
+struct TrackEventInit {
+ GC::Ref<RTCRtpReceiver> receiver;
+ GC::Ref<MediaCapture::MediaStreamTrack> track;
+ GC::RootVector<GC::Ref<MediaCapture::MediaStream>> streams;
+ GC::Ref<RTCRtpTransceiver> transceiver;
+};
+
+// Spec uses "(stream, track) pairs" in addList/removeList; alias for clarity.
+struct StreamTrackPair {
+ GC::Ref<MediaCapture::MediaStream> stream;
+ GC::Ref<MediaCapture::MediaStreamTrack> track;
+};
+
+constexpr bool direction_is_receive(Bindings::RTCRtpTransceiverDirection d)
+{
+ return d == Bindings::RTCRtpTransceiverDirection::Sendrecv
+ || d == Bindings::RTCRtpTransceiverDirection::Recvonly;
+}
+
+constexpr bool direction_is_send_only_or_inactive(Bindings::RTCRtpTransceiverDirection d)
+{
+ return d == Bindings::RTCRtpTransceiverDirection::Sendonly
+ || d == Bindings::RTCRtpTransceiverDirection::Inactive;
+}
+
+}
+
+// https://www.w3.org/TR/webrtc/#set-associated-remote-streams
+static void set_the_associated_remote_streams(RTCPeerConnection& pc, RTCRtpReceiver& receiver,
+ Vector<String> const& msids,
+ GC::ConservativeVector<StreamTrackPair>& add_list,
+ GC::ConservativeVector<StreamTrackPair>& remove_list)
+{
+ // 1. Let connection be the RTCPeerConnection object associated with receiver.
+ auto& connection = pc;
+
+ // 2. For each MSID in msids, unless a MediaStream object has previously been
+ // created with that id for this connection, create a MediaStream object with
+ // that id.
+ // 3. Let streams be a list of the MediaStream objects created for this connection
+ // with the ids corresponding to msids.
+ GC::RootVector<GC::Ref<MediaCapture::MediaStream>> streams;
+ streams.ensure_capacity(msids.size());
+ for (auto const& msid : msids) {
+ if (auto stream = connection.find_or_create_remote_stream_for_msid(msid))
+ streams.append(*stream);
+ }
+
+ // 4. Let track be receiver.[[ReceiverTrack]].
+ auto track = receiver.track();
+
+ // 5. For each stream in receiver.[[AssociatedRemoteMediaStreams]] that is not
+ // present in streams, add stream and track as a pair to removeList.
+ for (auto const& previous : receiver.associated_remote_streams()) {
+ bool still_associated = false;
+ for (auto const& fresh : streams) {
+ if (fresh.ptr() == previous.ptr()) {
+ still_associated = true;
+ break;
+ }
+ }
+ if (!still_associated)
+ remove_list.append({ previous, track });
+ }
+
+ // 6. For each stream in streams that is not present in
+ // receiver.[[AssociatedRemoteMediaStreams]], add stream and track as a pair
+ // to addList.
+ for (auto const& fresh : streams) {
+ bool was_already_associated = false;
+ for (auto const& previous : receiver.associated_remote_streams()) {
+ if (previous.ptr() == fresh.ptr()) {
+ was_already_associated = true;
+ break;
+ }
+ }
+ if (!was_already_associated)
+ add_list.append({ fresh, track });
+ }
+
+ // 7. Set receiver.[[AssociatedRemoteMediaStreams]] to streams.
+ receiver.set_associated_remote_streams(move(streams));
+}
+
+// https://www.w3.org/TR/webrtc/#process-the-addition-of-a-remote-track
+static void process_addition_of_remote_track(RTCRtpTransceiver& transceiver, GC::ConservativeVector<TrackEventInit>& track_event_inits)
+{
+ // 1. Let receiver be transceiver.[[Receiver]].
+ auto receiver = transceiver.receiver();
+ // 2. Let track be receiver.[[ReceiverTrack]].
+ auto track = receiver->track();
+ // 3. Let streams be receiver.[[AssociatedRemoteMediaStreams]].
+ GC::RootVector streams { receiver->associated_remote_streams().span() };
+ // 4. Create a new RTCTrackEventInit dictionary with receiver, track, streams and
+ // transceiver as members and add it to trackEventInits.
+ track_event_inits.append({ receiver, track, move(streams), GC::Ref { transceiver } });
+}
+
+// https://www.w3.org/TR/webrtc/#process-the-removal-of-a-remote-track
+static void process_removal_of_remote_track(RTCRtpTransceiver& transceiver, GC::RootVector<GC::Ref<MediaCapture::MediaStreamTrack>>& mute_tracks)
+{
+ // 1. Let receiver be transceiver.[[Receiver]].
+ auto receiver = transceiver.receiver();
+ // 2. Let track be receiver.[[ReceiverTrack]].
+ auto track = receiver->track();
+ // 3. If track.muted is false, add track to muteTracks.
+ if (!track->muted())
+ mute_tracks.append(track);
+}
+
+// https://www.w3.org/TR/webrtc/#process-remote-tracks
+static void process_remote_tracks(RTCPeerConnection& pc, RTCRtpTransceiver& transceiver,
+ Bindings::RTCRtpTransceiverDirection direction, Vector<String> const& msids,
+ GC::ConservativeVector<StreamTrackPair>& add_list,
+ GC::ConservativeVector<StreamTrackPair>& remove_list,
+ GC::ConservativeVector<TrackEventInit>& track_event_inits,
+ GC::RootVector<GC::Ref<MediaCapture::MediaStreamTrack>>& mute_tracks)
+{
+ auto add_list_size_before = add_list.size();
+ // 1. Set the associated remote streams with transceiver.[[Receiver]], msids,
+ // addList, and removeList.
+ set_the_associated_remote_streams(pc, transceiver.receiver(), msids, add_list, remove_list);
+
+ auto fired = transceiver.fired_direction();
+ bool fired_was_recv = fired.has_value() && direction_is_receive(fired.value());
+ bool add_list_grew = add_list.size() > add_list_size_before;
+ // 2. If direction is "sendrecv" or "recvonly" and transceiver.[[FiredDirection]]
+ // is neither "sendrecv" nor "recvonly", or the previous step increased the
+ // length of addList, process the addition of a remote track with transceiver
+ // and trackEventInits.
+ if ((direction_is_receive(direction) && !fired_was_recv) || add_list_grew)
+ process_addition_of_remote_track(transceiver, track_event_inits);
+
+ // 3. If direction is "sendonly" or "inactive", set transceiver.[[Receptive]] to false.
+ if (direction_is_send_only_or_inactive(direction))
+ transceiver.set_receptive(false);
+
+ // 4. If direction is "sendonly" or "inactive", and transceiver.[[FiredDirection]]
+ // is either "sendrecv" or "recvonly", process the removal of a remote track
+ // for the media description, with transceiver and muteTracks.
+ if (direction_is_send_only_or_inactive(direction) && fired_was_recv)
+ process_removal_of_remote_track(transceiver, mute_tracks);
+
+ // 5. Set transceiver.[[FiredDirection]] to direction.
+ transceiver.set_fired_direction(direction);
+}
+
+void RTCPeerConnection::on_remote_track_added(u64 receiver_id, u64 transceiver_id, String kind_string, Vector<String> stream_ids)
+{
+ auto& realm = relevant_realm();
+ HTML::TemporaryExecutionContext context(realm);
+
+ auto kind = kind_string == "video"sv ? Bindings::MediaStreamTrackKind::Video : Bindings::MediaStreamTrackKind::Audio;
+
+ // The backend tells us which of our transceivers the track arrived on when we created it.
+ // Otherwise, match a transceiver of matching kind whose [[FiredDirection]] hasn't already
+ // been set to a receive direction, and synthesize one if the remote surprised us with a
+ // track we never asked for.
+ // (Spec: this matching is normally done by "apply a remote description"; we get a
+ // pre-matched track via IPC, so we approximate the same selection here.)
+ GC::Ptr<RTCRtpTransceiver> transceiver;
+ if (transceiver_id != 0) {
+ for (auto& t : m_transceivers) {
+ if (t->transceiver_id() == transceiver_id && t->kind() == kind && !t->is_stopped()) {
+ transceiver = t;
+ break;
+ }
+ }
+ }
+ for (auto& t : m_transceivers) {
+ if (transceiver)
+ break;
+ if (t->kind() != kind || t->is_stopped())
+ continue;
+ if (t->fired_direction().has_value() && direction_is_receive(t->fired_direction().value()))
+ continue;
+ transceiver = t;
+ }
+ if (!transceiver) {
+ auto synth_sender_id = WebRTCAgent::the().next_sender_id();
+ auto synth_sender_ssrc = WebRTCAgent::the().next_ssrc();
+ auto sender = RTCRtpSender::create(*this, synth_sender_id, synth_sender_ssrc);
+ auto receiver = RTCRtpReceiver::create(kind);
+ auto new_transceiver = RTCRtpTransceiver::create(*this, sender, receiver, Bindings::RTCRtpTransceiverDirection::Recvonly, kind);
+ m_transceivers.append(new_transceiver);
+ transceiver = new_transceiver;
+ }
+
+ auto receiver = transceiver->receiver();
+ m_remote_receivers_by_id.set(receiver_id, receiver);
+
+ // Drive the spec's "process remote tracks" algorithm. The IPC only signals new
+ // tracks today (no removals), so direction is recvonly.
+ GC::ConservativeVector<StreamTrackPair> add_list;
+ GC::ConservativeVector<StreamTrackPair> remove_list;
+ GC::ConservativeVector<TrackEventInit> track_event_inits;
+ GC::RootVector<GC::Ref<MediaCapture::MediaStreamTrack>> mute_tracks;
+ process_remote_tracks(*this, *transceiver, Bindings::RTCRtpTransceiverDirection::Recvonly,
+ stream_ids, add_list, remove_list, track_event_inits, mute_tracks);
+
+ // The apply-remote-description algorithm follows up by:
+ // - Adding each (stream, track) pair from addList to its stream's track set
+ // (which fires "addtrack" on the stream).
+ // - Removing each (stream, track) pair from removeList from its stream's track
+ // set (which fires "removetrack" on the stream).
+ // - Firing one RTCTrackEvent per init.
+ // - Muting each track in muteTracks.
+ for (auto& pair : add_list)
+ pair.stream->add_track(pair.track);
+ for (auto& pair : remove_list)
+ pair.stream->remove_track(pair.track);
+ for (auto& init : track_event_inits) {
+ auto event = RTCTrackEvent::create(HTML::EventNames::track,
+ init.receiver, init.track, move(init.streams), init.transceiver,
+ HighResolutionTime::current_high_resolution_time(relevant_global_object()));
+ dispatch_event(event);
+ }
+ // FIXME: muteTracks step is "set track.muted to true and fire mute on it";
+ // MediaStreamTrack.muted is a getter so we'd need an internal set_muted.
+ (void)mute_tracks;
+}
+
+GC::Ptr<MediaCapture::MediaStream> RTCPeerConnection::find_or_create_remote_stream_for_msid(String const& msid)
+{
+ if (auto existing = m_remote_streams.get(msid); existing.has_value())
+ return existing.value();
+ auto fresh = MediaCapture::MediaStream::create_with_id(Utf16String::from_utf8(msid));
+ m_remote_streams.set(msid, fresh);
+ return fresh;
+}
+
+void RTCPeerConnection::stop_sender(RTCRtpSender& sender)
+{
+ auto id = sender.sender_id();
+ auto pipeline = m_outgoing_audio_pipelines.take(id);
+ if (pipeline.has_value() && (*pipeline)->track && (*pipeline)->sink)
+ (*pipeline)->track->remove_audio_sink(*(*pipeline)->sink);
+ if (m_requested_audio_senders.contains(id)) {
+ if (auto* client = WebRTCAgent::the().existing_client())
+ client->async_remove_track(m_pc_id, id);
+ }
+ m_requested_audio_senders.remove(id);
+ m_ready_audio_senders.remove(id);
+}
+
+WebIDL::ExceptionOr<void> RTCPeerConnection::remove_track(GC::Ref<RTCRtpSender> sender)
+{
+ if (m_is_closed)
+ return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);
+ if (sender->connection().ptr() != this)
+ return WebIDL::InvalidAccessError::create("Sender belongs to another connection"_utf16);
+ if (!sender->track())
+ return {};
+ stop_sender(*sender);
+ sender->set_track(nullptr);
+ for (auto& transceiver : m_transceivers) {
+ if (transceiver->sender() != sender)
+ continue;
+ if (transceiver->direction() == Bindings::RTCRtpTransceiverDirection::Sendrecv)
+ transceiver->set_direction(Bindings::RTCRtpTransceiverDirection::Recvonly);
+ else if (transceiver->direction() == Bindings::RTCRtpTransceiverDirection::Sendonly)
+ transceiver->set_direction(Bindings::RTCRtpTransceiverDirection::Inactive);
+ }
+ update_negotiation_needed_flag();
+ return {};
+}
+
+void RTCPeerConnection::on_sender_track_changed(RTCRtpSender& sender)
+{
+ if (m_is_closed)
+ return;
+ auto sender_id = sender.sender_id();
+ auto old = m_outgoing_audio_pipelines.take(sender_id);
+ if (old.has_value() && (*old)->track && (*old)->sink)
+ (*old)->track->remove_audio_sink(*(*old)->sink);
+ auto track = sender.track();
+ if (!track || track->track_kind() != Bindings::MediaStreamTrackKind::Audio)
+ return;
+ if (m_ready_audio_senders.contains(sender_id)) {
+ start_outgoing_audio_for_sender(sender);
+ return;
+ }
+ if (m_requested_audio_senders.contains(sender_id))
+ return;
+ m_requested_audio_senders.set(sender_id);
+ if (auto* client = WebRTCAgent::the().existing_client())
+ client->async_add_audio_track(m_pc_id, sender_id);
+}
+
+void RTCPeerConnection::on_audio_track_ssrc_assigned(u64 sender_id, u32 ssrc)
+{
+ if (m_is_closed)
+ return;
+ GC::Ptr<RTCRtpSender> sender;
+ for (auto& transceiver : m_transceivers) {
+ if (transceiver->sender()->sender_id() == sender_id) {
+ sender = transceiver->sender();
+ break;
+ }
+ }
+ if (!sender) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: on_audio_track_ssrc_assigned for unknown sender_id={}", sender_id);
+ return;
+ }
+ if (!m_requested_audio_senders.contains(sender_id))
+ return;
+ sender->set_ssrc(ssrc);
+ m_ready_audio_senders.set(sender_id);
+ if (m_outgoing_audio_pipelines.contains(sender_id))
+ return;
+ start_outgoing_audio_for_sender(*sender);
+}
+
+void RTCPeerConnection::on_sender_transform_changed(RTCRtpSender& sender)
+{
+ auto script_transform = sender.script_transform();
+ if (!script_transform)
+ return;
+ auto sender_id = sender.sender_id();
+ if (script_transform->has_frame_written_callback())
+ return;
+ script_transform->set_on_frame_written([self = GC::Weak { *this }, sender_id](ByteBuffer payload, u32, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) {
+ if (self)
+ self->on_outgoing_encrypted_frame(sender_id, move(payload), rtp_timestamp, sequence_number, payload_type);
+ });
+}
+
+void RTCPeerConnection::start_outgoing_audio_for_sender(GC::Ref<RTCRtpSender> sender)
+{
+ auto sender_id = sender->sender_id();
+ auto track = sender->track();
+ if (!track) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: sender_id={} has no track yet, deferring", sender_id);
+ return;
+ }
+ auto sample_spec = Audio::SampleSpecification(48000, Audio::ChannelMap::stereo());
+ constexpr int OPUS_BITRATE_BPS = 64'000;
+ auto encoder_or_err = Media::FFmpeg::FFmpegAudioEncoder::try_create(Media::CodecID::Opus, sample_spec, OPUS_BITRATE_BPS);
+ if (encoder_or_err.is_error()) {
+ dbgln("RTCPeerConnection: opus encoder init failed for sender_id={}: {}", sender_id, encoder_or_err.error().description());
+ return;
+ }
+ auto converter = Media::FFmpeg::FFmpegAudioConverter::try_create();
+ if (converter.is_error() || converter.value()->set_output_sample_specification(sample_spec).is_error())
+ return;
+ auto pipeline = make<OutgoingAudioPipeline>();
+ auto producer = adopt_ref(*new OutgoingAudioProducerState);
+ producer->converter = converter.release_value();
+ pipeline->encoder = encoder_or_err.release_value();
+ pipeline->generation = WebRTCAgent::the().next_request_id();
+ pipeline->track = track;
+
+ // Track sinks run on the producer thread; encoding and JS realm operations need the main loop.
+ auto main_loop_weak = Core::EventLoop::current_weak();
+ auto sink = adopt_ref(*new MediaCapture::AudioFrameSink);
+ sink->on_frames = [pc_id = m_pc_id, sender_id, producer, generation = pipeline->generation, main_loop_weak](float const* samples, size_t frame_count, u8 channels, u32 sample_rate) {
+ if (channels == 0 || frame_count == 0 || sample_rate == 0)
+ return;
+ constexpr size_t CHANNEL_COUNT = 2;
+ constexpr size_t INTERLEAVED_SAMPLES = 960 * CHANNEL_COUNT;
+ Media::AudioBlock input;
+ auto timestamp = AK::Duration::from_microseconds(static_cast<i64>(producer->source_frames) * 1'000'000 / sample_rate);
+ producer->source_frames += frame_count;
+ input.initialize(Audio::SampleSpecification(sample_rate, Audio::ChannelMap::stereo()), timestamp, frame_count);
+ for (size_t c = 0; c < CHANNEL_COUNT; ++c) {
+ auto output = input.channel_data(c);
+ for (size_t f = 0; f < frame_count; ++f)
+ output[f] = samples[f * channels + (c < channels ? c : 0)];
+ }
+ if (producer->converter->push_block(input).is_error())
+ return;
+ auto& accum = producer->float_accumulator;
+ while (true) {
+ Media::AudioBlock converted;
+ if (producer->converter->retrieve_block(converted).is_error() || converted.is_empty())
+ break;
+ auto left = converted.channel_data(0);
+ auto right = converted.channel_data(1);
+ for (size_t f = 0; f < converted.frame_count(); ++f) {
+ accum.append(AK::clamp(left[f], -1.0f, 1.0f));
+ accum.append(AK::clamp(right[f], -1.0f, 1.0f));
+ }
+ }
+ while (accum.size() >= INTERLEAVED_SAMPLES) {
+ auto buffer_or_err = ByteBuffer::create_uninitialized(INTERLEAVED_SAMPLES * sizeof(i16));
+ if (buffer_or_err.is_error())
+ break;
+ auto buffer = buffer_or_err.release_value();
+ auto* dst = reinterpret_cast<i16*>(buffer.data());
+ for (size_t i = 0; i < INTERLEAVED_SAMPLES; ++i)
+ dst[i] = static_cast<i16>(accum[i] * 32767.0f);
+ accum.remove(0, INTERLEAVED_SAMPLES);
+
+ auto strong = main_loop_weak->take();
+ if (!strong || producer->pending_frames.load() >= 5)
+ continue;
+ producer->pending_frames.fetch_add(1);
+ strong->deferred_invoke([pc_id, sender_id, producer, captured_at = MonotonicTime::now(), generation, buffer = move(buffer)]() mutable {
+ producer->pending_frames.fetch_sub(1);
+ auto self = WebRTCAgent::the().find_peer_connection(pc_id);
+ if (!self || self->m_is_closed || (MonotonicTime::now() - captured_at).to_milliseconds() > 200)
+ return;
+ auto pipeline = self->m_outgoing_audio_pipelines.find(sender_id);
+ if (pipeline == self->m_outgoing_audio_pipelines.end() || pipeline->value->generation != generation)
+ return;
+ self->encode_and_route_outgoing_pcm(sender_id, move(buffer));
+ });
+ }
+ };
+ track->add_audio_sink(sink);
+ pipeline->sink = sink;
+ m_outgoing_audio_pipelines.set(sender_id, move(pipeline));
+}
+
+void RTCPeerConnection::encode_and_route_outgoing_pcm(u64 sender_id, ByteBuffer pcm_s16le)
+{
+ if (m_is_closed)
+ return;
+ auto pipeline_iter = m_outgoing_audio_pipelines.find(sender_id);
+ if (pipeline_iter == m_outgoing_audio_pipelines.end())
+ return;
+ auto& pipeline = *pipeline_iter->value;
+ if (!pipeline.encoder)
+ return;
+
+ constexpr u32 SAMPLE_RATE = 48000;
+ constexpr size_t CHANNEL_COUNT = 2;
+ constexpr size_t SAMPLES_PER_FRAME = 960; // 20 ms
+ constexpr size_t INTERLEAVED_SAMPLES = SAMPLES_PER_FRAME * CHANNEL_COUNT;
+
+ auto sample_count = pcm_s16le.size() / sizeof(i16);
+ if (sample_count != INTERLEAVED_SAMPLES) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: outgoing PCM frame has {} samples, expected {}", sample_count, INTERLEAVED_SAMPLES);
+ return;
+ }
+
+ Media::AudioBlock block;
+ auto timestamp = AK::Duration::from_microseconds(static_cast<i64>(pipeline.next_rtp_timestamp) * 1'000'000 / SAMPLE_RATE);
+ auto sample_spec = Audio::SampleSpecification(SAMPLE_RATE, Audio::ChannelMap::stereo());
+ block.initialize(sample_spec, timestamp, SAMPLES_PER_FRAME);
+ auto const* samples = reinterpret_cast<i16 const*>(pcm_s16le.data());
+ for (size_t channel = 0; channel < CHANNEL_COUNT; ++channel) {
+ auto channel_data = block.channel_data(channel);
+ for (size_t frame = 0; frame < SAMPLES_PER_FRAME; ++frame)
+ channel_data[frame] = static_cast<float>(samples[(frame * CHANNEL_COUNT) + channel]) * (1.0f / 32768.0f);
+ }
+
+ if (auto rc = pipeline.encoder->receive_pcm_data(timestamp, block); rc.is_error()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: opus receive_pcm_data failed: {}", rc.error().description());
+ return;
+ }
+ while (true) {
+ Media::FFmpeg::FFmpegAudioEncoder::Packet packet;
+ auto got_packet_or_err = pipeline.encoder->write_next_packet(packet);
+ if (got_packet_or_err.is_error()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: opus write_next_packet failed: {}", got_packet_or_err.error().description());
+ return;
+ }
+ if (!got_packet_or_err.value())
+ break;
+
+ // The sender may have been collected since capture started.
+ GC::Ptr<RTCRtpSender> sender;
+ for (auto& t : m_transceivers) {
+ if (t->sender()->sender_id() == sender_id) {
+ sender = t->sender();
+ break;
+ }
+ }
+ if (!sender)
+ return;
+
+ auto rtp_ts = pipeline.next_rtp_timestamp;
+ auto seq = pipeline.next_sequence_number++;
+ pipeline.next_rtp_timestamp += SAMPLES_PER_FRAME;
+
+ auto script_transform = sender->script_transform();
+ if (!script_transform) {
+ if (sender->transform().has<Empty>())
+ on_outgoing_encrypted_frame(sender_id, move(packet.data), rtp_ts, seq, 111);
+ continue;
+ }
+
+ script_transform->enqueue_encoded_audio_frame(move(packet.data), sender->ssrc(), 111 /* opus */, rtp_ts, seq);
+ }
+}
+
+void RTCPeerConnection::on_outgoing_encrypted_frame(u64 sender_id, ByteBuffer payload, u32 rtp_timestamp, u16 sequence_number, u8 payload_type)
+{
+ if (m_is_closed)
+ return;
+ (void)rtp_timestamp;
+ (void)sequence_number;
+ (void)payload_type;
+ auto* client = WebRTCAgent::the().client();
+ if (!client)
+ return;
+ constexpr u32 FRAME_DURATION_MICROS = 20'000;
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: shipping encoded frame to rust sender_id={} len={}", sender_id, payload.size());
+ client->async_audio_track_encoded_frame(sender_id, FRAME_DURATION_MICROS, payload.bytes());
+}
+
+void RTCPeerConnection::on_remote_track_ended(u64 receiver_id)
+{
+ if (m_is_closed)
+ return;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ if (auto receiver = m_remote_receivers_by_id.get(receiver_id); receiver.has_value())
+ (*receiver)->track()->end();
+ auto playback = m_receiver_audio_playbacks.take(receiver_id);
+ if (playback.has_value() && (*playback)->playback_stream)
+ (void)(*playback)->playback_stream->discard_buffer_and_suspend();
+}
+
+void RTCPeerConnection::on_encoded_audio_frame_received(u64 receiver_id, u32 ssrc, u32 rtp_timestamp, u16 sequence_number, u8 payload_type, ByteBuffer payload)
+{
+ auto receiver_iter = m_remote_receivers_by_id.get(receiver_id);
+ if (!receiver_iter.has_value())
+ return;
+ auto receiver = *receiver_iter;
+
+ auto transform = receiver->transform();
+ auto* script_transform_ref = transform.get_pointer<GC::Ref<RTCRtpScriptTransform>>();
+ if (!script_transform_ref) {
+ if (transform.has<Empty>())
+ feed_decoded_audio(receiver_id, move(payload), rtp_timestamp);
+ return;
+ }
+ auto& script_transform = **script_transform_ref;
+ if (!script_transform.has_frame_written_callback()) {
+ script_transform.set_on_frame_written([self = GC::Weak { *this }, receiver_id](ByteBuffer transformed_payload, u32, u8, u32 rtp_timestamp, u16) {
+ if (self)
+ self->feed_decoded_audio(receiver_id, move(transformed_payload), rtp_timestamp);
+ });
+ }
+
+ script_transform.enqueue_encoded_audio_frame(move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
+// Decode one decrypted opus packet and push PCM into the receiver's playback stream.
+// FIXME: this is a shortcut around the spec — the right path is for MediaStreamTrack to
+// carry the audio data and HTMLMediaElement.srcObject playback to drain it.
+void RTCPeerConnection::feed_decoded_audio(u64 receiver_id, ByteBuffer payload, u32 rtp_timestamp)
+{
+ if (m_is_closed)
+ return;
+ auto playback_iter = m_receiver_audio_playbacks.find(receiver_id);
+ auto* playback = playback_iter == m_receiver_audio_playbacks.end() ? nullptr : playback_iter->value.ptr();
+ if (!playback) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: setting up audio playback for receiver={}", receiver_id);
+ // Opus is fundamentally 48 kHz; channel count comes out of the first decoded block.
+ auto sample_spec = Audio::SampleSpecification(48000, Audio::ChannelMap::stereo());
+ auto decoder_or_err = Media::FFmpeg::FFmpegAudioDecoder::try_create(Media::CodecID::Opus, sample_spec, {});
+ if (decoder_or_err.is_error()) {
+ dbgln("RTCPeerConnection: opus decoder init failed for receiver={}: {}", receiver_id, decoder_or_err.error().description());
+ return;
+ }
+ auto fresh = make<ReceiverAudioPlayback>();
+ fresh->decoder = decoder_or_err.release_value();
+ auto* fresh_ptr = fresh.ptr();
+ m_receiver_audio_playbacks.set(receiver_id, move(fresh));
+ playback = fresh_ptr;
+
+ auto data_callback = [buffer_state = playback->buffer](Span<float> buffer, MonotonicTime) -> ReadonlySpan<float> {
+ MutexLocker locker(buffer_state->mutex);
+ auto available = buffer_state->samples.size();
+ auto take = AK::min(available, buffer.size());
+ memcpy(buffer.data(), buffer_state->samples.data(), take * sizeof(float));
+ buffer_state->samples.remove(0, take);
+ // Pad the rest of the buffer with silence so the output keeps requesting
+ // data instead of treating a short span as the end of the stream.
+ if (take < buffer.size())
+ memset(buffer.data() + take, 0, (buffer.size() - take) * sizeof(float));
+ return buffer;
+ };
+ constexpr u32 target_latency_ms = 100;
+ auto promise = Audio::PlaybackStream::create(Audio::OutputState::Suspended, target_latency_ms, move(data_callback));
+ promise->when_resolved([self = GC::Weak { *this }, receiver_id](auto& stream) {
+ if (!self || self->m_is_closed)
+ return;
+ auto entry = self->m_receiver_audio_playbacks.find(receiver_id);
+ if (entry == self->m_receiver_audio_playbacks.end())
+ return;
+ auto* playback = entry->value.ptr();
+ playback->playback_stream = stream;
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: playback stream resolved receiver={} spec={}", receiver_id, stream->sample_specification());
+ auto converter_or_err = Media::FFmpeg::FFmpegAudioConverter::try_create();
+ if (converter_or_err.is_error()) {
+ dbgln("RTCPeerConnection: audio converter init failed for receiver={}: {}", receiver_id, converter_or_err.error());
+ } else {
+ auto converter = converter_or_err.release_value();
+ if (auto rc = converter->set_output_sample_specification(stream->sample_specification()); rc.is_error())
+ dbgln("RTCPeerConnection: converter set_output failed for receiver={}: {}", receiver_id, rc.error());
+ else
+ playback->converter = move(converter);
+ }
+ (void)stream->resume();
+ });
+ promise->when_rejected([receiver_id](auto& error) {
+ dbgln("RTCPeerConnection: playback stream init failed for receiver={}: {}", receiver_id, error);
+ });
+ }
+
+ if (!playback->decoder)
+ return;
+
+ auto timestamp = AK::Duration::from_milliseconds(static_cast<i64>(rtp_timestamp / 48));
+ Media::CodedFrame coded_frame { Media::CodecID::Opus, timestamp, timestamp, {}, Media::FrameFlags::Keyframe, MUST(FixedArray<u8>::create(payload.bytes())) };
+ if (auto result = playback->decoder->receive_coded_data(coded_frame); result.is_error()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: opus receive_coded_data failed: {}", result.error().description());
+ return;
+ }
+ Media::AudioBlock block;
+ if (auto result = playback->decoder->write_next_block(block); result.is_error()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: write_next_block failed: {}", result.error().description());
+ return;
+ }
+ if (block.is_empty()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: write_next_block produced empty block");
+ return;
+ }
+ // Drop frames until the playback stream is up — we need its sample-spec to set up the
+ // resampler, and feeding mismatched-rate samples in the meantime would just stretch.
+ if (!playback->converter)
+ return;
+ if (auto rc = playback->converter->push_block(block); rc.is_error()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: audio convert failed: {}", rc.error());
+ return;
+ }
+ while (true) {
+ Media::AudioBlock converted;
+ if (auto rc = playback->converter->retrieve_block(converted); rc.is_error()) {
+ break;
+ }
+ if (converted.is_empty())
+ continue;
+ MutexLocker locker(playback->buffer->mutex);
+ playback->channel_count = converted.channel_count();
+ auto max_samples = static_cast<size_t>(converted.sample_specification().sample_rate()) * converted.channel_count() / 5;
+ if (playback->buffer->samples.size() > max_samples)
+ playback->buffer->samples.remove(0, playback->buffer->samples.size() - max_samples);
+ auto base = playback->buffer->samples.size();
+ playback->buffer->samples.resize(base + converted.sample_count());
+ converted.copy_to_interleaved(playback->buffer->samples.span().slice(base));
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: feed_decoded_audio receiver={} samples={} channels={} spec={} buffer_total={}",
+ receiver_id, converted.sample_count(), converted.channel_count(), converted.sample_specification(), playback->buffer->samples.size());
+ }
+}
+
+static Bindings::RTCSdpType parse_sdp_type(StringView s)
+{
+ if (s == "answer"sv)
+ return Bindings::RTCSdpType::Answer;
+ if (s == "pranswer"sv)
+ return Bindings::RTCSdpType::Pranswer;
+ if (s == "rollback"sv)
+ return Bindings::RTCSdpType::Rollback;
+ return Bindings::RTCSdpType::Offer;
+}
+
+void RTCPeerConnection::on_create_offer_result_received(u64 request_id, bool ok, String sdp_type, String sdp, String, String error_message)
+{
+ auto promise = m_pending_description_requests.take(request_id);
+ if (!promise.has_value())
+ return;
+ auto& realm = relevant_realm();
+ auto& promise_ref = **promise;
+ HTML::TemporaryExecutionContext context(realm);
+ if (!ok) {
+ WebIDL::reject_promise(realm, promise_ref, WebIDL::OperationError::create(Utf16String::from_utf8(error_message)));
+ return;
+ }
+ m_last_created_offer = Utf16String::from_utf8(sdp);
+ auto init = JS::Object::create(realm, realm.intrinsics().object_prototype());
+ MUST(init->create_data_property("type"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), idl_enum_to_string(parse_sdp_type(sdp_type)))));
+ MUST(init->create_data_property("sdp"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(sdp))));
+ WebIDL::resolve_promise(realm, promise_ref, init);
+}
+
+void RTCPeerConnection::on_create_answer_result_received(u64 request_id, bool ok, String sdp_type, String sdp, String, String error_message)
+{
+ auto promise = m_pending_description_requests.take(request_id);
+ if (!promise.has_value())
+ return;
+ auto& realm = relevant_realm();
+ auto& promise_ref = **promise;
+ HTML::TemporaryExecutionContext context(realm);
+ if (!ok) {
+ WebIDL::reject_promise(realm, promise_ref, WebIDL::OperationError::create(Utf16String::from_utf8(error_message)));
+ return;
+ }
+ m_last_created_answer = Utf16String::from_utf8(sdp);
+ auto init = JS::Object::create(realm, realm.intrinsics().object_prototype());
+ MUST(init->create_data_property("type"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), idl_enum_to_string(parse_sdp_type(sdp_type)))));
+ MUST(init->create_data_property("sdp"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(sdp))));
+ WebIDL::resolve_promise(realm, promise_ref, init);
+}
+
+bool RTCPeerConnection::is_setting_local_description() const
+{
+ return any_of(m_pending_description_payloads, [](auto const& entry) { return entry.value.is_local; });
+}
+
+void RTCPeerConnection::on_set_local_description_result_received(u64 request_id, bool ok, String, String error_message)
+{
+ settle_local_description(request_id, ok, error_message);
+
+ // The page has seen the description by now, along with whatever its promise's reactions did with it, so the
+ // candidates gathered for it can follow.
+ if (!is_setting_local_description()) {
+ auto held_events = move(m_held_ice_events);
+ for (auto& event : held_events)
+ event();
+ }
+}
+
+void RTCPeerConnection::settle_local_description(u64 request_id, bool ok, String const& error_message)
+{
+ auto promise = m_pending_void_requests.take(request_id);
+ auto payload = m_pending_description_payloads.take(request_id);
+ if (!promise.has_value())
+ return;
+ auto& realm = relevant_realm();
+ auto& promise_ref = **promise;
+ HTML::TemporaryExecutionContext context(realm);
+ if (!ok) {
+ WebIDL::reject_promise(realm, promise_ref, WebIDL::OperationError::create(Utf16String::from_utf8(error_message)));
+ return;
+ }
+ if (payload.has_value() && payload->is_local) {
+ auto description = RTCSessionDescription::create(RTCSessionDescriptionInit { .sdp = payload->sdp, .type = payload->type });
+ switch (payload->type) {
+ case Bindings::RTCSdpType::Offer:
+ case Bindings::RTCSdpType::Pranswer:
+ m_pending_local_description = description;
+ break;
+ case Bindings::RTCSdpType::Answer:
+ m_current_local_description = description;
+ m_current_remote_description = m_pending_remote_description;
+ m_pending_local_description = nullptr;
+ m_pending_remote_description = nullptr;
+ m_restart_ice = false;
+ break;
+ case Bindings::RTCSdpType::Rollback:
+ m_pending_local_description = nullptr;
+ m_pending_remote_description = nullptr;
+ break;
+ }
+ }
+ WebIDL::resolve_promise(realm, promise_ref, JS::js_undefined());
+}
+
+void RTCPeerConnection::on_set_remote_description_result_received(u64 request_id, bool ok, String, String error_message)
+{
+ auto promise = m_pending_void_requests.take(request_id);
+ auto payload = m_pending_description_payloads.take(request_id);
+ if (!promise.has_value())
+ return;
+ auto& realm = relevant_realm();
+ auto& promise_ref = **promise;
+ HTML::TemporaryExecutionContext context(realm);
+ if (!ok) {
+ WebIDL::reject_promise(realm, promise_ref, WebIDL::OperationError::create(Utf16String::from_utf8(error_message)));
+ return;
+ }
+ if (payload.has_value() && !payload->is_local) {
+ auto description = RTCSessionDescription::create(RTCSessionDescriptionInit { .sdp = payload->sdp, .type = payload->type });
+ switch (payload->type) {
+ case Bindings::RTCSdpType::Offer:
+ case Bindings::RTCSdpType::Pranswer:
+ m_pending_remote_description = description;
+ break;
+ case Bindings::RTCSdpType::Answer:
+ m_current_remote_description = description;
+ m_current_local_description = m_pending_local_description;
+ m_pending_local_description = nullptr;
+ m_pending_remote_description = nullptr;
+ m_restart_ice = false;
+ break;
+ case Bindings::RTCSdpType::Rollback:
+ m_pending_local_description = nullptr;
+ m_pending_remote_description = nullptr;
+ break;
+ }
+ }
+ WebIDL::resolve_promise(realm, promise_ref, JS::js_undefined());
+}
+
+void RTCPeerConnection::on_add_ice_candidate_result_received(u64 request_id, bool ok, String, String error_message)
+{
+ auto promise = m_pending_void_requests.take(request_id);
+ if (!promise.has_value())
+ return;
+ auto& realm = relevant_realm();
+ auto& promise_ref = **promise;
+ HTML::TemporaryExecutionContext context(realm);
+ if (!ok)
+ WebIDL::reject_promise(realm, promise_ref, WebIDL::OperationError::create(Utf16String::from_utf8(error_message)));
+ else
+ WebIDL::resolve_promise(realm, promise_ref, JS::js_undefined());
+}
+
+void RTCPeerConnection::on_remote_data_channel_received(u64 channel_id, String label, bool ordered, Optional<u16> max_packet_life_time, Optional<u16> max_retransmits, String protocol, bool negotiated, Optional<u16> id)
+{
+ if (m_is_closed)
+ return;
+ HTML::TemporaryExecutionContext context(relevant_realm());
+ auto channel = RTCDataChannel::create(m_global_object);
+ channel->set_channel_id(channel_id);
+ channel->set_label(Utf16String::from_utf8(label));
+ channel->set_ordered(ordered);
+ channel->set_max_packet_life_time(max_packet_life_time);
+ channel->set_max_retransmits(max_retransmits);
+ channel->set_protocol(Utf16String::from_utf8(protocol));
+ channel->set_negotiated(negotiated);
+ channel->set_id(id);
+ channel->set_ready_state(Bindings::RTCDataChannelState::Open);
+ m_data_channels.append(channel);
+ m_data_channels_by_id.set(channel_id, channel);
+ WebRTCAgent::the().register_data_channel(channel_id, channel);
+ RTCDataChannelEventInit init { {}, channel };
+ dispatch_event(RTCDataChannelEvent::create(HTML::EventNames::datachannel, init, HighResolutionTime::current_high_resolution_time(relevant_global_object())));
+}
+
+#define EVENT_HANDLER(name, event_name) \
+ void RTCPeerConnection::set_##name(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::event_name, cb); } \
+ WebIDL::CallbackType* RTCPeerConnection::name() { return event_handler_attribute(HTML::EventNames::event_name); }
+
+EVENT_HANDLER(onnegotiationneeded, negotiationneeded)
+EVENT_HANDLER(onicecandidate, icecandidate)
+EVENT_HANDLER(onicecandidateerror, icecandidateerror)
+EVENT_HANDLER(onsignalingstatechange, signalingstatechange)
+EVENT_HANDLER(oniceconnectionstatechange, iceconnectionstatechange)
+EVENT_HANDLER(onicegatheringstatechange, icegatheringstatechange)
+EVENT_HANDLER(onconnectionstatechange, connectionstatechange)
+EVENT_HANDLER(ontrack, track)
+EVENT_HANDLER(ondatachannel, datachannel)
+
+#undef EVENT_HANDLER
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnection.h b/Libraries/LibWeb/WebRTC/RTCPeerConnection.h
new file mode 100644
index 00000000000..a60f4a199c5
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnection.h
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/HashMap.h>
+#include <AK/HashTable.h>
+#include <AK/Mutex.h>
+#include <AK/Utf16String.h>
+#include <LibAudio/Forward.h>
+#include <LibMedia/Forward.h>
+#include <LibWeb/Bindings/Forward.h>
+#include <LibWeb/Bindings/MediaStreamTrack.h>
+#include <LibWeb/Bindings/RTCPeerConnection.h>
+#include <LibWeb/Bindings/RTCRtpTransceiver.h>
+#include <LibWeb/Bindings/RTCSessionDescription.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+#include <LibWeb/WebIDL/Promise.h>
+
+namespace Web::WebRTC {
+
+class RTCDataChannel;
+class RTCRtpReceiver;
+class RTCRtpSender;
+class RTCRtpTransceiver;
+class RTCSctpTransport;
+class RTCSessionDescription;
+
+using Bindings::RTCAnswerOptions;
+using Bindings::RTCConfiguration;
+using Bindings::RTCDataChannelInit;
+using Bindings::RTCIceCandidateInit;
+using Bindings::RTCIceServer;
+using Bindings::RTCLocalSessionDescriptionInit;
+using Bindings::RTCOfferAnswerOptions;
+using Bindings::RTCOfferOptions;
+using Bindings::RTCRtpTransceiverInit;
+using Bindings::RTCSessionDescriptionInit;
+
+class RTCPeerConnection final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCPeerConnection, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCPeerConnection);
+
+public:
+ static WebIDL::ExceptionOr<GC::Ref<RTCPeerConnection>> create_for_constructor(JS::Object& relevant_global_object, RTCConfiguration const& = {});
+
+ virtual void finalize() override;
+
+ JS::Realm& relevant_realm() const;
+ JS::Object& relevant_global_object() const;
+ virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override { return m_global_object; }
+
+ Bindings::RTCSignalingState signaling_state() const { return m_signaling_state; }
+ Bindings::RTCIceGatheringState ice_gathering_state() const { return m_ice_gathering_state; }
+ Bindings::RTCIceConnectionState ice_connection_state() const { return m_ice_connection_state; }
+ Bindings::RTCPeerConnectionState connection_state() const { return m_connection_state; }
+ bool is_closed() const { return m_is_closed; }
+
+ GC::RootVector<GC::Ref<RTCRtpTransceiver>> collect_transceivers() const;
+ void update_negotiation_needed_flag();
+
+ GC::Ref<WebIDL::Promise> create_offer(RTCOfferOptions const&);
+ GC::Ref<WebIDL::Promise> create_an_offer();
+ RTCConfiguration const& get_configuration() const { return m_configuration; }
+ void restart_ice();
+ bool m_restart_ice { false };
+ GC::Ref<WebIDL::Promise> create_answer(RTCAnswerOptions const&);
+ GC::Ref<WebIDL::Promise> create_an_answer();
+ GC::Ref<WebIDL::Promise> set_local_description(RTCLocalSessionDescriptionInit const&);
+ GC::Ref<WebIDL::Promise> set_remote_description(RTCSessionDescriptionInit const&);
+ GC::Ref<WebIDL::Promise> add_ice_candidate(RTCIceCandidateInit const&);
+
+ GC::Ref<WebIDL::Promise> set_a_local_description(Bindings::RTCSdpType, Utf16String const& sdp);
+ GC::Ref<WebIDL::Promise> set_a_remote_description(RTCSessionDescriptionInit const&);
+
+ GC::Ptr<RTCSessionDescription> local_description() const;
+ GC::Ptr<RTCSessionDescription> current_local_description() const { return m_current_local_description; }
+ GC::Ptr<RTCSessionDescription> pending_local_description() const { return m_pending_local_description; }
+ GC::Ptr<RTCSessionDescription> remote_description() const;
+ GC::Ptr<RTCSessionDescription> current_remote_description() const { return m_current_remote_description; }
+ GC::Ptr<RTCSessionDescription> pending_remote_description() const { return m_pending_remote_description; }
+
+ GC::RootVector<GC::Ref<RTCRtpSender>> get_senders() const { return collect_senders(); }
+ GC::RootVector<GC::Ref<RTCRtpReceiver>> get_receivers() const;
+ GC::RootVector<GC::Ref<RTCRtpTransceiver>> get_transceivers() const { return collect_transceivers(); }
+
+ WebIDL::ExceptionOr<GC::Ref<RTCRtpSender>> add_track(GC::Ref<MediaCapture::MediaStreamTrack>, GC::Ref<MediaCapture::MediaStream>);
+ WebIDL::ExceptionOr<GC::Ref<RTCRtpSender>> add_track(GC::Ref<MediaCapture::MediaStreamTrack>, GC::RootVector<GC::Ref<MediaCapture::MediaStream>> const&);
+ WebIDL::ExceptionOr<GC::Ref<RTCRtpTransceiver>> add_transceiver(Variant<GC::Ref<MediaCapture::MediaStreamTrack>, Utf16String> const& track_or_kind, RTCRtpTransceiverInit const& = {});
+ GC::Ptr<RTCSctpTransport> sctp() const { return m_sctp; }
+ WebIDL::ExceptionOr<GC::Ref<RTCDataChannel>> create_data_channel(Utf16String const& label, RTCDataChannelInit const&);
+
+ GC::RootVector<GC::Ref<RTCRtpSender>> collect_senders() const;
+ WebIDL::ExceptionOr<void> remove_track(GC::Ref<RTCRtpSender>);
+ void stop_sender(RTCRtpSender&);
+
+ GC::Ref<WebIDL::Promise> get_stats(GC::Ptr<MediaCapture::MediaStreamTrack>);
+
+ void close();
+ void close_for_document_destruction();
+ void on_helper_died();
+
+ u64 pc_id() const { return m_pc_id; }
+
+ // Inbound IPC event hooks (called by WebRTCAgent's dispatch).
+ void on_stats_received(u64 request_id, String reports, String error);
+ void on_signaling_state_event(String state);
+ void on_connection_state_event(String state);
+ void on_ice_gathering_state_event(String state);
+ void on_ice_connection_state_event(String state);
+ void on_ice_candidate_received(Optional<String> candidate, Optional<String> sdp_mid, Optional<u32> sdp_mline_index);
+ void on_ice_candidate_error_received(Optional<String> address, Optional<u16> port, String url, u16 error_code, String error_text);
+ void on_negotiation_needed_received();
+ void on_remote_track_added(u64 receiver_id, u64 transceiver_id, String kind, Vector<String> stream_ids);
+ void on_remote_track_ended(u64 receiver_id);
+ void on_encoded_audio_frame_received(u64 receiver_id, u32 ssrc, u32 rtp_timestamp, u16 sequence_number, u8 payload_type, ByteBuffer payload);
+ void on_audio_track_ssrc_assigned(u64 sender_id, u32 ssrc);
+ void on_create_offer_result_received(u64 request_id, bool ok, String sdp_type, String sdp, String error_kind, String error_message);
+ void on_create_answer_result_received(u64 request_id, bool ok, String sdp_type, String sdp, String error_kind, String error_message);
+ void on_set_local_description_result_received(u64 request_id, bool ok, String error_kind, String error_message);
+ void on_set_remote_description_result_received(u64 request_id, bool ok, String error_kind, String error_message);
+ void on_add_ice_candidate_result_received(u64 request_id, bool ok, String error_kind, String error_message);
+ void on_remote_data_channel_received(u64 channel_id, String label, bool ordered, Optional<u16> max_packet_life_time, Optional<u16> max_retransmits, String protocol, bool negotiated, Optional<u16> id);
+
+#define EVENT_HANDLER(name) \
+ void set_##name(WebIDL::CallbackType*); \
+ WebIDL::CallbackType* name();
+ EVENT_HANDLER(onnegotiationneeded)
+ EVENT_HANDLER(onicecandidate)
+ EVENT_HANDLER(onicecandidateerror)
+ EVENT_HANDLER(onsignalingstatechange)
+ EVENT_HANDLER(oniceconnectionstatechange)
+ EVENT_HANDLER(onicegatheringstatechange)
+ EVENT_HANDLER(onconnectionstatechange)
+ EVENT_HANDLER(ontrack)
+ EVENT_HANDLER(ondatachannel)
+#undef EVENT_HANDLER
+
+private:
+ explicit RTCPeerConnection(GC::Ref<DOM::EventTarget> relevant_global_object, RTCConfiguration);
+
+ virtual void visit_edges(JS::Cell::Visitor&) override;
+
+ void close_the_connection_algorithm(bool disappear);
+ GC::Ref<WebIDL::Promise> chain_operation(GC::Ref<WebIDL::ReactionSteps>);
+ GC::Ptr<WebIDL::Promise> m_last_operation;
+ GC::Ref<WebIDL::Promise> create_offer_impl(RTCOfferOptions const&);
+ GC::Ref<WebIDL::Promise> create_answer_impl(RTCAnswerOptions const&);
+ GC::Ref<WebIDL::Promise> set_local_description_impl(RTCLocalSessionDescriptionInit const&);
+ GC::Ref<WebIDL::Promise> set_remote_description_impl(RTCSessionDescriptionInit const&);
+ GC::Ref<WebIDL::Promise> add_ice_candidate_impl(RTCIceCandidateInit const&);
+
+ // The global this connection was created for; used to recover the realm for
+ // promise/event work triggered by IPC.
+ GC::Ref<DOM::EventTarget> m_global_object;
+
+ RTCConfiguration m_configuration;
+
+ // [[SignalingState]]
+ Bindings::RTCSignalingState m_signaling_state { Bindings::RTCSignalingState::Stable };
+ // [[IceGatheringState]]
+ Bindings::RTCIceGatheringState m_ice_gathering_state { Bindings::RTCIceGatheringState::New };
+ // [[IceConnctionState]]
+ Bindings::RTCIceConnectionState m_ice_connection_state { Bindings::RTCIceConnectionState::New };
+ // [[ConnctionState]]
+ Bindings::RTCPeerConnectionState m_connection_state { Bindings::RTCPeerConnectionState::New };
+ // [[IsClosed]]
+ bool m_is_closed { false };
+ // [[SctpTransport]]
+ GC::Ptr<RTCSctpTransport> m_sctp;
+ // [[Transceivers]]
+ Vector<GC::Ref<RTCRtpTransceiver>> m_transceivers;
+ // [[DataChannels]]
+ Vector<GC::Ref<RTCDataChannel>> m_data_channels;
+ HashMap<u64, GC::Ref<RTCDataChannel>> m_data_channels_by_id;
+ // [[LastCreatedOffer]]
+ Utf16String m_last_created_offer;
+ u64 m_pc_id { 0 };
+ HashMap<u64, GC::Root<WebIDL::Promise>> m_pending_void_requests;
+ HashMap<u64, GC::Root<WebIDL::Promise>> m_pending_description_requests;
+
+ HashMap<String, GC::Ref<MediaCapture::MediaStream>> m_remote_streams;
+ HashMap<u64, GC::Ref<RTCRtpReceiver>> m_remote_receivers_by_id;
+
+public:
+ GC::Ptr<MediaCapture::MediaStream> find_or_create_remote_stream_for_msid(String const&);
+
+ // Start capturing audio only once there is a sender to feed.
+ void on_sender_track_changed(RTCRtpSender&);
+ void on_sender_transform_changed(RTCRtpSender&);
+
+private:
+ struct PendingDescription {
+ Bindings::RTCSdpType type;
+ Utf16String sdp;
+ bool is_local;
+ };
+ HashMap<u64, PendingDescription> m_pending_description_payloads;
+ bool is_setting_local_description() const;
+ void settle_local_description(u64 request_id, bool ok, String const& error_message);
+ // ICE events the helper sent before the local description they follow was set; see on_ice_candidate_received().
+ Vector<Function<void()>> m_held_ice_events;
+ // [[LastCreatedAnswer]]
+ Utf16String m_last_created_answer;
+ // [[CurrentLocalDescription]]
+ GC::Ptr<RTCSessionDescription> m_current_local_description;
+ // [[PendingLocalDescription]]
+ GC::Ptr<RTCSessionDescription> m_pending_local_description;
+ // [[CurrentRemoteDescription]]
+ GC::Ptr<RTCSessionDescription> m_current_remote_description;
+ // [[PendingRemoteDescription]]
+ GC::Ptr<RTCSessionDescription> m_pending_remote_description;
+
+ // Per-remote-receiver playback stack. We bypass the spec's MediaStream → audio-element
+ // path entirely and just opus-decode + push PCM straight to libmedia's audio output.
+ // Once we wire MediaStreamTrack as a real audio source, this should go away.
+ struct PlaybackBuffer : public AtomicRefCounted<PlaybackBuffer> {
+ Mutex mutex;
+ Vector<float> samples;
+ };
+ struct ReceiverAudioPlayback {
+ AK_ALLOC_WITH_KMALLOC;
+
+ OwnPtr<Media::AudioDecoder> decoder;
+ OwnPtr<Media::FFmpeg::FFmpegAudioConverter> converter;
+ RefPtr<Audio::PlaybackStream> playback_stream;
+ NonnullRefPtr<PlaybackBuffer> buffer = adopt_ref(*new PlaybackBuffer);
+ u8 channel_count { 0 };
+ bool started { false };
+ };
+ HashMap<u64, NonnullOwnPtr<ReceiverAudioPlayback>> m_receiver_audio_playbacks;
+ void feed_decoded_audio(u64 receiver_id, ByteBuffer payload, u32 rtp_timestamp);
+
+ // The track may outlive this connection, so its producer callback owns this state independently.
+ struct OutgoingAudioProducerState : public AtomicRefCounted<OutgoingAudioProducerState> {
+ OwnPtr<Media::FFmpeg::FFmpegAudioConverter> converter;
+ u64 source_frames { 0 };
+ Vector<float> float_accumulator;
+ Atomic<size_t> pending_frames { 0 };
+ };
+ // Main-thread state for encoding and routing the producer's 20 ms PCM frames.
+ struct OutgoingAudioPipeline {
+ AK_ALLOC_WITH_KMALLOC;
+
+ RefPtr<MediaCapture::AudioFrameSink> sink;
+ GC::Ptr<MediaCapture::MediaStreamTrack> track;
+ OwnPtr<Media::FFmpeg::FFmpegAudioEncoder> encoder;
+ u64 generation { 0 };
+ u32 next_rtp_timestamp { 0 };
+ u16 next_sequence_number { 0 };
+ };
+ HashMap<u64, NonnullOwnPtr<OutgoingAudioPipeline>> m_outgoing_audio_pipelines;
+ HashTable<u64> m_requested_audio_senders;
+ HashTable<u64> m_ready_audio_senders;
+ void start_outgoing_audio_for_sender(GC::Ref<RTCRtpSender>);
+ void encode_and_route_outgoing_pcm(u64 sender_id, ByteBuffer pcm_s16le);
+ void on_outgoing_encrypted_frame(u64 sender_id, ByteBuffer payload, u32 rtp_timestamp, u16 sequence_number, u8 payload_type);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnection.idl b/Libraries/LibWeb/WebRTC/RTCPeerConnection.idl
new file mode 100644
index 00000000000..7f9b3b8fcaa
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnection.idl
@@ -0,0 +1,134 @@
+
+// https://w3c.github.io/webrtc-pc/#interface-definition
+
+[Exposed=Window]
+interface RTCPeerConnection : EventTarget {
+ constructor(optional RTCConfiguration configuration = {});
+
+ Promise<RTCSessionDescriptionInit> createOffer(optional RTCOfferOptions options = {});
+ Promise<RTCSessionDescriptionInit> createAnswer(optional RTCAnswerOptions options = {});
+
+ Promise<undefined> setLocalDescription(optional RTCLocalSessionDescriptionInit description = {});
+ readonly attribute RTCSessionDescription? localDescription;
+ readonly attribute RTCSessionDescription? currentLocalDescription;
+ readonly attribute RTCSessionDescription? pendingLocalDescription;
+
+ Promise<undefined> setRemoteDescription(RTCSessionDescriptionInit description);
+ readonly attribute RTCSessionDescription? remoteDescription;
+ readonly attribute RTCSessionDescription? currentRemoteDescription;
+ readonly attribute RTCSessionDescription? pendingRemoteDescription;
+
+ Promise<undefined> addIceCandidate(optional RTCIceCandidateInit candidate = {});
+
+ readonly attribute RTCSignalingState signalingState;
+ readonly attribute RTCIceGatheringState iceGatheringState;
+ readonly attribute RTCIceConnectionState iceConnectionState;
+ readonly attribute RTCPeerConnectionState connectionState;
+ [FIXME] readonly attribute boolean? canTrickleIceCandidates;
+
+ undefined restartIce();
+ RTCConfiguration getConfiguration();
+ [FIXME] undefined setConfiguration(optional RTCConfiguration configuration = {});
+ undefined close();
+
+ attribute EventHandler onnegotiationneeded;
+ attribute EventHandler onicecandidate;
+ attribute EventHandler onicecandidateerror;
+ attribute EventHandler onsignalingstatechange;
+ attribute EventHandler oniceconnectionstatechange;
+ attribute EventHandler onicegatheringstatechange;
+ attribute EventHandler onconnectionstatechange;
+
+ // Legacy callback overloads — every site uses promises now, leave stubbed.
+ [FIXME] Promise<undefined> createOffer(RTCSessionDescriptionCallback successCallback,
+ RTCPeerConnectionErrorCallback failureCallback,
+ optional RTCOfferOptions options = {});
+ [FIXME] Promise<undefined> setLocalDescription(RTCLocalSessionDescriptionInit description,
+ VoidFunction successCallback,
+ RTCPeerConnectionErrorCallback failureCallback);
+ [FIXME] Promise<undefined> createAnswer(RTCSessionDescriptionCallback successCallback,
+ RTCPeerConnectionErrorCallback failureCallback);
+ [FIXME] Promise<undefined> setRemoteDescription(RTCSessionDescriptionInit description,
+ VoidFunction successCallback,
+ RTCPeerConnectionErrorCallback failureCallback);
+ [FIXME] Promise<undefined> addIceCandidate(RTCIceCandidateInit candidate,
+ VoidFunction successCallback,
+ RTCPeerConnectionErrorCallback failureCallback);
+
+ [FIXME] static Promise<RTCCertificate> generateCertificate(AlgorithmIdentifier keygenAlgorithm);
+
+ sequence<RTCRtpSender> getSenders();
+ sequence<RTCRtpReceiver> getReceivers();
+ sequence<RTCRtpTransceiver> getTransceivers();
+ // FIXME: spec is `MediaStream... streams`. The IDL codegen mishandles typed
+ // variadics after a required arg, and a plain `sequence<MediaStream>` would
+ // force WebIDL to iterate a single MediaStream argument (which isn't iterable),
+ // breaking the common `pc.addTrack(track, stream)` call shape that real libs
+ // (talky.io, janus, ...) use. Two overloads cover both call shapes.
+ RTCRtpSender addTrack(MediaStreamTrack track, MediaStream stream);
+ RTCRtpSender addTrack(MediaStreamTrack track, optional sequence<MediaStream> streams = []);
+ undefined removeTrack(RTCRtpSender sender);
+ RTCRtpTransceiver addTransceiver((MediaStreamTrack or DOMString) trackOrKind,
+ optional RTCRtpTransceiverInit init = {});
+ attribute EventHandler ontrack;
+
+ readonly attribute RTCSctpTransport? sctp;
+ RTCDataChannel createDataChannel(USVString label,
+ optional RTCDataChannelInit dataChannelDict = {});
+ attribute EventHandler ondatachannel;
+
+ Promise<RTCStatsReport> getStats(optional MediaStreamTrack? selector = null);
+};
+
+dictionary RTCConfiguration {
+ sequence<RTCIceServer> iceServers = [];
+ RTCIceTransportPolicy iceTransportPolicy = "all";
+ RTCBundlePolicy bundlePolicy = "balanced";
+ RTCRtcpMuxPolicy rtcpMuxPolicy = "require";
+ // FIXME: spec has `sequence<RTCCertificate>` here. Held as `sequence<object>`
+ // until RTCCertificate gen + serialization lands.
+ sequence<object> certificates = [];
+ [EnforceRange] octet iceCandidatePoolSize = 0;
+};
+
+dictionary RTCIceServer {
+ required (DOMString or sequence<DOMString>) urls;
+ DOMString username;
+ DOMString credential;
+};
+
+enum RTCIceTransportPolicy { "relay", "all" };
+enum RTCBundlePolicy { "balanced", "max-compat", "max-bundle" };
+enum RTCRtcpMuxPolicy { "require" };
+
+dictionary RTCOfferAnswerOptions {};
+
+dictionary RTCOfferOptions : RTCOfferAnswerOptions {
+ boolean iceRestart = false;
+ boolean offerToReceiveAudio;
+ boolean offerToReceiveVideo;
+};
+
+dictionary RTCAnswerOptions : RTCOfferAnswerOptions {};
+
+enum RTCSignalingState {
+ "stable",
+ "have-local-offer",
+ "have-remote-offer",
+ "have-local-pranswer",
+ "have-remote-pranswer",
+ "closed"
+};
+
+enum RTCIceGatheringState { "new", "gathering", "complete" };
+
+enum RTCPeerConnectionState {
+ "closed", "failed", "disconnected", "new", "connecting", "connected"
+};
+
+enum RTCIceConnectionState {
+ "closed", "failed", "disconnected", "new", "checking", "completed", "connected"
+};
+
+callback RTCPeerConnectionErrorCallback = undefined (DOMException error);
+callback RTCSessionDescriptionCallback = undefined (RTCSessionDescriptionInit description);
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.cpp b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.cpp
new file mode 100644
index 00000000000..f5bf6e1dcd3
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.cpp
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCPeerConnectionIceErrorEvent);
+
+GC::Ref<RTCPeerConnectionIceErrorEvent> RTCPeerConnectionIceErrorEvent::create(Utf16FlyString const& event_name, RTCPeerConnectionIceErrorEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCPeerConnectionIceErrorEvent>(event_name, event_init, time_stamp);
+}
+
+// FIXME: RTCPeerConnectionIceErrorEvent is a stub — store the address/port/url/errorCode/errorText once the attributes are implemented.
+RTCPeerConnectionIceErrorEvent::RTCPeerConnectionIceErrorEvent(Utf16FlyString const& event_name, RTCPeerConnectionIceErrorEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+{
+}
+
+RTCPeerConnectionIceErrorEvent::~RTCPeerConnectionIceErrorEvent() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.h b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.h
new file mode 100644
index 00000000000..cba2b8c06bf
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCPeerConnectionIceErrorEvent.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+using RTCPeerConnectionIceErrorEventInit = Bindings::RTCPeerConnectionIceErrorEventInit;
+
+class RTCPeerConnectionIceErrorEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCPeerConnectionIceErrorEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCPeerConnectionIceErrorEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCPeerConnectionIceErrorEvent> create(Utf16FlyString const& event_name, RTCPeerConnectionIceErrorEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+ virtual ~RTCPeerConnectionIceErrorEvent() override;
+
+private:
+ RTCPeerConnectionIceErrorEvent(Utf16FlyString const& event_name, RTCPeerConnectionIceErrorEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.idl b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.idl
new file mode 100644
index 00000000000..a18b8fcf194
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceErrorEvent.idl
@@ -0,0 +1,19 @@
+// https://w3c.github.io/webrtc-pc/#rtcpeerconnectioniceerrorevent
+
+[Exposed=Window]
+interface RTCPeerConnectionIceErrorEvent : Event {
+ [FIXME] constructor(DOMString type, RTCPeerConnectionIceErrorEventInit eventInitDict);
+ [FIXME] readonly attribute DOMString? address;
+ [FIXME] readonly attribute unsigned short? port;
+ [FIXME] readonly attribute DOMString url;
+ [FIXME] readonly attribute unsigned short errorCode;
+ [FIXME] readonly attribute USVString errorText;
+};
+
+dictionary RTCPeerConnectionIceErrorEventInit : EventInit {
+ DOMString? address;
+ unsigned short? port;
+ DOMString url;
+ required unsigned short errorCode;
+ USVString errorText;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.cpp b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.cpp
new file mode 100644
index 00000000000..4743a2a9911
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCIceCandidate.h>
+#include <LibWeb/WebRTC/RTCPeerConnectionIceEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCPeerConnectionIceEvent);
+
+GC::Ref<RTCPeerConnectionIceEvent> RTCPeerConnectionIceEvent::create(Utf16FlyString const& event_name, RTCPeerConnectionIceEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCPeerConnectionIceEvent>(event_name, event_init, time_stamp);
+}
+
+RTCPeerConnectionIceEvent::RTCPeerConnectionIceEvent(Utf16FlyString const& event_name, RTCPeerConnectionIceEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+ , m_candidate(event_init.candidate)
+ , m_url(event_init.url.value_or(Optional<Utf16String> {}))
+{
+}
+
+RTCPeerConnectionIceEvent::~RTCPeerConnectionIceEvent() = default;
+
+void RTCPeerConnectionIceEvent::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_candidate);
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.h b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.h
new file mode 100644
index 00000000000..5c9ac855451
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCPeerConnectionIceEvent.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+using RTCPeerConnectionIceEventInit = Bindings::RTCPeerConnectionIceEventInit;
+
+class RTCPeerConnectionIceEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCPeerConnectionIceEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCPeerConnectionIceEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCPeerConnectionIceEvent> create(Utf16FlyString const& event_name, RTCPeerConnectionIceEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+ static GC::Ref<RTCPeerConnectionIceEvent> create_for_constructor(Utf16String const& type, RTCPeerConnectionIceEventInit const& init, HighResolutionTime::DOMHighResTimeStamp time_stamp) { return create(Utf16FlyString { type }, init, time_stamp); }
+ GC::Ptr<RTCIceCandidate> candidate() const { return m_candidate; }
+ Optional<Utf16String> url() const { return m_url; }
+ virtual ~RTCPeerConnectionIceEvent() override;
+
+private:
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+ GC::Ptr<RTCIceCandidate> m_candidate;
+ Optional<Utf16String> m_url;
+ RTCPeerConnectionIceEvent(Utf16FlyString const& event_name, RTCPeerConnectionIceEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.idl b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.idl
new file mode 100644
index 00000000000..315446eb708
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnectionIceEvent.idl
@@ -0,0 +1,14 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcpeerconnectioniceevent
+
+[Exposed=Window]
+interface RTCPeerConnectionIceEvent : Event {
+ constructor(DOMString type, optional RTCPeerConnectionIceEventInit eventInitDict = {});
+ readonly attribute RTCIceCandidate? candidate;
+ readonly attribute DOMString? url;
+};
+
+dictionary RTCPeerConnectionIceEventInit : EventInit {
+ RTCIceCandidate? candidate = null;
+ DOMString? url;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpParameters.h b/Libraries/LibWeb/WebRTC/RTCRtpParameters.h
new file mode 100644
index 00000000000..cc958fdb7ba
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpParameters.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Vector.h>
+#include <LibWeb/Bindings/RTCRtpSender.h>
+
+namespace Web::WebRTC {
+
+using Bindings::RTCRtcpParameters;
+using Bindings::RTCRtpCapabilities;
+using Bindings::RTCRtpCodec;
+using Bindings::RTCRtpCodecParameters;
+using Bindings::RTCRtpCodingParameters;
+using Bindings::RTCRtpEncodingParameters;
+using Bindings::RTCRtpHeaderExtensionCapability;
+using Bindings::RTCRtpHeaderExtensionParameters;
+using Bindings::RTCRtpParameters;
+using Bindings::RTCRtpReceiveParameters;
+using Bindings::RTCRtpSendParameters;
+using Bindings::RTCSetParameterOptions;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpReceiver.cpp b/Libraries/LibWeb/WebRTC/RTCRtpReceiver.cpp
new file mode 100644
index 00000000000..01aee17aeea
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpReceiver.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Debug.h>
+#include <LibGC/Heap.h>
+#include <LibWeb/MediaCapture/MediaStream.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+#include <LibWeb/WebRTC/RTCRtpReceiver.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransform.h>
+#include <LibWeb/WebRTC/RTCSFrameReceiverTransform.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCRtpReceiver);
+
+GC::Ref<RTCRtpReceiver> RTCRtpReceiver::create(Bindings::MediaStreamTrackKind kind)
+{
+ auto track = MediaCapture::MediaStreamTrack::create(kind);
+ return GC::Heap::the().allocate<RTCRtpReceiver>(track);
+}
+
+RTCRtpReceiver::RTCRtpReceiver(GC::Ref<MediaCapture::MediaStreamTrack> track)
+ : m_track(track)
+{
+}
+
+RTCRtpReceiver::~RTCRtpReceiver() = default;
+
+GC::Ref<MediaCapture::MediaStreamTrack> RTCRtpReceiver::track() const { return m_track; }
+
+void RTCRtpReceiver::set_associated_remote_streams(Vector<GC::Ref<MediaCapture::MediaStream>>&& streams)
+{
+ m_associated_remote_streams = move(streams);
+}
+
+void RTCRtpReceiver::visit_edges(JS::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_track);
+ visitor.visit(m_transform);
+ for (auto& stream : m_associated_remote_streams)
+ visitor.visit(stream);
+}
+
+RTCRtpReceiverTransform RTCRtpReceiver::transform() const
+{
+ if (!m_transform)
+ return Empty {};
+ if (auto* script_transform = as_if<RTCRtpScriptTransform>(*m_transform))
+ return GC::Ref { *script_transform };
+ if (auto* sframe_transform = as_if<RTCSFrameReceiverTransform>(*m_transform))
+ return GC::Ref { *sframe_transform };
+ return Empty {};
+}
+
+// https://w3c.github.io/webrtc-encoded-transform/#dom-rtcrtpreceiver-transform
+WebIDL::ExceptionOr<void> RTCRtpReceiver::set_transform(RTCRtpReceiverTransform value)
+{
+ // NB: A script transform belongs to the first sender or receiver it's set on, even once it's replaced there.
+ auto* new_script_transform = value.get_pointer<GC::Ref<RTCRtpScriptTransform>>();
+ if (new_script_transform && (*new_script_transform)->has_owner())
+ return WebIDL::InvalidStateError::create("The transform is already in use"_utf16);
+ if (new_script_transform)
+ (*new_script_transform)->set_has_owner();
+
+ if (auto* old_script_transform = m_transform ? as_if<RTCRtpScriptTransform>(*m_transform) : nullptr)
+ old_script_transform->detach();
+ m_transform = value.visit(
+ [](Empty) -> GC::Ptr<Bindings::Wrappable> { return nullptr; },
+ [](GC::Ref<RTCSFrameReceiverTransform> const& t) -> GC::Ptr<Bindings::Wrappable> { return t.ptr(); },
+ [](GC::Ref<RTCRtpScriptTransform> const& t) -> GC::Ptr<Bindings::Wrappable> { return t.ptr(); });
+ dbgln_if(WEBRTC_DEBUG, "RTCRtpReceiver::set_transform: transform set={}", m_transform != nullptr);
+ return {};
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpReceiver.h b/Libraries/LibWeb/WebRTC/RTCRtpReceiver.h
new file mode 100644
index 00000000000..911af0a60d9
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpReceiver.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/MediaStreamTrack.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::WebRTC {
+
+using RTCRtpReceiverTransform = Variant<GC::Ref<RTCSFrameReceiverTransform>, GC::Ref<RTCRtpScriptTransform>, Empty>;
+
+class RTCRtpReceiver final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCRtpReceiver, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCRtpReceiver);
+
+public:
+ static GC::Ref<RTCRtpReceiver> create(Bindings::MediaStreamTrackKind);
+ virtual ~RTCRtpReceiver() override;
+
+ GC::Ref<MediaCapture::MediaStreamTrack> track() const;
+
+ RTCRtpReceiverTransform transform() const;
+ WebIDL::ExceptionOr<void> set_transform(RTCRtpReceiverTransform);
+
+ // [[AssociatedRemoteMediaStreams]]
+ Vector<GC::Ref<MediaCapture::MediaStream>> const& associated_remote_streams() const { return m_associated_remote_streams; }
+ void set_associated_remote_streams(Vector<GC::Ref<MediaCapture::MediaStream>>&&);
+
+private:
+ explicit RTCRtpReceiver(GC::Ref<MediaCapture::MediaStreamTrack>);
+ virtual void visit_edges(JS::Cell::Visitor&) override;
+
+ // [[ReceiverTrack]]
+ GC::Ref<MediaCapture::MediaStreamTrack> m_track;
+ GC::Ptr<Bindings::Wrappable> m_transform;
+ Vector<GC::Ref<MediaCapture::MediaStream>> m_associated_remote_streams;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpReceiver.idl b/Libraries/LibWeb/WebRTC/RTCRtpReceiver.idl
new file mode 100644
index 00000000000..33109af757e
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpReceiver.idl
@@ -0,0 +1,23 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcrtpreceiver-interface
+
+[Exposed=Window]
+interface RTCRtpReceiver {
+ readonly attribute MediaStreamTrack track;
+ [FIXME] readonly attribute RTCDtlsTransport? transport;
+ [FIXME] static RTCRtpCapabilities? getCapabilities(DOMString kind);
+ [FIXME] RTCRtpReceiveParameters getParameters();
+ [FIXME] sequence<RTCRtpContributingSource> getContributingSources();
+ [FIXME] sequence<RTCRtpSynchronizationSource> getSynchronizationSources();
+ [FIXME] Promise<RTCStatsReport> getStats();
+ [FIXME] attribute DOMHighResTimeStamp? jitterBufferTarget;
+};
+
+dictionary RTCRtpContributingSource {
+ required DOMHighResTimeStamp timestamp;
+ required unsigned long source;
+ double audioLevel;
+ required unsigned long rtpTimestamp;
+};
+
+dictionary RTCRtpSynchronizationSource : RTCRtpContributingSource { };
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.cpp b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.cpp
new file mode 100644
index 00000000000..eba3dfb2629
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.cpp
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Debug.h>
+#include <LibGC/Heap.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/StructuredSerialize.h>
+#include <LibWeb/HTML/Worker.h>
+#include <LibWeb/HTML/WorkerAgentParent.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransform.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCRtpScriptTransform);
+
+// https://w3c.github.io/webrtc-encoded-transform/#dom-rtcrtpscripttransform-rtcrtpscripttransform
+WebIDL::ExceptionOr<GC::Ref<RTCRtpScriptTransform>> RTCRtpScriptTransform::construct_impl(JS::Realm& realm,
+ Variant<GC::Ref<HTML::Worker>, WorkerAndParameters> const& worker_or_parameters,
+ Optional<JS::Value> options,
+ Optional<GC::RootVector<GC::Ref<JS::Object>>> const& transfer)
+{
+ // 1. Let worker be undefined.
+ GC::Ptr<HTML::Worker> worker;
+
+ // 2. Let useSFrame be undefined.
+ bool use_sframe = false;
+
+ // 3. If workerOrWorkerAndParameters is a Worker object, set worker to workerOrWorkerAndParameters
+ // and useSFrame to false.
+ // 4. Otherwise, run the following substeps:
+ // 4.1. Set worker to workerOrWorkerAndParameters["worker"].
+ // 4.2. Set useSFrame to true if workerOrWorkerAndParameters["type"] is "sframe" and false otherwise.
+ worker_or_parameters.visit(
+ [&](GC::Ref<HTML::Worker> const& bare_worker) {
+ worker = bare_worker;
+ use_sframe = false;
+ },
+ [&](WorkerAndParameters const& wap) {
+ worker = wap.worker;
+ use_sframe = wap.type == Bindings::RTCRtpScriptTransformType::Sframe;
+ });
+
+ auto transform = GC::Heap::the().allocate<RTCRtpScriptTransform>();
+ // 5. Initialize this's internal slot as follows: [[worker]] worker
+ transform->m_worker = worker;
+ // 6. Initialize this.[[useSFrame]] to useSFrame.
+ transform->m_use_sframe = use_sframe;
+
+ // 7. Let serializedOptions be the result of StructuredSerializeWithTransfer(options, transfer).
+ GC::RootVector<GC::Ref<JS::Object>> transfer_objects;
+ if (transfer.has_value()) {
+ for (auto const& object : *transfer)
+ transfer_objects.append(object);
+ }
+ auto serialized_options = TRY(HTML::structured_serialize_with_transfer(realm, options.value_or(JS::js_undefined()), transfer_objects));
+
+ // 8. Queue a global task on the DOM manipulation task source with worker's WorkerGlobalScope to:
+ // 8.1. Deserialize serializedOptions.
+ // 8.2. Create an RTCRtpScriptTransformer with the deserialized options.
+ // 8.3. Fire an event named rtctransform using RTCTransformEvent on the transformer's
+ // relevant global object.
+ // IPC delivers serializedOptions verbatim to ConnectionFromClient::rtc_transform_init,
+ // which runs steps 8.1–8.3 in the worker process's realm.
+ static u64 next_transform_id = 1;
+ transform->m_transform_id = next_transform_id++;
+ auto agent = transform->m_worker ? transform->m_worker->agent() : nullptr;
+ if (agent)
+ agent->rtc_transform_init(transform->m_transform_id, move(serialized_options));
+
+ return transform;
+}
+
+RTCRtpScriptTransform::RTCRtpScriptTransform() = default;
+
+RTCRtpScriptTransform::~RTCRtpScriptTransform() = default;
+
+void RTCRtpScriptTransform::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_worker);
+}
+
+void RTCRtpScriptTransform::detach()
+{
+ if (m_detached)
+ return;
+ m_detached = true;
+ m_on_frame_written = {};
+ if (auto agent = m_worker ? m_worker->agent() : nullptr)
+ agent->rtc_transform_teardown(m_transform_id);
+}
+
+void RTCRtpScriptTransform::enqueue_encoded_audio_frame(ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ auto agent = m_worker ? m_worker->agent() : nullptr;
+ if (!agent || m_detached)
+ return;
+ dbgln_if(WEBRTC_DEBUG, "RTCRtpScriptTransform::enqueue_encoded_audio_frame id={} ssrc={} seq={} len={}", m_transform_id, ssrc, sequence_number, payload.size());
+ if (!m_callback_registered) {
+ agent->register_transform_frame_callback(m_transform_id, [self = GC::Weak { *this }](ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) {
+ if (!self || !self->m_on_frame_written)
+ return;
+ self->m_on_frame_written(move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+ });
+ m_callback_registered = true;
+ }
+ agent->rtc_transform_encoded_audio_frame(m_transform_id, move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.h b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.h
new file mode 100644
index 00000000000..965907ebf5a
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCRtpScriptTransform.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/HTML/StructuredSerialize.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+using Bindings::WorkerAndParameters;
+
+class RTCRtpScriptTransform final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCRtpScriptTransform, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCRtpScriptTransform);
+
+public:
+ static WebIDL::ExceptionOr<GC::Ref<RTCRtpScriptTransform>> construct_impl(JS::Realm&,
+ Variant<GC::Ref<HTML::Worker>, WorkerAndParameters> const& worker_or_parameters,
+ Optional<JS::Value> options,
+ Optional<GC::RootVector<GC::Ref<JS::Object>>> const& transfer);
+
+ virtual ~RTCRtpScriptTransform() override;
+
+ GC::Ptr<HTML::Worker> worker() const { return m_worker; }
+ u64 transform_id() const { return m_transform_id; }
+
+ // Send a frame to the worker over IPC. Frames written to the transformer's writable
+ // return to the parent through on_frame_written.
+ void enqueue_encoded_audio_frame(ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number);
+
+ using FrameWrittenCallback = AK::Function<void(ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)>;
+ void set_on_frame_written(FrameWrittenCallback callback) { m_on_frame_written = move(callback); }
+ bool has_frame_written_callback() const { return static_cast<bool>(m_on_frame_written); }
+
+ bool has_owner() const { return m_has_owner; }
+ void set_has_owner() { m_has_owner = true; }
+
+ // Releases the transformer in the worker once the transform is no longer attached to a sender or receiver.
+ void detach();
+
+private:
+ explicit RTCRtpScriptTransform();
+ virtual void visit_edges(Cell::Visitor&) override;
+
+ GC::Ptr<HTML::Worker> m_worker;
+ bool m_use_sframe { false };
+ u64 m_transform_id { 0 };
+ bool m_callback_registered { false };
+ bool m_has_owner { false };
+ bool m_detached { false };
+
+ FrameWrittenCallback m_on_frame_written;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.idl b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.idl
new file mode 100644
index 00000000000..ae528c0af3b
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransform.idl
@@ -0,0 +1,28 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtcrtpscripttransform
+
+enum RTCRtpScriptTransformType {
+ "sframe"
+};
+
+dictionary WorkerAndParameters {
+ required Worker worker;
+ RTCRtpScriptTransformType type;
+};
+
+typedef (Worker or WorkerAndParameters) WorkerOrWorkerAndParameters;
+
+[Exposed=Window]
+interface RTCRtpScriptTransform {
+ constructor(WorkerOrWorkerAndParameters workerOrWorkerAndParameters, optional any options, optional sequence<object> transfer);
+};
+
+typedef (RTCSFrameSenderTransform or RTCRtpScriptTransform) RTCRtpSenderTransform;
+typedef (RTCSFrameReceiverTransform or RTCRtpScriptTransform) RTCRtpReceiverTransform;
+
+partial interface RTCRtpSender {
+ attribute RTCRtpSenderTransform? transform;
+};
+
+partial interface RTCRtpReceiver {
+ attribute RTCRtpReceiverTransform? transform;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cpp b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cpp
new file mode 100644
index 00000000000..e9e3dc4679d
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Math.h>
+#include <LibGC/Heap.h>
+#include <LibJS/Runtime/Promise.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
+#include <LibWeb/Streams/ReadableStream.h>
+#include <LibWeb/Streams/TransformStream.h>
+#include <LibWeb/Streams/WritableStream.h>
+#include <LibWeb/WebIDL/Promise.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransformer.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCRtpScriptTransformer);
+
+// https://w3c.github.io/webrtc-encoded-transform/#create-an-rtcrtpscripttransformer
+WebIDL::ExceptionOr<GC::Ref<RTCRtpScriptTransformer>> RTCRtpScriptTransformer::create(JS::Realm& realm, JS::Value options)
+{
+ auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(realm.global_object());
+ VERIFY(global_scope);
+ auto transformer = GC::Heap::the().allocate<RTCRtpScriptTransformer>(global_scope->this_impl());
+
+ // 1. Let transformer be a new RTCRtpScriptTransformer with:
+ // [[frameSource]] = undefined (set later via set_write_encoded_data_algorithm)
+ // [[options]] = options
+ // [[readable]] = a new ReadableStream
+ // [[writable]] = a new WritableStream
+ // [[lastReceivedFrameCounter]] = 0
+ // [[lastEnqueuedFrameCounter]] = 0
+ transformer->m_options = options;
+
+ // 2. Set up transformer.[[readable]]. The readEncodedData algorithm provides
+ // encoded frames to it. In our model, frames are pushed in via
+ // enqueue_encoded_frame from the upstream [[frameSource]] (the depacketizer
+ // on the parent side, plumbed through IPC), so the pull is a no-op.
+ // NB: Streams only lets C++ set up a ReadableStream of arbitrary chunks as the readable side of a TransformStream,
+ // so frames are enqueued into one whose writable side nothing writes to.
+ auto readable_transform = GC::create_function(realm.heap(), [transformer](JS::Value) -> GC::Ref<WebIDL::Promise> {
+ return WebIDL::create_resolved_promise(transformer->relevant_realm(), JS::js_undefined());
+ });
+ transformer->m_readable_source = Streams::TransformStream::create(realm);
+ transformer->m_readable_source->set_up(realm, readable_transform);
+ transformer->m_readable = transformer->m_readable_source->readable();
+
+ // 3. Let writeAlgorithm be an action that runs writeEncodedData with this as
+ // parameter and frame as input, given frame.
+ auto write_algorithm = GC::create_function(realm.heap(), [transformer](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {
+ // writeEncodedData step: hand the transformed frame to [[frameSource]] for
+ // continued pipeline processing (decode, playback, or send-out for senders).
+ if (transformer->m_write_encoded_data)
+ transformer->m_write_encoded_data->function()(chunk);
+ return WebIDL::create_resolved_promise(transformer->relevant_realm(), JS::js_undefined());
+ });
+ // 4. Set up transformer.[[writable]] with its writeAlgorithm set to writeAlgorithm
+ // and its highWaterMark set to Infinity.
+ transformer->m_writable = Streams::WritableStream::create(realm);
+ transformer->m_writable->set_up(realm, write_algorithm, AK::Infinity<double>);
+
+ // 5. Return transformer.
+ return transformer;
+}
+
+JS::Realm& RTCRtpScriptTransformer::relevant_realm() const
+{
+ return HTML::relevant_realm(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+}
+
+void RTCRtpScriptTransformer::set_write_encoded_data_algorithm(GC::Ptr<WriteEncodedDataAlgorithm> algorithm)
+{
+ m_write_encoded_data = algorithm;
+}
+
+WebIDL::ExceptionOr<void> RTCRtpScriptTransformer::enqueue_encoded_frame(JS::Value frame)
+{
+ if (!m_readable_source || !m_readable->is_readable())
+ return {};
+ // Encoded audio is real-time data. Bound unread frames to 200 ms at the
+ // normal 20 ms packet duration instead of replaying an ever-growing backlog.
+ // NB: The readable side of a TransformStream has a highWaterMark of 0, so its desired size is minus its queue size.
+ if (auto desired_size = m_readable->desired_size(); desired_size.has_value() && *desired_size <= -10)
+ return {};
+ ++m_last_received_frame_counter;
+ TRY(m_readable_source->enqueue(frame));
+ ++m_last_enqueued_frame_counter;
+ return {};
+}
+
+void RTCRtpScriptTransformer::set_onkeyframerequest(WebIDL::CallbackType*) { }
+WebIDL::CallbackType* RTCRtpScriptTransformer::onkeyframerequest() { return nullptr; }
+
+RTCRtpScriptTransformer::RTCRtpScriptTransformer(GC::Ref<DOM::EventTarget> relevant_global_object)
+ : DOM::EventTarget()
+ , m_global_object(relevant_global_object)
+{
+}
+
+RTCRtpScriptTransformer::~RTCRtpScriptTransformer() = default;
+
+void RTCRtpScriptTransformer::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_global_object);
+ visitor.visit(m_options);
+ visitor.visit(m_readable_source);
+ visitor.visit(m_readable);
+ visitor.visit(m_writable);
+ visitor.visit(m_write_encoded_data);
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.h b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.h
new file mode 100644
index 00000000000..5e8f6ab5466
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibGC/Function.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+// https://w3c.github.io/webrtc-encoded-transform/#rtcrtpscripttransformer
+class WEB_API RTCRtpScriptTransformer final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCRtpScriptTransformer, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCRtpScriptTransformer);
+
+public:
+ // The "writeEncodedData" algorithm. Spec: the writable's write algorithm runs
+ // writeEncodedData(transformer, frame) which "hands the frame to the next stage
+ // of the pipeline" — i.e. to [[frameSource]] (the encoder/depacketizer) for
+ // continued processing. The callback lets the worker route the frame back to the parent over IPC.
+ using WriteEncodedDataAlgorithm = GC::Function<void(JS::Value frame)>;
+
+ static WebIDL::ExceptionOr<GC::Ref<RTCRtpScriptTransformer>> create(JS::Realm&, JS::Value options);
+ virtual ~RTCRtpScriptTransformer() override;
+
+ GC::Ref<Streams::ReadableStream> readable() const { return *m_readable; }
+ GC::Ref<Streams::WritableStream> writable() const { return *m_writable; }
+ JS::Value options() const { return m_options; }
+
+ JS::Realm& relevant_realm() const;
+ virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override { return m_global_object; }
+
+ // Configure the action to run when the worker writes a transformed frame to
+ // [[writable]]. This represents the [[frameSource]]'s "consume the transformed
+ // frame" entry point. Per spec [[frameSource]] is set by the host before the
+ // rtctransform event is fired; we set it via this API immediately after construction.
+ void set_write_encoded_data_algorithm(GC::Ptr<WriteEncodedDataAlgorithm>);
+
+ // Enqueue a frame from [[frameSource]] into [[readable]], returning an exception if the controller rejects it.
+ WebIDL::ExceptionOr<void> enqueue_encoded_frame(JS::Value frame);
+
+ void set_onkeyframerequest(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onkeyframerequest();
+
+private:
+ explicit RTCRtpScriptTransformer(GC::Ref<DOM::EventTarget> relevant_global_object);
+ virtual void visit_edges(Cell::Visitor&) override;
+
+ // The worker global this transformer was created for; used to recover the
+ // realm at the bindings/streams edge.
+ GC::Ref<DOM::EventTarget> m_global_object;
+ // [[frameSource]] — modeled as an indirection to the spec algorithm that
+ // "hands the frame to the next pipeline stage". undefined per spec until the
+ // host wires it.
+ GC::Ptr<WriteEncodedDataAlgorithm> m_write_encoded_data;
+ // [[options]]
+ JS::Value m_options { JS::js_undefined() };
+ // The TransformStream whose readable side is [[readable]].
+ GC::Ptr<Streams::TransformStream> m_readable_source;
+ // [[readable]]
+ GC::Ptr<Streams::ReadableStream> m_readable;
+ // [[writable]]
+ GC::Ptr<Streams::WritableStream> m_writable;
+ // [[lastReceivedFrameCounter]]
+ u64 m_last_received_frame_counter { 0 };
+ // [[lastEnqueuedFrameCounter]]
+ u64 m_last_enqueued_frame_counter { 0 };
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.idl b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.idl
new file mode 100644
index 00000000000..b95ed597e18
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.idl
@@ -0,0 +1,11 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtcrtpscripttransformer
+
+[Exposed=DedicatedWorker]
+interface RTCRtpScriptTransformer : EventTarget {
+ readonly attribute ReadableStream readable;
+ [FIXME] Promise<undefined> generateKeyFrame(optional DOMString rid);
+ [FIXME] Promise<undefined> sendKeyFrameRequest();
+ readonly attribute WritableStream writable;
+ attribute EventHandler onkeyframerequest;
+ readonly attribute any options;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpSender.cpp b/Libraries/LibWeb/WebRTC/RTCRtpSender.cpp
new file mode 100644
index 00000000000..59ecdb36baf
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpSender.cpp
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Debug.h>
+#include <LibGC/Heap.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+#include <LibWeb/WebIDL/Promise.h>
+#include <LibWeb/WebRTC/RTCPeerConnection.h>
+#include <LibWeb/WebRTC/RTCRtpReceiver.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransform.h>
+#include <LibWeb/WebRTC/RTCRtpSender.h>
+#include <LibWeb/WebRTC/RTCRtpTransceiver.h>
+#include <LibWeb/WebRTC/RTCSFrameSenderTransform.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCRtpSender);
+
+GC::Ref<RTCRtpSender> RTCRtpSender::create(GC::Ref<RTCPeerConnection> connection, u64 sender_id, u32 ssrc)
+{
+ return GC::Heap::the().allocate<RTCRtpSender>(connection, sender_id, ssrc);
+}
+
+RTCRtpSender::RTCRtpSender(GC::Ref<RTCPeerConnection> connection, u64 sender_id, u32 ssrc)
+ : m_connection(connection)
+ , m_sender_id(sender_id)
+ , m_ssrc(ssrc)
+{
+ // Seed [[SendEncodings]] with a single encoding mirroring the wire-side SSRC. This is what consumers like
+ // Discord's EncryptionWorker read out of `getParameters().encodings[0].ssrc` to register their userId mapping.
+ RTCRtpEncodingParameters encoding;
+ encoding.ssrc = m_ssrc;
+ m_send_encodings.append(move(encoding));
+}
+
+void RTCRtpSender::set_ssrc(u32 ssrc)
+{
+ m_ssrc = ssrc;
+ m_ssrc_confirmed = true;
+ if (m_send_encodings.is_empty())
+ m_send_encodings.append({});
+ m_send_encodings[0].ssrc = m_ssrc;
+ // Rebuild getParameters() with the updated SSRC.
+ m_last_returned_parameters = {};
+}
+
+RTCRtpSender::~RTCRtpSender() = default;
+
+JS::Realm& RTCRtpSender::relevant_realm() const
+{
+ return m_connection->relevant_realm();
+}
+
+void RTCRtpSender::visit_edges(JS::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_connection);
+ visitor.visit(m_track);
+ visitor.visit(m_transform);
+}
+
+void RTCRtpSender::set_track(GC::Ptr<MediaCapture::MediaStreamTrack> track)
+{
+ m_track = track;
+ m_connection->on_sender_track_changed(*this);
+}
+
+RTCRtpSenderTransform RTCRtpSender::transform() const
+{
+ if (!m_transform)
+ return Empty {};
+ if (auto* script_transform = as_if<RTCRtpScriptTransform>(*m_transform))
+ return GC::Ref { *script_transform };
+ if (auto* sframe_transform = as_if<RTCSFrameSenderTransform>(*m_transform))
+ return GC::Ref { *sframe_transform };
+ return Empty {};
+}
+
+GC::Ptr<RTCRtpScriptTransform> RTCRtpSender::script_transform()
+{
+ if (!m_transform)
+ return nullptr;
+ return as_if<RTCRtpScriptTransform>(*m_transform);
+}
+
+// https://w3c.github.io/webrtc-encoded-transform/#dom-rtcrtpsender-transform
+WebIDL::ExceptionOr<void> RTCRtpSender::set_transform(RTCRtpSenderTransform value)
+{
+ // NB: A script transform belongs to the first sender or receiver it's set on, even once it's replaced there.
+ auto* new_script_transform = value.get_pointer<GC::Ref<RTCRtpScriptTransform>>();
+ if (new_script_transform && (*new_script_transform)->has_owner())
+ return WebIDL::InvalidStateError::create("The transform is already in use"_utf16);
+ if (new_script_transform)
+ (*new_script_transform)->set_has_owner();
+
+ if (auto* old_script_transform = m_transform ? as_if<RTCRtpScriptTransform>(*m_transform) : nullptr)
+ old_script_transform->detach();
+ m_transform = value.visit(
+ [](Empty) -> GC::Ptr<Bindings::Wrappable> { return nullptr; },
+ [](GC::Ref<RTCSFrameSenderTransform> const& t) -> GC::Ptr<Bindings::Wrappable> { return t.ptr(); },
+ [](GC::Ref<RTCRtpScriptTransform> const& t) -> GC::Ptr<Bindings::Wrappable> { return t.ptr(); });
+ dbgln_if(WEBRTC_DEBUG, "RTCRtpSender::set_transform: transform set={}", m_transform != nullptr);
+ m_connection->on_sender_transform_changed(*this);
+ return {};
+}
+
+GC::Ref<WebIDL::Promise> RTCRtpSender::replace_track(GC::Ptr<MediaCapture::MediaStreamTrack> with_track)
+{
+ auto& realm = relevant_realm();
+ auto promise = WebIDL::create_promise(realm);
+ if (m_connection->is_closed()) {
+ WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16));
+ return promise;
+ }
+ for (auto const& transceiver : m_connection->get_transceivers()) {
+ if (transceiver->sender().ptr() != this)
+ continue;
+ if (transceiver->is_stopping() || transceiver->is_stopped()) {
+ WebIDL::reject_promise(realm, promise, WebIDL::InvalidStateError::create("Transceiver is stopped"_utf16));
+ return promise;
+ }
+ if (with_track && with_track->track_kind() != transceiver->receiver()->track()->track_kind()) {
+ WebIDL::reject_promise_with_exception(realm, promise, WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Replacement track has a different kind"_utf16 });
+ return promise;
+ }
+ }
+ set_track(with_track);
+ WebIDL::resolve_promise(realm, promise, JS::js_undefined());
+ return promise;
+}
+
+// https://w3c.github.io/webrtc-pc/#dom-rtcrtpsender-setparameters
+GC::Ref<WebIDL::Promise> RTCRtpSender::set_parameters(RTCRtpSendParameters const& parameters, RTCSetParameterOptions const&)
+{
+ // 1. Let parameters be the method's first argument.
+ // 2. Let sender be the RTCRtpSender object on which setParameters is invoked.
+
+ // FIXME: 3. Let transceiver be the RTCRtpTransceiver object associated with sender (i.e. sender is transceiver.[[Sender]]).
+ // FIXME: 4. If transceiver.[[Stopping]] is true, return a promise rejected with a newly created InvalidStateError.
+
+ // FIXME: 5. If sender.[[LastReturnedParameters]] is null, return a promise rejected with a newly created InvalidStateError.
+ // Real browsers strictly require a getParameters() round-trip before each setParameters(); we don't
+ // enforce that yet because some apps (e.g. Discord's setTransceiverEncodingParameters) call
+ // setParameters early in setup before any getParameters.
+
+ // FIXME: 6. Validate parameters by running the setParameters validation steps.
+
+ // 7. Let p be a new promise.
+ auto p = WebIDL::create_promise(relevant_realm());
+
+ // 8. In parallel, configure the media stack to use parameters to transmit sender.[[SenderTrack]].
+ // FIXME: actually wire `parameters` into the media stack (bitrate caps, encoding rid, etc).
+ HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), [this, p, parameters] {
+ // Promise resolution calls into JS and needs a running execution context on the VM stack; tasks don't
+ // come with one by default.
+ auto& realm = relevant_realm();
+ HTML::TemporaryExecutionContext context(realm);
+ // 8.1. If the media stack is successfully configured with parameters, queue a task to run the following steps:
+ // 8.1.1. Set sender.[[LastReturnedParameters]] to null.
+ m_last_returned_parameters = {};
+ // 8.1.2. Set sender.[[SendEncodings]] to parameters.encodings.
+ m_send_encodings = parameters.encodings;
+ // 8.1.3. Resolve p with undefined.
+ WebIDL::resolve_promise(realm, p, JS::js_undefined());
+ // 8.2. If any error occurred while configuring the media stack, queue a task to run the following steps:
+ // 8.2.1. If an error occurred due to hardware resources not being available, reject p with a newly
+ // created RTCError whose errorDetail is set to "hardware-encoder-not-available" and abort
+ // these steps.
+ // 8.2.2. If an error occurred due to a hardware encoder not supporting parameters, reject p with a
+ // newly created RTCError whose errorDetail is set to "hardware-encoder-error" and abort these
+ // steps.
+ // 8.2.3. For all other errors, reject p with a newly created OperationError.
+ }));
+
+ // 9. Return p.
+ return p;
+}
+
+// https://w3c.github.io/webrtc-pc/#dom-rtcrtpsender-getparameters
+RTCRtpSendParameters RTCRtpSender::get_parameters()
+{
+ // Applications can read encodings immediately after addTrack, before the
+ // asynchronous acknowledgement. DAVE must register the actual wire SSRC.
+ if (!m_ssrc_confirmed && !m_connection->is_closed()) {
+ if (auto* client = WebRTCAgent::the().existing_client()) {
+ auto result = client->try_get_sender_ssrc(m_sender_id);
+ if (!result.is_error() && result.value() != 0)
+ set_ssrc(result.value());
+ }
+ }
+ // 1. Let sender be the RTCRtpSender object on which the getter was invoked.
+
+ // 2. If sender.[[LastReturnedParameters]] is not null, return sender.[[LastReturnedParameters]], and abort these steps.
+ if (m_last_returned_parameters.has_value())
+ return m_last_returned_parameters.value();
+
+ // 3. Let result be a new RTCRtpSendParameters dictionary constructed as follows:
+ RTCRtpSendParameters result;
+ // transactionId is set to a new unique identifier.
+ // FIXME: assign a fresh transaction id.
+ // encodings is set to the value of the [[SendEncodings]] internal slot.
+ result.encodings = m_send_encodings;
+ // The headerExtensions sequence is populated based on the header extensions that have been negotiated for sending.
+ // FIXME: populate from negotiated header extensions.
+ // codecs is set to the value of the [[SendCodecs]] internal slot.
+ // FIXME: populate from [[SendCodecs]].
+ // rtcp.cname is set to the CNAME of the associated RTCPeerConnection. rtcp.reducedSize is set to true if
+ // reduced-size RTCP has been negotiated for sending, and false otherwise.
+ // FIXME: populate rtcp.cname and rtcp.reducedSize from the connection.
+
+ // 4. Set sender.[[LastReturnedParameters]] to result.
+ m_last_returned_parameters = result;
+
+ // 5. Queue a task that sets sender.[[LastReturnedParameters]] to null.
+ HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), [this] {
+ m_last_returned_parameters = {};
+ }));
+
+ // 6. Return result.
+ return result;
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpSender.h b/Libraries/LibWeb/WebRTC/RTCRtpSender.h
new file mode 100644
index 00000000000..07228ebb1ff
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpSender.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Utf16String.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebRTC/RTCRtpParameters.h>
+
+namespace Web::WebRTC {
+
+using RTCRtpSenderTransform = Variant<GC::Ref<RTCSFrameSenderTransform>, GC::Ref<RTCRtpScriptTransform>, Empty>;
+
+class RTCRtpSender final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCRtpSender, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCRtpSender);
+
+public:
+ static GC::Ref<RTCRtpSender> create(GC::Ref<RTCPeerConnection>, u64 sender_id, u32 ssrc);
+ virtual ~RTCRtpSender() override;
+
+ GC::Ptr<MediaCapture::MediaStreamTrack> track() const { return m_track; }
+ void set_track(GC::Ptr<MediaCapture::MediaStreamTrack> track);
+
+ Vector<Utf16String> const& associated_media_stream_ids() const { return m_associated_media_stream_ids; }
+ void set_associated_media_stream_ids(Vector<Utf16String> ids) { m_associated_media_stream_ids = move(ids); }
+
+ RTCRtpSenderTransform transform() const;
+ WebIDL::ExceptionOr<void> set_transform(RTCRtpSenderTransform);
+ GC::Ptr<RTCRtpScriptTransform> script_transform();
+
+ GC::Ref<WebIDL::Promise> replace_track(GC::Ptr<MediaCapture::MediaStreamTrack> with_track);
+ RTCRtpSendParameters get_parameters();
+ GC::Ref<WebIDL::Promise> set_parameters(RTCRtpSendParameters const&, RTCSetParameterOptions const&);
+
+ u64 sender_id() const { return m_sender_id; }
+ u32 ssrc() const { return m_ssrc; }
+ void set_ssrc(u32 ssrc);
+ GC::Ref<RTCPeerConnection> connection() const { return m_connection; }
+
+private:
+ explicit RTCRtpSender(GC::Ref<RTCPeerConnection>, u64 sender_id, u32 ssrc);
+ virtual void visit_edges(JS::Cell::Visitor&) override;
+
+ JS::Realm& relevant_realm() const;
+
+ GC::Ref<RTCPeerConnection> m_connection;
+ u64 m_sender_id { 0 };
+ u32 m_ssrc { 0 };
+ bool m_ssrc_confirmed { false };
+
+ // [[SenderTrack]]
+ GC::Ptr<MediaCapture::MediaStreamTrack> m_track;
+ // [[AssociatedMediaStreamIds]]
+ Vector<Utf16String> m_associated_media_stream_ids;
+ // [[SendEncodings]]
+ Vector<RTCRtpEncodingParameters> m_send_encodings;
+ // [[LastReturnedParameters]]
+ Optional<RTCRtpSendParameters> m_last_returned_parameters;
+ GC::Ptr<Bindings::Wrappable> m_transform;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpSender.idl b/Libraries/LibWeb/WebRTC/RTCRtpSender.idl
new file mode 100644
index 00000000000..afff1e4860f
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpSender.idl
@@ -0,0 +1,78 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcrtpsender-interface
+
+[Exposed=Window]
+interface RTCRtpSender {
+ readonly attribute MediaStreamTrack? track;
+ [FIXME] readonly attribute RTCDtlsTransport? transport;
+ [FIXME] static RTCRtpCapabilities? getCapabilities(DOMString kind);
+ Promise<undefined> setParameters(RTCRtpSendParameters parameters,
+ optional RTCSetParameterOptions setParameterOptions = {});
+ RTCRtpSendParameters getParameters();
+ Promise<undefined> replaceTrack(MediaStreamTrack? withTrack);
+ [FIXME] undefined setStreams(MediaStream... streams);
+ [FIXME] Promise<RTCStatsReport> getStats();
+};
+
+partial interface RTCRtpSender {
+ [FIXME] readonly attribute RTCDTMFSender? dtmf;
+};
+
+dictionary RTCRtpParameters {
+ required sequence<RTCRtpHeaderExtensionParameters> headerExtensions;
+ required RTCRtcpParameters rtcp;
+ required sequence<RTCRtpCodecParameters> codecs;
+};
+
+dictionary RTCRtpSendParameters : RTCRtpParameters {
+ required DOMString transactionId;
+ required sequence<RTCRtpEncodingParameters> encodings;
+};
+
+dictionary RTCRtpReceiveParameters : RTCRtpParameters { };
+
+dictionary RTCRtpCodingParameters {
+ DOMString rid;
+};
+
+dictionary RTCRtpEncodingParameters : RTCRtpCodingParameters {
+ boolean active = true;
+ RTCRtpCodec codec;
+ unsigned long maxBitrate;
+ double maxFramerate;
+ double scaleResolutionDownBy;
+ unsigned long ssrc;
+};
+
+dictionary RTCRtcpParameters {
+ DOMString cname;
+ boolean reducedSize;
+};
+
+dictionary RTCRtpHeaderExtensionParameters {
+ required DOMString uri;
+ required unsigned short id;
+ boolean encrypted = false;
+};
+
+dictionary RTCRtpCodec {
+ required DOMString mimeType;
+ required unsigned long clockRate;
+ unsigned short channels;
+ DOMString sdpFmtpLine;
+};
+
+dictionary RTCRtpCodecParameters : RTCRtpCodec {
+ required octet payloadType;
+};
+
+dictionary RTCRtpCapabilities {
+ required sequence<RTCRtpCodec> codecs;
+ required sequence<RTCRtpHeaderExtensionCapability> headerExtensions;
+};
+
+dictionary RTCRtpHeaderExtensionCapability {
+ required DOMString uri;
+};
+
+dictionary RTCSetParameterOptions { };
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.cpp b/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.cpp
new file mode 100644
index 00000000000..1d18a6de8a9
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.cpp
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebRTC/RTCPeerConnection.h>
+#include <LibWeb/WebRTC/RTCRtpReceiver.h>
+#include <LibWeb/WebRTC/RTCRtpSender.h>
+#include <LibWeb/WebRTC/RTCRtpTransceiver.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCRtpTransceiver);
+
+GC::Ref<RTCRtpTransceiver> RTCRtpTransceiver::create(RTCPeerConnection& connection, GC::Ref<RTCRtpSender> sender, GC::Ref<RTCRtpReceiver> receiver, Bindings::RTCRtpTransceiverDirection direction, Bindings::MediaStreamTrackKind kind)
+{
+ return GC::Heap::the().allocate<RTCRtpTransceiver>(connection, sender, receiver, direction, kind);
+}
+
+RTCRtpTransceiver::RTCRtpTransceiver(RTCPeerConnection& connection, GC::Ref<RTCRtpSender> sender, GC::Ref<RTCRtpReceiver> receiver, Bindings::RTCRtpTransceiverDirection direction, Bindings::MediaStreamTrackKind kind)
+ : m_connection(connection)
+ , m_sender(sender)
+ , m_receiver(receiver)
+ , m_direction(direction)
+ , m_kind(kind)
+{
+}
+
+RTCRtpTransceiver::~RTCRtpTransceiver() = default;
+
+void RTCRtpTransceiver::visit_edges(JS::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_connection);
+ visitor.visit(m_sender);
+ visitor.visit(m_receiver);
+}
+
+void RTCRtpTransceiver::set_direction(Bindings::RTCRtpTransceiverDirection direction)
+{
+ if (m_stopping || m_connection->is_closed() || direction == m_direction)
+ return;
+ m_direction = direction;
+ if (auto* client = WebRTCAgent::the().existing_client())
+ client->async_set_transceiver_direction(m_connection->pc_id(), m_sender->sender_id(), idl_enum_to_string(direction).to_utf8());
+ m_connection->update_negotiation_needed_flag();
+}
+
+// https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-stop
+WebIDL::ExceptionOr<void> RTCRtpTransceiver::stop_method()
+{
+ // 1. Let transceiver be the RTCRtpTransceiver object on which the method is invoked.
+ // 2. Let connection be the RTCPeerConnection object associated with transceiver.
+ auto& connection = *m_connection;
+ // 3. If connection.[[IsClosed]] is true, throw an InvalidStateError.
+ if (connection.is_closed())
+ return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);
+ // 4. If transceiver.[[Stopping]] is true, abort these steps.
+ if (m_stopping)
+ return {};
+ // 5. Stop sending and receiving with transceiver.
+ stop_sending_and_receiving();
+ // 6. Update the negotiation-needed flag for connection.
+ connection.update_negotiation_needed_flag();
+ return {};
+}
+
+// https://www.w3.org/TR/webrtc/#stop-sending-and-receiving
+void RTCRtpTransceiver::stop_sending_and_receiving(bool disappear)
+{
+ // 1. Let sender be transceiver.[[Sender]].
+ // 2. Let receiver be transceiver.[[Receiver]].
+ m_connection->stop_sender(*m_sender);
+ if (auto* client = WebRTCAgent::the().existing_client())
+ client->async_stop_transceiver(m_connection->pc_id(), m_sender->sender_id());
+ // FIXME: 4. In parallel, stop receiving media with receiver.
+ // 5. If disappear is false, execute the steps for receiver.[[ReceiverTrack]] to be ended. This fires an event.
+ if (!disappear) {
+ m_receiver->track()->end();
+ }
+ // 6. Set transceiver.[[Direction]] to "inactive".
+ m_direction = Bindings::RTCRtpTransceiverDirection::Inactive;
+ // 7. Set transceiver.[[Stopping]] to true.
+ m_stopping = true;
+}
+
+// https://www.w3.org/TR/webrtc/#stop-the-rtcrtptransceiver
+void RTCRtpTransceiver::stop(bool disappear)
+{
+ // 1. If transceiver.[[Stopping]] is false, stop sending and receiving with transceiver and disappear.
+ if (!m_stopping)
+ stop_sending_and_receiving(disappear);
+ // 2. Set transceiver.[[Stopped]] to true.
+ m_stopped = true;
+ // 3. Set transceiver.[[Receptive]] to false.
+ m_receptive = false;
+ // 4. Set transceiver.[[CurrentDirection]] to null.
+ m_current_direction = {};
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.h b/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.h
new file mode 100644
index 00000000000..36e170a0753
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/MediaStreamTrack.h>
+#include <LibWeb/Bindings/RTCRtpTransceiver.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+class RTCPeerConnection;
+class RTCRtpReceiver;
+class RTCRtpSender;
+
+class RTCRtpTransceiver final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCRtpTransceiver, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCRtpTransceiver);
+
+public:
+ static GC::Ref<RTCRtpTransceiver> create(RTCPeerConnection&, GC::Ref<RTCRtpSender>, GC::Ref<RTCRtpReceiver>, Bindings::RTCRtpTransceiverDirection, Bindings::MediaStreamTrackKind);
+ virtual ~RTCRtpTransceiver() override;
+
+ GC::Ref<RTCRtpSender> sender() const { return m_sender; }
+ GC::Ref<RTCRtpReceiver> receiver() const { return m_receiver; }
+ Bindings::RTCRtpTransceiverDirection direction() const { return m_direction; }
+ void set_direction(Bindings::RTCRtpTransceiverDirection);
+ Bindings::MediaStreamTrackKind kind() const { return m_kind; }
+ Optional<Bindings::RTCRtpTransceiverDirection> current_direction() const { return m_current_direction; }
+ bool is_stopped() const { return m_stopped; }
+ bool is_stopping() const { return m_stopping; }
+
+ u64 transceiver_id() const { return m_transceiver_id; }
+ void set_transceiver_id(u64 id) { m_transceiver_id = id; }
+
+ Optional<Bindings::RTCRtpTransceiverDirection> fired_direction() const { return m_fired_direction; }
+ void set_fired_direction(Optional<Bindings::RTCRtpTransceiverDirection> d) { m_fired_direction = d; }
+
+ bool is_receptive() const { return m_receptive; }
+ void set_receptive(bool v) { m_receptive = v; }
+
+ WebIDL::ExceptionOr<void> stop_method();
+
+ void stop_sending_and_receiving(bool disappear = false);
+ void stop(bool disappear = false);
+
+private:
+ explicit RTCRtpTransceiver(RTCPeerConnection&, GC::Ref<RTCRtpSender>, GC::Ref<RTCRtpReceiver>, Bindings::RTCRtpTransceiverDirection, Bindings::MediaStreamTrackKind);
+ virtual void visit_edges(JS::Cell::Visitor&) override;
+
+ // [[Connection]]
+ GC::Ref<RTCPeerConnection> m_connection;
+ // [[Sender]]
+ GC::Ref<RTCRtpSender> m_sender;
+ // [[Receiver]]
+ GC::Ref<RTCRtpReceiver> m_receiver;
+ // [[Direction]]
+ Bindings::RTCRtpTransceiverDirection m_direction;
+ // [[CurrentDirection]]
+ Optional<Bindings::RTCRtpTransceiverDirection> m_current_direction;
+ // [[Stopping]]
+ bool m_stopping { false };
+ // [[Stopped]]
+ bool m_stopped { false };
+ // [[Receptive]]
+ bool m_receptive { false };
+
+ Bindings::MediaStreamTrackKind m_kind;
+ u64 m_transceiver_id { 0 };
+ // [[FiredDirection]]
+ Optional<Bindings::RTCRtpTransceiverDirection> m_fired_direction;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.idl b/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.idl
new file mode 100644
index 00000000000..fa24fa1ae7e
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCRtpTransceiver.idl
@@ -0,0 +1,29 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcrtptransceiver-interface
+
+[Exposed=Window]
+interface RTCRtpTransceiver {
+ [FIXME] readonly attribute DOMString? mid;
+ [SameObject] readonly attribute RTCRtpSender sender;
+ [SameObject] readonly attribute RTCRtpReceiver receiver;
+ attribute RTCRtpTransceiverDirection direction;
+ readonly attribute RTCRtpTransceiverDirection? currentDirection;
+ [ImplementedAs=stop_method] undefined stop();
+ [FIXME] undefined setCodecPreferences(sequence<RTCRtpCodec> codecs);
+};
+
+dictionary RTCRtpTransceiverInit {
+ RTCRtpTransceiverDirection direction = "sendrecv";
+ sequence<MediaStream> streams = [];
+ // FIXME: spec is `sequence<RTCRtpEncodingParameters>`. Held as `sequence<object>`
+ // until full encoding-parameters wiring lands.
+ sequence<object> sendEncodings = [];
+};
+
+enum RTCRtpTransceiverDirection {
+ "sendrecv",
+ "sendonly",
+ "recvonly",
+ "inactive",
+ "stopped"
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.cpp b/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.cpp
new file mode 100644
index 00000000000..69d9f007292
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/RTCSFrameReceiverTransform.h>
+#include <LibWeb/WebRTC/RTCSFrameReceiverTransform.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCSFrameReceiverTransform);
+
+GC::Ref<RTCSFrameReceiverTransform> RTCSFrameReceiverTransform::create() { return GC::Heap::the().allocate<RTCSFrameReceiverTransform>(); }
+
+// FIXME: RTCSFrameReceiverTransform is a stub — wire up the options once SFrame transforms are implemented.
+WebIDL::ExceptionOr<GC::Ref<RTCSFrameReceiverTransform>> RTCSFrameReceiverTransform::construct_impl(Bindings::SFrameTransformOptions const&)
+{
+ return create();
+}
+RTCSFrameReceiverTransform::RTCSFrameReceiverTransform() = default;
+RTCSFrameReceiverTransform::~RTCSFrameReceiverTransform() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.h b/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.h
new file mode 100644
index 00000000000..ab174a3837f
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/Forward.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+class RTCSFrameReceiverTransform final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCSFrameReceiverTransform, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCSFrameReceiverTransform);
+
+public:
+ static GC::Ref<RTCSFrameReceiverTransform> create();
+ static WebIDL::ExceptionOr<GC::Ref<RTCSFrameReceiverTransform>> construct_impl(Bindings::SFrameTransformOptions const&);
+ virtual ~RTCSFrameReceiverTransform() override;
+
+private:
+ explicit RTCSFrameReceiverTransform();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.idl b/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.idl
new file mode 100644
index 00000000000..93d952797f8
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSFrameReceiverTransform.idl
@@ -0,0 +1,7 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtcsframereceivertransform
+
+[Exposed=Window]
+interface RTCSFrameReceiverTransform : EventTarget {
+ [FIXME] constructor(SFrameTransformOptions options);
+};
+RTCSFrameReceiverTransform includes SFrameDecrypterManager;
diff --git a/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.cpp b/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.cpp
new file mode 100644
index 00000000000..f7158b27a5a
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/RTCSFrameSenderTransform.h>
+#include <LibWeb/WebRTC/RTCSFrameSenderTransform.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCSFrameSenderTransform);
+
+GC::Ref<RTCSFrameSenderTransform> RTCSFrameSenderTransform::create() { return GC::Heap::the().allocate<RTCSFrameSenderTransform>(); }
+
+// FIXME: RTCSFrameSenderTransform is a stub — wire up the options once SFrame transforms are implemented.
+WebIDL::ExceptionOr<GC::Ref<RTCSFrameSenderTransform>> RTCSFrameSenderTransform::construct_impl(Bindings::RTCSFrameSenderTransformOptions const&)
+{
+ return create();
+}
+RTCSFrameSenderTransform::RTCSFrameSenderTransform() = default;
+RTCSFrameSenderTransform::~RTCSFrameSenderTransform() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.h b/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.h
new file mode 100644
index 00000000000..df8b2d6cab4
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/Forward.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+class RTCSFrameSenderTransform final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCSFrameSenderTransform, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCSFrameSenderTransform);
+
+public:
+ static GC::Ref<RTCSFrameSenderTransform> create();
+ static WebIDL::ExceptionOr<GC::Ref<RTCSFrameSenderTransform>> construct_impl(Bindings::RTCSFrameSenderTransformOptions const&);
+ virtual ~RTCSFrameSenderTransform() override;
+
+private:
+ explicit RTCSFrameSenderTransform();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.idl b/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.idl
new file mode 100644
index 00000000000..8b7672bdc5c
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSFrameSenderTransform.idl
@@ -0,0 +1,45 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtcsframesendertransform
+
+enum SFrameCipherSuite {
+ "AES_128_CTR_HMAC_SHA256_80",
+ "AES_128_CTR_HMAC_SHA256_64",
+ "AES_128_CTR_HMAC_SHA256_32",
+ "AES_128_GCM_SHA256_128",
+ "AES_256_GCM_SHA512_128",
+ "AES_256_CTR_HMAC_SHA512_80",
+ "AES_256_CTR_HMAC_SHA512_64",
+ "AES_256_CTR_HMAC_SHA512_32"
+};
+
+dictionary SFrameTransformOptions {
+ required SFrameCipherSuite cipherSuite;
+};
+
+enum SFrameType {
+ "per-frame",
+ "per-packet"
+};
+
+dictionary RTCSFrameSenderTransformOptions : SFrameTransformOptions {
+ SFrameType type = "per-frame";
+};
+
+typedef [EnforceRange] unsigned long long SmallCryptoKeyID;
+// FIXME: spec is `(SmallCryptoKeyID or bigint)` — bigint isn't supported in our IDL yet.
+typedef SmallCryptoKeyID CryptoKeyID;
+
+interface mixin SFrameEncrypterManager {
+ [FIXME] Promise<undefined> setEncryptionKey(CryptoKey key, CryptoKeyID keyId);
+};
+
+interface mixin SFrameDecrypterManager {
+ [FIXME] Promise<undefined> addDecryptionKey(CryptoKey key, CryptoKeyID keyId);
+ [FIXME] Promise<undefined> removeDecryptionKey(CryptoKeyID keyId);
+ [FIXME] attribute EventHandler onerror;
+};
+
+[Exposed=Window]
+interface RTCSFrameSenderTransform {
+ [FIXME] constructor(RTCSFrameSenderTransformOptions options);
+};
+RTCSFrameSenderTransform includes SFrameEncrypterManager;
diff --git a/Libraries/LibWeb/WebRTC/RTCSctpTransport.cpp b/Libraries/LibWeb/WebRTC/RTCSctpTransport.cpp
new file mode 100644
index 00000000000..edf29fe1944
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSctpTransport.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/WebRTC/RTCSctpTransport.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCSctpTransport);
+
+GC::Ref<RTCSctpTransport> RTCSctpTransport::create() { return GC::Heap::the().allocate<RTCSctpTransport>(); }
+RTCSctpTransport::RTCSctpTransport() = default;
+RTCSctpTransport::~RTCSctpTransport() = default;
+void RTCSctpTransport::set_onstatechange(WebIDL::CallbackType* cb) { set_event_handler_attribute(HTML::EventNames::statechange, cb); }
+WebIDL::CallbackType* RTCSctpTransport::onstatechange() { return event_handler_attribute(HTML::EventNames::statechange); }
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSctpTransport.h b/Libraries/LibWeb/WebRTC/RTCSctpTransport.h
new file mode 100644
index 00000000000..73bc66c2732
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSctpTransport.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/DOM/EventTarget.h>
+
+namespace Web::WebRTC {
+
+class RTCSctpTransport final : public DOM::EventTarget {
+ WEB_WRAPPABLE(RTCSctpTransport, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(RTCSctpTransport);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCSctpTransport> create();
+ virtual ~RTCSctpTransport() override;
+
+ void set_onstatechange(WebIDL::CallbackType*);
+ WebIDL::CallbackType* onstatechange();
+
+private:
+ RTCSctpTransport();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSctpTransport.idl b/Libraries/LibWeb/WebRTC/RTCSctpTransport.idl
new file mode 100644
index 00000000000..652bba483c5
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSctpTransport.idl
@@ -0,0 +1,13 @@
+
+// https://w3c.github.io/webrtc-pc/#rtcsctptransport-interface
+
+[Exposed=Window]
+interface RTCSctpTransport : EventTarget {
+ [FIXME] readonly attribute RTCDtlsTransport transport;
+ [FIXME] readonly attribute RTCSctpTransportState state;
+ [FIXME] readonly attribute unrestricted double maxMessageSize;
+ [FIXME] readonly attribute unsigned short? maxChannels;
+ attribute EventHandler onstatechange;
+};
+
+enum RTCSctpTransportState { "connecting", "connected", "closed" };
diff --git a/Libraries/LibWeb/WebRTC/RTCSessionDescription.cpp b/Libraries/LibWeb/WebRTC/RTCSessionDescription.cpp
new file mode 100644
index 00000000000..aad9bdaf90b
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSessionDescription.cpp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCSessionDescription.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCSessionDescription);
+
+GC::Ref<RTCSessionDescription> RTCSessionDescription::create(RTCSessionDescriptionInit const& init)
+{
+ return GC::Heap::the().allocate<RTCSessionDescription>(init.type, init.sdp);
+}
+
+WebIDL::ExceptionOr<GC::Ref<RTCSessionDescription>> RTCSessionDescription::construct_impl(RTCSessionDescriptionInit const& init)
+{
+ return create(init);
+}
+
+RTCSessionDescription::RTCSessionDescription(Bindings::RTCSdpType type, Utf16String sdp)
+ : m_type(type)
+ , m_sdp(move(sdp))
+{
+}
+
+RTCSessionDescription::~RTCSessionDescription() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSessionDescription.h b/Libraries/LibWeb/WebRTC/RTCSessionDescription.h
new file mode 100644
index 00000000000..a126123ca59
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSessionDescription.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/RTCSessionDescription.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+using Bindings::RTCLocalSessionDescriptionInit;
+using Bindings::RTCSessionDescriptionInit;
+
+class RTCSessionDescription final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(RTCSessionDescription, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(RTCSessionDescription);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCSessionDescription> create(RTCSessionDescriptionInit const&);
+ static WebIDL::ExceptionOr<GC::Ref<RTCSessionDescription>> construct_impl(RTCSessionDescriptionInit const&);
+
+ virtual ~RTCSessionDescription() override;
+
+ Bindings::RTCSdpType type() const { return m_type; }
+ Utf16String const& sdp() const { return m_sdp; }
+ RTCSessionDescriptionInit to_json() const { return { .sdp = m_sdp, .type = m_type }; }
+
+private:
+ RTCSessionDescription(Bindings::RTCSdpType, Utf16String);
+
+ Bindings::RTCSdpType m_type {};
+ Utf16String m_sdp;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCSessionDescription.idl b/Libraries/LibWeb/WebRTC/RTCSessionDescription.idl
new file mode 100644
index 00000000000..f3909d1a4db
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCSessionDescription.idl
@@ -0,0 +1,26 @@
+// https://w3c.github.io/webrtc-pc/#rtcsessiondescription-class
+
+enum RTCSdpType {
+ "offer",
+ "pranswer",
+ "answer",
+ "rollback"
+};
+
+[Exposed=Window]
+interface RTCSessionDescription {
+ constructor(RTCSessionDescriptionInit descriptionInitDict);
+ readonly attribute RTCSdpType type;
+ readonly attribute DOMString sdp;
+ [FIXME] RTCSessionDescriptionInit toJSON();
+};
+
+dictionary RTCSessionDescriptionInit {
+ required RTCSdpType type;
+ DOMString sdp = "";
+};
+
+dictionary RTCLocalSessionDescriptionInit {
+ RTCSdpType type;
+ DOMString sdp = "";
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCStatsReport.cpp b/Libraries/LibWeb/WebRTC/RTCStatsReport.cpp
new file mode 100644
index 00000000000..bf0bde84fe2
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCStatsReport.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibJS/Runtime/Map.h>
+#include <LibJS/Runtime/PrimitiveString.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/WebRTC/BindingsGlue.h>
+#include <LibWeb/WebRTC/RTCStatsReport.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCStatsReport);
+
+GC::Ref<RTCStatsReport> RTCStatsReport::create()
+{
+ return GC::Heap::the().allocate<RTCStatsReport>();
+}
+
+RTCStatsReport::RTCStatsReport() = default;
+
+RTCStatsReport::~RTCStatsReport() = default;
+
+void RTCStatsReport::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ for (auto const& entry : m_entries)
+ visitor.visit(entry.value);
+}
+
+}
+
+namespace Web::Bindings {
+
+GC::Ref<JS::Map> map_entries(JS::Realm& realm, WebRTC::RTCStatsReport& report)
+{
+ auto map_entries = JS::Map::create(realm);
+ for (auto const& entry : report.entries()) {
+ auto key = JS::PrimitiveString::create(realm.vm(), entry.key);
+ map_entries->map_set(JS::Value { key.ptr() }, JS::Value { entry.value.ptr() });
+ }
+ return map_entries;
+}
+
+Optional<JS::Value> map_get(JS::Realm&, WebRTC::RTCStatsReport& report, Utf16View key)
+{
+ auto it = report.entries().find(key);
+ if (it == report.entries().end())
+ return {};
+ return JS::Value { it->value.ptr() };
+}
+
+bool map_has(WebRTC::RTCStatsReport& report, Utf16View key)
+{
+ return report.entries().contains(key);
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCStatsReport.h b/Libraries/LibWeb/WebRTC/RTCStatsReport.h
new file mode 100644
index 00000000000..203956622ad
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCStatsReport.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/Utf16String.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::WebRTC {
+
+// https://w3c.github.io/webrtc-pc/#rtcstatsreport-object
+//
+// Read-only maplike<DOMString, object>. Native entries live here; the bindings
+// glue materializes a JS::Map on demand. The values are plain JS objects built
+// by the stats gathering code (see RTCPeerConnection::get_stats()).
+class RTCStatsReport final : public Bindings::Wrappable {
+ WEB_WRAPPABLE(RTCStatsReport, Bindings::Wrappable);
+ GC_DECLARE_ALLOCATOR(RTCStatsReport);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCStatsReport> create();
+
+ virtual ~RTCStatsReport() override;
+
+ OrderedHashMap<Utf16String, GC::Ref<JS::Object>> const& entries() const { return m_entries; }
+ void set_entry(Utf16String key, GC::Ref<JS::Object> value) { m_entries.set(move(key), value); }
+
+private:
+ RTCStatsReport();
+
+ virtual void visit_edges(Cell::Visitor&) override;
+
+ OrderedHashMap<Utf16String, GC::Ref<JS::Object>> m_entries;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCStatsReport.idl b/Libraries/LibWeb/WebRTC/RTCStatsReport.idl
new file mode 100644
index 00000000000..c6991707bb8
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCStatsReport.idl
@@ -0,0 +1,19 @@
+
+// https://w3c.github.io/webrtc-stats/#dom-rtcstatsreport
+//
+// NOTE: The source IDL referenced `RTCStatsType` without defining it. The
+// real spec defines a long enum (codec, candidate-pair, transport, etc.).
+// Treating it as DOMString until the stats taxonomy is wired up.
+
+[Exposed=Window]
+interface RTCStatsReport {
+ readonly maplike<DOMString, object>;
+};
+
+dictionary RTCStats {
+ required DOMHighResTimeStamp timestamp;
+ required RTCStatsType type;
+ required DOMString id;
+};
+
+typedef DOMString RTCStatsType;
diff --git a/Libraries/LibWeb/WebRTC/RTCTrackEvent.cpp b/Libraries/LibWeb/WebRTC/RTCTrackEvent.cpp
new file mode 100644
index 00000000000..b704322c4eb
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCTrackEvent.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/MediaCapture/MediaStream.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+#include <LibWeb/WebRTC/RTCRtpReceiver.h>
+#include <LibWeb/WebRTC/RTCRtpTransceiver.h>
+#include <LibWeb/WebRTC/RTCTrackEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCTrackEvent);
+
+GC::Ref<RTCTrackEvent> RTCTrackEvent::create(Utf16FlyString const& event_name,
+ GC::Ref<RTCRtpReceiver> receiver, GC::Ref<MediaCapture::MediaStreamTrack> track,
+ Vector<GC::Ref<MediaCapture::MediaStream>>&& streams, GC::Ref<RTCRtpTransceiver> transceiver,
+ HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCTrackEvent>(event_name, receiver, track, move(streams), transceiver, time_stamp);
+}
+
+WebIDL::ExceptionOr<GC::Ref<RTCTrackEvent>> RTCTrackEvent::construct_impl(Utf16String const& type, RTCTrackEventInit const& event_init)
+{
+ // NOTE: The init dictionary members are typed `object` (see RTCTrackEvent.idl); unwrap them to their
+ // actual interface types here and reject anything else.
+ auto* receiver = Bindings::impl_from<RTCRtpReceiver>(event_init.receiver.ptr());
+ if (!receiver)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "receiver is not an RTCRtpReceiver"_utf16 };
+
+ auto* track = Bindings::impl_from<MediaCapture::MediaStreamTrack>(event_init.track.ptr());
+ if (!track)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "track is not a MediaStreamTrack"_utf16 };
+
+ auto* transceiver = Bindings::impl_from<RTCRtpTransceiver>(event_init.transceiver.ptr());
+ if (!transceiver)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "transceiver is not an RTCRtpTransceiver"_utf16 };
+
+ GC::RootVector<GC::Ref<MediaCapture::MediaStream>> streams;
+ streams.ensure_capacity(event_init.streams.size());
+ for (auto const& stream_object : event_init.streams) {
+ auto* stream = Bindings::impl_from<MediaCapture::MediaStream>(stream_object.ptr());
+ if (!stream)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "streams contains a non-MediaStream object"_utf16 };
+ streams.unchecked_append(*stream);
+ }
+
+ auto time_stamp = HighResolutionTime::current_high_resolution_time(HTML::current_global_object());
+ auto event = create(Utf16FlyString { type }, *receiver, *track, move(streams), *transceiver, time_stamp);
+ event->set_bubbles(event_init.bubbles);
+ event->set_cancelable(event_init.cancelable);
+ event->set_composed(event_init.composed);
+ return event;
+}
+
+RTCTrackEvent::RTCTrackEvent(Utf16FlyString const& event_name,
+ GC::Ref<RTCRtpReceiver> receiver, GC::Ref<MediaCapture::MediaStreamTrack> track,
+ Vector<GC::Ref<MediaCapture::MediaStream>>&& streams, GC::Ref<RTCRtpTransceiver> transceiver,
+ HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, time_stamp)
+ , m_receiver(receiver)
+ , m_track(track)
+ , m_streams(move(streams))
+ , m_transceiver(transceiver)
+{
+}
+
+RTCTrackEvent::~RTCTrackEvent() = default;
+
+void RTCTrackEvent::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_receiver);
+ visitor.visit(m_track);
+ visitor.visit(m_transceiver);
+ for (auto& stream : m_streams)
+ visitor.visit(stream);
+}
+
+GC::Ref<RTCRtpReceiver> RTCTrackEvent::receiver() const { return m_receiver; }
+GC::Ref<RTCRtpTransceiver> RTCTrackEvent::transceiver() const { return m_transceiver; }
+GC::Ref<MediaCapture::MediaStreamTrack> RTCTrackEvent::track() const { return m_track; }
+
+GC::RootVector<GC::Ref<MediaCapture::MediaStream>> RTCTrackEvent::streams() const
+{
+ return m_streams.span();
+}
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCTrackEvent.h b/Libraries/LibWeb/WebRTC/RTCTrackEvent.h
new file mode 100644
index 00000000000..fbdfd2eeb16
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCTrackEvent.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibGC/RootVector.h>
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/RTCTrackEvent.h>
+#include <LibWeb/DOM/Event.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::WebRTC {
+
+class RTCRtpReceiver;
+class RTCRtpTransceiver;
+
+using RTCTrackEventInit = Bindings::RTCTrackEventInit;
+
+class RTCTrackEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCTrackEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCTrackEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<RTCTrackEvent> create(Utf16FlyString const& event_name,
+ GC::Ref<RTCRtpReceiver>, GC::Ref<MediaCapture::MediaStreamTrack>,
+ Vector<GC::Ref<MediaCapture::MediaStream>>&& streams,
+ GC::Ref<RTCRtpTransceiver>,
+ HighResolutionTime::DOMHighResTimeStamp);
+ static WebIDL::ExceptionOr<GC::Ref<RTCTrackEvent>> construct_impl(Utf16String const& type, RTCTrackEventInit const&);
+ virtual ~RTCTrackEvent() override;
+
+ GC::Ref<RTCRtpReceiver> receiver() const;
+ GC::Ref<RTCRtpTransceiver> transceiver() const;
+ GC::Ref<MediaCapture::MediaStreamTrack> track() const;
+ GC::RootVector<GC::Ref<MediaCapture::MediaStream>> streams() const;
+
+private:
+ RTCTrackEvent(Utf16FlyString const& event_name,
+ GC::Ref<RTCRtpReceiver>, GC::Ref<MediaCapture::MediaStreamTrack>,
+ Vector<GC::Ref<MediaCapture::MediaStream>>&& streams,
+ GC::Ref<RTCRtpTransceiver>,
+ HighResolutionTime::DOMHighResTimeStamp);
+
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ GC::Ref<RTCRtpReceiver> m_receiver;
+ GC::Ref<MediaCapture::MediaStreamTrack> m_track;
+ Vector<GC::Ref<MediaCapture::MediaStream>> m_streams;
+ GC::Ref<RTCRtpTransceiver> m_transceiver;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCTrackEvent.idl b/Libraries/LibWeb/WebRTC/RTCTrackEvent.idl
new file mode 100644
index 00000000000..86a3e49ca73
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCTrackEvent.idl
@@ -0,0 +1,20 @@
+
+// https://w3c.github.io/webrtc-pc/#rtctrackevent
+
+[Exposed=Window]
+interface RTCTrackEvent : Event {
+ [FIXME] constructor(DOMString type, RTCTrackEventInit eventInitDict);
+ readonly attribute RTCRtpReceiver receiver;
+ readonly attribute MediaStreamTrack track;
+ [SameObject] readonly attribute FrozenArray<MediaStream> streams;
+ readonly attribute RTCRtpTransceiver transceiver;
+};
+
+dictionary RTCTrackEventInit : EventInit {
+ // FIXME: spec types are RTCRtpReceiver / MediaStreamTrack /
+ // sequence<MediaStream> / RTCRtpTransceiver respectively.
+ required object receiver;
+ required object track;
+ sequence<object> streams = [];
+ required object transceiver;
+};
diff --git a/Libraries/LibWeb/WebRTC/RTCTransformEvent.cpp b/Libraries/LibWeb/WebRTC/RTCTransformEvent.cpp
new file mode 100644
index 00000000000..b6586f4717f
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCTransformEvent.cpp
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransformer.h>
+#include <LibWeb/WebRTC/RTCTransformEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(RTCTransformEvent);
+
+GC::Ref<RTCTransformEvent> RTCTransformEvent::create(Utf16FlyString const& event_name, GC::Ref<RTCRtpScriptTransformer> transformer, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<RTCTransformEvent>(event_name, transformer, time_stamp);
+}
+
+RTCTransformEvent::RTCTransformEvent(Utf16FlyString const& event_name, GC::Ref<RTCRtpScriptTransformer> transformer, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, time_stamp)
+ , m_transformer(transformer)
+{
+}
+
+RTCTransformEvent::~RTCTransformEvent() = default;
+
+void RTCTransformEvent::visit_edges(Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_transformer);
+}
+
+GC::Ref<RTCRtpScriptTransformer> RTCTransformEvent::transformer() const { return m_transformer; }
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCTransformEvent.h b/Libraries/LibWeb/WebRTC/RTCTransformEvent.h
new file mode 100644
index 00000000000..f0540509f81
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCTransformEvent.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/DOM/Event.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
+
+namespace Web::WebRTC {
+
+class RTCRtpScriptTransformer;
+
+class WEB_API RTCTransformEvent final : public DOM::Event {
+ WEB_WRAPPABLE(RTCTransformEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(RTCTransformEvent);
+
+public:
+ static GC::Ref<RTCTransformEvent> create(Utf16FlyString const& event_name, GC::Ref<RTCRtpScriptTransformer>, HighResolutionTime::DOMHighResTimeStamp);
+ virtual ~RTCTransformEvent() override;
+
+ GC::Ref<RTCRtpScriptTransformer> transformer() const;
+
+private:
+ RTCTransformEvent(Utf16FlyString const&, GC::Ref<RTCRtpScriptTransformer>, HighResolutionTime::DOMHighResTimeStamp);
+ virtual void visit_edges(Cell::Visitor&) override;
+
+ GC::Ref<RTCRtpScriptTransformer> m_transformer;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCTransformEvent.idl b/Libraries/LibWeb/WebRTC/RTCTransformEvent.idl
new file mode 100644
index 00000000000..7b8a0d0ebac
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/RTCTransformEvent.idl
@@ -0,0 +1,10 @@
+// https://w3c.github.io/webrtc-encoded-transform/#rtctransformevent
+
+[Exposed=DedicatedWorker]
+interface RTCTransformEvent : Event {
+ readonly attribute RTCRtpScriptTransformer transformer;
+};
+
+partial interface DedicatedWorkerGlobalScope {
+ attribute EventHandler onrtctransform;
+};
diff --git a/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.cpp b/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.cpp
new file mode 100644
index 00000000000..48ea94bcac3
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/SFrameDecrypterStream.h>
+#include <LibWeb/WebRTC/SFrameDecrypterStream.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(SFrameDecrypterStream);
+
+GC::Ref<SFrameDecrypterStream> SFrameDecrypterStream::create() { return GC::Heap::the().allocate<SFrameDecrypterStream>(); }
+
+// FIXME: SFrameDecrypterStream is a stub — wire up the options once SFrame transforms are implemented.
+WebIDL::ExceptionOr<GC::Ref<SFrameDecrypterStream>> SFrameDecrypterStream::construct_impl(Bindings::SFrameTransformOptions const&)
+{
+ return create();
+}
+SFrameDecrypterStream::SFrameDecrypterStream() = default;
+SFrameDecrypterStream::~SFrameDecrypterStream() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.h b/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.h
new file mode 100644
index 00000000000..467a7d8797b
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/Forward.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+class SFrameDecrypterStream final : public DOM::EventTarget {
+ WEB_WRAPPABLE(SFrameDecrypterStream, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(SFrameDecrypterStream);
+
+public:
+ static GC::Ref<SFrameDecrypterStream> create();
+ static WebIDL::ExceptionOr<GC::Ref<SFrameDecrypterStream>> construct_impl(Bindings::SFrameTransformOptions const&);
+ virtual ~SFrameDecrypterStream() override;
+
+private:
+ explicit SFrameDecrypterStream();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.idl b/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.idl
new file mode 100644
index 00000000000..c3c95785aa0
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameDecrypterStream.idl
@@ -0,0 +1,11 @@
+// https://w3c.github.io/webrtc-encoded-transform/#sframedecrypterstream
+
+// FIXME: spec is `SFrameDecrypterStream includes GenericTransformStream;` — that mixin
+// expects the implementation to actually back a TransformStream, which we don't here.
+[Exposed=(Window,DedicatedWorker)]
+interface SFrameDecrypterStream : EventTarget {
+ [FIXME] constructor(SFrameTransformOptions options);
+ [FIXME] readonly attribute ReadableStream readable;
+ [FIXME] readonly attribute WritableStream writable;
+};
+SFrameDecrypterStream includes SFrameDecrypterManager;
diff --git a/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.cpp b/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.cpp
new file mode 100644
index 00000000000..7c1b173ade3
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/SFrameEncrypterStream.h>
+#include <LibWeb/WebRTC/SFrameEncrypterStream.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(SFrameEncrypterStream);
+
+GC::Ref<SFrameEncrypterStream> SFrameEncrypterStream::create() { return GC::Heap::the().allocate<SFrameEncrypterStream>(); }
+
+// FIXME: SFrameEncrypterStream is a stub — wire up the options once SFrame transforms are implemented.
+WebIDL::ExceptionOr<GC::Ref<SFrameEncrypterStream>> SFrameEncrypterStream::construct_impl(Bindings::SFrameTransformOptions const&)
+{
+ return create();
+}
+SFrameEncrypterStream::SFrameEncrypterStream() = default;
+SFrameEncrypterStream::~SFrameEncrypterStream() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.h b/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.h
new file mode 100644
index 00000000000..c9cefec25c8
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Bindings/Forward.h>
+#include <LibWeb/DOM/EventTarget.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::WebRTC {
+
+class SFrameEncrypterStream final : public DOM::EventTarget {
+ WEB_WRAPPABLE(SFrameEncrypterStream, DOM::EventTarget);
+ GC_DECLARE_ALLOCATOR(SFrameEncrypterStream);
+
+public:
+ static GC::Ref<SFrameEncrypterStream> create();
+ static WebIDL::ExceptionOr<GC::Ref<SFrameEncrypterStream>> construct_impl(Bindings::SFrameTransformOptions const&);
+ virtual ~SFrameEncrypterStream() override;
+
+private:
+ explicit SFrameEncrypterStream();
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.idl b/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.idl
new file mode 100644
index 00000000000..753eedfb3ee
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameEncrypterStream.idl
@@ -0,0 +1,11 @@
+// https://w3c.github.io/webrtc-encoded-transform/#sframeencrypterstream
+
+// FIXME: spec is `SFrameEncrypterStream includes GenericTransformStream;` — that mixin
+// expects the implementation to actually back a TransformStream, which we don't here.
+[Exposed=(Window,DedicatedWorker)]
+interface SFrameEncrypterStream : EventTarget {
+ [FIXME] constructor(SFrameTransformOptions options);
+ [FIXME] readonly attribute ReadableStream readable;
+ [FIXME] readonly attribute WritableStream writable;
+};
+SFrameEncrypterStream includes SFrameEncrypterManager;
diff --git a/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.cpp b/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.cpp
new file mode 100644
index 00000000000..ea8eca2fad5
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.cpp
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/WebRTC/SFrameTransformErrorEvent.h>
+
+namespace Web::WebRTC {
+
+GC_DEFINE_ALLOCATOR(SFrameTransformErrorEvent);
+
+GC::Ref<SFrameTransformErrorEvent> SFrameTransformErrorEvent::create(Utf16FlyString const& event_name, SFrameTransformErrorEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+{
+ return GC::Heap::the().allocate<SFrameTransformErrorEvent>(event_name, event_init, time_stamp);
+}
+
+// FIXME: SFrameTransformErrorEvent is a stub — store the errorType/keyID/frame once the attributes are implemented.
+SFrameTransformErrorEvent::SFrameTransformErrorEvent(Utf16FlyString const& event_name, SFrameTransformErrorEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
+ : DOM::Event(event_name, event_init, time_stamp)
+{
+}
+
+SFrameTransformErrorEvent::~SFrameTransformErrorEvent() = default;
+
+}
diff --git a/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.h b/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.h
new file mode 100644
index 00000000000..cbae680e635
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/SFrameTransformErrorEvent.h>
+#include <LibWeb/DOM/Event.h>
+
+namespace Web::WebRTC {
+
+using SFrameTransformErrorEventInit = Bindings::SFrameTransformErrorEventInit;
+
+class SFrameTransformErrorEvent final : public DOM::Event {
+ WEB_WRAPPABLE(SFrameTransformErrorEvent, DOM::Event);
+ GC_DECLARE_ALLOCATOR(SFrameTransformErrorEvent);
+
+public:
+ [[nodiscard]] static GC::Ref<SFrameTransformErrorEvent> create(Utf16FlyString const& event_name, SFrameTransformErrorEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+ virtual ~SFrameTransformErrorEvent() override;
+
+private:
+ SFrameTransformErrorEvent(Utf16FlyString const& event_name, SFrameTransformErrorEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.idl b/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.idl
new file mode 100644
index 00000000000..b10d364aaed
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/SFrameTransformErrorEvent.idl
@@ -0,0 +1,22 @@
+// https://w3c.github.io/webrtc-encoded-transform/#sframetransformerrorevent
+
+enum SFrameTransformErrorEventType {
+ "authentication",
+ "keyID",
+ "syntax"
+};
+
+dictionary SFrameTransformErrorEventInit : EventInit {
+ required SFrameTransformErrorEventType errorType;
+ required any frame;
+ CryptoKeyID? keyID;
+};
+
+[Exposed=(Window,DedicatedWorker)]
+interface SFrameTransformErrorEvent : Event {
+ [FIXME] constructor(DOMString type, SFrameTransformErrorEventInit eventInitDict);
+
+ [FIXME] readonly attribute SFrameTransformErrorEventType errorType;
+ [FIXME] readonly attribute CryptoKeyID? keyID;
+ [FIXME] readonly attribute any frame;
+};
diff --git a/Libraries/LibWeb/WebRTC/WebRTCAgent.cpp b/Libraries/LibWeb/WebRTC/WebRTCAgent.cpp
new file mode 100644
index 00000000000..55b3aff77a0
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/WebRTCAgent.cpp
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Format.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/ScopeGuard.h>
+#include <LibIPC/Transport.h>
+#include <LibJS/Runtime/ArrayBuffer.h>
+#include <LibJS/Runtime/PrimitiveString.h>
+#include <LibWeb/Bindings/Intrinsics.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/DOM/Event.h>
+#include <LibWeb/FileAPI/Blob.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/MessageEvent.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/Loader/ResourceLoader.h>
+#include <LibWeb/WebRTC/RTCDataChannel.h>
+#include <LibWeb/WebRTC/RTCPeerConnection.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
+
+namespace Web::WebRTC {
+
+static NeverDestroyed<WebRTCAgent::TransportFactory> s_transport_factory;
+
+void WebRTCAgent::set_transport_factory(TransportFactory factory)
+{
+ *s_transport_factory = move(factory);
+}
+
+WebRTCAgent& WebRTCAgent::the()
+{
+ static auto& s_agent = *new WebRTCAgent;
+ return s_agent;
+}
+
+bool WebRTCAgent::is_ready()
+{
+ ensure_client();
+ return m_client;
+}
+
+WebRTCClient::Client* WebRTCAgent::client()
+{
+ ensure_client();
+ return m_client.ptr();
+}
+
+void WebRTCAgent::register_peer_connection(u64 pc_id, GC::Ref<RTCPeerConnection> pc)
+{
+ m_peer_connections.set(pc_id, pc);
+}
+
+GC::Ptr<RTCPeerConnection> WebRTCAgent::find_peer_connection(u64 pc_id)
+{
+ if (auto connection = m_peer_connections.get(pc_id); connection.has_value())
+ return connection->ptr();
+ return nullptr;
+}
+
+void WebRTCAgent::unregister_peer_connection(u64 pc_id)
+{
+ m_peer_connections.remove(pc_id);
+}
+
+void WebRTCAgent::register_data_channel(u64 channel_id, GC::Ref<RTCDataChannel> channel)
+{
+ m_data_channels.set(channel_id, channel);
+}
+
+void WebRTCAgent::unregister_data_channel(u64 channel_id)
+{
+ m_data_channels.remove(channel_id);
+}
+
+void WebRTCAgent::close_connections_for_global(DOM::EventTarget& global)
+{
+ auto connections = m_peer_connections;
+ for (auto& [_, connection] : connections) {
+ if (connection->relevant_global_impl().ptr() == &global)
+ connection->close_for_document_destruction();
+ }
+}
+
+void WebRTCAgent::ensure_client()
+{
+ if (m_client || m_attempted_to_launch)
+ return;
+ m_attempted_to_launch = true;
+ ScopeGuard reset_attempt = [&] { m_attempted_to_launch = false; };
+
+ if (!*s_transport_factory) {
+ dbgln("WebRTCAgent: No way to reach a WebRTCClient in this process");
+ return;
+ }
+ auto transport = (*s_transport_factory)();
+ if (transport.is_error()) {
+ dbgln("WebRTCAgent: Unable to connect to a WebRTCClient: {}", transport.error());
+ return;
+ }
+
+ m_client = adopt_ref(*new WebRTCClient::Client(transport.release_value()));
+ wire_event_handlers();
+ // The helper has no resolver of its own, so that its lookups follow the browser's DNS settings like any other.
+ m_client->on_resolve_host = [client = m_client.ptr()](u64 request_id, String host) {
+ // NB: A lookup carries no site's state, so it goes to the RequestServer with no site.
+ auto request_client = ResourceLoader::the().request_client_for_top_level_site({});
+ if (!request_client) {
+ client->async_resolved_host(request_id, {});
+ return;
+ }
+ request_client->resolve_host(host.to_byte_string(), [client = NonnullRefPtr { *client }, request_id](Vector<ByteString> addresses) {
+ if (!client->is_open())
+ return;
+ Vector<String> resolved;
+ for (auto const& address : addresses)
+ resolved.append(MUST(String::from_byte_string(address)));
+ client->async_resolved_host(request_id, resolved);
+ });
+ };
+ m_client->on_death = [this] {
+ m_client = nullptr;
+ m_attempted_to_launch = false;
+ auto connections = m_peer_connections;
+ for (auto& [_, connection] : connections)
+ connection->on_helper_died();
+ };
+}
+
+#define ROUTE_PC_EVENT(slot, method) \
+ m_client->slot = [this](u64 pc_id, auto&&... args) { \
+ if (auto pc = m_peer_connections.get(pc_id); pc.has_value()) \
+ (*pc)->method(forward<decltype(args)>(args)...); \
+ };
+
+void WebRTCAgent::wire_event_handlers()
+{
+ ROUTE_PC_EVENT(on_stats_result, on_stats_received);
+ ROUTE_PC_EVENT(on_signaling_state_change, on_signaling_state_event);
+ ROUTE_PC_EVENT(on_connection_state_change, on_connection_state_event);
+ ROUTE_PC_EVENT(on_ice_gathering_state_change, on_ice_gathering_state_event);
+ ROUTE_PC_EVENT(on_ice_connection_state_change, on_ice_connection_state_event);
+ ROUTE_PC_EVENT(on_ice_candidate_event, on_ice_candidate_received);
+ ROUTE_PC_EVENT(on_ice_candidate_error_event, on_ice_candidate_error_received);
+ ROUTE_PC_EVENT(on_negotiation_needed_event, on_negotiation_needed_received);
+ ROUTE_PC_EVENT(on_track_event, on_remote_track_added);
+ ROUTE_PC_EVENT(on_track_ended_event, on_remote_track_ended);
+ ROUTE_PC_EVENT(on_encoded_audio_frame_event, on_encoded_audio_frame_received);
+ ROUTE_PC_EVENT(on_audio_track_added_event, on_audio_track_ssrc_assigned);
+ ROUTE_PC_EVENT(on_create_offer_completion, on_create_offer_result_received);
+ ROUTE_PC_EVENT(on_create_answer_completion, on_create_answer_result_received);
+ ROUTE_PC_EVENT(on_set_local_description_completion, on_set_local_description_result_received);
+ ROUTE_PC_EVENT(on_set_remote_description_completion, on_set_remote_description_result_received);
+ ROUTE_PC_EVENT(on_add_ice_candidate_completion, on_add_ice_candidate_result_received);
+ ROUTE_PC_EVENT(on_data_channel_event, on_remote_data_channel_received);
+
+ m_client->on_data_channel_open_event = [this](u64 channel_id) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ HTML::TemporaryExecutionContext context((*channel)->relevant_realm());
+ (*channel)->set_ready_state(Bindings::RTCDataChannelState::Open);
+ (*channel)->dispatch_event(DOM::Event::create((*channel)->relevant_global_object(), HTML::EventNames::open));
+ }
+ };
+ m_client->on_data_channel_closing_event = [this](u64 channel_id) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ HTML::TemporaryExecutionContext context((*channel)->relevant_realm());
+ (*channel)->set_ready_state(Bindings::RTCDataChannelState::Closing);
+ (*channel)->dispatch_event(DOM::Event::create((*channel)->relevant_global_object(), HTML::EventNames::closing));
+ }
+ };
+ m_client->on_data_channel_closed_event = [this](u64 channel_id) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ HTML::TemporaryExecutionContext context((*channel)->relevant_realm());
+ (*channel)->set_ready_state(Bindings::RTCDataChannelState::Closed);
+ (*channel)->dispatch_event(DOM::Event::create((*channel)->relevant_global_object(), HTML::EventNames::close));
+ }
+ m_data_channels.remove(channel_id);
+ };
+ m_client->on_data_channel_error_event = [this](u64 channel_id, String) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ HTML::TemporaryExecutionContext context((*channel)->relevant_realm());
+ // FIXME: dispatch RTCErrorEvent("error") with the error detail; bare Event for now.
+ (*channel)->dispatch_event(DOM::Event::create((*channel)->relevant_global_object(), HTML::EventNames::error));
+ }
+ };
+ m_client->on_data_channel_buffered_amount_low_event = [this](u64 channel_id) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ HTML::TemporaryExecutionContext context((*channel)->relevant_realm());
+ (*channel)->dispatch_event(DOM::Event::create((*channel)->relevant_global_object(), HTML::EventNames::bufferedamountlow));
+ }
+ };
+ m_client->on_data_channel_message_text_event = [this](u64 channel_id, String text) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ auto& realm = (*channel)->relevant_realm();
+ HTML::TemporaryExecutionContext context(realm);
+ HTML::MessageEventInit init;
+ init.data = JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(text));
+ (*channel)->dispatch_event(HTML::MessageEvent::create((*channel)->relevant_global_object(), HTML::EventNames::message, init));
+ }
+ };
+ m_client->on_data_channel_message_binary_event = [this](u64 channel_id, ByteBuffer bytes) {
+ if (auto channel = m_data_channels.get(channel_id); channel.has_value()) {
+ auto& realm = (*channel)->relevant_realm();
+ HTML::TemporaryExecutionContext context(realm);
+ HTML::MessageEventInit init;
+ if ((*channel)->binary_type() == Bindings::BinaryType::Blob)
+ init.data = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, FileAPI::Blob::create(move(bytes), String {}));
+ else
+ init.data = JS::ArrayBuffer::create(realm, bytes);
+ (*channel)->dispatch_event(HTML::MessageEvent::create((*channel)->relevant_global_object(), HTML::EventNames::message, init));
+ }
+ };
+}
+
+#undef ROUTE_PC_EVENT
+
+}
diff --git a/Libraries/LibWeb/WebRTC/WebRTCAgent.h b/Libraries/LibWeb/WebRTC/WebRTCAgent.h
new file mode 100644
index 00000000000..4d4490989f4
--- /dev/null
+++ b/Libraries/LibWeb/WebRTC/WebRTCAgent.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/HashMap.h>
+#include <AK/RefPtr.h>
+#include <LibGC/Heap.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/Root.h>
+#include <LibIPC/Forward.h>
+#include <LibWeb/Export.h>
+#include <LibWebRTCClient/Client.h>
+
+namespace Web::WebRTC {
+
+class RTCDataChannel;
+class RTCPeerConnection;
+
+class WebRTCAgent {
+ AK_MAKE_NONCOPYABLE(WebRTCAgent);
+ AK_MAKE_NONMOVABLE(WebRTCAgent);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ static WebRTCAgent& the();
+
+ using TransportFactory = Function<ErrorOr<NonnullOwnPtr<IPC::Transport>>()>;
+ // The factory reaches the Browser, which launches a helper for this process.
+ WEB_API static void set_transport_factory(TransportFactory);
+
+ bool is_ready();
+ WebRTCClient::Client* client();
+ WebRTCClient::Client* existing_client() { return m_client.ptr(); }
+ void close_connections_for_global(DOM::EventTarget&);
+
+ u64 next_pc_id() { return ++m_next_pc_id; }
+ u64 next_request_id() { return ++m_next_request_id; }
+ u64 next_sender_id() { return ++m_next_sender_id; }
+ u64 next_channel_id() { return ++m_next_channel_id; }
+ // Start above the small SSRC values webrtc-rs tends to allocate to avoid collisions.
+ u32 next_ssrc() { return ++m_next_ssrc; }
+
+ void register_peer_connection(u64 pc_id, GC::Ref<RTCPeerConnection>);
+ void unregister_peer_connection(u64 pc_id);
+ GC::Ptr<RTCPeerConnection> find_peer_connection(u64 pc_id);
+
+ void register_data_channel(u64 channel_id, GC::Ref<RTCDataChannel>);
+ void unregister_data_channel(u64 channel_id);
+
+private:
+ WebRTCAgent() = default;
+
+ void ensure_client();
+ void wire_event_handlers();
+
+ RefPtr<WebRTCClient::Client> m_client;
+ bool m_attempted_to_launch { false };
+
+ HashMap<u64, GC::Root<RTCPeerConnection>> m_peer_connections;
+ HashMap<u64, GC::Root<RTCDataChannel>> m_data_channels;
+
+ u64 m_next_pc_id { 0 };
+ u64 m_next_request_id { 0 };
+ u64 m_next_sender_id { 0 };
+ u64 m_next_channel_id { 0 };
+ u32 m_next_ssrc { 0xa0000000 };
+};
+
+}
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 3829acc0e26..eb7bd5abecf 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -710,6 +710,37 @@ libweb_js_bindings(WebIDL/Buffers)
libweb_js_bindings(WebIDL/DOMException)
libweb_js_bindings(WebIDL/Function)
libweb_js_bindings(WebIDL/QuotaExceededError)
+libweb_js_bindings(WebRTC/KeyFrameRequestEvent)
+libweb_js_bindings(WebRTC/RTCCertificate)
+libweb_js_bindings(WebRTC/RTCDataChannel)
+libweb_js_bindings(WebRTC/RTCDataChannelEvent)
+libweb_js_bindings(WebRTC/RTCDtlsTransport)
+libweb_js_bindings(WebRTC/RTCDTMFSender)
+libweb_js_bindings(WebRTC/RTCDTMFToneChangeEvent)
+libweb_js_bindings(WebRTC/RTCEncodedAudioFrame)
+libweb_js_bindings(WebRTC/RTCEncodedVideoFrame)
+libweb_js_bindings(WebRTC/RTCError)
+libweb_js_bindings(WebRTC/RTCErrorEvent)
+libweb_js_bindings(WebRTC/RTCIceCandidate)
+libweb_js_bindings(WebRTC/RTCIceTransport)
+libweb_js_bindings(WebRTC/RTCPeerConnection)
+libweb_js_bindings(WebRTC/RTCPeerConnectionIceErrorEvent)
+libweb_js_bindings(WebRTC/RTCPeerConnectionIceEvent)
+libweb_js_bindings(WebRTC/RTCRtpReceiver)
+libweb_js_bindings(WebRTC/RTCRtpScriptTransform)
+libweb_js_bindings(WebRTC/RTCRtpScriptTransformer)
+libweb_js_bindings(WebRTC/RTCRtpSender)
+libweb_js_bindings(WebRTC/RTCRtpTransceiver)
+libweb_js_bindings(WebRTC/RTCSctpTransport)
+libweb_js_bindings(WebRTC/RTCSessionDescription)
+libweb_js_bindings(WebRTC/RTCSFrameReceiverTransform)
+libweb_js_bindings(WebRTC/RTCSFrameSenderTransform)
+libweb_js_bindings(WebRTC/RTCStatsReport)
+libweb_js_bindings(WebRTC/RTCTrackEvent)
+libweb_js_bindings(WebRTC/RTCTransformEvent)
+libweb_js_bindings(WebRTC/SFrameDecrypterStream)
+libweb_js_bindings(WebRTC/SFrameEncrypterStream)
+libweb_js_bindings(WebRTC/SFrameTransformErrorEvent)
libweb_js_bindings(WebSockets/WebSocket)
libweb_js_bindings(WebVTT/VTTCue)
libweb_js_bindings(WebVTT/VTTRegion)
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 4ae323c5a10..acb191be49e 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -2344,6 +2344,9 @@ void Application::process_did_exit(Process&& process, Optional<int>)
case ProcessType::VideoDecoderServer:
// The MediaServer it served asks for a new one once its decoders notice the loss.
break;
+ case ProcessType::WebRTCClient:
+ // The WebContent process it served asks for a new one the next time it needs one.
+ break;
case ProcessType::RequestServer:
if (auto client = process.client<Requests::RequestControlClient>()) {
dbgln_if(WEBVIEW_PROCESS_DEBUG, "Restart request server");
diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cpp
index 30b27b691b2..383c01dc5d0 100644
--- a/Libraries/LibWebView/HelperProcess.cpp
+++ b/Libraries/LibWebView/HelperProcess.cpp
@@ -440,6 +440,46 @@ static void connect_client_to_image_decoder(ClientType& client, ImageDecoderConn
});
}
+ErrorOr<IPC::TransportHandle> launch_webrtc_client_process(WebContentClient& client)
+{
+ // A renderer only asks again once it has lost its helper, so one that is still around is on its way out. Never let
+ // a renderer hold more than one.
+ Vector<u64> previous_helpers;
+ Application::process_manager().for_each_process([&](Process& process) {
+ if (process.type() == ProcessType::WebRTCClient && process.owner_child_id() == client.child_id())
+ previous_helpers.append(process.child_id());
+ });
+ for (auto child_id : previous_helpers)
+ (void)Application::process_manager().terminate_child(child_id, Core::Process::TerminationMode::Forceful);
+
+ Vector<ByteString> arguments;
+ if (WebView::Application::browser_options().disable_sandbox == DisableSandbox::Yes)
+ arguments.append("--disable-sandbox"sv);
+ // None of WebRTC's traffic could go through a proxy, so with one configured the helper gets no network access at
+ // all rather than reveal the user's address.
+ if (!Application::request_server_options().proxy_configuration.is_empty() || Application::web_content_options().proxy_autoconfig_url.has_value())
+ arguments.append("--disable-network"sv);
+ if (auto server = mach_server_name(); server.has_value()) {
+ arguments.append("--mach-server-name"sv);
+ arguments.append(server.value());
+ }
+
+ // NB: The renderer's sandbox does not let it spawn processes, so the Browser launches the helper and hands its end
+ // of the transport over, as it does for the ImageDecoder.
+ OwnPtr<IPC::Transport> transport;
+ auto identity = TRY(launch_helper_process("WebRTCClient"sv, move(arguments), [&](Core::ProcessSpawnOptions const& options, bool capture_output) -> ErrorOr<WebView::Process> {
+ auto [process, new_transport] = TRY(WebView::Process::spawn_with_transport(ProcessType::WebRTCClient, options, capture_output));
+ transport = move(new_transport);
+ return move(process);
+ }));
+
+ auto process = Application::process_manager().find_child(identity.child_id);
+ VERIFY(process.has_value());
+ process->set_owner_child_id(client.child_id());
+
+ return transport->release_for_transfer();
+}
+
void connect_to_image_decoder(WebContentClient& client, ImageDecoderConnection decoder)
{
connect_client_to_image_decoder(client, move(decoder));
diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.h
index 0636ad4615b..73dab12abd5 100644
--- a/Libraries/LibWebView/HelperProcess.h
+++ b/Libraries/LibWebView/HelperProcess.h
@@ -48,6 +48,10 @@ WEBVIEW_API ErrorOr<ImageDecoderConnection> launch_image_decoder_process();
WEBVIEW_API void connect_to_image_decoder(WebContentClient&, ImageDecoderConnection);
WEBVIEW_API void connect_to_image_decoder(WebWorkerClient&, ImageDecoderConnection);
+// Launches a WebRTCClient that serves the given renderer alone, which talks to it over the returned handle, and ends any
+// helper the renderer had before. The helper exits once that renderer's end of the transport is gone.
+WEBVIEW_API ErrorOr<IPC::TransportHandle> launch_webrtc_client_process(WebContentClient&);
+
struct RequestServerClientConnection {
IPC::TransportHandle handle;
int client_id { -1 };
diff --git a/Libraries/LibWebView/ProcessManager.cpp b/Libraries/LibWebView/ProcessManager.cpp
index 9cd1a999ba9..e2bd03e760b 100644
--- a/Libraries/LibWebView/ProcessManager.cpp
+++ b/Libraries/LibWebView/ProcessManager.cpp
@@ -33,6 +33,8 @@ ProcessType process_type_from_name(StringView name)
return ProcessType::AudioServer;
if (name == "VideoDecoderServer"sv)
return ProcessType::VideoDecoderServer;
+ if (name == "WebRTCClient"sv)
+ return ProcessType::WebRTCClient;
dbgln("Unknown process type: '{}'", name);
VERIFY_NOT_REACHED();
@@ -59,6 +61,8 @@ StringView process_name_from_type(ProcessType type)
return "AudioServer"sv;
case ProcessType::VideoDecoderServer:
return "VideoDecoderServer"sv;
+ case ProcessType::WebRTCClient:
+ return "WebRTCClient"sv;
}
VERIFY_NOT_REACHED();
}
diff --git a/Libraries/LibWebView/ProcessType.h b/Libraries/LibWebView/ProcessType.h
index fcdb856e3b2..792eacdbcd6 100644
--- a/Libraries/LibWebView/ProcessType.h
+++ b/Libraries/LibWebView/ProcessType.h
@@ -20,6 +20,7 @@ enum class ProcessType : u8 {
MediaServer,
AudioServer,
VideoDecoderServer,
+ WebRTCClient,
};
}
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 95c8fc85b2b..72e502681e0 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -1110,6 +1110,27 @@ Messages::WebContentClient::RequestAudioServerConnectionResponse WebContentClien
return handle.release_value();
}
+Messages::WebContentClient::RequestWebrtcClientConnectionResponse WebContentClient::request_webrtc_client_connection()
+{
+ // A renderer asks again whenever its helper dies, so a helper that keeps crashing, or a renderer that keeps asking,
+ // would otherwise have us spawn processes in a loop.
+ static constexpr size_t MAX_WEBRTC_CLIENT_LAUNCHES_PER_MINUTE = 5;
+ auto now = MonotonicTime::now_coarse();
+ m_webrtc_client_launch_times.remove_all_matching([&](auto launch_time) { return now - launch_time >= AK::Duration::from_seconds(60); });
+ if (m_webrtc_client_launch_times.size() >= MAX_WEBRTC_CLIENT_LAUNCHES_PER_MINUTE) {
+ warnln("Not launching another WebRTCClient for WebContent {}: it had {} in the last minute", child_id(), m_webrtc_client_launch_times.size());
+ return OptionalNone {};
+ }
+ m_webrtc_client_launch_times.append(now);
+
+ auto handle = launch_webrtc_client_process(*this);
+ if (handle.is_error()) {
+ warnln("Unable to launch a WebRTCClient: {}", handle.error());
+ return OptionalNone {};
+ }
+ return handle.release_value();
+}
+
Optional<u64> WebContentClient::exclusive_performance_owner() const
{
Optional<u64> owner;
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index a39b0a5ab0d..52169b18989 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -15,6 +15,7 @@
#include <AK/SourceLocation.h>
#include <AK/String.h>
#include <AK/StringView.h>
+#include <AK/Time.h>
#include <AK/WeakPtr.h>
#include <LibAudio/Audibility.h>
#include <LibAudio/PlaybackGroupId.h>
@@ -227,6 +228,7 @@ private:
virtual Messages::WebContentClient::DidLoseRequestServerConnectionResponse did_lose_request_server_connection(Optional<Utf16String> top_level_site) override;
virtual Messages::WebContentClient::RequestMediaServerConnectionResponse request_media_server_connection() override;
virtual Messages::WebContentClient::RequestAudioServerConnectionResponse request_audio_server_connection() override;
+ virtual Messages::WebContentClient::RequestWebrtcClientConnectionResponse request_webrtc_client_connection() override;
virtual void request_video_presentation_channel() override;
virtual void gamepad_play_effect(Web::Gamepad::GamepadHandle handle, Web::Gamepad::GamepadEffect effect) override;
virtual void gamepad_stop_effects(Web::Gamepad::GamepadHandle handle) override;
@@ -288,6 +290,9 @@ private:
AudioServerAudibility m_audio_server_audibility { [this](Audio::PlaybackGroupId group, Audio::Audibility audibility) { did_change_audio_playback_audibility(group, audibility); } };
RefPtr<Core::Timer> m_detached_page_close_timer;
+ // When this process last got a WebRTCClient, so that it can't make us spawn them in a loop.
+ Vector<MonotonicTime> m_webrtc_client_launch_times;
+
static HashTable<WebContentClient*>& clients();
};
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index d1ad4e1c9aa..d24deadaf6e 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -3268,6 +3268,21 @@ void WebContentPage::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::
WorkerProcessManager::the().close_worker_agent(client(), agent_id, owner_token);
}
+void WebContentPage::rtc_transform_init(Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record)
+{
+ WorkerProcessManager::the().rtc_transform_init(client(), agent_id, transform_id, move(options_record));
+}
+
+void WebContentPage::rtc_transform_teardown(Web::HTML::WorkerAgentId agent_id, u64 transform_id)
+{
+ WorkerProcessManager::the().rtc_transform_teardown(client(), agent_id, transform_id);
+}
+
+void WebContentPage::rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ WorkerProcessManager::the().rtc_transform_encoded_audio_frame(client(), agent_id, transform_id, move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
void WebContentPage::did_finish_test(String text)
{
if (displays_tab() && view().on_test_finish)
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 91df2b552a9..4fa823046ba 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -384,6 +384,9 @@ private:
Messages::WebContentClient::DidRequestStorageUsageResponse did_request_storage_usage(Web::HTML::EnvironmentId environment_id);
virtual void did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) override;
virtual void close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) override;
+ virtual void rtc_transform_init(Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) override;
+ virtual void rtc_transform_teardown(Web::HTML::WorkerAgentId agent_id, u64 transform_id) override;
+ virtual void rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;
Messages::WebContentClient::DidRequestCookieResponse did_request_cookie(Optional<Web::HTML::EnvironmentId> const&, URL::URL, HTTP::Cookie::Source);
Messages::WebContentClient::DidRequestAllCookiesCookiestoreResponse did_request_all_cookies_cookiestore(Web::HTML::EnvironmentId const&, URL::URL);
Messages::WebContentClient::DidAddBlobUrlEntryResponse did_add_blob_url_entry(Web::HTML::EnvironmentId environment_id, Utf16String url, Web::FileAPI::SerializedBlobURLEntry);
diff --git a/Libraries/LibWebView/WebWorkerClient.cpp b/Libraries/LibWebView/WebWorkerClient.cpp
index ee4845fdb7c..e0574a336be 100644
--- a/Libraries/LibWebView/WebWorkerClient.cpp
+++ b/Libraries/LibWebView/WebWorkerClient.cpp
@@ -209,4 +209,9 @@ void WebWorkerClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web:
WorkerProcessManager::the().close_worker_agent(*this, agent_id, owner_token);
}
+void WebWorkerClient::rtc_transform_encoded_audio_frame_written(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ WorkerProcessManager::the().worker_did_write_rtc_transform_encoded_audio_frame(m_agent_id, transform_id, move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
}
diff --git a/Libraries/LibWebView/WebWorkerClient.h b/Libraries/LibWebView/WebWorkerClient.h
index 56452ab4453..f21baadea9a 100644
--- a/Libraries/LibWebView/WebWorkerClient.h
+++ b/Libraries/LibWebView/WebWorkerClient.h
@@ -67,6 +67,7 @@ public:
virtual void did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage) override;
virtual Messages::WebWorkerClient::StartWorkerAgentResponse start_worker_agent(Web::HTML::WorkerAgentStartRequest request) override;
virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;
+ virtual void rtc_transform_encoded_audio_frame_written(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;
private:
virtual void did_misbehave(StringView message_name, StringView reason) override;
diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cpp
index cd840dc16b7..d51c1352347 100644
--- a/Libraries/LibWebView/WorkerProcessManager.cpp
+++ b/Libraries/LibWebView/WorkerProcessManager.cpp
@@ -537,6 +537,55 @@ void WorkerProcessManager::notify_worker_content_security_policy_violation(Owner
});
}
+WorkerProcessManager::WorkerAgent* WorkerProcessManager::agent_owned_by(WebContentClient& client, Web::HTML::WorkerAgentId agent_id)
+{
+ auto agent = m_agents.find(agent_id);
+ if (agent == m_agents.end())
+ return nullptr;
+ for (auto const& owner : agent->value.owners) {
+ auto const* web_content_owner = owner.client.get_pointer<WebContentOwner>();
+ if (web_content_owner && web_content_owner->client.ptr() == &client)
+ return &agent->value;
+ }
+ return nullptr;
+}
+
+void WorkerProcessManager::rtc_transform_init(WebContentClient& client, Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record)
+{
+ if (auto* agent = agent_owned_by(client, agent_id))
+ agent->client->async_rtc_transform_init(transform_id, move(options_record));
+}
+
+void WorkerProcessManager::rtc_transform_teardown(WebContentClient& client, Web::HTML::WorkerAgentId agent_id, u64 transform_id)
+{
+ if (auto* agent = agent_owned_by(client, agent_id))
+ agent->client->async_rtc_transform_teardown(transform_id);
+}
+
+void WorkerProcessManager::rtc_transform_encoded_audio_frame(WebContentClient& client, Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ if (auto* agent = agent_owned_by(client, agent_id))
+ agent->client->async_rtc_transform_encoded_audio_frame(transform_id, payload.bytes(), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
+void WorkerProcessManager::worker_did_write_rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ auto agent = m_agents.find(agent_id);
+ if (agent == m_agents.end())
+ return;
+
+ for (auto const& owner : agent->value.owners) {
+ owner.client.visit(
+ [&](WebContentOwner const& web_content_owner) {
+ if (web_content_owner.client)
+ web_content_owner.client->async_did_worker_rtc_transform_encoded_audio_frame_written(owner.token, transform_id, payload, ssrc, payload_type, rtp_timestamp, sequence_number);
+ },
+ [&](WebWorkerOwner const&) {
+ // FIXME: Route transform frames back to nested-worker owners once the WebWorkerServer endpoint carries this message.
+ });
+ }
+}
+
void WorkerProcessManager::notify_worker_close(Owner const& owner)
{
owner.client.visit(
diff --git a/Libraries/LibWebView/WorkerProcessManager.h b/Libraries/LibWebView/WorkerProcessManager.h
index c08c4b0b68e..8365a38c294 100644
--- a/Libraries/LibWebView/WorkerProcessManager.h
+++ b/Libraries/LibWebView/WorkerProcessManager.h
@@ -62,6 +62,10 @@ public:
void close_worker_agent(WebContentClient&, Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken);
void close_worker_agent(WebWorkerClient&, Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken);
+
+ void rtc_transform_init(WebContentClient&, Web::HTML::WorkerAgentId, u64 transform_id, Web::HTML::SerializedTransferRecord options_record);
+ void rtc_transform_teardown(WebContentClient&, Web::HTML::WorkerAgentId, u64 transform_id);
+ void rtc_transform_encoded_audio_frame(WebContentClient&, Web::HTML::WorkerAgentId, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number);
void remove_web_content_owner(WebContentClient&);
void remove_web_worker_owner(WebWorkerClient&);
@@ -120,6 +124,10 @@ private:
void worker_did_die(Web::HTML::WorkerAgentId);
void worker_process_did_exit(WebWorkerClient&);
void worker_did_request_file(Web::HTML::WorkerAgentId, ByteString path, i32 request_id);
+ void worker_did_write_rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number);
+
+ struct WorkerAgent;
+ WorkerAgent* agent_owned_by(WebContentClient&, Web::HTML::WorkerAgentId);
enum class AgentRemovalCause {
OwnerSetEmptied,
diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmake
index e0c88d8dd0d..4d4aee55079 100644
--- a/Meta/CMake/all_the_debug_macros.cmake
+++ b/Meta/CMake/all_the_debug_macros.cmake
@@ -66,6 +66,7 @@ set(VIDEO_PRESENTATION_CHANNEL_DEBUG ON)
set(WEBVIEW_PROCESS_DEBUG ON)
set(WEB_FETCH_DEBUG ON)
set(WEB_WORKER_DEBUG ON)
+set(WEBRTC_DEBUG ON)
set(XML_PARSER_DEBUG ON)
# False positive: ANDROID_LOG_DEBUG is a log level, not a debug flag
diff --git a/Meta/Generators/generate-build-information.py b/Meta/Generators/generate-build-information.py
index a28f38bb688..48822cb21ad 100755
--- a/Meta/Generators/generate-build-information.py
+++ b/Meta/Generators/generate-build-information.py
@@ -21,6 +21,7 @@ HELPERS = (
"VideoDecoderServer",
"WebContent",
"WebWorker",
+ "WebRTCClient",
)
diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.py
index ffa1411227d..32b37c5cdf0 100644
--- a/Meta/Generators/libweb_bindings/glue_headers.py
+++ b/Meta/Generators/libweb_bindings/glue_headers.py
@@ -19,6 +19,7 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_n
"IndexedDB": "LibWeb/IndexedDB/BindingsGlue.h",
"TrustedTypes": "LibWeb/TrustedTypes/BindingsGlue.h",
"WebAudio": "LibWeb/WebAudio/BindingsGlue.h",
+ "WebRTC": "LibWeb/WebRTC/BindingsGlue.h",
}
if module in module_headers:
return module_headers[module]
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 8b5eb2ca13a..386435a28e9 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -91,6 +91,12 @@ ALLOWED_REALM_MENTIONS = {
"WebDriver": (2, 7, "WebDriver execute/JSON conversion still materializes JS values for automation"),
"WebGL": (4, 9, "WebGL contexts are created in the realm of their canvas, and their events and promises in it"),
"WebLocks": (6, 7, "Web Locks queue/callback algorithms still use callback and promise realms"),
+ "WebRTC": (
+ 13,
+ 22,
+ "peer connections, data channels and senders resolve promises and fire events in their relevant realm, encoded "
+ "frames are constructed and deserialized in the worker's realm, and the stats report's maplike glue",
+ ),
"XHR": (4, 7, "XHR/FormData/FileReader-style paths still materialize JS values and events"),
}
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 570d0286d8e..3549a53da08 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -508,6 +508,14 @@ ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_audio_serve
return response->take_handle()->create_transport();
}
+ErrorOr<NonnullOwnPtr<IPC::Transport>> ConnectionFromClient::request_webrtc_client_transport()
+{
+ auto response = send_sync_but_allow_failure<Messages::WebContentClient::RequestWebrtcClientConnection>();
+ if (!response || !response->handle().has_value())
+ return Error::from_string_literal("The Browser did not launch a WebRTCClient");
+ return response->take_handle()->create_transport();
+}
+
TestConnection* ConnectionFromClient::test_connection()
{
if (m_test_connection)
@@ -3747,6 +3755,11 @@ void ConnectionFromClient::did_worker_agent_die(Web::HTML::WorkerAgentOwnerToken
Web::HTML::WorkerAgentParent::did_worker_agent_die(owner_token);
}
+void ConnectionFromClient::did_worker_rtc_transform_encoded_audio_frame_written(Web::HTML::WorkerAgentOwnerToken owner_token, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ Web::HTML::WorkerAgentParent::did_write_rtc_transform_encoded_audio_frame(owner_token, transform_id, move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
// https://html.spec.whatwg.org/multipage/speculative-loading.html#nav-traversal-ui:close-a-top-level-traversable
void ConnectionFromClient::request_close(Web::PageId page_id)
{
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index cc89ca837f3..e0265edd923 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -77,6 +77,7 @@ public:
// Asks the Browser to spawn this process's MediaServer if it has none, and to connect a client to it.
ErrorOr<NonnullOwnPtr<IPC::Transport>> request_media_server_transport();
ErrorOr<NonnullOwnPtr<IPC::Transport>> request_audio_server_transport();
+ ErrorOr<NonnullOwnPtr<IPC::Transport>> request_webrtc_client_transport();
// Null outside test mode: the UI process connects the test endpoint only when it runs tests.
TestConnection* test_connection();
@@ -355,6 +356,7 @@ private:
virtual void did_worker_agent_report_content_security_policy_violation(Web::HTML::WorkerAgentOwnerToken owner_token, u64 policy_index, String effective_directive, URL::URL resource) override;
virtual void did_worker_agent_close(Web::HTML::WorkerAgentOwnerToken owner_token) override;
virtual void did_worker_agent_die(Web::HTML::WorkerAgentOwnerToken owner_token) override;
+ virtual void did_worker_rtc_transform_encoded_audio_frame_written(Web::HTML::WorkerAgentOwnerToken owner_token, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;
virtual void request_close(Web::PageId page_id) override;
virtual void request_close_preflight(Web::PageId page_id, u64 request_id) override;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index bc7343ef282..c5dbe46b14b 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -2224,6 +2224,21 @@ void PageClient::close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML
client().async_close_worker_agent(m_id, agent_id, owner_token);
}
+void PageClient::rtc_transform_init(Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record)
+{
+ client().async_rtc_transform_init(m_id, agent_id, transform_id, move(options_record));
+}
+
+void PageClient::rtc_transform_teardown(Web::HTML::WorkerAgentId agent_id, u64 transform_id)
+{
+ client().async_rtc_transform_teardown(m_id, agent_id, transform_id);
+}
+
+void PageClient::rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ client().async_rtc_transform_encoded_audio_frame(m_id, agent_id, transform_id, payload.bytes(), ssrc, payload_type, rtp_timestamp, sequence_number);
+}
+
void PageClient::page_did_mutate_dom(Utf16FlyString const& type, Web::DOM::Node const& target, Web::DOM::NodeList& added_nodes, Web::DOM::NodeList& removed_nodes, GC::Ptr<Web::DOM::Node>, GC::Ptr<Web::DOM::Node>, Optional<Utf16FlyString> const& attribute_name)
{
Optional<WebView::Mutation::Type> mutation;
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 8360e6c9ed4..05713d531bb 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -406,6 +406,9 @@ private:
virtual void reset_gamepad_access_for_testing() override;
virtual Web::HTML::WorkerAgentId start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;
virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;
+ virtual void rtc_transform_init(Web::HTML::WorkerAgentId, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) override;
+ virtual void rtc_transform_teardown(Web::HTML::WorkerAgentId, u64 transform_id) override;
+ virtual void rtc_transform_encoded_audio_frame(Web::HTML::WorkerAgentId, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;
virtual void page_did_mutate_dom(Utf16FlyString const& type, Web::DOM::Node const& target, Web::DOM::NodeList& added_nodes, Web::DOM::NodeList& removed_nodes, GC::Ptr<Web::DOM::Node> previous_sibling, GC::Ptr<Web::DOM::Node> next_sibling, Optional<Utf16FlyString> const& attribute_name) override;
virtual void flush_pending_dom_mutations() override;
virtual void page_did_change_accessibility_tree() override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index cde41596d2f..8e73a1f51ce 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -201,6 +201,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_lose_request_server_connection(Optional<Utf16String> top_level_site) => (Optional<IPC::TransportHandle> handle)
request_media_server_connection() => (Optional<IPC::TransportHandle> handle)
request_audio_server_connection() => (Optional<IPC::TransportHandle> handle)
+ request_webrtc_client_connection() => (Optional<IPC::TransportHandle> handle)
request_video_presentation_channel() =|
[NotRouted] did_request_storage_usage(Web::PageId page_id, Web::HTML::EnvironmentId environment_id) => (u64 usage)
@@ -315,4 +316,7 @@ endpoint WebContentClient routed by Web::PageId page_id
[NotRouted] start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id)
close_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|
+ rtc_transform_init(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id, Web::HTML::SerializedTransferRecord options_record) =|
+ rtc_transform_teardown(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id) =|
+ rtc_transform_encoded_audio_frame(Web::PageId page_id, Web::HTML::WorkerAgentId agent_id, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|
}
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 472b10e3dda..e53de9bf988 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -331,6 +331,7 @@ endpoint WebContentServer routed by Web::PageId page_id
did_worker_agent_report_content_security_policy_violation(Web::HTML::WorkerAgentOwnerToken owner_token, u64 policy_index, String effective_directive, URL::URL resource) =|
did_worker_agent_close(Web::HTML::WorkerAgentOwnerToken owner_token) =|
did_worker_agent_die(Web::HTML::WorkerAgentOwnerToken owner_token) =|
+ did_worker_rtc_transform_encoded_audio_frame_written(Web::HTML::WorkerAgentOwnerToken owner_token, u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|
request_close(Web::PageId page_id) =|
request_close_preflight(Web::PageId page_id, u64 request_id) =|
diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cpp
index 74ecedcc98b..ec212309a40 100644
--- a/Services/WebContent/main.cpp
+++ b/Services/WebContent/main.cpp
@@ -40,6 +40,7 @@
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Platform/RemoteImageCodecPlugin.h>
+#include <LibWeb/WebRTC/WebRTCAgent.h>
#include <LibWebCommon/WebView/Utilities.h>
#include <Services/RendererSandbox.h>
#include <WebContent/ConnectionFromClient.h>
@@ -311,6 +312,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
Audio::ClientConnection::set_transport_factory([webcontent_client] {
return webcontent_client->request_audio_server_transport();
});
+ // The sandbox keeps this process from spawning the WebRTC helper, so the Browser launches one for it.
+ Web::WebRTC::WebRTCAgent::set_transport_factory([webcontent_client] {
+ return webcontent_client->request_webrtc_client_transport();
+ });
if (stats_log) {
stats_log->start_sampling([&heap](JsonObject& values) {
diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cpp
index 2ffcc212106..15710bfa40c 100644
--- a/Services/WebWorker/ConnectionFromClient.cpp
+++ b/Services/WebWorker/ConnectionFromClient.cpp
@@ -4,17 +4,34 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Debug.h>
#include <LibCompositing/FontServiceClient.h>
+#include <LibCore/EventLoop.h>
#include <LibCore/Process.h>
+#include <LibGC/Function.h>
+#include <LibJS/Runtime/ArrayBuffer.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/Compositor/CompositorConnection.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/FileAPI/BlobURLStore.h>
#include <LibWeb/HTML/BroadcastChannel.h>
+#include <LibWeb/HTML/EventLoop/EventLoop.h>
+#include <LibWeb/HTML/EventLoop/Task.h>
+#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/WorkerAgentParent.h>
+#include <LibWeb/HTML/WorkerGlobalScope.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/LoaderConfig.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/PermissionsAPI/PermissionStore.h>
#include <LibWeb/Platform/FontPlugin.h>
+#include <LibWeb/WebRTC/RTCEncodedAudioFrame.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransformer.h>
+#include <LibWeb/WebRTC/RTCTransformEvent.h>
#include <WebWorker/ConnectionFromClient.h>
#include <WebWorker/PageHost.h>
#include <WebWorker/WorkerHost.h>
@@ -177,6 +194,12 @@ void ConnectionFromClient::start_worker(URL::URL url, Web::HTML::WorkerType type
// FIXME: Add an assertion that the agent_type passed here is the same that was passed at process creation to initialize_main_thread_vm()
+ m_worker_host->set_on_script_ready([this] {
+ auto pending = move(m_pending_transform_inits);
+ for (auto& entry : pending)
+ run_transform_init(entry.key, move(entry.value));
+ });
+
m_worker_host->run(page(), move(implicit_port), outside_settings, credentials, is_shared, move(origin), move(environment_id));
}
@@ -227,4 +250,110 @@ void ConnectionFromClient::broadcast_channel_message(Web::HTML::BroadcastChannel
Web::HTML::deliver_broadcast_channel_message_locally(move(message));
}
+void ConnectionFromClient::rtc_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record)
+{
+ if (!m_worker_host)
+ return;
+ if (!m_worker_host->script_has_run()) {
+ // Wait for the worker script to install onrtctransform so the event is not dropped.
+ m_pending_transform_inits.set(transform_id, move(options_record));
+ return;
+ }
+ run_transform_init(transform_id, move(options_record));
+}
+
+void ConnectionFromClient::rtc_transform_teardown(u64 transform_id)
+{
+ m_pending_transform_inits.remove(transform_id);
+
+ // The worker's script may hold on to the transformer, but nothing it writes has anywhere to go anymore.
+ if (auto transformer = m_transformers.take(transform_id); transformer.has_value())
+ (*transformer)->set_write_encoded_data_algorithm(nullptr);
+}
+
+void ConnectionFromClient::run_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record)
+{
+ if (!m_worker_host)
+ return;
+ auto global_scope = m_worker_host->global_scope();
+ if (!global_scope) {
+ dbgln("ConnectionFromClient::rtc_transform_init: no worker global scope yet (transform_id={})", transform_id);
+ return;
+ }
+ auto& realm = Web::HTML::relevant_realm(*global_scope);
+ Web::HTML::TemporaryExecutionContext context(realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
+
+ // Spec step 8.1: deserialize serializedOptions in the worker realm.
+ auto deserialized_or_err = Web::HTML::structured_deserialize_with_transfer(options_record, realm);
+ if (deserialized_or_err.is_exception()) {
+ dbgln("ConnectionFromClient::rtc_transform_init: failed to deserialize options for id={}", transform_id);
+ return;
+ }
+ auto options = deserialized_or_err.release_value().deserialized;
+
+ // Spec step 8.2: create an RTCRtpScriptTransformer with the deserialized options.
+ auto transformer_or_err = Web::WebRTC::RTCRtpScriptTransformer::create(realm, options);
+ if (transformer_or_err.is_exception()) {
+ dbgln("ConnectionFromClient::rtc_transform_init: failed to construct transformer for id={}", transform_id);
+ return;
+ }
+ auto transformer = transformer_or_err.release_value();
+ m_transformers.set(transform_id, GC::make_root(transformer));
+
+ // Return transformed frames to the parent over IPC. Capturing `this` is safe because
+ // the connection outlives the transformer; close_worker tears it down via die().
+ auto write_encoded_data = GC::create_function(realm.heap(), [this, transform_id](JS::Value chunk) {
+ auto* frame = chunk.is_object() ? Web::Bindings::impl_from<Web::WebRTC::RTCEncodedAudioFrame>(&chunk.as_object()) : nullptr;
+ if (!frame) {
+ dbgln_if(WEBRTC_DEBUG, "worker: write algorithm got non-frame value (chunk_is_object={}, class={}) for id={}",
+ chunk.is_object(),
+ chunk.is_object() ? chunk.as_object().class_name() : "n/a"sv,
+ transform_id);
+ return;
+ }
+ dbgln_if(WEBRTC_DEBUG, "worker: write algorithm received frame id={}", transform_id);
+ auto data = frame->data();
+ auto bytes = data->copy_to_byte_buffer(0, data->byte_length()).release_value_but_fixme_should_propagate_errors();
+ auto metadata = frame->get_metadata();
+ u32 ssrc = metadata.synchronization_source.value_or(0);
+ u8 payload_type = metadata.payload_type.value_or(0);
+ u32 rtp_timestamp = metadata.rtp_timestamp.value_or(0);
+ u16 sequence_number = static_cast<u16>(metadata.sequence_number.value_or(0));
+ async_rtc_transform_encoded_audio_frame_written(transform_id, bytes.bytes(), ssrc, payload_type, rtp_timestamp, sequence_number);
+ });
+ transformer->set_write_encoded_data_algorithm(write_encoded_data);
+
+ // Spec step 8: queue a global task on the DOM manipulation task source so the
+ // event fires on the worker's own event loop, after any pending script setup
+ // (e.g. `self.onrtctransform = ...`) has had a chance to run.
+ Web::HTML::queue_global_task(Web::HTML::Task::Source::DOMManipulation, Web::HTML::relevant_global_object(*global_scope),
+ GC::create_function(realm.heap(), [global_scope, transformer, &realm] {
+ Web::HTML::TemporaryExecutionContext context(realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
+ auto event = Web::WebRTC::RTCTransformEvent::create(Web::HTML::EventNames::rtctransform, transformer,
+ Web::HighResolutionTime::current_high_resolution_time(Web::HTML::relevant_global_object(*global_scope)));
+ global_scope->dispatch_event(event);
+ }));
+}
+
+void ConnectionFromClient::rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number)
+{
+ auto entry = m_transformers.get(transform_id);
+ if (!entry.has_value()) {
+ dbgln_if(WEBRTC_DEBUG, "worker: rtc_transform_encoded_audio_frame for unknown id={} (have {} transformers)", transform_id, m_transformers.size());
+ return;
+ }
+ auto transformer = *entry;
+ dbgln_if(WEBRTC_DEBUG, "worker: rtc_transform_encoded_audio_frame id={} ssrc={} seq={} len={}", transform_id, ssrc, sequence_number, payload.size());
+
+ if (!m_worker_host || !m_worker_host->global_scope())
+ return;
+ auto& realm = Web::HTML::relevant_realm(*m_worker_host->global_scope());
+ Web::HTML::TemporaryExecutionContext context(realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
+
+ auto frame = Web::WebRTC::RTCEncodedAudioFrame::create_from_packet(realm, move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
+ auto wrapped_frame = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, frame);
+ if (auto result = transformer->enqueue_encoded_frame(wrapped_frame); result.is_exception())
+ dbgln_if(WEBRTC_DEBUG, "rtc_transform_encoded_audio_frame: enqueue failed for transform_id={}", transform_id);
+}
+
}
diff --git a/Services/WebWorker/ConnectionFromClient.h b/Services/WebWorker/ConnectionFromClient.h
index 6aac41b95c6..2eb9df814fc 100644
--- a/Services/WebWorker/ConnectionFromClient.h
+++ b/Services/WebWorker/ConnectionFromClient.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/ByteBuffer.h>
#include <AK/HashMap.h>
#include <AK/Utf16String.h>
#include <LibGC/Root.h>
@@ -13,6 +14,7 @@
#include <LibJS/Forward.h>
#include <LibWeb/Forward.h>
#include <LibWeb/Loader/FileRequest.h>
+#include <LibWeb/WebRTC/RTCRtpScriptTransformer.h>
#include <LibWebCommon/Forward.h>
#include <LibWebCommon/HTML/BroadcastChannelMessage.h>
#include <LibWebCommon/HTML/WorkerAgentTypes.h>
@@ -74,6 +76,9 @@ private:
virtual void did_worker_agent_close(Web::HTML::WorkerAgentOwnerToken owner_token) override;
virtual void did_worker_agent_die(Web::HTML::WorkerAgentOwnerToken owner_token) override;
virtual void broadcast_channel_message(Web::HTML::BroadcastChannelMessage message) override;
+ virtual void rtc_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record) override;
+ virtual void rtc_transform_teardown(u64 transform_id) override;
+ virtual void rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) override;
GC::Root<PageHost> m_page_host;
@@ -84,6 +89,11 @@ private:
HashMap<int, Web::FileRequest> m_requested_files {};
int last_id { 0 };
+ HashMap<u64, GC::Root<Web::WebRTC::RTCRtpScriptTransformer>> m_transformers;
+ HashMap<u64, Web::HTML::SerializedTransferRecord> m_pending_transform_inits;
+
+ void run_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record);
+
RefPtr<WorkerHost> m_worker_host;
Function<void()> m_request_server_died_callback_for_testing;
bool m_enable_test_mode { false };
diff --git a/Services/WebWorker/WebWorkerClient.ipc b/Services/WebWorker/WebWorkerClient.ipc
index 251c0dbe43c..b1662cd0022 100644
--- a/Services/WebWorker/WebWorkerClient.ipc
+++ b/Services/WebWorker/WebWorkerClient.ipc
@@ -27,4 +27,6 @@ endpoint WebWorkerClient {
did_post_broadcast_channel_message(Web::HTML::PostedBroadcastChannelMessage message) =|
start_worker_agent(Web::HTML::WorkerAgentStartRequest request) => (Web::HTML::WorkerAgentId agent_id)
close_worker_agent(Web::HTML::WorkerAgentId agent_id, Web::HTML::WorkerAgentOwnerToken owner_token) =|
+
+ rtc_transform_encoded_audio_frame_written(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|
}
diff --git a/Services/WebWorker/WebWorkerServer.ipc b/Services/WebWorker/WebWorkerServer.ipc
index a9270b470c4..28ee0610f99 100644
--- a/Services/WebWorker/WebWorkerServer.ipc
+++ b/Services/WebWorker/WebWorkerServer.ipc
@@ -51,4 +51,8 @@ endpoint WebWorkerServer {
handle_file_return(i32 error, Optional<IPC::File> file, i32 request_id) =|
blob_url_entry_removed(Utf16String url) =|
+
+ rtc_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record) =|
+ rtc_transform_teardown(u64 transform_id) =|
+ rtc_transform_encoded_audio_frame(u64 transform_id, ByteBuffer payload, u32 ssrc, u8 payload_type, u32 rtp_timestamp, u16 sequence_number) =|
}
diff --git a/Services/WebWorker/WorkerHost.cpp b/Services/WebWorker/WorkerHost.cpp
index 8bed86542f0..f4d8c9c60a2 100644
--- a/Services/WebWorker/WorkerHost.cpp
+++ b/Services/WebWorker/WorkerHost.cpp
@@ -45,6 +45,13 @@ WorkerHost::WorkerHost(URL::URL url, Web::HTML::WorkerType type, String name)
WorkerHost::~WorkerHost() = default;
+void WorkerHost::notify_script_ran()
+{
+ m_script_has_run = true;
+ if (auto callback = move(m_on_script_ready))
+ callback();
+}
+
// https://html.spec.whatwg.org/multipage/workers.html#relevant-owner-to-add
static Web::HTML::WorkerGlobalScope::Owner relevant_owner_to_add(Web::HTML::SerializedEnvironmentSettingsObject const& outside_settings)
{
@@ -291,6 +298,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes
(void)classic_script->run();
else
(void)as<Web::HTML::ModuleScript>(*script).run();
+ protected_this->notify_script_ran();
as<WebWorker::PageHost>(page->client()).did_finish_loading_worker_script(Web::HTML::is_secure_context(*inside_settings));
diff --git a/Services/WebWorker/WorkerHost.h b/Services/WebWorker/WorkerHost.h
index 271d7f7a029..c8a9b3851f3 100644
--- a/Services/WebWorker/WorkerHost.h
+++ b/Services/WebWorker/WorkerHost.h
@@ -17,6 +17,12 @@
#include <LibWeb/HTML/WorkerGlobalScope.h>
#include <LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h>
+namespace Web::HTML {
+
+class WorkerGlobalScope;
+
+}
+
namespace WebWorker {
class WorkerHost : public RefCounted<WorkerHost> {
@@ -27,6 +33,14 @@ public:
void run(GC::Ref<Web::Page>, Web::HTML::TransferDataEncoder message_port_data, Web::HTML::SerializedEnvironmentSettingsObject const&, Web::HTML::RequestCredentials, bool is_shared, URL::Origin origin, Web::HTML::EnvironmentId environment_id);
void connect_shared_worker(Web::HTML::TransferDataEncoder message_port_data, Web::HTML::SerializedEnvironmentSettingsObject);
+ GC::Ptr<Web::HTML::WorkerGlobalScope> global_scope() { return m_worker_global_scope.cell(); }
+
+ bool script_has_run() const { return m_script_has_run; }
+ void set_on_script_ready(Function<void()> callback) { m_on_script_ready = move(callback); }
+
+ // Called from WorkerHost::run's on_complete callback once the initial script has executed.
+ void notify_script_ran();
+
private:
struct PendingSharedWorkerConnection {
Web::HTML::TransferDataEncoder message_port_data;
@@ -52,6 +66,9 @@ private:
bool m_accepting_shared_worker_connections { false };
// WorkerHost is only touched on the WebWorker main thread.
Vector<PendingSharedWorkerConnection> m_pending_shared_worker_connections;
+
+ bool m_script_has_run { false };
+ Function<void()> m_on_script_ready;
};
}
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 3b829f40e50..33fd332f59d 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -8,6 +8,10 @@ Text/input/wpt-import/custom-elements/connected-callbacks.html
Text/input/wpt-import/html/rendering/replaced-elements/attributes-for-embedded-content-and-images/picture-aspect-ratio.html
; Permissions are kept for a site's origin, and a file: page has none.
Text/input/PermissionsAPI/
+Text/input/WebRTC/audio-loopback.html
+Text/input/WebRTC/data-channel-loopback.html
+Text/input/WebRTC/script-transform-roundtrip.html
+Text/input/WebRTC/track-event-transceiver.html
Text/input/wpt-import/geolocation/
Text/input/wpt-import/permissions/
; A stored notifications grant needs a site origin.
diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
index 4b3ef467185..8bd752658e4 100644
--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
@@ -26,7 +26,9 @@
#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebIDL/ExceptionOrUtils.h>
#include <LibWeb/WebIDL/QuotaExceededError.h>
+#include <LibWeb/WebRTC/RTCEncodedAudioFrame.h>
#if !defined(AK_OS_WINDOWS)
# include <fcntl.h>
@@ -937,3 +939,95 @@ TEST_CASE(serializable_payload_version_bumps_require_migration_support)
for (auto const& entry : Web::HTML::serializable_storage_registry())
EXPECT(!entry.identifier.is_empty());
}
+
+TEST_CASE(rtc_encoded_audio_frame_serialization_preserves_metadata_and_buffer_identity)
+{
+ auto& realm = test_realm();
+ auto& vm = realm.vm();
+ Array<u8, 4> payload { 0x12, 0x34, 0x56, 0x78 };
+ auto data = JS::ArrayBuffer::create(realm, MUST(ByteBuffer::copy(payload)));
+ Web::Bindings::RTCEncodedAudioFrameMetadata metadata;
+ metadata.synchronization_source = 0xfedcba98;
+ metadata.payload_type = 111;
+ metadata.contributing_sources = Vector<u32> { 0, 0xffffffff };
+ metadata.rtp_timestamp = 0x87654321;
+ metadata.receive_time = 1234.5;
+ metadata.capture_time = 1200.25;
+ metadata.sender_capture_time_offset = -34.25;
+ metadata.mime_type = "audio/opus; test=🎵"_utf16;
+ metadata.sequence_number = -1234;
+ metadata.audio_level = 0.5;
+ auto frame = Web::WebRTC::RTCEncodedAudioFrame::create(data, metadata);
+ auto wrapper = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, frame);
+ auto array = MUST(JS::Array::create(realm, 0));
+ MUST(array->create_data_property_or_throw(0, wrapper));
+ MUST(array->create_data_property_or_throw(1, data));
+ MUST(array->create_data_property_or_throw(2, wrapper));
+
+ auto record = MUST(Web::HTML::structured_serialize(vm, array));
+ auto clone = MUST(Web::HTML::structured_deserialize(vm, ipc_round_trip(record), realm));
+ auto cloned_frame_value = MUST(clone.as_object().get(0));
+ auto& cloned_frame = unwrap_wrappable<Web::WebRTC::RTCEncodedAudioFrame>(cloned_frame_value);
+ EXPECT(&cloned_frame != frame.ptr());
+ EXPECT(cloned_frame.data().ptr() != data.ptr());
+ auto cloned_payload = MUST(cloned_frame.data()->copy_to_byte_buffer());
+ EXPECT_EQ(cloned_payload.bytes(), payload.span());
+ EXPECT(cloned_frame.data().ptr() == &MUST(clone.as_object().get(1)).as_object());
+ EXPECT_EQ(cloned_frame_value, MUST(clone.as_object().get(2)));
+ auto cloned_metadata = cloned_frame.get_metadata();
+ EXPECT_EQ(cloned_metadata.synchronization_source, metadata.synchronization_source);
+ EXPECT_EQ(cloned_metadata.payload_type, metadata.payload_type);
+ EXPECT_EQ(cloned_metadata.contributing_sources, metadata.contributing_sources);
+ EXPECT_EQ(cloned_metadata.rtp_timestamp, metadata.rtp_timestamp);
+ EXPECT_EQ(cloned_metadata.receive_time, metadata.receive_time);
+ EXPECT_EQ(cloned_metadata.capture_time, metadata.capture_time);
+ EXPECT_EQ(cloned_metadata.sender_capture_time_offset, metadata.sender_capture_time_offset);
+ EXPECT_EQ(cloned_metadata.mime_type, metadata.mime_type);
+ EXPECT_EQ(cloned_metadata.sequence_number, metadata.sequence_number);
+ EXPECT_EQ(cloned_metadata.audio_level, metadata.audio_level);
+}
+
+TEST_CASE(rtc_encoded_audio_frame_serialization_preserves_missing_and_empty_metadata)
+{
+ auto& realm = test_realm();
+ auto& vm = realm.vm();
+ for (bool present : { false, true }) {
+ Web::Bindings::RTCEncodedAudioFrameMetadata metadata;
+ if (present) {
+ metadata.contributing_sources = Vector<u32> {};
+ metadata.mime_type = Utf16String {};
+ metadata.sequence_number = 0;
+ }
+ auto frame = Web::WebRTC::RTCEncodedAudioFrame::create(MUST(JS::ArrayBuffer::create(realm, 0)), metadata);
+ auto record = structured_serialize(vm, frame);
+ auto clone = MUST(Web::HTML::structured_deserialize(vm, record, realm));
+ auto& cloned_frame = unwrap_wrappable<Web::WebRTC::RTCEncodedAudioFrame>(clone);
+ auto cloned_metadata = cloned_frame.get_metadata();
+ EXPECT_EQ(cloned_metadata.contributing_sources, metadata.contributing_sources);
+ EXPECT_EQ(cloned_metadata.mime_type, metadata.mime_type);
+ EXPECT_EQ(cloned_metadata.sequence_number, metadata.sequence_number);
+ EXPECT(!cloned_metadata.synchronization_source.has_value());
+ EXPECT(!cloned_metadata.payload_type.has_value());
+ EXPECT(!cloned_metadata.rtp_timestamp.has_value());
+ EXPECT(!cloned_metadata.receive_time.has_value());
+ EXPECT(!cloned_metadata.capture_time.has_value());
+ EXPECT(!cloned_metadata.sender_capture_time_offset.has_value());
+ EXPECT(!cloned_metadata.audio_level.has_value());
+ EXPECT_EQ(cloned_frame.data()->byte_length(), 0u);
+ }
+}
+
+TEST_CASE(rtc_encoded_audio_frame_cannot_be_serialized_for_storage)
+{
+ auto& realm = test_realm();
+ auto frame = Web::WebRTC::RTCEncodedAudioFrame::create(MUST(JS::ArrayBuffer::create(realm, 0)), {});
+ auto wrapper = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, frame);
+ auto result = Web::WebIDL::throw_dom_exception_if_needed(realm.vm(), realm, [&] {
+ return Web::HTML::structured_serialize_for_storage(realm.vm(), wrapper);
+ });
+ EXPECT(result.is_error());
+ if (result.is_error()) {
+ auto& exception = unwrap_wrappable<Web::WebIDL::DOMException>(result.error_value());
+ EXPECT_EQ(exception.name(), "DataCloneError"_utf16);
+ }
+}
diff --git a/Tests/LibWeb/Text/expected/WebRTC/audio-loopback.txt b/Tests/LibWeb/Text/expected/WebRTC/audio-loopback.txt
new file mode 100644
index 00000000000..f7e1922671b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/audio-loopback.txt
@@ -0,0 +1,2 @@
+remote track kind: audio
+audio packets received: true
diff --git a/Tests/LibWeb/Text/expected/WebRTC/data-channel-loopback.txt b/Tests/LibWeb/Text/expected/WebRTC/data-channel-loopback.txt
new file mode 100644
index 00000000000..8f177d4985a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/data-channel-loopback.txt
@@ -0,0 +1,9 @@
+offer pending: true
+negotiated: true
+trickle ICE: true
+remote label: echo
+text payload: hello 🐦
+binary payload: 0,1,127,255
+blob payload: true
+real stats report: true
+channel close: closed
diff --git a/Tests/LibWeb/Text/expected/WebRTC/document-cleanup.txt b/Tests/LibWeb/Text/expected/WebRTC/document-cleanup.txt
new file mode 100644
index 00000000000..9ffdbf7be8f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/document-cleanup.txt
@@ -0,0 +1,2 @@
+connection after document cleanup: closed
+ended events during document cleanup: 0
diff --git a/Tests/LibWeb/Text/expected/WebRTC/events-and-lifecycle.txt b/Tests/LibWeb/Text/expected/WebRTC/events-and-lifecycle.txt
new file mode 100644
index 00000000000..a864c684a2a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/events-and-lifecycle.txt
@@ -0,0 +1,8 @@
+candidate roundtrip: true
+candidate identity: true
+end of candidates: true
+configuration retained: true
+channel attributes: test, false, 2, echo, true, 0, arraybuffer
+channel event identity: true
+closed: closed, closed, closed, closed
+all transceivers stopped: true
diff --git a/Tests/LibWeb/Text/expected/WebRTC/host-candidates-hide-local-addresses.txt b/Tests/LibWeb/Text/expected/WebRTC/host-candidates-hide-local-addresses.txt
new file mode 100644
index 00000000000..a4d9e905c08
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/host-candidates-hide-local-addresses.txt
@@ -0,0 +1,3 @@
+gathered host candidates: true
+every host candidate is an mDNS name: true
+the description has no IPv4 host candidates: true
diff --git a/Tests/LibWeb/Text/expected/WebRTC/replace-track.txt b/Tests/LibWeb/Text/expected/WebRTC/replace-track.txt
new file mode 100644
index 00000000000..09428f27ba5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/replace-track.txt
@@ -0,0 +1,6 @@
+SSRC available immediately: true
+replacement selected: true
+sender identity retained: true
+detached: true
+replace after stop: InvalidStateError
+replace after close: InvalidStateError
diff --git a/Tests/LibWeb/Text/expected/WebRTC/script-transform-reuse.txt b/Tests/LibWeb/Text/expected/WebRTC/script-transform-reuse.txt
new file mode 100644
index 00000000000..8b5a5986756
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/script-transform-reuse.txt
@@ -0,0 +1,4 @@
+attached: true
+same sender: InvalidStateError
+other sender: InvalidStateError
+after replacement: InvalidStateError
diff --git a/Tests/LibWeb/Text/expected/WebRTC/script-transform-roundtrip.txt b/Tests/LibWeb/Text/expected/WebRTC/script-transform-roundtrip.txt
new file mode 100644
index 00000000000..3e6f620f743
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/script-transform-roundtrip.txt
@@ -0,0 +1 @@
+frames written back: 5
diff --git a/Tests/LibWeb/Text/expected/WebRTC/track-event-transceiver.txt b/Tests/LibWeb/Text/expected/WebRTC/track-event-transceiver.txt
new file mode 100644
index 00000000000..a57f5781676
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/track-event-transceiver.txt
@@ -0,0 +1,2 @@
+track on sending transceiver: false
+track on receiving transceiver: true
diff --git a/Tests/LibWeb/Text/expected/all-window-properties.txt b/Tests/LibWeb/Text/expected/all-window-properties.txt
index dfce470327e..dfd1dd3d8cc 100644
--- a/Tests/LibWeb/Text/expected/all-window-properties.txt
+++ b/Tests/LibWeb/Text/expected/all-window-properties.txt
@@ -392,6 +392,31 @@ ProgressEvent
Promise
PromiseRejectionEvent
QuotaExceededError
+RTCCertificate
+RTCDTMFSender
+RTCDTMFToneChangeEvent
+RTCDataChannel
+RTCDataChannelEvent
+RTCDtlsTransport
+RTCEncodedAudioFrame
+RTCEncodedVideoFrame
+RTCError
+RTCErrorEvent
+RTCIceCandidate
+RTCIceTransport
+RTCPeerConnection
+RTCPeerConnectionIceErrorEvent
+RTCPeerConnectionIceEvent
+RTCRtpReceiver
+RTCRtpScriptTransform
+RTCRtpSender
+RTCRtpTransceiver
+RTCSFrameReceiverTransform
+RTCSFrameSenderTransform
+RTCSctpTransport
+RTCSessionDescription
+RTCStatsReport
+RTCTrackEvent
RadioNodeList
Range
RangeError
@@ -408,6 +433,9 @@ ResizeObserver
ResizeObserverEntry
ResizeObserverSize
Response
+SFrameDecrypterStream
+SFrameEncrypterStream
+SFrameTransformErrorEvent
SVGAElement
SVGAngle
SVGAnimateElement
diff --git a/Tests/LibWeb/Text/input/WebRTC/audio-loopback.html b/Tests/LibWeb/Text/input/WebRTC/audio-loopback.html
new file mode 100644
index 00000000000..a440eb5906c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/audio-loopback.html
@@ -0,0 +1,42 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+asyncTest(async done => {
+ // Use numeric host candidates so this loopback test does not depend on mDNS multicast.
+ await internals.setPermission("microphone", "granted");
+ const a = new RTCPeerConnection();
+ const b = new RTCPeerConnection();
+ a.onicecandidate = event => event.candidate && b.addIceCandidate(event.candidate).catch(() => {});
+ b.onicecandidate = event => event.candidate && a.addIceCandidate(event.candidate).catch(() => {});
+ const context = new AudioContext();
+ const oscillator = context.createOscillator();
+ const destination = context.createMediaStreamDestination();
+ oscillator.connect(destination);
+ oscillator.start();
+ const track = new Promise(resolve => b.ontrack = event => resolve(event.track));
+ try {
+ a.addTrack(destination.stream.getAudioTracks()[0], destination.stream);
+ await a.setLocalDescription(await a.createOffer());
+ await b.setRemoteDescription(a.localDescription);
+ await b.setLocalDescription(await b.createAnswer());
+ await a.setRemoteDescription(b.localDescription);
+ println(`remote track kind: ${(await track).kind}`);
+ // The sender encodes 20ms Opus frames; wait until some of them have made it across.
+ let received = 0;
+ for (let attempt = 0; attempt < 100 && received === 0; ++attempt) {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ const stats = await b.getStats();
+ for (const entry of stats.values()) {
+ if (entry.type === "inbound-rtp" && entry.kind === "audio")
+ received = entry.packetsReceived ?? 0;
+ }
+ }
+ println(`audio packets received: ${received > 0}`);
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ oscillator.stop();
+ a.close(); b.close(); context.close(); done();
+ }
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/data-channel-loopback.html b/Tests/LibWeb/Text/input/WebRTC/data-channel-loopback.html
new file mode 100644
index 00000000000..214f0f9693b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/data-channel-loopback.html
@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<script src="../include.js"></script>
+<script>
+asyncTest(async done => {
+ // Use numeric host candidates so this loopback test does not depend on mDNS multicast.
+ await internals.setPermission("microphone", "granted");
+ const a = new RTCPeerConnection();
+ const b = new RTCPeerConnection();
+ const pendingA = [], pendingB = [];
+ let candidateCount = 0;
+ function forward(peer, queue, event) {
+ if (!event.candidate) return;
+ ++candidateCount;
+ if (peer.remoteDescription) peer.addIceCandidate(event.candidate).catch(error => println(`ICE error: ${error.name}`));
+ else queue.push(event.candidate);
+ }
+ a.onicecandidate = event => forward(b, pendingB, event);
+ b.onicecandidate = event => forward(a, pendingA, event);
+ const channel = a.createDataChannel("echo");
+ const opened = new Promise(resolve => channel.onopen = resolve);
+ const incoming = new Promise(resolve => b.ondatachannel = event => resolve(event.channel));
+ try {
+ const offer = await a.createOffer();
+ await a.setLocalDescription(offer);
+ println(`offer pending: ${a.currentLocalDescription === null && a.pendingLocalDescription.type === "offer"}`);
+ await b.setRemoteDescription(offer);
+ for (const candidate of pendingB) await b.addIceCandidate(candidate);
+ const answer = await b.createAnswer();
+ await b.setLocalDescription(answer);
+ await a.setRemoteDescription(answer);
+ for (const candidate of pendingA) await a.addIceCandidate(candidate);
+ await opened;
+ const remote = await incoming;
+ println(`negotiated: ${a.pendingLocalDescription === null && a.currentLocalDescription.type === "offer" && a.currentRemoteDescription.type === "answer"}`);
+ println(`trickle ICE: ${candidateCount > 0}`);
+ println(`remote label: ${remote.label}`);
+ let message = new Promise(resolve => remote.onmessage = resolve);
+ channel.send("hello 🐦");
+ println(`text payload: ${(await message).data}`);
+ message = new Promise(resolve => remote.onmessage = resolve);
+ channel.send(new Uint8Array([0, 1, 127, 255]));
+ println(`binary payload: ${Array.from(new Uint8Array((await message).data))}`);
+ remote.binaryType = "blob";
+ message = new Promise(resolve => remote.onmessage = resolve);
+ channel.send(new Uint8Array([42]));
+ const blob = (await message).data;
+ println(`blob payload: ${blob instanceof Blob && blob.size === 1}`);
+ const stats = await a.getStats();
+ println(`real stats report: ${stats instanceof RTCStatsReport && Array.from(stats.values()).some(entry => entry.type === "data-channel")}`);
+ const closed = new Promise(resolve => channel.onclose = resolve);
+ channel.close();
+ await closed;
+ println(`channel close: ${channel.readyState}`);
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ a.close(); b.close(); done();
+ }
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/document-cleanup.html b/Tests/LibWeb/Text/input/WebRTC/document-cleanup.html
new file mode 100644
index 00000000000..e14aaca4d55
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/document-cleanup.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<body>
+<script src="../include.js"></script>
+<script>
+asyncTest(async done => {
+ const frame = document.createElement("iframe");
+ const loaded = new Promise(resolve => frame.onload = resolve);
+ frame.srcdoc = "<!DOCTYPE html>";
+ document.body.append(frame);
+ await loaded;
+ const pc = new frame.contentWindow.RTCPeerConnection();
+ const transceiver = pc.addTransceiver("audio");
+ let endedEvents = 0;
+ transceiver.receiver.track.onended = () => ++endedEvents;
+ frame.remove();
+ for (let attempt = 0; attempt < 50 && pc.signalingState !== "closed"; ++attempt)
+ await new Promise(resolve => setTimeout(resolve, 20));
+ println(`connection after document cleanup: ${pc.signalingState}`);
+ println(`ended events during document cleanup: ${endedEvents}`);
+ done();
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/events-and-lifecycle.html b/Tests/LibWeb/Text/input/WebRTC/events-and-lifecycle.html
new file mode 100644
index 00000000000..18037f89675
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/events-and-lifecycle.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+test(() => {
+ const candidate = new RTCIceCandidate({ candidate: "candidate:1 1 udp 2122260223 127.0.0.1 12345 typ host", sdpMid: "audio", sdpMLineIndex: 0, usernameFragment: "ufrag" });
+ const roundtrip = candidate.toJSON();
+ println(`candidate roundtrip: ${roundtrip.candidate === candidate.candidate && roundtrip.sdpMid === "audio" && roundtrip.sdpMLineIndex === 0 && roundtrip.usernameFragment === "ufrag"}`);
+ const event = new RTCPeerConnectionIceEvent("icecandidate", { candidate });
+ println(`candidate identity: ${event.candidate === candidate}`);
+ println(`end of candidates: ${new RTCPeerConnectionIceEvent("icecandidate").candidate === null}`);
+
+ const pc = new RTCPeerConnection({ iceServers: [{ urls: "stun:localhost:3478" }], bundlePolicy: "max-bundle" });
+ println(`configuration retained: ${pc.getConfiguration().iceServers[0].urls === "stun:localhost:3478" && pc.getConfiguration().bundlePolicy === "max-bundle"}`);
+ const channel = pc.createDataChannel("test", { ordered: false, maxRetransmits: 2, protocol: "echo", negotiated: true, id: 0 });
+ println(`channel attributes: ${channel.label}, ${channel.ordered}, ${channel.maxRetransmits}, ${channel.protocol}, ${channel.negotiated}, ${channel.id}, ${channel.binaryType}`);
+ println(`channel event identity: ${new RTCDataChannelEvent("datachannel", { channel }).channel === channel}`);
+ const first = pc.addTransceiver("audio");
+ const second = pc.addTransceiver("audio");
+ first.stop();
+ pc.close();
+ pc.close();
+ println(`closed: ${pc.signalingState}, ${pc.connectionState}, ${pc.iceConnectionState}, ${channel.readyState}`);
+ println(`all transceivers stopped: ${first.direction === "inactive" && second.direction === "inactive"}`);
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/host-candidates-hide-local-addresses.html b/Tests/LibWeb/Text/input/WebRTC/host-candidates-hide-local-addresses.html
new file mode 100644
index 00000000000..ce2a7923214
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/host-candidates-hide-local-addresses.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+asyncTest(async done => {
+ const connection = new RTCPeerConnection();
+ const candidates = [];
+ const gathered = new Promise(resolve => {
+ connection.onicecandidate = event => {
+ if (event.candidate)
+ candidates.push(event.candidate);
+ else
+ resolve();
+ };
+ });
+ try {
+ connection.createDataChannel("test");
+ await connection.setLocalDescription(await connection.createOffer());
+ await gathered;
+ // candidate:<foundation> <component> <transport> <priority> <address> <port> typ <type>
+ const hosts = candidates.map(candidate => candidate.candidate.split(" ")).filter(fields => fields[7] === "host");
+ println(`gathered host candidates: ${hosts.length > 0}`);
+ println(`every host candidate is an mDNS name: ${hosts.every(fields => fields[4].endsWith(".local"))}`);
+ const description = connection.localDescription.sdp;
+ println(`the description has no IPv4 host candidates: ${!/a=candidate:\S+ \d+ udp \d+ \d+\.\d+\.\d+\.\d+ \d+ typ host/.test(description)}`);
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ connection.close();
+ done();
+ }
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/replace-track.html b/Tests/LibWeb/Text/input/WebRTC/replace-track.html
new file mode 100644
index 00000000000..9e0933de6c4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/replace-track.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+asyncTest(async done => {
+ const context = new AudioContext({ sampleRate: 44100 });
+ const first = context.createMediaStreamDestination();
+ const second = context.createMediaStreamDestination();
+ const pc = new RTCPeerConnection();
+ try {
+ const sender = pc.addTrack(first.stream.getAudioTracks()[0], first.stream);
+ const ssrc = sender.getParameters().encodings[0].ssrc;
+ await pc.createOffer();
+ println(`SSRC available immediately: ${ssrc === sender.getParameters().encodings[0].ssrc}`);
+ await sender.replaceTrack(second.stream.getAudioTracks()[0]);
+ await pc.createOffer();
+ println(`replacement selected: ${sender.track === second.stream.getAudioTracks()[0]}`);
+ println(`sender identity retained: ${pc.getSenders()[0] === sender && sender.getParameters().encodings[0].ssrc === ssrc}`);
+ await sender.replaceTrack(null);
+ println(`detached: ${sender.track === null}`);
+ pc.getTransceivers()[0].stop();
+ try { await sender.replaceTrack(first.stream.getAudioTracks()[0]); }
+ catch (error) { println(`replace after stop: ${error.name}`); }
+ pc.close();
+ try { await sender.replaceTrack(first.stream.getAudioTracks()[0]); }
+ catch (error) { println(`replace after close: ${error.name}`); }
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ pc.close(); await context.close(); done();
+ }
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/script-transform-reuse.html b/Tests/LibWeb/Text/input/WebRTC/script-transform-reuse.html
new file mode 100644
index 00000000000..ae92398d2d7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/script-transform-reuse.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+// A script transform belongs to the first sender or receiver it's set on, so one that's been replaced can't come back.
+test(() => {
+ const pc = new RTCPeerConnection();
+ const worker = new Worker(URL.createObjectURL(new Blob([""], { type: "text/javascript" })));
+ const [first, second] = [pc.addTransceiver("audio").sender, pc.addTransceiver("audio").sender];
+ const transform = new RTCRtpScriptTransform(worker);
+
+ first.transform = transform;
+ println(`attached: ${first.transform === transform}`);
+
+ for (const [description, attach] of [
+ ["same sender", () => first.transform = transform],
+ ["other sender", () => second.transform = transform],
+ ]) {
+ try {
+ attach();
+ println(`${description}: no exception`);
+ } catch (error) {
+ println(`${description}: ${error.name}`);
+ }
+ }
+
+ first.transform = new RTCRtpScriptTransform(worker);
+ try {
+ second.transform = transform;
+ println("after replacement: no exception");
+ } catch (error) {
+ println(`after replacement: ${error.name}`);
+ }
+
+ worker.terminate();
+ pc.close();
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/script-transform-roundtrip.html b/Tests/LibWeb/Text/input/WebRTC/script-transform-roundtrip.html
new file mode 100644
index 00000000000..2e390a933bd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/script-transform-roundtrip.html
@@ -0,0 +1,51 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+// Frames a receiver's script transform writes back have to reach the rest of the pipeline. Discord decrypts every
+// incoming frame this way, so a write that never completes means remote audio never plays.
+asyncTest(async done => {
+ // Use numeric host candidates so this loopback test does not depend on mDNS multicast.
+ await internals.setPermission("microphone", "granted");
+ const a = new RTCPeerConnection();
+ const b = new RTCPeerConnection();
+ a.onicecandidate = event => event.candidate && b.addIceCandidate(event.candidate).catch(() => {});
+ b.onicecandidate = event => event.candidate && a.addIceCandidate(event.candidate).catch(() => {});
+ const context = new AudioContext();
+ const oscillator = context.createOscillator();
+ const destination = context.createMediaStreamDestination();
+ oscillator.connect(destination);
+ oscillator.start();
+ const workerSource = `
+ onrtctransform = async event => {
+ const reader = event.transformer.readable.getReader();
+ const writer = event.transformer.writable.getWriter();
+ for (let written = 1; ; ++written) {
+ const { value, done } = await reader.read();
+ if (done)
+ return;
+ await writer.write(value);
+ if (written === 5)
+ postMessage({ written });
+ }
+ };
+ `;
+ const worker = new Worker(URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" })));
+ const written = new Promise(resolve => worker.onmessage = event => resolve(event.data.written));
+ b.ontrack = event => event.receiver.transform = new RTCRtpScriptTransform(worker);
+ try {
+ a.addTrack(destination.stream.getAudioTracks()[0], destination.stream);
+ await a.setLocalDescription(await a.createOffer());
+ await b.setRemoteDescription(a.localDescription);
+ await b.setLocalDescription(await b.createAnswer());
+ await a.setRemoteDescription(b.localDescription);
+ const result = await Promise.race([written, new Promise(resolve => setTimeout(() => resolve(0), 5000))]);
+ println(`frames written back: ${result}`);
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ oscillator.stop();
+ worker.terminate();
+ a.close(); b.close(); context.close(); done();
+ }
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/track-event-transceiver.html b/Tests/LibWeb/Text/input/WebRTC/track-event-transceiver.html
new file mode 100644
index 00000000000..02dde4d6b0d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/track-event-transceiver.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+// Like Discord: the page sends from its first audio transceiver and receives on a later recvonly one, so an incoming
+// track has to land on the transceiver the backend actually received it on rather than the first audio one.
+asyncTest(async done => {
+ // Use numeric host candidates so this loopback test does not depend on mDNS multicast.
+ await internals.setPermission("microphone", "granted");
+ const a = new RTCPeerConnection();
+ const b = new RTCPeerConnection();
+ a.onicecandidate = event => event.candidate && b.addIceCandidate(event.candidate).catch(() => {});
+ b.onicecandidate = event => event.candidate && a.addIceCandidate(event.candidate).catch(() => {});
+ const context = new AudioContext();
+ const oscillator = context.createOscillator();
+ const sentByA = context.createMediaStreamDestination();
+ const sentByB = context.createMediaStreamDestination();
+ oscillator.connect(sentByA);
+ oscillator.connect(sentByB);
+ oscillator.start();
+ const event = new Promise(resolve => a.ontrack = resolve);
+ try {
+ const sending = a.addTransceiver(sentByA.stream.getAudioTracks()[0], { direction: "sendonly" });
+ const receiving = a.addTransceiver("audio", { direction: "recvonly" });
+ b.addTransceiver("audio", { direction: "recvonly" });
+ b.addTransceiver(sentByB.stream.getAudioTracks()[0], { direction: "sendonly", streams: [sentByB.stream] });
+ await b.setLocalDescription(await b.createOffer());
+ await a.setRemoteDescription(b.localDescription);
+ await a.setLocalDescription(await a.createAnswer());
+ await b.setRemoteDescription(a.localDescription);
+ const { transceiver } = await event;
+ println(`track on sending transceiver: ${transceiver === sending}`);
+ println(`track on receiving transceiver: ${transceiver === receiving}`);
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ oscillator.stop();
+ a.close(); b.close(); context.close(); done();
+ }
+});
+</script>