Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(webcodecs): expose secure video encoder and decoder interface shells
ldm019f388b4f1ac
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rsindex 7cccbec62..a7944dc44 100644--- a/moli-renderer-v8/src/context_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap.rs@@ -191,6 +191,7 @@ mod touch_runtime;mod trusted_types;mod url_form;mod url_search_params_runtime;+mod video_codecs;mod view_transition_runtime;mod web_audio_runtime;mod web_storage;diff --git a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rsindex 13d15b5f7..b83455d29 100644--- a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs+++ b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs@@ -424,6 +424,11 @@ pub(super) fn install_constructor_template_bindings<'s>(}install_media_cue_template_bindings(scope, template, spec.interface.name());install_media_source_template_bindings(scope, template, spec.interface.name());+ super::super::video_codecs::install_video_codec_template_bindings(+ scope,+ template,+ spec.interface.name(),+ );install_message_port_template_bindings(scope, template, spec.interface.name());if spec.interface.name() == "BroadcastChannel" {install_broadcast_channel_template_bindings(scope, template);diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rsindex bfbd97a50..2cf928cf6 100644--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs@@ -65,6 +65,8 @@ pub(in crate::context_bootstrap) const WORKER_SHARED_INTERFACE_NAMES: &[&str] ="TextMetrics","OffscreenCanvas","OffscreenCanvasRenderingContext2D",+ "VideoDecoder",+ "VideoEncoder","WebGLRenderingContext","WebGL2RenderingContext","WebGLObject",@@ -125,6 +127,8 @@ const SECURE_CONTEXT_ONLY_INTERFACE_NAMES: &[&str] = &["ClipboardItem","Cache","CacheStorage",+ "VideoDecoder",+ "VideoEncoder",];const WORKER_ONLY_INTERFACE_NAMES: &[&str] = &["WorkerNavigator", "WorkerLocation"];const WINDOW_DEDICATED_AND_SHARED_WORKER_INTERFACE_NAMES: &[&str] = &[@@ -416,6 +420,7 @@ fn exposure_for_name(name: &str) -> ExposureSet {_ if DEDICATED_AND_SHARED_WORKER_INTERFACE_NAMES.contains(&name) => {ExposureSet::DEDICATED_AND_SHARED_WORKER}+ "VideoDecoder" | "VideoEncoder" => ExposureSet::WINDOW_AND_DEDICATED_WORKER,_ if WORKER_ONLY_INTERFACE_NAMES.contains(&name) => ExposureSet::WORKERS,_ if STORAGE_INTERFACE_NAMES.contains(&name)|| WORKER_SHARED_INTERFACE_NAMES.contains(&name)@@ -553,6 +558,32 @@ mod tests {assert!(!sync.is_exposed(RealmKind::SharedWorker, true));}+ #[test]+ fn shell_video_codecs_uses_the_expected_exposure_and_lazy_policy() {+ let table = ExposedInterfaceMetadataTable::from_constructor_specs(+ &crate::context_bootstrap::specs::constructor_specs(),+ )+ .expect("shell exposure metadata");+ for name in ["VideoDecoder", "VideoEncoder"] {+ let metadata = table.metadata_by_name(name).expect("interface metadata");+ assert_eq!(metadata.installation, GlobalInstallation::Lazy, "{name}");+ for (realm, expected) in [+ (RealmKind::Window, true),+ (RealmKind::DedicatedWorker, true),+ (RealmKind::SharedWorker, false),+ (RealmKind::ServiceWorker, false),+ ] {+ assert_eq!(metadata.is_exposed(realm, true), expected, "{name}");+ assert!(!metadata.is_exposed(realm, false), "{name}");+ assert_eq!(+ metadata.is_supported_by(TemplateBuildProfile::for_realm(realm)),+ expected,+ "{name}"+ );+ }+ }+ }+#[test]fn shared_and_window_only_interface_exposure_is_explicit() {let table = ExposedInterfaceMetadataTable::from_constructor_specs(&[diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rsindex bd637dcac..9215e3a0d 100644--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs@@ -676,6 +676,14 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[interface: web_api_interfaces::MediaCapabilities::DESCRIPTOR,kind: ConstructorKind::Illegal,},+ ConstructorSpec {+ interface: web_api_interfaces::VideoDecoder::DESCRIPTOR,+ kind: ConstructorKind::Shell { length: 1 },+ },+ ConstructorSpec {+ interface: web_api_interfaces::VideoEncoder::DESCRIPTOR,+ kind: ConstructorKind::Shell { length: 1 },+ },ConstructorSpec {interface: web_api_interfaces::Touch::DESCRIPTOR,kind: ConstructorKind::Touch,diff --git a/moli-renderer-v8/src/context_bootstrap/video_codecs.rs b/moli-renderer-v8/src/context_bootstrap/video_codecs.rsnew file mode 100644index 000000000..4e0877f6a--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/video_codecs.rs@@ -0,0 +1,520 @@+use crate::{+ util::{v8_string, v8_string_from_utf16_units},+ web_api_interfaces, webidl,+};+use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject, WebApiValue};++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "HardwareAcceleration")]+enum HardwareAcceleration {+ #[webidl(token = "no-preference")]+ NoPreference,+ #[webidl(token = "prefer-hardware")]+ PreferHardware,+ #[webidl(token = "prefer-software")]+ PreferSoftware,+}+impl HardwareAcceleration {+ fn as_str(self) -> &'static str {+ match self {+ Self::NoPreference => "no-preference",+ Self::PreferHardware => "prefer-hardware",+ Self::PreferSoftware => "prefer-software",+ }+ }+}++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "AlphaOption")]+enum AlphaOption {+ #[webidl(token = "discard")]+ Discard,+ #[webidl(token = "keep")]+ Keep,+}+impl AlphaOption {+ fn as_str(self) -> &'static str {+ match self {+ Self::Discard => "discard",+ Self::Keep => "keep",+ }+ }+}++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "LatencyMode")]+enum LatencyMode {+ #[webidl(token = "quality")]+ Quality,+ #[webidl(token = "realtime")]+ Realtime,+}+impl LatencyMode {+ fn as_str(self) -> &'static str {+ match self {+ Self::Quality => "quality",+ Self::Realtime => "realtime",+ }+ }+}++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "VideoEncoderBitrateMode")]+enum VideoEncoderBitrateMode {+ #[webidl(token = "variable")]+ Variable,+ #[webidl(token = "constant")]+ Constant,+ #[webidl(token = "quantizer")]+ Quantizer,+}+impl VideoEncoderBitrateMode {+ fn as_str(self) -> &'static str {+ match self {+ Self::Variable => "variable",+ Self::Constant => "constant",+ Self::Quantizer => "quantizer",+ }+ }+}++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "VideoColorPrimaries")]+enum VideoColorPrimaries {+ #[webidl(token = "bt709")]+ Bt709,+ #[webidl(token = "bt470bg")]+ Bt470bg,+ #[webidl(token = "smpte170m")]+ Smpte170m,+ #[webidl(token = "bt2020")]+ Bt2020,+ #[webidl(token = "smpte432")]+ Smpte432,+}+impl VideoColorPrimaries {+ fn as_str(self) -> &'static str {+ match self {+ Self::Bt709 => "bt709",+ Self::Bt470bg => "bt470bg",+ Self::Smpte170m => "smpte170m",+ Self::Bt2020 => "bt2020",+ Self::Smpte432 => "smpte432",+ }+ }+}++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "VideoTransferCharacteristics")]+enum VideoTransferCharacteristics {+ #[webidl(token = "bt709")]+ Bt709,+ #[webidl(token = "smpte170m")]+ Smpte170m,+ #[webidl(token = "iec61966-2-1")]+ Srgb,+ #[webidl(token = "linear")]+ Linear,+ #[webidl(token = "pq")]+ Pq,+ #[webidl(token = "hlg")]+ Hlg,+}+impl VideoTransferCharacteristics {+ fn as_str(self) -> &'static str {+ match self {+ Self::Bt709 => "bt709",+ Self::Smpte170m => "smpte170m",+ Self::Srgb => "iec61966-2-1",+ Self::Linear => "linear",+ Self::Pq => "pq",+ Self::Hlg => "hlg",+ }+ }+}++#[derive(Clone, Copy, webidl::WebIdlEnum)]+#[webidl(name = "VideoMatrixCoefficients")]+enum VideoMatrixCoefficients {+ #[webidl(token = "rgb")]+ Rgb,+ #[webidl(token = "bt709")]+ Bt709,+ #[webidl(token = "bt470bg")]+ Bt470bg,+ #[webidl(token = "smpte170m")]+ Smpte170m,+ #[webidl(token = "bt2020-ncl")]+ Bt2020Ncl,+}+impl VideoMatrixCoefficients {+ fn as_str(self) -> &'static str {+ match self {+ Self::Rgb => "rgb",+ Self::Bt709 => "bt709",+ Self::Bt470bg => "bt470bg",+ Self::Smpte170m => "smpte170m",+ Self::Bt2020Ncl => "bt2020-ncl",+ }+ }+}++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "VideoColorSpaceInit")]+struct VideoColorSpaceInit {+ #[webidl(nullable)]+ full_range: Option<bool>,+ #[webidl(nullable, converter = "enum")]+ matrix: Option<VideoMatrixCoefficients>,+ #[webidl(nullable, converter = "enum")]+ primaries: Option<VideoColorPrimaries>,+ #[webidl(nullable, converter = "enum")]+ transfer: Option<VideoTransferCharacteristics>,+}++struct Description<'s>(v8::Local<'s, v8::Value>);++impl<'s> webidl::WebIdlConverter<'s> for Description<'s> {+ type Options = ();+ fn convert(+ _scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ _options: &(),+ ) -> Result<Self, webidl::WebIdlError> {+ if value.is_array_buffer()+ || value.is_shared_array_buffer()+ || value.is_typed_array()+ || value.is_data_view()+ {+ Ok(Self(value))+ } else {+ Err(webidl::WebIdlError::cannot_convert(+ context,+ "AllowSharedBufferSource",+ ))+ }+ }+}++impl<'s> Description<'s> {+ fn is_detached(&self, scope: &mut v8::PinScope<'s, '_>) -> bool {+ if let Ok(buffer) = v8::Local::<v8::ArrayBuffer>::try_from(self.0) {+ return buffer.was_detached();+ }+ if self.0.is_shared_array_buffer() {+ return false;+ }+ v8::Local::<v8::ArrayBufferView>::try_from(self.0)+ .ok()+ .is_none_or(|view| {+ if view+ .get_backing_store()+ .is_some_and(|store| store.is_shared())+ {+ return false;+ }+ view.buffer(scope)+ .is_none_or(|buffer| buffer.was_detached())+ })+ }+}++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "VideoDecoderConfig")]+struct VideoDecoderConfig<'s> {+ #[webidl(converter = "raw")]+ coded_height: Option<webidl::EnforceRangeUnsignedLong>,+ #[webidl(converter = "raw")]+ coded_width: Option<webidl::EnforceRangeUnsignedLong>,+ #[webidl(required, converter = "raw")]+ codec: webidl::DomString16,+ #[webidl(dictionary)]+ color_space: Option<VideoColorSpaceInit>,+ #[webidl(converter = "raw")]+ description: Option<Description<'s>>,+ #[webidl(converter = "raw")]+ display_aspect_height: Option<webidl::EnforceRangeUnsignedLong>,+ #[webidl(converter = "raw")]+ display_aspect_width: Option<webidl::EnforceRangeUnsignedLong>,+ #[webidl(default = false)]+ flip: bool,+ #[webidl(converter = "enum", default = HardwareAcceleration::NoPreference)]+ hardware_acceleration: HardwareAcceleration,+ #[webidl(default = false)]+ optimize_for_latency: bool,+ #[webidl(converter = "double", default = 0.0)]+ rotation: f64,+}++#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "VideoEncoderConfig")]+struct VideoEncoderConfig {+ #[webidl(converter = "enum", default = AlphaOption::Discard)]+ alpha: AlphaOption,+ #[webidl(converter = "raw")]+ bitrate: Option<webidl::EnforceRangeUnsignedLongLong>,+ #[webidl(converter = "enum", default = VideoEncoderBitrateMode::Variable)]+ bitrate_mode: VideoEncoderBitrateMode,+ #[webidl(required, converter = "raw")]+ codec: webidl::DomString16,+ #[webidl(converter = "raw")]+ content_hint: Option<webidl::DomString16>,+ #[webidl(converter = "raw")]+ display_height: Option<webidl::EnforceRangeUnsignedLong>,+ #[webidl(converter = "raw")]+ display_width: Option<webidl::EnforceRangeUnsignedLong>,+ #[webidl(converter = "double")]+ framerate: Option<f64>,+ #[webidl(converter = "enum", default = HardwareAcceleration::NoPreference)]+ hardware_acceleration: HardwareAcceleration,+ #[webidl(required, converter = "raw")]+ height: webidl::EnforceRangeUnsignedLong,+ #[webidl(converter = "enum", default = LatencyMode::Quality)]+ latency_mode: LatencyMode,+ #[webidl(converter = "raw")]+ scalability_mode: Option<webidl::DomString16>,+ #[webidl(required, converter = "raw")]+ width: webidl::EnforceRangeUnsignedLong,+}++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "VideoDecoder.isConfigSupported")]+struct DecoderSupportArgs<'s> {+ #[webidl(required, dictionary)]+ config: VideoDecoderConfig<'s>,+}+#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "VideoEncoder.isConfigSupported")]+struct EncoderSupportArgs {+ #[webidl(required, dictionary)]+ config: VideoEncoderConfig,+}++#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::VideoDecoder, enumerable)]+struct VideoDecoderStatics {+ #[webapi(static_method, length = 1, returns_promise, callback = decoder_is_config_supported)]+ is_config_supported: (),+}+#[derive(WebApiFunctionTemplate)]+#[webapi(interface = web_api_interfaces::VideoEncoder, enumerable)]+struct VideoEncoderStatics {+ #[webapi(static_method, length = 1, returns_promise, callback = encoder_is_config_supported)]+ is_config_supported: (),+}++#[derive(WebApiObject)]+#[webapi(plain, data_properties, enumerable)]+struct VideoSupport<'s> {+ supported: bool,+ config: v8::Local<'s, v8::Object>,+}++pub(super) fn install_video_codec_template_bindings<'s>(+ scope: &mut v8::PinScope<'s, '_, ()>,+ template: v8::Local<'s, v8::FunctionTemplate>,+ name: &str,+) {+ match name {+ "VideoDecoder" => VideoDecoderStatics::initialize_template(scope, template),+ "VideoEncoder" => VideoEncoderStatics::initialize_template(scope, template),+ _ => {}+ }+}++fn nonempty_codec(codec: &webidl::DomString16) -> bool {+ codec+ .0+ .iter()+ .any(|unit| !matches!(*unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20))+}+fn valid_dimensions(+ a: Option<webidl::EnforceRangeUnsignedLong>,+ b: Option<webidl::EnforceRangeUnsignedLong>,+) -> bool {+ a.is_some() == b.is_some()+ && a.is_none_or(|value| value.0 != 0)+ && b.is_none_or(|value| value.0 != 0)+}+fn property<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &str,+ value: impl WebApiValue<'s>,+) {+ let key = v8_string(scope, name).expect("video config key");+ let value = value.to_v8_value(scope).expect("video config value");+ assert_eq!(+ object.create_data_property(scope, key.into(), value),+ Some(true)+ );+}+fn string_property<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ object: v8::Local<'s, v8::Object>,+ name: &str,+ value: &webidl::DomString16,+) {+ let value = v8_string_from_utf16_units(scope, &value.0).expect("video config string");+ property(scope, object, name, value);+}+fn resolve_unsupported<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ config: v8::Local<'s, v8::Object>,+ mut rv: v8::ReturnValue<'_, v8::Value>,+) {+ let support = VideoSupport::new(false, config)+ .bind(scope)+ .expect("video support result");+ let resolver = v8::PromiseResolver::new(scope).expect("video support promise");+ let _ = resolver.resolve(scope, support.into());+ rv.set(resolver.get_promise(scope).into());+}++fn decoder_is_config_supported<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'_, v8::Value>,+) {+ let Some(parsed) = webidl::parse_args::<DecoderSupportArgs>(scope, &args) else {+ return;+ };+ let config = parsed.config;+ if !nonempty_codec(&config.codec)+ || !valid_dimensions(config.coded_width, config.coded_height)+ || !valid_dimensions(config.display_aspect_width, config.display_aspect_height)+ || config+ .description+ .as_ref()+ .is_some_and(|description| description.is_detached(scope))+ {+ crate::context_bootstrap::throw_type_error(scope, "Invalid VideoDecoderConfig.");+ return;+ }+ let clone = v8::Object::new(scope);+ string_property(scope, clone, "codec", &config.codec);+ for (name, value) in [+ ("codedHeight", config.coded_height),+ ("codedWidth", config.coded_width),+ ("displayAspectHeight", config.display_aspect_height),+ ("displayAspectWidth", config.display_aspect_width),+ ] {+ if let Some(value) = value {+ property(scope, clone, name, value.0);+ }+ }+ property(+ scope,+ clone,+ "hardwareAcceleration",+ config.hardware_acceleration.as_str(),+ );+ property(+ scope,+ clone,+ "optimizeForLatency",+ config.optimize_for_latency,+ );+ property(scope, clone, "rotation", config.rotation);+ property(scope, clone, "flip", config.flip);+ if let Some(description) = config.description {+ let context = webidl::Context::member("VideoDecoderConfig", "description");+ let bytes = match webidl::convert::<webidl::BufferSource>(scope, description.0, context) {+ Ok(bytes) => bytes.0,+ Err(error) => {+ webidl::throw_error(scope, &error);+ return;+ }+ };+ let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();+ let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);+ property(scope, clone, "description", buffer);+ }+ if let Some(color_space) = config.color_space {+ let color = v8::Object::new(scope);+ for (name, value) in [+ (+ "primaries",+ color_space.primaries.map(VideoColorPrimaries::as_str),+ ),+ (+ "transfer",+ color_space+ .transfer+ .map(VideoTransferCharacteristics::as_str),+ ),+ (+ "matrix",+ color_space.matrix.map(VideoMatrixCoefficients::as_str),+ ),+ ] {+ let value: v8::Local<v8::Value> = match value {+ Some(value) => v8_string(scope, value).expect("video color enum").into(),+ None => v8::null(scope).into(),+ };+ property(scope, color, name, value);+ }+ let full_range: v8::Local<v8::Value> = match color_space.full_range {+ Some(value) => v8::Boolean::new(scope, value).into(),+ None => v8::null(scope).into(),+ };+ property(scope, color, "fullRange", full_range);+ property(scope, clone, "colorSpace", color);+ }+ resolve_unsupported(scope, clone, rv);+}++fn encoder_is_config_supported<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ rv: v8::ReturnValue<'_, v8::Value>,+) {+ let Some(parsed) = webidl::parse_args::<EncoderSupportArgs>(scope, &args) else {+ return;+ };+ let config = parsed.config;+ if !nonempty_codec(&config.codec)+ || config.width.0 == 0+ || config.height.0 == 0+ || config.display_width.is_some_and(|value| value.0 == 0)+ || config.display_height.is_some_and(|value| value.0 == 0)+ {+ crate::context_bootstrap::throw_type_error(scope, "Invalid VideoEncoderConfig.");+ return;+ }+ let clone = v8::Object::new(scope);+ string_property(scope, clone, "codec", &config.codec);+ property(scope, clone, "width", config.width.0);+ property(scope, clone, "height", config.height.0);+ for (name, value) in [+ ("displayHeight", config.display_height),+ ("displayWidth", config.display_width),+ ] {+ if let Some(value) = value {+ property(scope, clone, name, value.0);+ }+ }+ if let Some(value) = config.bitrate {+ property(scope, clone, "bitrate", value.0);+ }+ if let Some(value) = config.framerate {+ property(scope, clone, "framerate", value);+ }+ if let Some(value) = config.scalability_mode {+ string_property(scope, clone, "scalabilityMode", &value);+ }+ if let Some(value) = config.content_hint {+ string_property(scope, clone, "contentHint", &value);+ }+ property(+ scope,+ clone,+ "hardwareAcceleration",+ config.hardware_acceleration.as_str(),+ );+ property(scope, clone, "alpha", config.alpha.as_str());+ property(scope, clone, "bitrateMode", config.bitrate_mode.as_str());+ property(scope, clone, "latencyMode", config.latency_mode.as_str());+ resolve_unsupported(scope, clone, rv);+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex 8be94b647..60f4a8a4e 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -72,3 +72,5 @@ mod document_domain_setter;mod error_event_init;mod message_event_init;mod window_current_event_private;++mod video_codec_support;diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.js b/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.jsnew file mode 100644index 000000000..81b580c0c--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.js@@ -0,0 +1,79 @@+(async () => {+ async function probe(realm) {+ const assert = (ok, message) => { if (!ok) throw new Error(message); };+ for (const name of ['VideoDecoder', 'VideoEncoder']) {+ const encoder = name === 'VideoEncoder';+ const ctor = realm[name];+ const query = ctor.isConfigSupported;+ const descriptor = Object.getOwnPropertyDescriptor(ctor, 'isConfigSupported');+ assert(typeof query === 'function' && query.length === 1 && descriptor.enumerable && descriptor.writable && descriptor.configurable, name + ' static operation');+ const config = { codec: 'vp8', ...(encoder ? {width: 640, height: 480} : {}) };+ const promise = query.call({}, config);+ assert(promise instanceof realm.Promise, name + ' promise belongs to callee realm');+ const support = await promise;+ assert(support.supported === false && support.config !== config && Object.getPrototypeOf(support.config) === realm.Object.prototype, name + ' honest independent config');+ assert(support.config.codec === 'vp8' && support.config.hardwareAcceleration === 'no-preference', name + ' converted defaults');+ assert(!Object.hasOwn(support.config, encoder ? 'displayWidth' : 'codedWidth'), name + ' absent members stay absent');+ const inherited = Object.create({codec: {toString: () => 'vp8'}});+ if (encoder) { inherited.width = '640.9'; inherited.height = 480; }+ inherited.ignored = 'unknown';+ const inheritedSupport = await query(inherited);+ assert(inheritedSupport.config.codec === 'vp8' && !Object.hasOwn(inheritedSupport.config, 'ignored'), name + ' dictionary conversion and unknown keys');+ if (encoder) assert(inheritedSupport.config.width === 640, 'EnforceRange truncation');+ const invalids = [undefined, null, {}, {...config, codec: ''}, {...config, codec: ' \t\n'},+ {...config, hardwareAcceleration: 'invalid'}, {...config, [encoder ? 'width' : 'codedWidth']: -1},+ {...config, [encoder ? 'height' : 'codedHeight']: Infinity},+ {...config, [encoder ? 'displayWidth' : 'displayAspectWidth']: 0}];+ if (encoder) invalids.push({...config, width: 0}, {...config, alpha: 'opaque'}, {...config, framerate: NaN}, {...config, bitrate: 2n});+ else invalids.push({...config, codedWidth: 12}, {...config, codedWidth: 0, codedHeight: 12}, {...config, colorSpace: {primaries: 'invalid'}}, {...config, description: {}}, {...config, rotation: Infinity});+ for (const invalid of invalids) {+ let rejected;+ let result;+ try { result = query(invalid); } catch (_) { throw Error(name + ' must reject instead of throwing synchronously'); }+ assert(result instanceof realm.Promise, name + ' invalid config returns promise');+ try { await result; } catch (error) { rejected = error; }+ assert(rejected instanceof realm.TypeError, name + ' invalid config rejects in callee realm');+ }+ const sentinel = {};+ let caught;+ try { await query({...config, get codec() { throw sentinel; }}); } catch (error) { caught = error; }+ assert(caught === sentinel, name + ' preserves getter exceptions');+ const reads = [];+ const ordered = new Proxy(config, {get(target, key, receiver) { reads.push(key); return Reflect.get(target, key, receiver); }});+ await query(ordered);+ const expected = encoder ? ['alpha','bitrate','bitrateMode','codec','contentHint','displayHeight','displayWidth','framerate','hardwareAcceleration','height','latencyMode','scalabilityMode','width']+ : ['codedHeight','codedWidth','codec','colorSpace','description','displayAspectHeight','displayAspectWidth','flip','hardwareAcceleration','optimizeForLatency','rotation'];+ assert(JSON.stringify(reads) === JSON.stringify(expected), name + ' dictionary getter order');+ const unsupported = await query({...config, codec: 'not-a-supported-codec'});+ assert(unsupported.supported === false, name + ' unknown codec is unsupported, not invalid');+ const lone = await query({...config, codec: '\ud800'});+ assert(lone.config.codec.charCodeAt(0) === 0xd800, name + ' lossless DOMString');+ }+ const bytes = new Uint8Array([9,1,2,8]);+ const promise = realm.VideoDecoder.isConfigSupported({codec:'vp8', description: new DataView(bytes.buffer, 1, 2),+ get hardwareAcceleration() { bytes[2] = 3; return 'prefer-software'; }, colorSpace: {primaries:'bt709', fullRange:true, ignored:7}});+ bytes.fill(0);+ const cloned = (await promise).config;+ assert(cloned.description instanceof realm.ArrayBuffer && Array.from(new Uint8Array(cloned.description)).join() === '1,3', 'description bytes snapshot after conversion without author access');+ assert(cloned.colorSpace.primaries === 'bt709' && cloned.colorSpace.fullRange === true && cloned.colorSpace.matrix === null && !Object.hasOwn(cloned.colorSpace, 'ignored'), 'nested color-space conversion');+ const buffer = new ArrayBuffer(1);+ let detachedError;+ try { await realm.VideoDecoder.isConfigSupported({codec:'vp8', description:buffer,+ get hardwareAcceleration() { structuredClone(buffer, {transfer:[buffer]}); return 'no-preference'; }}); }+ catch (error) { detachedError = error; }+ assert(detachedError instanceof realm.TypeError, 'description detached by a later getter rejects');+ return 'ok';+ }+ await probe(window);+ await probe(document.getElementById('child').contentWindow);+ const workerSource = `(${probe.toString()})(self).then(value => postMessage(value), error => postMessage(String(error)))`;+ const url = URL.createObjectURL(new Blob([workerSource], {type:'text/javascript'}));+ const result = await new Promise((resolve, reject) => {+ const worker = new Worker(url);+ worker.onmessage = event => { worker.terminate(); resolve(event.data); };+ worker.onerror = event => { event.preventDefault(); worker.terminate(); reject(Error(event.message)); };+ });+ URL.revokeObjectURL(url);+ if (result !== 'ok') throw Error(result);+ return 'ok';+})()diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.rsnew file mode 100644index 000000000..f2b0f4975--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/video_codec_support.rs@@ -0,0 +1,24 @@+use super::service_worker_drain::drain_service_worker_test_turn;+use super::*;++#[tokio::test]+async fn video_codec_support_queries_convert_clone_and_reject_in_window_child_and_worker_realms() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let (mut vm, browser_context_runtime) =+ new_service_worker_page_test_vm_with_loader_and_browser_context_runtime(+ "https://codec-support.test/",+ &loader,+ );+ vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")+ .unwrap();+ let source = include_str!("video_codec_support.js");+ vm.eval(&format!("({source}).then(value => globalThis.__codecSupport = value, error => globalThis.__codecSupport = String(error));")).unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(30), async {+ while vm.eval("globalThis.__codecSupport !== undefined").unwrap() != "true" {+ drain_service_worker_test_turn(&mut vm, &browser_context_runtime, &loader).await;+ }+ })+ .await+ .expect("codec support probes should settle");+ assert_eq!(vm.eval("globalThis.__codecSupport").unwrap(), "ok");+}diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex 45ab7b1af..c9e3ec12e 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -2189,6 +2189,7 @@ mod svg_switch_mpath_interfaces;mod text_encoder_utf16_progress;mod time_ranges;mod url_components;+mod video_codecs_shell;mod webgl_interfaces;mod webidl_collections;mod webidl_fetch;diff --git a/moli-renderer-v8/src/script_vm/tests/video_codecs_shell.js b/moli-renderer-v8/src/script_vm/tests/video_codecs_shell.jsnew file mode 100644index 000000000..69b52b376--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/video_codecs_shell.js@@ -0,0 +1,34 @@+(() => {+ const assert = (ok, message) => { if (!ok) throw Error(message); };+ const interfaces = [["VideoDecoder", "EventTarget", 1], ["VideoEncoder", "EventTarget", 1]];+ for (const realm of [window, document.getElementById('child').contentWindow]) {+ for (const [name, parentName, length] of interfaces) {+ if (!realm.isSecureContext) {+ assert(!(name in realm), name + ' must be absent in an insecure context');+ continue;+ }+ const constructor = realm[name], parent = realm[parentName ?? 'Object'];+ assert(typeof constructor === 'function' && constructor.name === name && constructor.length === length,+ name + ' interface object');+ const descriptor = Object.getOwnPropertyDescriptor(realm, name);+ assert(descriptor.writable && descriptor.configurable && !descriptor.enumerable, name + ' global descriptor');+ assert(Object.getPrototypeOf(constructor.prototype) === parent.prototype, name + ' prototype inheritance');+ assert(Object.getPrototypeOf(constructor) === (parentName ? parent : realm.Function.prototype), name + ' interface inheritance');+ assert(constructor.prototype.constructor === constructor, name + ' prototype constructor');+ const tag = Object.getOwnPropertyDescriptor(constructor.prototype, Symbol.toStringTag);+ assert(tag.value === name && !tag.writable && !tag.enumerable && tag.configurable, name + ' prototype tag');+ let callError;+ try { constructor(); } catch (error) { callError = error; }+ assert(callError instanceof realm.TypeError, name + ' call requires new in the callee realm');+ if (realm !== window) assert(!(callError instanceof TypeError), name + ' foreign TypeError');+ // Encoding and decoding backends remain unavailable; capability queries have a separate native contract.+ let constructionError;+ try { Reflect.construct(constructor, []); } catch (error) { constructionError = error; }+ assert(constructionError instanceof realm.DOMException && constructionError.name === 'NotSupportedError' && constructionError.code === 9,+ name + ' unavailable construction is explicit in the callee realm');+ if (realm !== window) assert(!(constructionError instanceof DOMException), name + ' foreign DOMException');+ assert(realm[name] === constructor, name + ' materialization remains stable');+ }+ }+ return 'ok';+})()diff --git a/moli-renderer-v8/src/script_vm/tests/video_codecs_shell.rs b/moli-renderer-v8/src/script_vm/tests/video_codecs_shell.rsnew file mode 100644index 000000000..76a49d1d4--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/video_codecs_shell.rs@@ -0,0 +1,19 @@+use super::*;++#[test]+fn shell_video_codecs_preserves_native_identity_and_callee_error_realms() {+ for url in [+ "https://shell-interfaces.test/",+ "http://shell-interfaces.test/",+ "http://localhost/",+ ] {+ let mut vm = new_storage_page_task_executor_test_vm(url);+ vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")+ .unwrap();+ assert_eq!(+ vm.eval(include_str!("video_codecs_shell.js")).unwrap(),+ "ok",+ "{url}"+ );+ }+}diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rsindex e2ab3a2f1..70d5c16af 100644--- a/moli-renderer-v8/src/web_api_interfaces.rs+++ b/moli-renderer-v8/src/web_api_interfaces.rs@@ -561,6 +561,8 @@ interfaces! {URLSearchParams;URLSearchParamsIterator = "URLSearchParams Iterator";UserActivation;+ VideoDecoder: EventTarget;+ VideoEncoder: EventTarget;VTTCue: TextTrackCue;ValidityState;ViewTransition;