From 7f5e805e31f44c19ddc9101ab4596e0798962773 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Mon, 5 Oct 2026 08:26:35 +0800 Subject: [PATCH] feat(webcodecs): implement native encoded video chunk byte containers --- moli-core/tests/web_apis.rs | 2 - .../assets/prototype_bindings.rs | 4 ++ .../script_vm/tests/encoded_video_chunk.rs | 20 ++++++ .../tests/encoded_video_chunk_shell.rs | 20 ------ .../tests/encoded_video_chunk_storage.js | 42 ++++++++++++ moli-renderer-v8/src/script_vm/tests/mod.rs | 3 +- moli-renderer-v8/src/structured_clone.rs | 2 +- .../src/worker/thread/tests/mod.rs | 5 +- .../src/worker/thread/tests/postmessage.rs | 68 ++++++++++++++++++- moli-webidl-derive/src/converter.rs | 10 +-- moli-webidl/src/convert.rs | 28 ++++---- moli-webidl/src/lib.rs | 12 ++-- moli-webidl/src/types.rs | 17 ++--- 13 files changed, 173 insertions(+), 60 deletions(-) delete mode 100644 moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_shell.rs create mode 100644 moli-renderer-v8/src/script_vm/tests/encoded_video_chunk_storage.js diff --git a/moli-core/tests/web_apis.rs b/moli-core/tests/web_apis.rs index 4e3d44ceecb..fa5b44db06c 100644 --- a/moli-core/tests/web_apis.rs +++ b/moli-core/tests/web_apis.rs @@ -41,8 +41,6 @@ mod fetch_body_realm; mod fetch_opaque_stream; #[path = "web_apis/fetch_preaborted_upload.rs"] mod fetch_preaborted_upload; -#[path = "web_apis/locked_body.rs"] -mod locked_body; #[path = "web_apis/pipe_disturbed.rs"] mod pipe_disturbed; #[path = "web_apis/request_init.rs"] 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 b0bccfce62e..1631195ebe7 100644 --- a/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs +++ b/moli-renderer-v8/src/context_bootstrap/assets/prototype_bindings.rs @@ -15,6 +15,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, @@ -405,6 +406,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/script_vm/tests/encoded_video_chunk.rs b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.rs index e04f919472b..9bca8b90306 100644 --- a/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.rs +++ b/moli-renderer-v8/src/script_vm/tests/encoded_video_chunk.rs @@ -63,3 +63,23 @@ fn encoded_video_chunk_accepts_registered_native_proxy_receivers() { ); 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.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 21749203621..85455e3157f 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2341,7 +2341,7 @@ mod svg_length_list_native_receivers; #[cfg(feature = "devtools")] 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; @@ -2548,7 +2548,6 @@ mod dom_rect_structured_clone; mod domrect_receiver_consolidation; mod resize_observer_entries; -mod encoded_video_chunk; mod payment_events; mod file_value_receivers; diff --git a/moli-renderer-v8/src/structured_clone.rs b/moli-renderer-v8/src/structured_clone.rs index f9678fce84e..499b18750d7 100644 --- a/moli-renderer-v8/src/structured_clone.rs +++ b/moli-renderer-v8/src/structured_clone.rs @@ -53,12 +53,12 @@ pub(crate) const HOST_OBJECT_TAG_FILE_SYSTEM_HANDLE: u32 = 7; pub(crate) const HOST_OBJECT_TAG_QUOTA_EXCEEDED_ERROR: u32 = 8; const HOST_OBJECT_TAG_WRITABLE_STREAM: u32 = 9; const HOST_OBJECT_TAG_TRANSFORM_STREAM: u32 = 10; -const HOST_OBJECT_TAG_ENCODED_VIDEO_CHUNK: u32 = 13; pub(crate) const HOST_OBJECT_TAG_WEB_TRANSPORT_ERROR: u32 = 14; pub(crate) const HOST_OBJECT_TAG_GEOMETRY: u32 = 11; pub(crate) const HOST_OBJECT_TAG_FILE_LIST: u32 = 12; const HOST_OBJECT_TAG_RTC_ENCODED_AUDIO_FRAME: u32 = 16; const HOST_OBJECT_TAG_RTC_ENCODED_VIDEO_FRAME: u32 = 17; +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; diff --git a/moli-renderer-v8/src/worker/thread/tests/mod.rs b/moli-renderer-v8/src/worker/thread/tests/mod.rs index 8730113f8d5..1bc27cfa2ee 100644 --- a/moli-renderer-v8/src/worker/thread/tests/mod.rs +++ b/moli-renderer-v8/src/worker/thread/tests/mod.rs @@ -308,7 +308,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 3b7486e0214..30286ac10dc 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 5fd1ec89c5d..7cb741f9a5f 100644 --- a/moli-webidl-derive/src/converter.rs +++ b/moli-webidl-derive/src/converter.rs @@ -20,6 +20,7 @@ pub(crate) enum ConverterKind { LongLong, ClampedLongLong, EnforceRangeLong, + EnforceRangeLongLong, Short, UnsignedShort, EnforceRangeUnsignedShort, @@ -27,7 +28,6 @@ pub(crate) enum ConverterKind { UnsignedLong, ClampedUnsignedLong, EnforceRangeUnsignedLong, - EnforceRangeLongLong, UnsignedLongLong, EnforceRangeUnsignedLongLong, Float, @@ -61,6 +61,7 @@ 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), @@ -68,7 +69,6 @@ impl ConverterKind { "unsigned_long" => Ok(Self::UnsignedLong), "clamped_unsigned_long" => Ok(Self::ClampedUnsignedLong), "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), @@ -100,6 +100,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), @@ -109,7 +110,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) @@ -149,6 +149,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 => { @@ -162,7 +163,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)) @@ -193,6 +193,7 @@ impl ConverterKind { | Self::LongLong | Self::ClampedLongLong | Self::EnforceRangeLong + | Self::EnforceRangeLongLong | Self::Short | Self::UnsignedShort | Self::EnforceRangeUnsignedShort @@ -200,7 +201,6 @@ impl ConverterKind { | Self::UnsignedLong | Self::ClampedUnsignedLong | 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 3a3e2a86ebe..3ef0ae5ecbb 100644 --- a/moli-webidl/src/convert.rs +++ b/moli-webidl/src/convert.rs @@ -366,20 +366,6 @@ impl<'s> WebIdlConverter<'s> for crate::ClampedUnsignedLong { } } -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( @@ -426,6 +412,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 0f17aff4451..bfca953fae7 100644 --- a/moli-webidl/src/lib.rs +++ b/moli-webidl/src/lib.rs @@ -126,13 +126,13 @@ pub mod __private { pub use traits::{ParseOutcome, WebIdlArguments, WebIdlConverter, WebIdlDictionary, WebIdlEnum}; pub use types::{ Boolean, BufferSource, ByteString, ClampedLongLong, ClampedUnsignedLong, ClampedUnsignedShort, - Dictionary, DomString, DomString16, Double, EnforceRangeLong, EnforceRangeUnsignedLong, - EnforceRangeUnsignedLongLong, EnumValue, EventListenerOptions, InterfaceObject, - InterfaceOptions, Long, LongLong, Octet, Record, Sequence, Short, StringOptions, - Uint8ArrayOptions, UnrestrictedDouble, UnrestrictedFloat, UnsignedLong, UnsignedLongLong, - UnsignedShort, UsvString, + Dictionary, DomString, DomString16, Double, EnforceRangeLong, EnforceRangeLongLong, + EnforceRangeUnsignedLong, EnforceRangeUnsignedLongLong, EnumValue, EventListenerOptions, + InterfaceObject, InterfaceOptions, Long, LongLong, Octet, Record, Sequence, Short, + StringOptions, Uint8ArrayOptions, UnrestrictedDouble, UnrestrictedFloat, UnsignedLong, + UnsignedLongLong, UnsignedShort, UsvString, }; +pub use types::EnforceRangeUnsignedShort; /// Restricted WebIDL float represented as a finite binary32 value. pub use types::Float; -pub use types::{EnforceRangeLongLong, EnforceRangeUnsignedShort}; diff --git a/moli-webidl/src/types.rs b/moli-webidl/src/types.rs index 9362f013639..c74a7c7fb3b 100644 --- a/moli-webidl/src/types.rs +++ b/moli-webidl/src/types.rs @@ -346,6 +346,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); @@ -364,14 +373,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,