diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 23a0acf25f9..b0903b35f3c 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -24,6 +24,7 @@ pub(crate) mod css_stylesheet_runtime; mod dom_quad; mod dom_rect; mod dom_rect_list; +mod encoded_video_chunk; mod event_document; mod event_legacy; pub(crate) mod event_target_dispatch; @@ -308,6 +309,10 @@ pub(crate) use self::css_stylesheet_runtime::{ }; pub(crate) use self::dom_rect::build_dom_rect_object; pub(crate) use self::dom_rect_list::build_dom_rect_list_object; +pub(crate) use self::encoded_video_chunk::{ + EncodedVideoChunkClonePayload, EncodedVideoChunkType, + build_encoded_video_chunk_from_clone_payload, encoded_video_chunk_clone_payload_from_object, +}; pub(crate) use self::events::{ EVENT_DISPATCHING_SLOT, EVENT_PASSIVE_SLOT, diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs index 3ac5ec312e7..9d0a4a1aa2d 100644 --- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs +++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs @@ -24,6 +24,7 @@ use super::super::{ }, css_stylesheet_runtime::css_style_sheet_constructor_callback, dom_quad::dom_quad_constructor_callback, + encoded_video_chunk::encoded_video_chunk_constructor_callback, events::{ EventSubclassKind, ValueEventKind, build_event_subclass_template, build_value_event_template, device_motion_event_constructor, @@ -495,6 +496,14 @@ pub(in crate::context_bootstrap) fn build_constructor_template_for_profile<'s>( .length(0) .build(scope) } + ConstructorKind::EncodedVideoChunk => { + v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!( + web_api_interfaces::EncodedVideoChunk, + encoded_video_chunk_constructor_callback + )) + .length(1) + .build(scope) + } ConstructorKind::ImageData => { let template = v8::FunctionTemplate::builder(moli_webapi_declare::web_api_constructor!( diff --git a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs index 5347a2b2c50..31d09e432cf 100644 --- a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs +++ b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs @@ -18,6 +18,7 @@ use super::super::{ dom_quad::install_dom_quad_template_bindings, dom_rect::install_dom_rect_template_bindings, dom_rect_list::install_dom_rect_list_template_bindings, + encoded_video_chunk::install_encoded_video_chunk_template_bindings, event_template::install_event_template_bindings, exposed_interfaces::TemplateBuildProfile, file_api::install_file_api_template_bindings, @@ -418,6 +419,9 @@ pub(super) fn install_constructor_template_bindings<'s>( if spec.interface.name() == "ImageData" { install_image_data_template_bindings(scope, template); } + if spec.interface.name() == "EncodedVideoChunk" { + install_encoded_video_chunk_template_bindings(scope, template); + } if spec.interface.name() == "MediaQueryList" { install_media_query_list_template_bindings(scope, template); } diff --git a/moli-renderer-v8/src/context_bootstrap/encoded_video_chunk.rs b/moli-renderer-v8/src/context_bootstrap/encoded_video_chunk.rs new file mode 100644 index 00000000000..7c1d6d04f64 --- /dev/null +++ b/moli-renderer-v8/src/context_bootstrap/encoded_video_chunk.rs @@ -0,0 +1,311 @@ +//! Immutable encoded bytes; no encoder or decoder backend is needed. + +use crate::{ + blob::array_buffer_from_bytes, + util::{get_private_value, throw_type_error, v8str}, + web_api_interfaces, webidl, +}; +use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject}; + +const TYPE_SLOT: &str = "__moliEncodedVideoChunkType"; +const TIMESTAMP_SLOT: &str = "__moliEncodedVideoChunkTimestamp"; +const DURATION_SLOT: &str = "__moliEncodedVideoChunkDuration"; +const DATA_SLOT: &str = "__moliEncodedVideoChunkData"; + +#[derive(Clone, Copy, Debug, webidl::WebIdlEnum)] +#[webidl(name = "EncodedVideoChunkType")] +pub(crate) enum EncodedVideoChunkType { + Key, + Delta, +} + +impl EncodedVideoChunkType { + fn label(self) -> &'static str { + match self { + Self::Key => "key", + Self::Delta => "delta", + } + } +} + +#[derive(webidl::WebIdlDictionary)] +#[webidl(prefix = "EncodedVideoChunkInit")] +struct EncodedVideoChunkInit<'s> { + #[webidl(required, converter = "raw")] + data: webidl::AllowSharedBufferSource<'s>, + #[webidl(converter = "enforce_range_unsigned_long_long")] + duration: Option, + #[webidl(required, converter = "enforce_range_long_long")] + timestamp: i64, + #[webidl(converter = "raw", default = webidl::Sequence(Vec::new()))] + transfer: webidl::Sequence>, + #[webidl(name = "type", required, converter = "enum")] + kind: EncodedVideoChunkType, +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "EncodedVideoChunk")] +struct EncodedVideoChunkConstructorArgs<'s> { + #[webidl(with = parse_init)] + init: EncodedVideoChunkInit<'s>, +} + +fn parse_init<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: &v8::FunctionCallbackArguments<'s>, + index: i32, +) -> Result, webidl::WebIdlError> { + let context = webidl::Context::argument("EncodedVideoChunk", (index + 1) as usize); + if args.length() <= index { + return Err(webidl::WebIdlError::cannot_convert( + context, + "EncodedVideoChunkInit", + )); + } + // Nullish dictionaries have no members, regardless of Object.prototype. + // This dictionary requires data, so an empty dictionary cannot be valid. + let object = webidl::dictionary_arg(args, index, context)? + .ok_or_else(|| webidl::WebIdlError::cannot_convert(context, "EncodedVideoChunkInit"))?; + webidl::parse_dictionary_object(scope, object) +} + +#[derive(webidl::WebIdlArgs)] +#[webidl(prefix = "EncodedVideoChunk.copyTo")] +struct CopyToArgs<'s> { + #[webidl(required, converter = "raw")] + destination: webidl::AllowSharedBufferSource<'s>, +} + +#[derive(WebApiObject)] +#[webapi(interface = web_api_interfaces::EncodedVideoChunk, require_prototype)] +struct EncodedVideoChunkObjectDeclaration<'s> { + #[webapi(slot = TYPE_SLOT)] + kind: &'static str, + #[webapi(slot = TIMESTAMP_SLOT)] + timestamp: f64, + #[webapi(slot = DURATION_SLOT)] + duration: v8::Local<'s, v8::Value>, + // This buffer is private and never returned to author code. + #[webapi(slot = DATA_SLOT)] + bytes: v8::Local<'s, v8::ArrayBuffer>, +} + +#[derive(WebApiFunctionTemplate)] +#[webapi(interface = web_api_interfaces::EncodedVideoChunk, enumerable, receiver)] +struct EncodedVideoChunkPrototypeDeclaration { + #[webapi(accessor_property = "type", getter = slot_getter, data = v8str(scope, TYPE_SLOT))] + kind: (), + #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, TIMESTAMP_SLOT))] + timestamp: (), + #[webapi(accessor_property, getter = slot_getter, data = v8str(scope, DURATION_SLOT))] + duration: (), + #[webapi(accessor_property, getter = byte_length_getter)] + byte_length: (), + #[webapi(method, length = 1, callback = copy_to_callback)] + copy_to: (), +} + +pub(in crate::context_bootstrap) fn install_encoded_video_chunk_template_bindings<'s>( + scope: &mut v8::PinScope<'s, '_, ()>, + template: v8::Local<'s, v8::FunctionTemplate>, +) { + let prototype = template.prototype_template(scope); + EncodedVideoChunkPrototypeDeclaration::initialize_prototype_template(scope, prototype); +} + +pub(in crate::context_bootstrap) fn encoded_video_chunk_constructor_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + if !args.is_construct_call() { + throw_type_error(scope, "EncodedVideoChunk requires the 'new' operator."); + return; + } + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + let init = parsed.init; + for (index, buffer) in init.transfer.0.iter().enumerate() { + if init.transfer.0[..index] + .iter() + .any(|other| buffer.strict_equals((*other).into())) + { + webidl::throw_dom_exception( + scope, + "DataCloneError", + "Duplicate ArrayBuffer in transfer.", + ); + return; + } + } + for buffer in &init.transfer.0 { + if buffer.was_detached() || !buffer.is_detachable() { + webidl::throw_dom_exception( + scope, + "DataCloneError", + "ArrayBuffer cannot be transferred.", + ); + return; + } + } + // Read only after all dictionary getters and transfer iteration have run. + let payload = EncodedVideoChunkClonePayload { + kind: init.kind, + timestamp: init.timestamp, + duration: init.duration, + bytes: init.data.to_vec(scope), + }; + let declaration = chunk_declaration(scope, payload); + declaration + .initialize(scope, args.this()) + .expect("EncodedVideoChunk slots initialize"); + for buffer in &init.transfer.0 { + if buffer.detach(None) != Some(true) { + webidl::throw_dom_exception( + scope, + "DataCloneError", + "ArrayBuffer could not be transferred.", + ); + return; + } + } + rv.set(args.this().into()); +} + +fn slot_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let slot = args.data().to_rust_string_lossy(scope); + let target = moli_webapi_declare::web_api_object_target(scope, args.this()) + .expect("validated EncodedVideoChunk receiver"); + rv.set(get_private_value(scope, target, &slot).expect("EncodedVideoChunk slot")); +} + +fn chunk_bytes<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> v8::Local<'s, v8::ArrayBuffer> { + let object = moli_webapi_declare::web_api_object_target(scope, object) + .expect("validated EncodedVideoChunk receiver"); + v8::Local::try_from( + get_private_value(scope, object, DATA_SLOT).expect("EncodedVideoChunk bytes"), + ) + .expect("EncodedVideoChunk bytes are a private ArrayBuffer") +} + +fn byte_length_getter<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + rv.set_uint32(chunk_bytes(scope, args.this()).byte_length() as u32); +} + +fn copy_to_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + mut rv: v8::ReturnValue<'_, v8::Value>, +) { + let Some(parsed) = webidl::parse_args::(scope, &args) else { + return; + }; + let bytes = chunk_bytes(scope, args.this()); + if bytes.byte_length() > parsed.destination.byte_length() { + throw_type_error( + scope, + "The destination is too small for this EncodedVideoChunk.", + ); + return; + } + let backing = bytes.get_backing_store(); + let bytes = if backing.byte_length() == 0 { + &[] + } else { + // SAFETY: private fixed storage is retained by `backing`, never exposed + // or mutated, and no JavaScript runs during this copy. + unsafe { + std::slice::from_raw_parts( + backing + .data() + .expect("nonempty chunk backing") + .as_ptr() + .cast::(), + backing.byte_length(), + ) + } + }; + assert!(parsed.destination.write_bytes(scope, bytes)); + rv.set_undefined(); +} + +#[derive(Clone, Debug)] +pub(crate) struct EncodedVideoChunkClonePayload { + pub(crate) kind: EncodedVideoChunkType, + pub(crate) timestamp: i64, + pub(crate) duration: Option, + pub(crate) bytes: Vec, +} + +fn chunk_declaration<'s>( + scope: &mut v8::PinScope<'s, '_>, + payload: EncodedVideoChunkClonePayload, +) -> EncodedVideoChunkObjectDeclaration<'s> { + let duration = payload + .duration + .map(|duration| v8::Number::new(scope, duration as f64).into()) + .unwrap_or_else(|| v8::null(scope).into()); + let bytes = + array_buffer_from_bytes(scope, payload.bytes).expect("EncodedVideoChunk bytes allocate"); + EncodedVideoChunkObjectDeclaration::new( + payload.kind.label(), + payload.timestamp as f64, + duration, + bytes, + ) +} + +pub(crate) fn encoded_video_chunk_clone_payload_from_object<'s>( + scope: &mut v8::PinScope<'s, '_>, + object: v8::Local<'s, v8::Object>, +) -> Option { + if !web_api_interfaces::EncodedVideoChunk::is_instance(scope, object) { + return None; + } + let object = moli_webapi_declare::web_api_object_target(scope, object)?; + let kind = match get_private_value(scope, object, TYPE_SLOT)? + .to_rust_string_lossy(scope) + .as_str() + { + "key" => EncodedVideoChunkType::Key, + "delta" => EncodedVideoChunkType::Delta, + _ => return None, + }; + let timestamp = get_private_value(scope, object, TIMESTAMP_SLOT)?.number_value(scope)? as i64; + let duration = get_private_value(scope, object, DURATION_SLOT)?; + let duration = if duration.is_null() { + None + } else { + Some(duration.number_value(scope)? as u64) + }; + let backing = chunk_bytes(scope, object).get_backing_store(); + Some(EncodedVideoChunkClonePayload { + kind, + timestamp, + duration, + bytes: backing.iter().map(|byte| byte.get()).collect(), + }) +} + +pub(crate) fn build_encoded_video_chunk_from_clone_payload<'s>( + scope: &mut v8::PinScope<'s, '_>, + payload: EncodedVideoChunkClonePayload, +) -> Option> { + if !super::exposed_interfaces::is_realm_interface_exposed(scope, "EncodedVideoChunk") { + return None; + } + // Native allocation also works inside V8's no-JavaScript deserializer scope. + chunk_declaration(scope, payload).bind(scope).ok() +} diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/clone.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/clone.rs index 550fea00371..708b3cafb1c 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/clone.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/clone.rs @@ -99,6 +99,15 @@ impl v8::ValueSerializerImpl for IndexedDbStructuredCloneSerializer { serializer: &dyn v8::ValueSerializerHelper, ) -> Option { match moli_webapi_declare::web_api_object_type(scope, object).map(|kind| kind.name()) { + Some("EncodedVideoChunk") => { + let exception = dom_exception_value( + scope, + "EncodedVideoChunk cannot be stored.", + "DataCloneError", + ); + scope.throw_exception(exception); + return None; + } Some("CryptoKey") => { if write_crypto_key_payload(scope, object, serializer).is_some() { return Some(true); diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs index 8ee14c76e5f..4dc66d515d4 100644 --- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs +++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs @@ -278,7 +278,7 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[ }, ConstructorSpec { interface: web_api_interfaces::EncodedVideoChunk::DESCRIPTOR, - kind: ConstructorKind::Shell { length: 1 }, + kind: ConstructorKind::EncodedVideoChunk, }, ConstructorSpec { interface: web_api_interfaces::LargestContentfulPaint::DESCRIPTOR, diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rs index 75829e91f08..0f860fa9cb2 100644 --- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs +++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs @@ -87,6 +87,7 @@ pub(in crate::context_bootstrap) enum ConstructorKind { Blob, DataTransfer, ImageData, + EncodedVideoChunk, OffscreenCanvas, CanvasRenderingContext2D, OffscreenCanvasRenderingContext2D, diff --git a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.js b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.js new file mode 100644 index 00000000000..06ac15be745 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.js @@ -0,0 +1,274 @@ +(() => { + const checks = []; + const check = (name, run) => { + try { + if (run() === false) throw Error('assertion returned false'); + checks.push({name, passed: true}); + } catch (error) { + checks.push({name, passed: false, error: String(error), stack: error.stack}); + } + }; + const equal = (actual, expected) => { + if (!Object.is(actual, expected)) throw Error(`expected ${expected}, got ${actual}`); + }; + const bytesEqual = (actual, expected) => equal(Array.from(actual).join(','), expected.join(',')); + const throws = (realm, name, run) => { + let error; + try { run(); } catch (caught) { error = caught; } + if (!error || error.name !== name || !(error instanceof realm[name === 'TypeError' ? 'TypeError' : 'DOMException'])) + throw Error(`expected ${name} in the callee realm, got ${error}`); + if (realm !== globalThis && name === 'TypeError' && error instanceof TypeError) + throw Error('wrong TypeError realm'); + return error; + }; + const init = overrides => ({type: 'key', timestamp: -17, data: new Uint8Array([1, 2, 3]), ...overrides}); + const copy = chunk => {const result = new Uint8Array(chunk.byteLength); chunk.copyTo(result); return result;}; + const realms = [globalThis]; + if (typeof document !== 'undefined') realms.push(document.getElementById('child').contentWindow); + for (const [realmIndex, realm] of realms.entries()) { + const C = realm.EncodedVideoChunk; + const test = (name, run) => check(`${realmIndex}: ${name}`, run); + test('interface descriptor and native prototype', () => { + equal(typeof C, 'function'); equal(C.name, 'EncodedVideoChunk'); equal(C.length, 1); + const d = Object.getOwnPropertyDescriptor(realm, 'EncodedVideoChunk'); + equal(d.enumerable, false); equal(d.writable, true); equal(d.configurable, true); + equal(Object.getPrototypeOf(C), realm.Function.prototype); + equal(Object.getPrototypeOf(C.prototype), realm.Object.prototype); + equal(C.prototype.constructor, C); + const tag = Object.getOwnPropertyDescriptor(C.prototype, Symbol.toStringTag); + equal(tag.value, 'EncodedVideoChunk'); equal(tag.writable, false); + equal(tag.enumerable, false); equal(tag.configurable, true); + }); + for (const args of [[], [undefined], [null], [{}], [0], ['x']]) + test(`invalid required dictionary ${String(args)}`, () => throws(realm, 'TypeError', () => Reflect.construct(C, args))); + test('requires new before conversion', () => { + let converted = false; + throws(realm, 'TypeError', () => C(new Proxy({}, {get() {converted = true;}}))); + equal(converted, false); + }); + test('nullish dictionary ignores Object.prototype while objects inherit members', () => { + const proto = realm.Object.prototype, saved = new Map(); let reads = 0; + try { + for (const [name, value] of [['data', new Uint8Array([1])], ['timestamp', -2], ['type', 'key']]) { + saved.set(name, Object.getOwnPropertyDescriptor(proto, name)); + Object.defineProperty(proto, name, {configurable: true, get() {reads++; return value;}}); + } + throws(realm, 'TypeError', () => new C(null)); + throws(realm, 'TypeError', () => new C(undefined)); equal(reads, 0); + const inherited = new C(new realm.Object()); + equal(inherited.timestamp, -2); bytesEqual(copy(inherited), [1]); equal(reads, 3); + } finally { + for (const [name, descriptor] of saved) { + if (descriptor) Object.defineProperty(proto, name, descriptor); else Reflect.deleteProperty(proto, name); + } + } + }); + for (const type of ['key', 'delta']) test(`immutable ${type} bytes`, () => { + const data = new Uint8Array([9, 1, 2, 3, 8]); + const chunk = new C(init({type, duration: 27, data: data.subarray(1, 4)})); + data.fill(99); + equal(chunk.type, type); equal(chunk.timestamp, -17); equal(chunk.duration, 27); equal(chunk.byteLength, 3); + bytesEqual(copy(chunk), [1, 2, 3]); equal(Object.keys(chunk).length, 0); + equal(Object.prototype.toString.call(chunk), '[object EncodedVideoChunk]'); + }); + for (const type of ['', 'KEY', ' key', null, undefined, 1, Symbol('type')]) + test(`invalid enum ${String(type)}`, () => throws(realm, 'TypeError', () => new C(init({type})))); + for (const [value, expected] of [[-1.9, -1], [1.9, 1], [-0.9, 0], [-0, 0], [null, 0], [true, 1], ['23', 23], [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], [-Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER]]) + test(`timestamp conversion ${String(value)}`, () => equal(new C(init({timestamp: value})).timestamp, expected)); + for (const value of [undefined, NaN, Infinity, -Infinity, 2 ** 53, -(2 ** 53), 2 ** 63, Symbol('timestamp'), 1n]) + test(`invalid timestamp ${String(value)}`, () => throws(realm, 'TypeError', () => new C(init({timestamp: value})))); + for (const [value, expected] of [[undefined, null], [null, 0], [-0.9, 0], [-0, 0], [0, 0], [1.9, 1], ['12', 12], [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]]) + test(`duration conversion ${String(value)}`, () => equal(new C(init({duration: value})).duration, expected)); + for (const value of [NaN, Infinity, -Infinity, -1, 2 ** 53, 2 ** 64, Symbol('duration'), 1n]) + test(`invalid duration ${String(value)}`, () => throws(realm, 'TypeError', () => new C(init({duration: value})))); + test('missing duration remains null', () => equal(new C(init()).duration, null)); + const dataBuffer = new Uint8Array([9, 1, 2, 3, 8]).buffer; + for (const [name, data, expected] of [ + ['ArrayBuffer', dataBuffer, [9, 1, 2, 3, 8]], + ['Uint8Array offset', new Uint8Array(dataBuffer, 1, 3), [1, 2, 3]], + ['DataView offset', new DataView(dataBuffer, 1, 3), [1, 2, 3]], + ['Int16Array', new Int16Array(new Uint8Array([1, 2, 3, 4]).buffer), [1, 2, 3, 4]], + ['empty buffer', new ArrayBuffer(0), []], + ['empty view', new Uint8Array(dataBuffer, 5, 0), []], + ]) test(`construct from ${name}`, () => bytesEqual(copy(new C(init({data}))), expected)); + const revokedBuffer = Proxy.revocable(dataBuffer, {}); revokedBuffer.revoke(); + for (const [index, data] of [undefined, null, 0, [], {}, 'data', Symbol('data'), 1n, new Proxy(dataBuffer, {}), revokedBuffer.proxy].entries()) + test(`invalid data ${index}`, () => throws(realm, 'TypeError', () => new C(init({data})))); + test('detached source is an empty byte sequence', () => { + const data = new Uint8Array([1, 2]); data.buffer.transfer(); + equal(new C(init({data})).byteLength, 0); equal(new C(init({data: data.buffer})).byteLength, 0); + }); + test('copy after all dictionary getter effects', () => { + const data = new Uint8Array([1, 2, 3]); + const options = init({data}); Object.defineProperty(options, 'type', {get() {data[1] = 7; return 'delta';}}); + bytesEqual(copy(new C(options)), [1, 7, 3]); + }); + test('dictionary getters may detach data before copy', () => { + const data = new Uint8Array([1, 2, 3]); + const options = init({data}); Object.defineProperty(options, 'duration', {get() {data.buffer.transfer(); return 1;}}); + equal(new C(options).byteLength, 0); + }); + test('dictionary conversion order', () => { + const order = [], options = init({duration: 5}); + const proxy = new Proxy(options, {get(target, key) {order.push(key); return target[key];}}); + new C(proxy); bytesEqual(order, ['data', 'duration', 'timestamp', 'transfer', 'type']); + }); + for (const property of ['data', 'duration', 'timestamp', 'transfer', 'type']) test(`propagates ${property} getter exception`, () => { + const marker = {}, options = init(); Object.defineProperty(options, property, {get() {throw marker;}}); + let caught; try {new C(options);} catch (error) {caught = error;} equal(caught, marker); + }); + for (const property of ['duration', 'timestamp', 'type']) test(`propagates ${property} conversion exception`, () => { + const marker = {}, options = init({[property]: {[Symbol.toPrimitive]() {throw marker;}}}); + let caught; try {new C(options);} catch (error) {caught = error;} equal(caught, marker); + }); + for (const property of ['type', 'timestamp', 'data']) test(`missing required ${property}`, () => { + const options = init(); delete options[property]; throws(realm, 'TypeError', () => new C(options)); + }); + test('subclass retains native slots', () => { + class Sub extends C {} + const chunk = new Sub(init()); equal(Object.getPrototypeOf(chunk), Sub.prototype); bytesEqual(copy(chunk), [1, 2, 3]); + }); + const chunk = (() => {try {return new C(init());} catch {return null;}})(); + for (const name of ['type', 'timestamp', 'duration', 'byteLength']) test(`readonly ${name} descriptor`, () => { + const d = Object.getOwnPropertyDescriptor(C.prototype, name); + equal(typeof d.get, 'function'); equal(d.get.length, 0); equal(d.set, undefined); + equal(d.enumerable, true); equal(d.configurable, true); + equal(Reflect.set(chunk, name, 'replacement'), false); + }); + test('copyTo descriptor', () => { + const d = Object.getOwnPropertyDescriptor(C.prototype, 'copyTo'); + equal(d.value.name, 'copyTo'); equal(d.value.length, 1); + equal(d.writable, true); equal(d.configurable, true); equal(d.enumerable, true); + }); + for (const name of ['type', 'timestamp', 'duration', 'byteLength', 'copyTo']) { + let trapCount = 0; + const revoked = Proxy.revocable(chunk || {}, {}); revoked.revoke(); + const receivers = [null, undefined, 1, {}, C.prototype, Object.create(C.prototype), Object.create(chunk || {}), + new Proxy(chunk || {}, {get() {trapCount++;}, getPrototypeOf() {trapCount++;}}), revoked.proxy]; + for (const [index, receiver] of receivers.entries()) test(`${name} receiver brand ${index}`, () => { + const method = name === 'copyTo' ? C.prototype.copyTo : Object.getOwnPropertyDescriptor(C.prototype, name).get; + throws(realm, 'TypeError', () => Reflect.apply(method, receiver, [new Uint8Array(3)])); equal(trapCount, 0); + }); + } + for (const kind of ['ArrayBuffer', 'Uint8Array', 'DataView', 'Int16Array', 'Float32Array']) test(`copyTo ${kind} respects offsets and tail`, () => { + const backing = new ArrayBuffer(12), bytes = new Uint8Array(backing); bytes.fill(8); + const destination = kind === 'ArrayBuffer' ? backing : kind === 'DataView' ? new DataView(backing, 4, 4) : new globalThis[kind](backing, 4, 4 / globalThis[kind].BYTES_PER_ELEMENT); + equal(chunk.copyTo(destination), undefined); + bytesEqual(bytes, kind === 'ArrayBuffer' ? [1, 2, 3, 8, 8, 8, 8, 8, 8, 8, 8, 8] : [8, 8, 8, 8, 1, 2, 3, 8, 8, 8, 8, 8]); + }); + test('copyTo insufficient destination is unchanged', () => { + const dest = new Uint8Array([9, 9]); throws(realm, 'TypeError', () => chunk.copyTo(dest)); bytesEqual(dest, [9, 9]); + }); + test('copyTo detached destination', () => { + const dest = new Uint8Array(3); dest.buffer.transfer(); throws(realm, 'TypeError', () => chunk.copyTo(dest)); + }); + test('copyTo required argument', () => throws(realm, 'TypeError', () => chunk.copyTo())); + for (const [index, dest] of [null, {}, [], 1, 'x', new Proxy(new Uint8Array(3), {})].entries()) + test(`copyTo invalid destination ${index}`, () => throws(realm, 'TypeError', () => chunk.copyTo(dest))); + test('zero chunk can copy to zero destination', () => { + const empty = new C(init({data: new ArrayBuffer(0)})); equal(empty.copyTo(new ArrayBuffer(0)), undefined); + }); + test('transfer includes unused buffers and preserves view data', () => { + const data = new Uint8Array([8, 1, 2, 3, 9]), extra = new ArrayBuffer(2); + const result = new C(init({data: new DataView(data.buffer, 1, 3), transfer: new Set([extra, data.buffer])})); + equal(data.byteLength, 0); equal(extra.byteLength, 0); bytesEqual(copy(result), [1, 2, 3]); + }); + test('transfer iterator finishes before byte snapshot', () => { + const data = new Uint8Array([1, 2, 3]); + const transfer = {*[Symbol.iterator]() {data[0] = 4; yield data.buffer; data[2] = 6;}}; + bytesEqual(copy(new C(init({data, transfer}))), [4, 2, 6]); equal(data.byteLength, 0); + }); + test('duplicate transfer rejects before detaching anything', () => { + const a = new ArrayBuffer(1), b = new ArrayBuffer(2); + throws(realm, 'DataCloneError', () => new C(init({transfer: [a, b, a]}))); equal(a.byteLength, 1); equal(b.byteLength, 2); + }); + test('detached transfer rejects before detaching other buffers', () => { + const a = new ArrayBuffer(1), b = new ArrayBuffer(2); b.transfer(); + throws(realm, 'DataCloneError', () => new C(init({transfer: [a, b]}))); equal(a.byteLength, 1); + }); + for (const bad of [null, {}, 1, 'x', [new Uint8Array(1)], [new Proxy(new ArrayBuffer(1), {})]]) + test(`invalid transfer ${String(bad)}`, () => throws(realm, 'TypeError', () => new C(init({transfer: bad})))); + test('failed transfer conversion preserves iterator and attached buffers', () => { + const buffer = new ArrayBuffer(1); let closed = 0; + const transfer = {*[Symbol.iterator]() {try {yield buffer; yield {};} finally {closed++;}}}; + // WebIDL sequence conversion propagates without IteratorClose. + throws(realm, 'TypeError', () => new C(init({transfer}))); equal(closed, 0); equal(buffer.byteLength, 1); + }); + test('failed type conversion leaves valid transfers attached', () => { + const buffer = new ArrayBuffer(1); throws(realm, 'TypeError', () => new C(init({type: 'bad', transfer: [buffer]}))); equal(buffer.byteLength, 1); + }); + if (typeof ArrayBuffer.prototype.resize === 'function') for (const view of [false, true]) { + test(`resizable data rejected ${view}`, () => { + const data = new ArrayBuffer(3, {maxByteLength: 8}); + throws(realm, 'TypeError', () => new C(init({data: view ? new Uint8Array(data) : data}))); + }); + test(`resizable destination rejected ${view}`, () => { + const dest = new ArrayBuffer(3, {maxByteLength: 8}); + throws(realm, 'TypeError', () => chunk.copyTo(view ? new DataView(dest) : dest)); + }); + } + if (typeof ArrayBuffer.prototype.resize === 'function') test('resizable transfer rejected without detaching valid entry', () => { + const fixed = new ArrayBuffer(1), resizable = new ArrayBuffer(1, {maxByteLength: 2}); + throws(realm, 'TypeError', () => new C(init({transfer: [fixed, resizable]}))); equal(fixed.byteLength, 1); + }); + if (typeof SharedArrayBuffer === 'function') { + for (const view of [false, true]) test(`shared BufferSource snapshot and destination ${view}`, () => { + const data = new SharedArrayBuffer(5), source = new Uint8Array(data); source.set([8, 1, 2, 3, 9]); + const result = new C(init({data: view ? new DataView(data, 1, 3) : data})); source.fill(7); + const destination = new SharedArrayBuffer(9), bytes = new Uint8Array(destination); bytes.fill(8); + result.copyTo(new Uint8Array(destination, 2, 5)); + bytesEqual(bytes, view ? [8, 8, 1, 2, 3, 8, 8, 8, 8] : [8, 8, 8, 1, 2, 3, 9, 8, 8]); + }); + test('shared buffer is not an ArrayBuffer transfer', () => throws(realm, 'TypeError', () => new C(init({transfer: [new SharedArrayBuffer(3)]})))); + if (typeof SharedArrayBuffer.prototype.grow === 'function') for (const view of [false, true]) test(`growable shared source rejected ${view}`, () => { + const data = new SharedArrayBuffer(3, {maxByteLength: 8}); + throws(realm, 'TypeError', () => new C(init({data: view ? new Uint8Array(data) : data}))); + }); + } + test('structured clone preserves slots and graph aliases in destination realm', () => { + const source = new C(init({duration: Number.MAX_SAFE_INTEGER})); + const graph = realm.structuredClone([source, source]); + equal(graph[0], graph[1]); equal(graph[0] === source, false); + equal(Object.getPrototypeOf(graph[0]), C.prototype); equal(graph[0].timestamp, -17); + equal(graph[0].duration, Number.MAX_SAFE_INTEGER); bytesEqual(copy(graph[0]), [1, 2, 3]); + }); + test('structured clone ignores overridden public getters', () => { + const source = new C(init()); + for (const key of ['type', 'timestamp', 'duration', 'byteLength', 'copyTo', 'extra']) + Object.defineProperty(source, key, {enumerable: true, get() {throw Error('public getter read');}}); + const cloned = realm.structuredClone(source); + equal(cloned.type, 'key'); equal(cloned.timestamp, -17); equal(cloned.duration, null); bytesEqual(copy(cloned), [1, 2, 3]); + }); + test('structured clone uses intrinsic constructor after global replacement', () => { + const source = new C(init()); + try { + realm.EncodedVideoChunk = function () {throw Error('author constructor called');}; + const cloned = realm.structuredClone(source); + equal(Object.getPrototypeOf(cloned), C.prototype); bytesEqual(copy(cloned), [1, 2, 3]); + } finally {realm.EncodedVideoChunk = C;} + }); + test('chunk is serializable but not transferable', () => { + const buffer = new ArrayBuffer(2); + throws(realm, 'DataCloneError', () => realm.structuredClone(chunk, {transfer: [buffer, chunk]})); equal(buffer.byteLength, 2); + }); + if (typeof document !== 'undefined') { + test('history serialization rejects nested chunk without mutation', () => { + const before = realm.history.length; + throws(realm, 'DataCloneError', () => realm.history.pushState({chunk}, '')); equal(realm.history.length, before); + }); + test('postMessage serialization preserves source slots', () => { + const channel = new realm.MessageChannel(); + channel.port1.postMessage(chunk); equal(chunk.timestamp, -17); bytesEqual(copy(chunk), [1, 2, 3]); + channel.port1.close(); channel.port2.close(); + }); + } + } + if (typeof document !== 'undefined') check('cross-realm genuine receiver shares native slots', () => { + const main = new EncodedVideoChunk(init()), other = realms[1]; + equal(Object.getOwnPropertyDescriptor(other.EncodedVideoChunk.prototype, 'timestamp').get.call(main), -17); + const dest = new Uint8Array(3); other.EncodedVideoChunk.prototype.copyTo.call(main, dest); bytesEqual(dest, [1, 2, 3]); + const clone = other.structuredClone(main); equal(Object.getPrototypeOf(clone), other.EncodedVideoChunk.prototype); bytesEqual(copy(clone), [1, 2, 3]); + }); + globalThis.__uiEventResults = {complete: true, passed: checks.filter(row => row.passed).length, total: checks.length, checks}; + return true; +})() diff --git a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.rs b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.rs new file mode 100644 index 00000000000..f4b45d8e7da --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.rs @@ -0,0 +1,85 @@ +use super::*; + +#[test] +fn encoded_video_chunk_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 = ''") + .unwrap(); + assert_eq!( + vm.eval(include_str!("encoded_video_chunk_shell.js")) + .unwrap(), + "ok", + "{url}" + ); + } +} + +#[test] +fn encoded_video_chunk_preserves_bytes_transfer_conversion_and_serialization() { + let mut vm = new_storage_page_task_executor_test_vm("https://encoded-video-chunk.test/"); + vm.eval("document.body.innerHTML = ''") + .unwrap(); + vm.eval(include_str!("encoded_video_chunk.js")).unwrap(); + assert_eq!(vm.eval("__uiEventResults.complete").unwrap(), "true"); + assert_eq!( + vm.eval("JSON.stringify(__uiEventResults.checks.filter(row => !row.passed))") + .unwrap(), + "[]" + ); +} + +#[test] +fn encoded_video_chunk_accepts_registered_native_proxy_receivers() { + let mut vm = new_storage_page_task_executor_test_vm("https://encoded-video-chunk.test/"); + vm.eval("globalThis.nativeChunk = new EncodedVideoChunk({type:'delta', timestamp:-5, data:new Uint8Array([4,5])})").unwrap(); + let context_ptr = &vm.page_default_context as *const _; + vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| { + let global = scope.get_current_context().global(scope); + let key = crate::util::v8str(scope, "nativeChunk"); + let chunk = + v8::Local::::try_from(global.get(scope, key.into()).unwrap()).unwrap(); + let handler = crate::util::new_null_prototype_object(scope); + let proxy = v8::Proxy::new(scope, chunk, handler).unwrap(); + moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap(); + assert_eq!( + global.create_data_property(scope, key.into(), proxy.into()), + Some(true) + ); + Ok(()) + }) + .unwrap(); + assert_eq!(vm.eval("nativeChunk.type + '|' + nativeChunk.timestamp + '|' + nativeChunk.duration + '|' + nativeChunk.byteLength").unwrap(), "delta|-5|null|2"); + assert_eq!( + vm.eval( + "const dest = new Uint8Array(2); nativeChunk.copyTo(dest); Array.from(dest).join(',')" + ) + .unwrap(), + "4,5" + ); + assert_eq!(vm.eval("try { new Proxy(nativeChunk, {}).copyTo(dest); 'accepted' } catch(error) { error.name }").unwrap(), "TypeError"); +} + +#[test] +fn encoded_video_chunk_rejects_indexed_db_storage_and_roundtrips_message_ports() { + let mut vm = + new_storage_page_task_executor_test_vm("https://encoded-video-chunk-storage.test/"); + vm.eval("document.body.innerHTML = ''") + .unwrap(); + vm.eval(include_str!("encoded_video_chunk_storage.js")) + .unwrap(); + assert_eq!( + vm.eval_after_selected_page_tasks("__uiEventResults.complete") + .unwrap(), + "true" + ); + assert_eq!( + vm.eval("JSON.stringify(__uiEventResults.checks.filter(row => !row.passed))") + .unwrap(), + "[]" + ); +} diff --git a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.js b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.js index 1dea2990be5..79add69bc3d 100644 --- a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.js +++ b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.js @@ -17,12 +17,12 @@ 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'); - // These are interface shells. Argument conversion and backend operations remain unavailable. + // The native constructor validates its required init dictionary. 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(constructionError instanceof realm.TypeError, + name + ' invalid construction throws in the callee realm'); + if (realm !== window) assert(!(constructionError instanceof TypeError), name + ' foreign TypeError'); assert(realm[name] === constructor, name + ' materialization remains stable'); } } diff --git a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.rs b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.rs deleted file mode 100644 index 6de293cb03a..00000000000 --- a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.rs +++ /dev/null @@ -1,20 +0,0 @@ -use super::*; - -#[test] -fn shell_encoded_video_chunk_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 = ''") - .unwrap(); - assert_eq!( - vm.eval(include_str!("encoded_video_chunk_shell.js")) - .unwrap(), - "ok", - "{url}" - ); - } -} diff --git a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_storage.js b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_storage.js new file mode 100644 index 00000000000..e0285e93684 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_storage.js @@ -0,0 +1,42 @@ +(async () => { + const checks = []; + const check = (name, passed) => checks.push({name, passed: !!passed}); + const request = req => new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); + }); + const realms = [globalThis]; + if (typeof document !== 'undefined') realms.push(document.getElementById('child').contentWindow); + try { + for (const [index, realm] of realms.entries()) { + const C = realm.EncodedVideoChunk; + const chunk = new C({type: 'delta', timestamp: -3, data: new Uint8Array([7, 8, 9])}); + const ports = new realm.MessageChannel(); + try { + const received = new Promise(resolve => {ports.port2.onmessage = event => resolve(event.data);}); + ports.port1.postMessage([chunk, chunk]); + const graph = await received, dest = new Uint8Array(3); + graph[0].copyTo(dest); + check(`${index}: MessagePort native identity and destination prototype`, graph[0] !== chunk && graph[0] === graph[1] && Object.getPrototypeOf(graph[0]) === C.prototype); + check(`${index}: MessagePort preserves nullable duration and negative timestamp`, graph[0].duration === null && graph[0].timestamp === -3 && graph[0].type === 'delta'); + check(`${index}: MessagePort preserves bytes and sender`, dest.join(',') === '7,8,9' && chunk.byteLength === 3); + } finally {ports.port1.close(); ports.port2.close();} + const name = `encoded-video-chunk-storage-${index}`, open = realm.indexedDB.open(name, 1); + open.onupgradeneeded = () => open.result.createObjectStore('chunks'); + const db = await request(open); + try { + const tx = db.transaction('chunks', 'readwrite'), store = tx.objectStore('chunks'); + const done = new Promise((resolve, reject) => {tx.oncomplete = resolve; tx.onabort = () => reject(tx.error);}); + let error; + try {store.put({chunk}, 'rejected');} catch (caught) {error = caught;} + check(`${index}: IndexedDB rejects nested chunk synchronously in callee realm`, error instanceof realm.DOMException && error.name === 'DataCloneError'); + store.put('safe', 'accepted'); await done; + const read = db.transaction('chunks'); + const rejected = request(read.objectStore('chunks').get('rejected')); + const accepted = request(read.objectStore('chunks').get('accepted')); + check(`${index}: clone rejection leaves transaction usable and inserts no record`, await rejected === undefined && await accepted === 'safe'); + } finally {db.close(); await request(realm.indexedDB.deleteDatabase(name));} + } + } catch (error) {checks.push({name: 'async completion', passed: false, error: String(error), stack: error.stack});} + globalThis.__uiEventResults = {complete: true, passed: checks.filter(row => row.passed).length, total: checks.length, checks}; + return true; +})() diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index 9adeb4e29db..804360b5234 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2266,6 +2266,7 @@ mod dynamic_inline_scripts; mod element_click; mod eme_owner_interface_exposure_interfaces; mod encoded_video_chunk_shell; +mod encoded_video_chunk; mod event_receivers; mod extracted; mod fetch_integrity; diff --git a/moli-renderer-v8/src/structured_clone.rs b/moli-renderer-v8/src/structured_clone.rs index 34ee9d70426..faf7f981fbf 100644 --- a/moli-renderer-v8/src/structured_clone.rs +++ b/moli-renderer-v8/src/structured_clone.rs @@ -8,17 +8,20 @@ use std::{ use crate::{ context_bootstrap::{ - CryptoKeyAlgorithmClonePayload, CryptoKeyClonePayload, FileSystemFileSnapshotClonePayload, - FileSystemHandleClonePayload, GeometryClonePayload, ImageDataClonePayload, - ReadableStreamClonePayload, TransformStreamClonePayload, WritableStreamClonePayload, - attach_file_system_file_snapshot_clone_payload, build_file_list_object, build_file_object, + CryptoKeyAlgorithmClonePayload, CryptoKeyClonePayload, EncodedVideoChunkClonePayload, + EncodedVideoChunkType, FileSystemFileSnapshotClonePayload, FileSystemHandleClonePayload, + GeometryClonePayload, ImageDataClonePayload, ReadableStreamClonePayload, + TransformStreamClonePayload, WritableStreamClonePayload, + attach_file_system_file_snapshot_clone_payload, + build_encoded_video_chunk_from_clone_payload, build_file_list_object, build_file_object, build_file_system_handle_from_clone_payload, build_geometry_object_from_clone_payload, build_image_data_object_from_clone_payload, build_readable_stream_clone_shell, build_transform_stream_clone_shell, build_writable_stream_clone_shell, crypto_key_clone_payload_from_object, crypto_key_object_from_clone_payload, detach_message_port_owner_for_transfer, detach_transferred_message_port, - dom_exception_clone_fields, ensure_message_port_wrapper_for_id, - file_list_files_from_object, file_system_file_snapshot_clone_payload_from_object, + dom_exception_clone_fields, encoded_video_chunk_clone_payload_from_object, + ensure_message_port_wrapper_for_id, file_list_files_from_object, + file_system_file_snapshot_clone_payload_from_object, file_system_handle_clone_payload_from_object, geometry_clone_payload_from_object, image_data_clone_payload_from_object, initialize_readable_stream_clone_shell, initialize_transform_stream_clone_shell, initialize_writable_stream_clone_shell, @@ -47,6 +50,7 @@ const HOST_OBJECT_TAG_WRITABLE_STREAM: u32 = 9; const HOST_OBJECT_TAG_TRANSFORM_STREAM: u32 = 10; pub(crate) const HOST_OBJECT_TAG_GEOMETRY: u32 = 11; pub(crate) const HOST_OBJECT_TAG_FILE_LIST: u32 = 12; +const HOST_OBJECT_TAG_ENCODED_VIDEO_CHUNK: u32 = 13; const HOST_OBJECT_TAG_TRANSFERRED_MESSAGE_PORT: u32 = 22; const GEOMETRY_KIND_DOM_POINT_READONLY: u32 = 0; @@ -436,6 +440,17 @@ impl v8::ValueSerializerImpl for WireSerializer { return Some(true); } } + Some("EncodedVideoChunk") => { + if self.policy == StructuredClonePolicy::Storage { + throw_data_clone_exception(scope, "EncodedVideoChunk cannot be stored."); + return None; + } + if let Some(payload) = encoded_video_chunk_clone_payload_from_object(scope, object) + { + write_encoded_video_chunk_payload(serializer, payload); + return Some(true); + } + } Some("CryptoKey") => { if write_crypto_key_payload(scope, object, serializer).is_some() { return Some(true); @@ -703,6 +718,12 @@ impl v8::ValueDeserializerImpl for WireDeserializer { ensure_message_port_wrapper_for_id(scope, port_id) } HOST_OBJECT_TAG_IMAGE_DATA => read_image_data_payload(scope, deserializer), + HOST_OBJECT_TAG_ENCODED_VIDEO_CHUNK => read_encoded_video_chunk_payload(deserializer) + .and_then(|payload| build_encoded_video_chunk_from_clone_payload(scope, payload)) + .or_else(|| { + throw_data_clone_exception(scope, "Failed to deserialize EncodedVideoChunk."); + None + }), HOST_OBJECT_TAG_CRYPTO_KEY => { read_crypto_key_payload(scope, deserializer).or_else(|| { throw_data_clone_exception( @@ -1268,6 +1289,54 @@ fn read_optional_raw_vec( } } +fn write_encoded_video_chunk_payload( + serializer: &dyn v8::ValueSerializerHelper, + payload: EncodedVideoChunkClonePayload, +) { + serializer.write_uint32(HOST_OBJECT_TAG_ENCODED_VIDEO_CHUNK); + serializer.write_uint32(match payload.kind { + EncodedVideoChunkType::Key => 0, + EncodedVideoChunkType::Delta => 1, + }); + serializer.write_uint64(payload.timestamp as u64); + serializer.write_uint32(u32::from(payload.duration.is_some())); + if let Some(duration) = payload.duration { + serializer.write_uint64(duration); + } + write_raw_vec(serializer, &payload.bytes); +} + +fn read_encoded_video_chunk_payload( + deserializer: &dyn v8::ValueDeserializerHelper, +) -> Option { + let kind = match read_u32(deserializer)? { + 0 => EncodedVideoChunkType::Key, + 1 => EncodedVideoChunkType::Delta, + _ => return None, + }; + let mut timestamp = 0; + if !deserializer.read_uint64(&mut timestamp) { + return None; + } + let duration = match read_u32(deserializer)? { + 0 => None, + 1 => { + let mut duration = 0; + if !deserializer.read_uint64(&mut duration) { + return None; + } + Some(duration) + } + _ => return None, + }; + Some(EncodedVideoChunkClonePayload { + kind, + timestamp: timestamp as i64, + duration, + bytes: read_raw_vec(deserializer)?, + }) +} + fn write_raw_vec(serializer: &dyn v8::ValueSerializerHelper, bytes: &[u8]) { serializer.write_uint32(bytes.len() as u32); serializer.write_raw_bytes(bytes); diff --git a/moli-renderer-v8/src/worker/thread/tests/mod.rs b/moli-renderer-v8/src/worker/thread/tests/mod.rs index e93aedfdc7b..e567a198152 100644 --- a/moli-renderer-v8/src/worker/thread/tests/mod.rs +++ b/moli-renderer-v8/src/worker/thread/tests/mod.rs @@ -237,7 +237,10 @@ fn inspect_payload(payload: &V8StructuredClonePayload, expression: &str) -> Stri result.to_rust_string_lossy(scope) } -fn inspect_payload_with_image_data(payload: &V8StructuredClonePayload, expression: &str) -> String { +fn inspect_payload_with_worker_interfaces( + payload: &V8StructuredClonePayload, + expression: &str, +) -> String { let mut isolate = v8::Isolate::new(Default::default()); let scope = pin!(v8::HandleScope::new(&mut isolate)); let scope = &mut scope.init(); diff --git a/moli-renderer-v8/src/worker/thread/tests/postmessage.rs b/moli-renderer-v8/src/worker/thread/tests/postmessage.rs index 602ebdf0ce6..ca97135af48 100644 --- a/moli-renderer-v8/src/worker/thread/tests/postmessage.rs +++ b/moli-renderer-v8/src/worker/thread/tests/postmessage.rs @@ -1400,6 +1400,72 @@ async fn worker_postmessage_arraybuffer_to_parent() { } } +#[tokio::test] +async fn worker_postmessage_encoded_video_chunk_preserves_native_slots_and_aliases() { + ensure_v8(); + let mut handle = spawn_worker( + r#" + const buffer = new Uint8Array([9, 4, 5, 6, 8]).buffer; + const chunk = new EncodedVideoChunk({ + type: 'delta', timestamp: -123, duration: 27, + data: new Uint8Array(buffer, 1, 3), transfer: [buffer] + }); + if (buffer.byteLength !== 0) throw Error('transfer did not detach'); + postMessage([chunk, chunk]); + "# + .into(), + "https://encoded-video-chunk.test/worker.js".into(), + ); + let message = timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap(); + match message { + WorkerToParentMessage::Post(payload) => { + // This helper installs the native DedicatedWorker interface registry + // in a fresh destination context before deserializing. + let description = inspect_payload_with_worker_interfaces( + &payload, + r#"(() => { + const chunk = __wire[0], bytes = new Uint8Array(chunk.byteLength); + chunk.copyTo(bytes); + return [chunk instanceof EncodedVideoChunk, __wire[0] === __wire[1], + chunk.type, chunk.timestamp, chunk.duration, Array.from(bytes).join(',')].join('|'); + })()"#, + ); + assert_eq!(description, "true|true|delta|-123|27|4,5,6"); + for realm in [ + crate::context_bootstrap::exposed_interfaces::RealmKind::SharedWorker, + crate::context_bootstrap::exposed_interfaces::RealmKind::ServiceWorker, + ] { + let mut isolate = v8::Isolate::new(Default::default()); + let scope = pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = v8::Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + let global = context.global(scope); + crate::context_bootstrap::install_worker_lazy_exposed_interfaces( + scope, global, realm, true, + ) + .unwrap(); + let source = v8::String::new(scope, "Object.defineProperty(globalThis, 'EncodedVideoChunk', {get() {throw Error('public constructor lookup');}})").unwrap(); + let script = v8::Script::compile(scope, source, None).unwrap(); + crate::script_execution::execute_compiled_script(scope, script).unwrap(); + let try_catch = pin!(v8::TryCatch::new(scope)); + let scope = &mut try_catch.init(); + assert!(structured_deserialize_value(scope, &payload).is_none()); + let error = scope.exception().unwrap().to_object(scope).unwrap(); + let name = crate::util::v8str(scope, "name"); + assert_eq!( + error + .get(scope, name.into()) + .unwrap() + .to_rust_string_lossy(scope), + "DataCloneError" + ); + } + } + other => panic!("expected Post, got {other:?}"), + } +} + #[tokio::test] async fn worker_postmessage_image_data_to_parent_preserves_interface_and_pixels() { ensure_v8(); @@ -1419,7 +1485,7 @@ async fn worker_postmessage_image_data_to_parent_preserves_interface_and_pixels( .expect("channel closed"); match msg { WorkerToParentMessage::Post(payload) => { - let description = inspect_payload_with_image_data( + let description = inspect_payload_with_worker_interfaces( &payload, r#" (() => [ diff --git a/moli-webidl-derive/src/converter.rs b/moli-webidl-derive/src/converter.rs index 93e1dc52b12..c14c647d608 100644 --- a/moli-webidl-derive/src/converter.rs +++ b/moli-webidl-derive/src/converter.rs @@ -19,13 +19,13 @@ pub(crate) enum ConverterKind { LongLong, ClampedLongLong, EnforceRangeLong, + EnforceRangeLongLong, Short, UnsignedShort, EnforceRangeUnsignedShort, ClampedUnsignedShort, UnsignedLong, EnforceRangeUnsignedLong, - EnforceRangeLongLong, UnsignedLongLong, EnforceRangeUnsignedLongLong, Float, @@ -59,13 +59,13 @@ impl ConverterKind { "long_long" => Ok(Self::LongLong), "clamped_long_long" => Ok(Self::ClampedLongLong), "enforce_range_long" => Ok(Self::EnforceRangeLong), + "enforce_range_long_long" => Ok(Self::EnforceRangeLongLong), "short" => Ok(Self::Short), "unsigned_short" => Ok(Self::UnsignedShort), "enforce_range_unsigned_short" => Ok(Self::EnforceRangeUnsignedShort), "clamped_unsigned_short" => Ok(Self::ClampedUnsignedShort), "unsigned_long" => Ok(Self::UnsignedLong), "enforce_range_unsigned_long" => Ok(Self::EnforceRangeUnsignedLong), - "enforce_range_long_long" => Ok(Self::EnforceRangeLongLong), "unsigned_long_long" => Ok(Self::UnsignedLongLong), "enforce_range_unsigned_long_long" => Ok(Self::EnforceRangeUnsignedLongLong), "float" => Ok(Self::Float), @@ -97,6 +97,7 @@ impl ConverterKind { Self::LongLong => quote!(::moli_webidl::LongLong), Self::ClampedLongLong => quote!(::moli_webidl::ClampedLongLong), Self::EnforceRangeLong => quote!(::moli_webidl::EnforceRangeLong), + Self::EnforceRangeLongLong => quote!(::moli_webidl::EnforceRangeLongLong), Self::Short => quote!(::moli_webidl::Short), Self::UnsignedShort => quote!(::moli_webidl::UnsignedShort), Self::EnforceRangeUnsignedShort => quote!(::moli_webidl::EnforceRangeUnsignedShort), @@ -105,7 +106,6 @@ impl ConverterKind { Self::EnforceRangeUnsignedLong => { quote!(::moli_webidl::EnforceRangeUnsignedLong) } - Self::EnforceRangeLongLong => quote!(::moli_webidl::EnforceRangeLongLong), Self::UnsignedLongLong => quote!(::moli_webidl::UnsignedLongLong), Self::EnforceRangeUnsignedLongLong => { quote!(::moli_webidl::EnforceRangeUnsignedLongLong) @@ -145,6 +145,7 @@ impl ConverterKind { Self::LongLong => quote!(::moli_webidl::LongLong(#expr)), Self::ClampedLongLong => quote!(::moli_webidl::ClampedLongLong(#expr)), Self::EnforceRangeLong => quote!(::moli_webidl::EnforceRangeLong(#expr)), + Self::EnforceRangeLongLong => quote!(::moli_webidl::EnforceRangeLongLong(#expr)), Self::Short => quote!(::moli_webidl::Short(#expr)), Self::UnsignedShort => quote!(::moli_webidl::UnsignedShort(#expr)), Self::EnforceRangeUnsignedShort => { @@ -157,7 +158,6 @@ impl ConverterKind { Self::EnforceRangeUnsignedLong => { quote!(::moli_webidl::EnforceRangeUnsignedLong(#expr)) } - Self::EnforceRangeLongLong => quote!(::moli_webidl::EnforceRangeLongLong(#expr)), Self::UnsignedLongLong => quote!(::moli_webidl::UnsignedLongLong(#expr)), Self::EnforceRangeUnsignedLongLong => { quote!(::moli_webidl::EnforceRangeUnsignedLongLong(#expr)) @@ -188,13 +188,13 @@ impl ConverterKind { | Self::LongLong | Self::ClampedLongLong | Self::EnforceRangeLong + | Self::EnforceRangeLongLong | Self::Short | Self::UnsignedShort | Self::EnforceRangeUnsignedShort | Self::ClampedUnsignedShort | Self::UnsignedLong | Self::EnforceRangeUnsignedLong - | Self::EnforceRangeLongLong | Self::UnsignedLongLong | Self::EnforceRangeUnsignedLongLong | Self::Float diff --git a/moli-webidl/src/convert.rs b/moli-webidl/src/convert.rs index d27822de11a..4cfd540e1f7 100644 --- a/moli-webidl/src/convert.rs +++ b/moli-webidl/src/convert.rs @@ -352,20 +352,6 @@ impl<'s> WebIdlConverter<'s> for ClampedUnsignedShort { } } -impl<'s> WebIdlConverter<'s> for UnsignedLongLong { - type Options = (); - - fn convert( - scope: &mut v8::PinScope<'s, '_>, - value: v8::Local<'s, v8::Value>, - context: Context, - _options: &Self::Options, - ) -> Result { - number_value(scope, value, context, "unsigned long long") - .map(|value| Self(unsigned_long_long(value))) - } -} - impl<'s> WebIdlConverter<'s> for crate::LongLong { type Options = (); fn convert( @@ -412,6 +398,20 @@ impl<'s> WebIdlConverter<'s> for EnforceRangeLongLong { } } +impl<'s> WebIdlConverter<'s> for UnsignedLongLong { + type Options = (); + + fn convert( + scope: &mut v8::PinScope<'s, '_>, + value: v8::Local<'s, v8::Value>, + context: Context, + _options: &Self::Options, + ) -> Result { + number_value(scope, value, context, "unsigned long long") + .map(|value| Self(unsigned_long_long(value))) + } +} + impl<'s> WebIdlConverter<'s> for EnforceRangeUnsignedLongLong { type Options = (); diff --git a/moli-webidl/src/lib.rs b/moli-webidl/src/lib.rs index ee5ecc47741..a663e527ecd 100644 --- a/moli-webidl/src/lib.rs +++ b/moli-webidl/src/lib.rs @@ -74,6 +74,7 @@ mod snapshot; mod traits; mod types; +pub use buffer_source::AllowSharedBufferSource; pub use convert::{ argument, argument_with_options, convert, convert_optional_sequence, convert_with_options, legacy_bool_member_or, legacy_number_member_or, legacy_optional_member, @@ -121,12 +122,11 @@ pub mod __private { } pub use traits::{ParseOutcome, WebIdlArguments, WebIdlConverter, WebIdlDictionary, WebIdlEnum}; pub use types::{ - Boolean, BufferSource, ByteString, ClampedLongLong, ClampedUnsignedShort, Dictionary, - DomString, DomString16, Double, EnforceRangeLong, EnforceRangeUnsignedLong, - EnforceRangeUnsignedLongLong, EnumValue, EventListenerOptions, InterfaceObject, - InterfaceOptions, Long, LongLong, Octet, Record, Sequence, Short, StringOptions, - UnrestrictedDouble, UnrestrictedFloat, UnsignedLong, UnsignedLongLong, UnsignedShort, - UsvString, + Boolean, BufferSource, ByteString, ClampedLongLong, ClampedUnsignedShort, Dictionary, DomString, DomString16, + Double, EnforceRangeLong, EnforceRangeLongLong, EnforceRangeUnsignedLong, + EnforceRangeUnsignedLongLong, EnumValue, EventListenerOptions, InterfaceObject, InterfaceOptions, + Long, LongLong, Octet, Record, Sequence, Short, StringOptions, UnrestrictedDouble, + UnrestrictedFloat, UnsignedLong, UnsignedLongLong, UnsignedShort, UsvString, }; /// Restricted WebIDL float represented as a finite binary32 value. diff --git a/moli-webidl/src/types.rs b/moli-webidl/src/types.rs index 2fcebeb3d23..c684ce5f50a 100644 --- a/moli-webidl/src/types.rs +++ b/moli-webidl/src/types.rs @@ -331,6 +331,15 @@ impl From for i64 { } } +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct EnforceRangeLongLong(pub i64); + +impl From for i64 { + fn from(value: EnforceRangeLongLong) -> Self { + value.0 + } +} + #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct UnsignedLongLong(pub u64); @@ -349,14 +358,6 @@ impl From for u64 { } } -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -pub struct EnforceRangeLongLong(pub i64); -impl From for i64 { - fn from(value: EnforceRangeLongLong) -> Self { - value.0 - } -} - #[derive(Debug, Default)] pub struct StringOptions { pub treat_null_as_empty_string: bool,