Skip to content

Truly independent web browser

LibWeb: Implement a basic Media Session API

sideshowbarkerb9918de41002
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index abf163153fc..68d4c31fae1 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -665,6 +665,9 @@ set(SOURCES
MediaCapture/MediaStream.cpp
MediaCapture/MediaStreamTrack.cpp
MediaCapture/MediaStreamTrackEvent.cpp
+ MediaSession/ChapterInformation.cpp
+ MediaSession/MediaMetadata.cpp
+ MediaSession/MediaSession.cpp
MediaSourceExtensions/BufferedChangeEvent.cpp
MediaSourceExtensions/EventNames.cpp
MediaSourceExtensions/ManagedMediaSource.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 39a6e68f68b..cd456594806 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -943,6 +943,14 @@ class MediaCapabilities;
}
+namespace Web::MediaSession {
+
+class ChapterInformation;
+class MediaMetadata;
+class MediaSession;
+
+}
+
namespace Web::MediaSourceExtensions {
class BufferedChangeEvent;
diff --git a/Libraries/LibWeb/HTML/Navigator.cpp b/Libraries/LibWeb/HTML/Navigator.cpp
index dec6df5db4a..bc4f7032941 100644
--- a/Libraries/LibWeb/HTML/Navigator.cpp
+++ b/Libraries/LibWeb/HTML/Navigator.cpp
@@ -23,6 +23,7 @@
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/MediaCapture/MediaDevices.h>
+#include <LibWeb/MediaSession/MediaSession.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/PermissionsAPI/Permissions.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
@@ -83,6 +84,7 @@ void Navigator::visit_edges(GC::Cell::Visitor& visitor)
visitor.visit(m_user_activation);
visitor.visit(m_service_worker_container);
visitor.visit(m_media_capabilities);
+ visitor.visit(m_media_session);
visitor.visit(m_media_devices);
visitor.visit(m_credentials);
visitor.visit(m_permissions);
@@ -151,6 +153,15 @@ GC::Ref<MediaCapabilitiesAPI::MediaCapabilities> Navigator::media_capabilities()
return *m_media_capabilities;
}
+// https://w3c.github.io/mediasession/#dom-navigator-mediasession
+GC::Ref<MediaSession::MediaSession> Navigator::media_session()
+{
+ // The mediaSession attribute MUST return the MediaSession instance associated with the Navigator object.
+ if (!m_media_session)
+ m_media_session = MediaSession::MediaSession::create();
+ return *m_media_session;
+}
+
GC::Ref<MediaCapture::MediaDevices> Navigator::media_devices()
{
if (!m_media_devices)
diff --git a/Libraries/LibWeb/HTML/Navigator.h b/Libraries/LibWeb/HTML/Navigator.h
index dca427766e1..1d0afad0ff7 100644
--- a/Libraries/LibWeb/HTML/Navigator.h
+++ b/Libraries/LibWeb/HTML/Navigator.h
@@ -75,6 +75,7 @@ public:
GC::Ref<ServiceWorker::ServiceWorkerContainer> service_worker();
GC::Ref<MediaCapabilitiesAPI::MediaCapabilities> media_capabilities();
+ GC::Ref<MediaSession::MediaSession> media_session();
GC::Ref<MediaCapture::MediaDevices> media_devices();
void webkit_get_user_media(MediaCapture::MediaStreamConstraints const&, GC::Ref<WebIDL::CallbackType> success_callback, GC::Ref<WebIDL::CallbackType> error_callback);
GC::Ptr<MediaCapture::MediaDevices> media_devices_if_created() const { return m_media_devices; }
@@ -118,6 +119,9 @@ private:
// https://w3c.github.io/media-capabilities/#dom-navigator-mediacapabilities
GC::Ptr<MediaCapabilitiesAPI::MediaCapabilities> m_media_capabilities;
+ // https://w3c.github.io/mediasession/#dom-navigator-mediasession
+ GC::Ptr<MediaSession::MediaSession> m_media_session;
+
// https://w3c.github.io/mediacapture-main/#dom-navigator-mediadevices
GC::Ptr<MediaCapture::MediaDevices> m_media_devices;
diff --git a/Libraries/LibWeb/HTML/Navigator.idl b/Libraries/LibWeb/HTML/Navigator.idl
index 64d649abafa..78f06133997 100644
--- a/Libraries/LibWeb/HTML/Navigator.idl
+++ b/Libraries/LibWeb/HTML/Navigator.idl
@@ -21,6 +21,9 @@ interface Navigator {
// https://w3c.github.io/media-capabilities/#dom-navigator-mediacapabilities
[SameObject] readonly attribute MediaCapabilities mediaCapabilities;
+ // https://w3c.github.io/mediasession/#dom-navigator-mediasession
+ [SameObject] readonly attribute MediaSession mediaSession;
+
// https://w3c.github.io/mediacapture-main/#dom-navigator-mediadevices
[SecureContext, SameObject] readonly attribute MediaDevices mediaDevices;
diff --git a/Libraries/LibWeb/MediaSession/ChapterInformation.cpp b/Libraries/LibWeb/MediaSession/ChapterInformation.cpp
new file mode 100644
index 00000000000..16890688c4a
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/ChapterInformation.cpp
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibJS/Runtime/Array.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/MediaSession/ChapterInformation.h>
+#include <LibWeb/MediaSession/MediaMetadata.h>
+
+namespace Web::MediaSession {
+
+GC_DEFINE_ALLOCATOR(ChapterInformation);
+
+// https://w3c.github.io/mediasession/#create-a-chapterinformation
+WebIDL::ExceptionOr<GC::Ref<ChapterInformation>> ChapterInformation::create(Bindings::ChapterInformationInit const& init)
+{
+ // 1. Let chapterInfo be a new ChapterInformation object.
+ auto chapter_info = GC::Heap::the().allocate<ChapterInformation>();
+
+ // 2. Set chapterInfo's title to init's title.
+ chapter_info->m_title = init.title;
+
+ // 3. Set chapterInfo's startTime to init's startTime. If the startTime is negative or greater than duration, throw
+ // a TypeError.
+ // NB: Nothing here has a duration, so only a negative startTime is rejected.
+ if (init.start_time < 0)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Chapter startTime must not be negative"_utf16 };
+ chapter_info->m_start_time = init.start_time;
+
+ // 4. Let artwork be the result of running the convert artwork algorithm with init's artwork as input.
+ // 5. Set chapterInfo's artwork images to the result of creating a frozen array from artwork.
+ // NB: The frozen array is created when the artwork attribute is first read in a wrapper world.
+ chapter_info->m_artwork_images = TRY(convert_artwork(init.artwork));
+
+ // 6. Return chapterInfo.
+ return chapter_info;
+}
+
+void ChapterInformation::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_retained_artwork_arrays);
+}
+
+// https://w3c.github.io/mediasession/#dom-chapterinformation-artwork
+JS::Value ChapterInformation::artwork(JS::Realm& realm)
+{
+ // On getting, it MUST return the ChapterInformation's artwork images.
+ auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
+ if (auto array = m_artwork_arrays.get(wrapper_world))
+ return array.ptr();
+
+ auto array = MUST(JS::Array::create(realm, 0));
+ for (size_t index = 0; index < m_artwork_images.size(); ++index)
+ MUST(array->create_data_property_or_throw(index, Bindings::media_image_to_value(realm, m_artwork_images[index])));
+ MUST(array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
+ m_artwork_arrays.set(wrapper_world, array);
+ m_retained_artwork_arrays.append(array);
+ return array;
+}
+
+}
diff --git a/Libraries/LibWeb/MediaSession/ChapterInformation.h b/Libraries/LibWeb/MediaSession/ChapterInformation.h
new file mode 100644
index 00000000000..6ab34d8ba5e
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/ChapterInformation.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibJS/Runtime/Array.h>
+#include <LibWeb/Bindings/ChapterInformation.h>
+#include <LibWeb/Bindings/MediaMetadata.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::MediaSession {
+
+// https://w3c.github.io/mediasession/#chapterinformation
+class ChapterInformation final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(ChapterInformation, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(ChapterInformation);
+
+public:
+ static WebIDL::ExceptionOr<GC::Ref<ChapterInformation>> create(Bindings::ChapterInformationInit const&);
+ virtual ~ChapterInformation() override = default;
+
+ Utf16String const& title() const { return m_title; }
+ double start_time() const { return m_start_time; }
+ JS::Value artwork(JS::Realm&);
+
+private:
+ ChapterInformation() = default;
+
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ Utf16String m_title;
+ double m_start_time { 0 };
+ Vector<Bindings::MediaImage> m_artwork_images;
+
+ // The frozen array that the artwork attribute returns, created once for each wrapper world that gets it.
+ Bindings::WrapperWorldWeakValueCache<JS::Array> m_artwork_arrays;
+ // The cache holds its arrays weakly, so these keep them alive: Otherwise a script that keeps just an element of one
+ // would get a new array, with new elements, after a collection.
+ Vector<GC::Ref<JS::Array>> m_retained_artwork_arrays;
+};
+
+}
diff --git a/Libraries/LibWeb/MediaSession/ChapterInformation.idl b/Libraries/LibWeb/MediaSession/ChapterInformation.idl
new file mode 100644
index 00000000000..bb76d288509
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/ChapterInformation.idl
@@ -0,0 +1,17 @@
+// https://w3c.github.io/mediasession/#chapterinformation
+[Exposed=Window]
+interface ChapterInformation {
+ readonly attribute DOMString title;
+ readonly attribute double startTime;
+ // AD-HOC: The spec requires a frozen array of MediaImage dictionaries, created once. ReturnsJSValue lets the
+ // implementation supply that array, since the bindings otherwise convert FrozenArray into a fresh array on
+ // each get.
+ [SameObject, ReturnsJSValue] readonly attribute FrozenArray<object> artwork;
+};
+
+// https://w3c.github.io/mediasession/#dictdef-chapterinformationinit
+dictionary ChapterInformationInit {
+ DOMString title = "";
+ double startTime = 0;
+ sequence<MediaImage> artwork = [];
+};
diff --git a/Libraries/LibWeb/MediaSession/MediaMetadata.cpp b/Libraries/LibWeb/MediaSession/MediaMetadata.cpp
new file mode 100644
index 00000000000..b74162544d9
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/MediaMetadata.cpp
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibJS/Runtime/Array.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/DOMURL/DOMURL.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/Infra/SerializedURL.h>
+#include <LibWeb/MediaSession/ChapterInformation.h>
+#include <LibWeb/MediaSession/MediaMetadata.h>
+#include <LibWeb/MediaSession/MediaSession.h>
+
+namespace Web::MediaSession {
+
+GC_DEFINE_ALLOCATOR(MediaMetadata);
+
+// https://w3c.github.io/mediasession/#convert-artwork-algorithm
+WebIDL::ExceptionOr<Vector<Bindings::MediaImage>> convert_artwork(Vector<Bindings::MediaImage> const& input)
+{
+ // 1. Let output be an empty list of type MediaImage.
+ Vector<Bindings::MediaImage> output;
+
+ // 2. For each entry in input (which is a MediaImage list), perform the following steps:
+ for (auto const& entry : input) {
+ // 1. Let image be a new MediaImage.
+ Bindings::MediaImage image;
+
+ // 2. Let baseURL be the API base URL specified by the entry settings object.
+ // AD-HOC: Use the current settings object's base URL instead of the entry settings object's, as the
+ // web-platform-tests expect. Artwork built with another realm's constructor uses that realm's base URL.
+ auto base_url = HTML::current_settings_object().api_base_url();
+
+ // 3. Parse entry's src using baseURL. If it does not return failure, set image's src to the return value.
+ // Otherwise, throw a TypeError and abort these steps.
+ auto url = DOMURL::parse(entry.src, base_url);
+ if (!url.has_value())
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Artwork src could not be parsed as a URL"_utf16 };
+ image.src = utf16_string_from_url_ascii(url->serialize());
+
+ // 4. Set image's sizes to entry's sizes.
+ image.sizes = entry.sizes;
+
+ // 5. Set image's type to entry's type.
+ image.type = entry.type;
+
+ // 6. Append image to the output.
+ output.append(move(image));
+ }
+
+ // 3. Return output as result.
+ return output;
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-mediametadata
+WebIDL::ExceptionOr<GC::Ref<MediaMetadata>> MediaMetadata::create(Bindings::MediaMetadataInit const& init)
+{
+ // 1. Let metadata be a new MediaMetadata object.
+ auto metadata = GC::Heap::the().allocate<MediaMetadata>();
+
+ // 2. Set metadata's title to init's title.
+ metadata->m_title = init.title;
+
+ // 3. Set metadata's artist to init's artist.
+ metadata->m_artist = init.artist;
+
+ // 4. Set metadata's album to init's album.
+ metadata->m_album = init.album;
+
+ // 5. Run the convert artwork algorithm with init's artwork as input and set metadata's artwork images as the
+ // result if it succeeded.
+ metadata->m_artwork_images = TRY(convert_artwork(init.artwork));
+
+ // 6. Let chapters be an empty list of type ChapterInformation.
+ // 7. For each entry in init's chapterInfo, create a ChapterInformation from entry and append it to chapters.
+ // 8. Set metadata's chapter information to the result of creating a frozen array from chapters.
+ // NB: The chapters go straight into metadata's chapter information, which keeps them alive. The frozen array is
+ // created when the chapterInfo attribute is first read in a wrapper world.
+ for (auto const& entry : init.chapter_info)
+ metadata->m_chapter_information.append(TRY(ChapterInformation::create(entry)));
+
+ // 9. Return metadata.
+ return metadata;
+}
+
+void MediaMetadata::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_retained_converted_artwork_images);
+ visitor.visit(m_chapter_information);
+ visitor.visit(m_retained_chapter_information_arrays);
+ visitor.visit(m_media_session);
+}
+
+void MediaMetadata::set_media_session(GC::Ptr<MediaSession> session)
+{
+ m_media_session = session;
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-title
+void MediaMetadata::set_title(Utf16String value)
+{
+ // On setting, it MUST set the MediaMetadata's title to the given value.
+ m_title = move(value);
+ metadata_updated();
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-artist
+void MediaMetadata::set_artist(Utf16String value)
+{
+ // On setting, it MUST set the MediaMetadata's artist to the given value.
+ m_artist = move(value);
+ metadata_updated();
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-album
+void MediaMetadata::set_album(Utf16String value)
+{
+ // On setting, it MUST set the MediaMetadata's album to the given value.
+ m_album = move(value);
+ metadata_updated();
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-artwork
+JS::Value MediaMetadata::artwork(JS::Realm& realm)
+{
+ // 1. If the MediaMetadata's converted artwork images is undefined, run the following steps:
+ // NB: We keep the converted artwork images for each wrapper world that reads them, so that no world gets another's
+ // array.
+ auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
+ auto converted_artwork_images = m_converted_artwork_images.get(wrapper_world);
+ if (!converted_artwork_images) {
+ // 1. Let frozenArtwork be a JavaScript Array value.
+ auto frozen_artwork = MUST(JS::Array::create(realm, 0));
+
+ // 2. For each entry in the MediaMetadata's artwork images, perform the following steps:
+ for (size_t index = 0; index < m_artwork_images.size(); ++index) {
+ // 1. Let image be the result of converting to a JavaScript object entry.
+ auto image = Bindings::media_image_to_value(realm, m_artwork_images[index]);
+
+ // 2. Perform SetIntegrityLevel(image, "frozen"), to prevent accidental mutation by scripts.
+ MUST(image.as_object().set_integrity_level(JS::Object::IntegrityLevel::Frozen));
+
+ // 3. Push image to frozenArtwork.
+ MUST(frozen_artwork->create_data_property_or_throw(index, image));
+ }
+
+ // 3. Perform SetIntegrityLevel(frozenArtwork, "frozen").
+ MUST(frozen_artwork->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
+
+ // 4. Set the MediaMetadata's converted artwork images to frozenArtwork.
+ m_converted_artwork_images.set(wrapper_world, frozen_artwork);
+ m_retained_converted_artwork_images.append(frozen_artwork);
+ converted_artwork_images = frozen_artwork;
+ }
+
+ // 2. Return the MediaMetadata's converted artwork images.
+ return converted_artwork_images.ptr();
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-chapterinfo
+JS::Value MediaMetadata::chapter_info(JS::Realm& realm)
+{
+ // On getting, it MUST return the MediaMetadata's chapter information.
+ auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
+ if (auto array = m_chapter_information_arrays.get(wrapper_world))
+ return array.ptr();
+
+ auto array = MUST(JS::Array::create(realm, 0));
+ for (size_t index = 0; index < m_chapter_information.size(); ++index) {
+ auto wrapper = Bindings::wrap(wrapper_world, realm, m_chapter_information[index]);
+
+ // AD-HOC: The spec freezes only the array, but each ChapterInformation object is frozen too, as the
+ // web-platform-tests expect.
+ MUST(wrapper->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
+ MUST(array->create_data_property_or_throw(index, wrapper));
+ }
+ MUST(array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
+ m_chapter_information_arrays.set(wrapper_world, array);
+ m_retained_chapter_information_arrays.append(array);
+ return array;
+}
+
+// https://w3c.github.io/mediasession/#dom-mediametadata-artwork
+WebIDL::ExceptionOr<void> MediaMetadata::set_artwork(JS::Realm& realm, GC::RootVector<GC::Ref<JS::Object>> const& value)
+{
+ // 1. Let convertedArtwork be the result of converting value to a sequence of type MediaImage.
+ Vector<Bindings::MediaImage> converted_artwork;
+ for (auto const& entry : value)
+ converted_artwork.append(TRY(Bindings::convert_to_idl_value_for_media_image(realm.vm(), entry)));
+
+ // 2. Run convert artwork algorithm with convertedArtwork, and set the MediaMetadata's artwork images as the
+ // result if it succeeds.
+ m_artwork_images = TRY(convert_artwork(converted_artwork));
+
+ // 3. Set the MediaMetadata's converted artwork images to undefined.
+ m_converted_artwork_images.clear();
+ m_retained_converted_artwork_images.clear();
+ metadata_updated();
+ return {};
+}
+
+// https://w3c.github.io/mediasession/#the-mediametadata-interface
+void MediaMetadata::metadata_updated()
+{
+ // 1. If the instance has no associated media session, abort these steps.
+ if (!m_media_session)
+ return;
+
+ // FIXME: 2. Otherwise, queue a task to run the following substeps:
+ // 1. If the instance no longer has an associated media session, abort these steps.
+ // 2. Otherwise, in parallel, run the update metadata algorithm.
+}
+
+}
diff --git a/Libraries/LibWeb/MediaSession/MediaMetadata.h b/Libraries/LibWeb/MediaSession/MediaMetadata.h
new file mode 100644
index 00000000000..fc324bc7cad
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/MediaMetadata.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibGC/RootVector.h>
+#include <LibJS/Runtime/Array.h>
+#include <LibWeb/Bindings/MediaMetadata.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::MediaSession {
+
+// https://w3c.github.io/mediasession/#convert-artwork-algorithm
+WebIDL::ExceptionOr<Vector<Bindings::MediaImage>> convert_artwork(Vector<Bindings::MediaImage> const&);
+
+// https://w3c.github.io/mediasession/#mediametadata
+class MediaMetadata final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(MediaMetadata, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(MediaMetadata);
+
+public:
+ static WebIDL::ExceptionOr<GC::Ref<MediaMetadata>> create(Bindings::MediaMetadataInit const&);
+ virtual ~MediaMetadata() override = default;
+
+ Utf16String const& title() const { return m_title; }
+ void set_title(Utf16String);
+ Utf16String const& artist() const { return m_artist; }
+ void set_artist(Utf16String);
+ Utf16String const& album() const { return m_album; }
+ void set_album(Utf16String);
+
+ JS::Value artwork(JS::Realm&);
+ WebIDL::ExceptionOr<void> set_artwork(JS::Realm&, GC::RootVector<GC::Ref<JS::Object>> const&);
+
+ JS::Value chapter_info(JS::Realm&);
+
+ void set_media_session(GC::Ptr<MediaSession>);
+
+private:
+ MediaMetadata() = default;
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ void metadata_updated();
+
+ Utf16String m_title;
+ Utf16String m_artist;
+ Utf16String m_album;
+ Vector<Bindings::MediaImage> m_artwork_images;
+
+ // The MediaMetadata's converted artwork images, created once for each wrapper world that gets them, and dropped
+ // whenever the artwork is set.
+ Bindings::WrapperWorldWeakValueCache<JS::Array> m_converted_artwork_images;
+ // The cache holds its arrays weakly, so these keep them alive: Otherwise a script that keeps just an element of one
+ // would get a new array, with new elements, after a collection.
+ Vector<GC::Ref<JS::Array>> m_retained_converted_artwork_images;
+
+ // https://w3c.github.io/mediasession/#mediametadata-chapter-information
+ Vector<GC::Ref<ChapterInformation>> m_chapter_information;
+
+ // The frozen array that the chapterInfo attribute returns, created once for each wrapper world that gets it.
+ Bindings::WrapperWorldWeakValueCache<JS::Array> m_chapter_information_arrays;
+ Vector<GC::Ref<JS::Array>> m_retained_chapter_information_arrays;
+
+ GC::Ptr<MediaSession> m_media_session;
+};
+
+}
diff --git a/Libraries/LibWeb/MediaSession/MediaMetadata.idl b/Libraries/LibWeb/MediaSession/MediaMetadata.idl
new file mode 100644
index 00000000000..1d1437225c9
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/MediaMetadata.idl
@@ -0,0 +1,32 @@
+// https://w3c.github.io/mediasession/#mediametadata
+[Exposed=Window]
+interface MediaMetadata {
+ constructor(optional MediaMetadataInit init = {});
+ attribute DOMString title;
+ attribute DOMString artist;
+ attribute DOMString album;
+ // AD-HOC: The spec requires a cached frozen array of frozen objects. ReturnsJSValue lets the implementation
+ // supply that array, since the bindings otherwise convert FrozenArray into a fresh array on each get.
+ [ReturnsJSValue] attribute FrozenArray<object> artwork;
+ // AD-HOC: The spec requires a frozen array of ChapterInformation objects, created once. ReturnsJSValue lets the
+ // implementation supply that array, since the bindings otherwise convert FrozenArray into a fresh array on
+ // each get.
+ [SameObject, ReturnsJSValue] readonly attribute FrozenArray<ChapterInformation> chapterInfo;
+};
+
+// https://w3c.github.io/mediasession/#dictdef-mediametadatainit
+dictionary MediaMetadataInit {
+ DOMString title = "";
+ DOMString artist = "";
+ DOMString album = "";
+ sequence<MediaImage> artwork = [];
+ sequence<ChapterInformationInit> chapterInfo = [];
+};
+
+// https://w3c.github.io/mediasession/#dictdef-mediaimage
+[GenerateToValue]
+dictionary MediaImage {
+ required USVString src;
+ DOMString sizes = "";
+ DOMString type = "";
+};
diff --git a/Libraries/LibWeb/MediaSession/MediaSession.cpp b/Libraries/LibWeb/MediaSession/MediaSession.cpp
new file mode 100644
index 00000000000..5d275d68439
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/MediaSession.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/MediaSession/MediaMetadata.h>
+#include <LibWeb/MediaSession/MediaSession.h>
+#include <LibWeb/WebIDL/CallbackType.h>
+#include <math.h>
+
+namespace Web::MediaSession {
+
+GC_DEFINE_ALLOCATOR(MediaSession);
+
+GC::Ref<MediaSession> MediaSession::create()
+{
+ return GC::Heap::the().allocate<MediaSession>();
+}
+
+void MediaSession::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_metadata);
+ visitor.visit(m_action_handlers);
+}
+
+// https://w3c.github.io/mediasession/#dom-mediasession-metadata
+void MediaSession::set_metadata(GC::Ptr<MediaMetadata> value)
+{
+ // 1. If the MediaSession's metadata is not null, set its media session to null.
+ if (m_metadata)
+ m_metadata->set_media_session(nullptr);
+
+ // 2. Set the MediaSession's metadata to value.
+ m_metadata = value;
+
+ // 3. If the MediaSession's metadata is not null, set its media session to the current MediaSession.
+ if (m_metadata)
+ m_metadata->set_media_session(this);
+
+ // FIXME: 4. In parallel, run the update metadata algorithm.
+}
+
+// https://w3c.github.io/mediasession/#dom-mediasession-playbackstate
+void MediaSession::set_playback_state(Bindings::MediaSessionPlaybackState value)
+{
+ // On setting, the user agent MUST set the IDL attribute to the new value if it is a valid
+ // MediaSessionPlaybackState value.
+ m_playback_state = value;
+
+ // FIXME: Setting playbackState may cause the actual playback state to change and run the media session actions
+ // update algorithm.
+}
+
+// https://w3c.github.io/mediasession/#update-action-handler-algorithm
+void MediaSession::set_action_handler(Bindings::MediaSessionAction action, GC::Ptr<WebIDL::CallbackType> handler)
+{
+ // 1. If handler is null, remove action from the supported media session actions for MediaSession
+ // and abort these steps.
+ if (!handler) {
+ m_action_handlers.remove(action);
+ // FIXME: Run the media session actions update algorithm when the supported media session actions change.
+ return;
+ }
+
+ // 2. Add action to the supported media session actions for MediaSession and associate to it the handler.
+ m_action_handlers.set(action, handler);
+
+ // FIXME: Run the media session actions update algorithm when the supported media session actions change.
+}
+
+// https://w3c.github.io/mediasession/#dom-mediasession-setpositionstate
+WebIDL::ExceptionOr<void> MediaSession::set_position_state(Bindings::MediaPositionState state)
+{
+ // 1. If state is an empty dictionary, clear the position state and abort these steps.
+ if (!state.duration.has_value() && !state.position.has_value() && !state.playback_rate.has_value()) {
+ m_position_state.clear();
+ return {};
+ }
+
+ // 2. If state's duration is not present, throw a TypeError.
+ if (!state.duration.has_value())
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Position state requires a duration"_utf16 };
+
+ // 3. If state's duration is negative or NaN, throw a TypeError.
+ if (*state.duration < 0 || isnan(*state.duration))
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Position state duration must be non-negative and not NaN"_utf16 };
+
+ // 4. If state's position is not present, set it to zero.
+ if (!state.position.has_value())
+ state.position = 0;
+
+ // 5. If state's position is negative or greater than duration, throw a TypeError.
+ if (*state.position < 0 || *state.position > *state.duration)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Position must be between zero and duration"_utf16 };
+
+ // 6. If state's playbackRate is not present, set it to 1.0.
+ if (!state.playback_rate.has_value())
+ state.playback_rate = 1.0;
+
+ // 7. If state's playbackRate is zero, throw a TypeError.
+ if (*state.playback_rate == 0)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Position state playback rate must be nonzero"_utf16 };
+
+ // 8. Update the position state and last position updated time.
+ m_position_state = PositionState { *state.duration, *state.playback_rate, *state.position, MonotonicTime::now() };
+ return {};
+}
+
+}
diff --git a/Libraries/LibWeb/MediaSession/MediaSession.h b/Libraries/LibWeb/MediaSession/MediaSession.h
new file mode 100644
index 00000000000..82dd7196a4e
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/MediaSession.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/Optional.h>
+#include <AK/Time.h>
+#include <LibWeb/Bindings/MediaSession.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
+
+namespace Web::MediaSession {
+
+// https://w3c.github.io/mediasession/#mediasession
+class MediaSession final : public Bindings::GCAllocatedWrappable {
+ WEB_WRAPPABLE(MediaSession, Bindings::GCAllocatedWrappable);
+ GC_DECLARE_ALLOCATOR(MediaSession);
+
+public:
+ static GC::Ref<MediaSession> create();
+ virtual ~MediaSession() override = default;
+
+ GC::Ptr<MediaMetadata> metadata() const { return m_metadata; }
+ void set_metadata(GC::Ptr<MediaMetadata>);
+
+ Bindings::MediaSessionPlaybackState playback_state() const { return m_playback_state; }
+ void set_playback_state(Bindings::MediaSessionPlaybackState);
+
+ void set_action_handler(Bindings::MediaSessionAction, GC::Ptr<WebIDL::CallbackType>);
+ WebIDL::ExceptionOr<void> set_position_state(Bindings::MediaPositionState);
+
+private:
+ MediaSession() = default;
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ GC::Ptr<MediaMetadata> m_metadata;
+ Bindings::MediaSessionPlaybackState m_playback_state { Bindings::MediaSessionPlaybackState::None };
+ HashMap<Bindings::MediaSessionAction, GC::Ptr<WebIDL::CallbackType>> m_action_handlers;
+
+ struct PositionState {
+ double duration;
+ double playback_rate;
+ double position;
+ MonotonicTime last_position_updated_time;
+ };
+ Optional<PositionState> m_position_state;
+};
+
+}
diff --git a/Libraries/LibWeb/MediaSession/MediaSession.idl b/Libraries/LibWeb/MediaSession/MediaSession.idl
new file mode 100644
index 00000000000..4c2563aabc6
--- /dev/null
+++ b/Libraries/LibWeb/MediaSession/MediaSession.idl
@@ -0,0 +1,62 @@
+// https://w3c.github.io/mediasession/#enumdef-mediasessionplaybackstate
+enum MediaSessionPlaybackState {
+ "none",
+ "paused",
+ "playing"
+};
+
+// https://w3c.github.io/mediasession/#enumdef-mediasessionaction
+enum MediaSessionAction {
+ "play",
+ "pause",
+ "seekbackward",
+ "seekforward",
+ "previoustrack",
+ "nexttrack",
+ "skipad",
+ "stop",
+ "seekto",
+ "togglemicrophone",
+ "togglecamera",
+ "togglescreenshare",
+ "hangup",
+ "previousslide",
+ "nextslide",
+ "enterpictureinpicture",
+ "voiceactivity"
+};
+
+// https://w3c.github.io/mediasession/#enumdef-mediasessionenterpictureinpicturereason
+enum MediaSessionEnterPictureInPictureReason {
+ "other",
+ "useraction",
+ "contentoccluded"
+};
+
+callback MediaSessionActionHandler = undefined(MediaSessionActionDetails details);
+
+// https://w3c.github.io/mediasession/#mediasession
+[Exposed=Window]
+interface MediaSession {
+ attribute MediaMetadata? metadata;
+ attribute MediaSessionPlaybackState playbackState;
+ undefined setActionHandler(MediaSessionAction action, MediaSessionActionHandler? handler);
+ undefined setPositionState(optional MediaPositionState state = {});
+};
+
+// https://w3c.github.io/mediasession/#dictdef-mediapositionstate
+dictionary MediaPositionState {
+ unrestricted double duration;
+ double playbackRate;
+ double position;
+};
+
+// https://w3c.github.io/mediasession/#dictdef-mediasessionactiondetails
+dictionary MediaSessionActionDetails {
+ required MediaSessionAction action;
+ double seekOffset;
+ double seekTime;
+ boolean fastSeek;
+ boolean isActivating;
+ MediaSessionEnterPictureInPictureReason enterPictureInPictureReason;
+};
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 77f05b31170..04fe87a558a 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -425,6 +425,9 @@ libweb_js_bindings(MediaCapture/MediaStream)
libweb_js_bindings(MediaCapture/MediaStreamConstraints)
libweb_js_bindings(MediaCapture/MediaStreamTrack)
libweb_js_bindings(MediaCapture/MediaStreamTrackEvent)
+libweb_js_bindings(MediaSession/ChapterInformation)
+libweb_js_bindings(MediaSession/MediaMetadata)
+libweb_js_bindings(MediaSession/MediaSession)
libweb_js_bindings(MediaSourceExtensions/BufferedChangeEvent)
libweb_js_bindings(MediaSourceExtensions/ManagedMediaSource)
libweb_js_bindings(MediaSourceExtensions/ManagedSourceBuffer)
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index cd484ed2c6e..1165cf028b6 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -78,6 +78,12 @@ ALLOWED_REALM_MENTIONS = {
),
"Infra": (2, 13, "JSON parse/serialization helpers still expose JS values in selected realms"),
"Internals": (1, 1, "test-only internals still expose JS-facing helper objects and promises"),
+ "MediaSession": (
+ 4,
+ 10,
+ "MediaMetadata and ChapterInformation build the frozen arrays their [SameObject] FrozenArray attributes return, "
+ "freezing the elements too, which the generated conversion doesn't do",
+ ),
"SVG": (2, 8, "SVG length objects still store/use realms for detached/reflected JS/CSS materialization"),
"ServiceWorker": (
6,
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 84a29f38ffa..b6e94e85ebe 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -241,6 +241,7 @@ Text/input/HTML/media-source-waiting-at-end-of-appended-data.html
Text/input/HTML/media-source-waiting-at-end-of-disabled-track.html
Text/input/HTML/media-source-webm-block-groups.html
Text/input/HTML/media-source-mismatched-codec-configuration.html
+Text/input/wpt-import/mediasession/mediametadata.html
Text/input/wpt-import/media-source/mediasource-activesourcebuffers.html
Text/input/wpt-import/media-source/mediasource-appendwindow.html
Text/input/wpt-import/media-source/mediasource-invalid-codec.html
@@ -1477,6 +1478,7 @@ Text/input/wpt-import/html/semantics/forms/the-label-element/iframe-label-attrib
Text/input/wpt-import/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/015-1.html
Text/input/wpt-import/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/016-1.html
Text/input/wpt-import/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-03-frame.html
+Text/input/wpt-import/mediasession/helper/artwork-generator.html
; Timing out Fullscreen tests
Ref/input/wpt-import/fullscreen/rendering/backdrop-iframe.html
diff --git a/Tests/LibWeb/Text/expected/MediaSession/artwork-same-object-after-gc.txt b/Tests/LibWeb/Text/expected/MediaSession/artwork-same-object-after-gc.txt
new file mode 100644
index 00000000000..03503c8dabd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/MediaSession/artwork-same-object-after-gc.txt
@@ -0,0 +1,3 @@
+artwork element is the same object: true
+chapterInfo element is the same object: true
+chapter artwork element is the same object: true
diff --git a/Tests/LibWeb/Text/expected/all-window-properties.txt b/Tests/LibWeb/Text/expected/all-window-properties.txt
index 7e192feec10..eb6a87da90c 100644
--- a/Tests/LibWeb/Text/expected/all-window-properties.txt
+++ b/Tests/LibWeb/Text/expected/all-window-properties.txt
@@ -109,6 +109,7 @@ CanvasRenderingContext2D
CaretPosition
ChannelMergerNode
ChannelSplitterNode
+ChapterInformation
CharacterData
Clipboard
ClipboardEvent
@@ -321,8 +322,10 @@ MediaElementAudioSourceNode
MediaError
MediaKeySystemAccess
MediaList
+MediaMetadata
MediaQueryList
MediaQueryListEvent
+MediaSession
MediaSource
MediaSourceHandle
MediaStream
diff --git a/Tests/LibWeb/Text/expected/wpt-import/mediasession/mediametadata.txt b/Tests/LibWeb/Text/expected/wpt-import/mediasession/mediametadata.txt
new file mode 100644
index 00000000000..6e1b6f0ffe4
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/mediasession/mediametadata.txt
@@ -0,0 +1,25 @@
+Harness status: OK
+
+Found 20 tests
+
+20 Pass
+Pass Test that mediaSession.metadata is properly set
+Pass Test that changes to metadata propagate properly
+Pass Test that resetting metadata to null is reflected
+Pass Test that MediaMetadata is constructed using a dictionary
+Pass Test that MediaMetadata constructor can take no parameter
+Pass Test the different values allowed in MediaMetadata init dictionary
+Pass Test the default values for MediaMetadata with empty init dictionary
+Pass Test the default values for MediaMetadata with no init dictionary
+Pass Test that passing unknown values to the dictionary is a no-op
+Pass Test that MediaMetadata is read/write
+Pass Test that MediaMetadata.artwork can't be modified
+Pass Test that MediaMetadata.artwork will not expose unknown properties
+Pass Test that MediaMetadata.artwork is Frozen
+Pass Test that MediaMetadata.chapterInfo is Frozen
+Pass Test that MediaMetadata.artwork returns parsed urls
+Pass Test that MediaMetadata.chapterInfo's artwork returns parsed urls
+Pass Test that MediaMetadata throws when setting an invalid url
+Pass Test MediaImage default values
+Pass Test that MediaImage.src is required
+Pass Test that the base URL of MediaImage is the base URL of entry setting object
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/mediasession/playbackstate.txt b/Tests/LibWeb/Text/expected/wpt-import/mediasession/playbackstate.txt
new file mode 100644
index 00000000000..f6f068626af
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/mediasession/playbackstate.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass Test that playbackState is initialized as "none"
+Pass Test that playbackState is read/write
+Pass Test that warning is thrown when setting invalid playbackState
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/mediasession/positionstate.txt b/Tests/LibWeb/Text/expected/wpt-import/mediasession/positionstate.txt
new file mode 100644
index 00000000000..d74d6281168
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/mediasession/positionstate.txt
@@ -0,0 +1,17 @@
+Harness status: OK
+
+Found 12 tests
+
+12 Pass
+Pass Test setPositionState with a null value
+Pass Test setPositionState with a valid value for forward playback
+Pass Test setPositionState with optional position
+Pass Test setPositionState with optional playback rate
+Pass Test setPositionState with only duration
+Pass Test setPositionState with zero duration
+Pass Test setPositionState with negative playback rate
+Pass Test setPositionState throws a TypeError if duration is negative
+Pass Test setPositionState throws a TypeError if position is negative
+Pass Test setPositionState throws a TypeError if duration is less than position
+Pass Test setPositionState throws a TypeError if playback rate is zero
+Pass Test setPositionState throws a TypeError if duration is not specified
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/mediasession/setactionhandler.txt b/Tests/LibWeb/Text/expected/wpt-import/mediasession/setactionhandler.txt
new file mode 100644
index 00000000000..f4e1527dca6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/mediasession/setactionhandler.txt
@@ -0,0 +1,23 @@
+Harness status: OK
+
+Found 18 tests
+
+18 Pass
+Pass Test that setActionHandler("play") succeeds
+Pass Test that setActionHandler("pause") succeeds
+Pass Test that setActionHandler("previoustrack") succeeds
+Pass Test that setActionHandler("nexttrack") succeeds
+Pass Test that setActionHandler("seekbackward") succeeds
+Pass Test that setActionHandler("seekforward") succeeds
+Pass Test that setActionHandler("stop") succeeds
+Pass Test that setActionHandler("seekto") succeeds
+Pass Test that setActionHandler("skipad") succeeds
+Pass Test that setActionHandler("togglemicrophone") succeeds
+Pass Test that setActionHandler("togglecamera") succeeds
+Pass Test that setActionHandler("togglescreenshare") succeeds
+Pass Test that setActionHandler("hangup") succeeds
+Pass Test that setActionHandler("previousslide") succeeds
+Pass Test that setActionHandler("nextslide") succeeds
+Pass Test that setActionHandler("enterpictureinpicture") succeeds
+Pass Test that setActionHandler("voiceactivity") succeeds
+Pass Test that setActionHandler() throws exception for unsupported actions
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/MediaSession/artwork-same-object-after-gc.html b/Tests/LibWeb/Text/input/MediaSession/artwork-same-object-after-gc.html
new file mode 100644
index 00000000000..c661a24de5f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/MediaSession/artwork-same-object-after-gc.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const metadata = new MediaMetadata({
+ artwork: [{ src: "cover.png" }],
+ chapterInfo: [{ title: "Chapter", startTime: 0, artwork: [{ src: "chapter.png" }] }],
+ });
+
+ // Keep only an element of each array, so that only the attribute can keep the arrays themselves alive.
+ const image = metadata.artwork[0];
+ const chapter = metadata.chapterInfo[0];
+ const chapterImage = chapter.artwork[0];
+ internals.gc();
+
+ println(`artwork element is the same object: ${metadata.artwork[0] === image}`);
+ println(`chapterInfo element is the same object: ${metadata.chapterInfo[0] === chapter}`);
+ println(`chapter artwork element is the same object: ${chapter.artwork[0] === chapterImage}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/mediasession/helper/artwork-generator.html b/Tests/LibWeb/Text/input/wpt-import/mediasession/helper/artwork-generator.html
new file mode 100644
index 00000000000..5a2fbb151d9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/mediasession/helper/artwork-generator.html
@@ -0,0 +1,18 @@
+<!DOCTYPE html>
+<title>MediaImage</title>
+<script>
+function createArtworkFromURLs(sources) {
+ let artwork = [];
+ for (const source of sources) {
+ artwork.push({
+ src: source
+ });
+ }
+
+ let metadata = new MediaMetadata({
+ artwork: artwork
+ });
+ return metadata.artwork;
+}
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/mediasession/mediametadata.html b/Tests/LibWeb/Text/input/wpt-import/mediasession/mediametadata.html
new file mode 100644
index 00000000000..3e5f2c45cf8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/mediasession/mediametadata.html
@@ -0,0 +1,376 @@
+<!DOCTYPE html>
+<title>MediaMetadata interface</title>
+<script src=../resources/testharness.js></script>
+<script src="../resources/testharnessreport.js"></script>
+<script>
+
+function load_iframe(src) {
+ return new Promise(resolve => {
+ const iframe = document.createElement('iframe');
+ iframe.onload = () => { resolve(iframe); };
+ iframe.src = src;
+ iframe.style.display = 'none';
+ document.documentElement.appendChild(iframe);
+ });
+}
+
+test(function() {
+ var metadata = new MediaMetadata({});
+ navigator.mediaSession.metadata = metadata;
+ assert_equals(navigator.mediaSession.metadata, metadata);
+}, "Test that mediaSession.metadata is properly set");
+
+test(function() {
+ var metadata = new MediaMetadata({});
+ navigator.mediaSession.metadata = metadata;
+ metadata.title = 'foo';
+ assert_equals(navigator.mediaSession.metadata.title, 'foo');
+}, "Test that changes to metadata propagate properly");
+
+test(function() {
+ var metadata = new MediaMetadata({});
+ navigator.mediaSession.metadata = metadata;
+ navigator.mediaSession.metadata = null;
+ assert_equals(navigator.mediaSession.metadata, null);
+}, "Test that resetting metadata to null is reflected");
+
+test(function() {
+ var metadata = new MediaMetadata({});
+ assert_not_equals(metadata, null);
+
+ assert_throws_js(TypeError, _ => new MediaMetadata('foobar'));
+ assert_throws_js(TypeError, _ => new MediaMetadata(42));
+}, 'Test that MediaMetadata is constructed using a dictionary');
+
+test(function() {
+ var metadata = new MediaMetadata();
+ assert_not_equals(metadata, null);
+}, "Test that MediaMetadata constructor can take no parameter");
+
+test(function() {
+ var image1 = { src: 'http://example.com/1', sizes: 'sizes1', type: 'type1' };
+ var image2 = { src: 'http://example.com/2', sizes: 'sizes2', type: 'type2' };
+ var chapter1_image1 = { src: 'http://chapterexample.com/1', sizes: '128x128', type: 'image/png' };
+ var chapter1_image2 = { src: 'http://chapterexample.com/2', sizes: '512x512', type: 'image/png' };
+ var chapter2_image1 = { src: 'http://chapterexample.com/3', sizes: '128x128', type: 'image/png' };
+ var chapter2_image2 = { src: 'http://chapterexample.com/4', sizes: '512x512', type: 'image/png' };
+ var metadata = new MediaMetadata({
+ title: 'foo', album: 'bar', artist: 'plop', artwork: [image1, image2],
+ chapterInfo: [{
+ title: 'Chapter 1',
+ startTime: 0,
+ artwork: [
+ chapter1_image1,
+ chapter1_image2
+ ]
+ }, {
+ title: 'Chapter 2',
+ startTime: 16,
+ artwork: [
+ chapter2_image1,
+ chapter2_image2,
+ ]
+ }]
+ });
+
+ assert_equals(metadata.title, 'foo');
+ assert_equals(metadata.album, 'bar');
+ assert_equals(metadata.artist, 'plop');
+ assert_equals(metadata.artwork.length, 2);
+ assert_equals(metadata.artwork[0].src, image1.src);
+ assert_equals(metadata.artwork[0].sizes, image1.sizes);
+ assert_equals(metadata.artwork[0].type, image1.type);
+ assert_equals(metadata.artwork[1].src, image2.src);
+ assert_equals(metadata.artwork[1].sizes, image2.sizes);
+ assert_equals(metadata.artwork[1].type, image2.type);
+ assert_equals(metadata.chapterInfo[0].title, 'Chapter 1');
+ assert_equals(metadata.chapterInfo[0].startTime, 0);
+ assert_equals(metadata.chapterInfo[0].artwork[0].src, chapter1_image1.src);
+ assert_equals(metadata.chapterInfo[0].artwork[1].src, chapter1_image2.src);
+ assert_equals(metadata.chapterInfo[0].artwork[0].sizes, chapter1_image1.sizes);
+ assert_equals(metadata.chapterInfo[0].artwork[1].sizes, chapter1_image2.sizes);
+ assert_equals(metadata.chapterInfo[0].artwork[0].type, chapter1_image1.type);
+ assert_equals(metadata.chapterInfo[0].artwork[1].type, chapter1_image2.type);
+ assert_equals(metadata.chapterInfo[1].title, 'Chapter 2');
+ assert_equals(metadata.chapterInfo[1].startTime, 16);
+ assert_equals(metadata.chapterInfo[1].artwork[0].src, chapter2_image1.src);
+ assert_equals(metadata.chapterInfo[1].artwork[1].src, chapter2_image2.src);
+ assert_equals(metadata.chapterInfo[1].artwork[0].sizes, chapter2_image1.sizes);
+ assert_equals(metadata.chapterInfo[1].artwork[1].sizes, chapter2_image2.sizes);
+ assert_equals(metadata.chapterInfo[1].artwork[0].type, chapter2_image1.type);
+ assert_equals(metadata.chapterInfo[1].artwork[1].type, chapter2_image2.type);
+}, 'Test the different values allowed in MediaMetadata init dictionary');
+
+test(function() {
+ var metadata = new MediaMetadata({});
+ assert_equals(metadata.title, '');
+ assert_equals(metadata.artist, '');
+ assert_equals(metadata.album, '');
+ assert_equals(0, metadata.artwork.length);
+ assert_equals(0, metadata.chapterInfo.length);
+}, 'Test the default values for MediaMetadata with empty init dictionary');
+
+test(function() {
+ var metadata = new MediaMetadata();
+ assert_equals(metadata.title, '');
+ assert_equals(metadata.artist, '');
+ assert_equals(metadata.album, '');
+ assert_equals(0, metadata.artwork.length);
+ assert_equals(0, metadata.chapterInfo.length);
+}, 'Test the default values for MediaMetadata with no init dictionary');
+
+test(function() {
+ var metadata = new MediaMetadata({ randomValueThatWillNotBeAdded: '... hopefully ;)' });
+ assert_equals(metadata.randomValueThatWillNotBeAdded, undefined);
+}, 'Test that passing unknown values to the dictionary is a no-op');
+
+test(function() {
+ var image1 = { src: 'http://example.com/1', sizes: 'sizes1', type: 'type1' };
+ var image2 = { src: 'http://example.com/2', sizes: 'sizes2', type: 'type2' };
+ var chapter1_image1 = { src: 'http://chapterexample.com/1', sizes: '128x128', type: 'image/png' };
+ var chapter1_image2 = { src: 'http://chapterexample.com/2', sizes: '512x512', type: 'image/png' };
+ var chapter2_image1 = { src: 'http://chapterexample.com/3', sizes: '128x128', type: 'image/png' };
+ var chapter2_image2 = { src: 'http://chapterexample.com/4', sizes: '512x512', type: 'image/png' };
+
+ var metadata = new MediaMetadata({
+ title: 'foo', album: 'bar', artist: 'plop', artwork: [image1, image2],
+ chapterInfo: [{
+ title: 'Chapter 1',
+ startTime: 0,
+ artwork: [
+ chapter1_image1,
+ chapter1_image2
+ ]
+ }, {
+ title: 'Chapter 2',
+ startTime: 16,
+ artwork: [
+ chapter2_image1,
+ chapter2_image2,
+ ]
+ }]
+ });
+
+ metadata.title = 'something else';
+ assert_equals(metadata.title, 'something else');
+
+ metadata.album = 'other value';
+ assert_equals(metadata.album, 'other value');
+
+ metadata.artist = 'someone else';
+ assert_equals(metadata.artist, 'someone else');
+
+ var image = { src: 'http://example.com/', sizes: '40x40', type: 'image/png' };
+ metadata.artwork = [ image ];
+ assert_equals(metadata.artwork.length, 1);
+ assert_equals(metadata.artwork[0].src, 'http://example.com/');
+ assert_equals(metadata.artwork[0].sizes, '40x40');
+ assert_equals(metadata.artwork[0].type, 'image/png');
+
+ // The chapterInfo cannot be modified.
+ var chapter_image = { src: 'http://example.com/', sizes: '40x40', type: 'image/png' };
+ var chapter = {
+ title: 'Chapter 3',
+ startTime: 22,
+ artwork: [chapter_image]
+ };
+ metadata.chapterInfo = [chapter];
+ assert_equals(metadata.chapterInfo[0].title, 'Chapter 1');
+ assert_equals(metadata.chapterInfo[0].startTime, 0);
+ assert_equals(metadata.chapterInfo.length, 2);
+}, "Test that MediaMetadata is read/write");
+
+test(function() {
+ var metadata = new MediaMetadata({ artwork: [ { src: 'http://foo.com/' } ] });
+ assert_throws_js(TypeError, _ => {
+ metadata.artwork.push({
+ src: 'http://example.com/', sizes: '40x40', type: 'image/png',
+ });
+ });
+
+ metadata.artwork[0].src = 'bar';
+ assert_equals(metadata.artwork[0].src, 'http://foo.com/');
+}, "Test that MediaMetadata.artwork can't be modified");
+
+test(function() {
+ var metadata = new MediaMetadata({ artwork: [{
+ src: 'http://example.com/', sizes: '40x40', type: 'image/png',
+ some_other_value: 'foo',
+ }]});
+ assert_equals(metadata.artwork[0].src, 'http://example.com/');
+ assert_equals(metadata.artwork[0].sizes, '40x40');
+ assert_equals(metadata.artwork[0].type, 'image/png');
+ assert_false('some_other_value' in metadata.artwork[0]);
+
+ metadata.artwork[0].something_else = 'bar';
+ assert_false('something_else' in metadata.artwork[0]);
+}, "Test that MediaMetadata.artwork will not expose unknown properties");
+
+test(function() {
+ var metadata = new MediaMetadata({ artwork: [
+ { src: 'http://example.com/1', sizes: '40x40', type: 'image/png' },
+ { src: 'http://example.com/2', sizes: '40x40', type: 'image/png' },
+ ]});
+
+ assert_true(Object.isFrozen(metadata.artwork));
+ for (var i = 0; i < metadata.artwork.length; ++i)
+ assert_true(Object.isFrozen(metadata.artwork[i]));
+}, "Test that MediaMetadata.artwork is Frozen");
+
+test(function() {
+ var chapter1_image1 = { src: 'http://chapterexample.com/1', sizes: '128x128', type: 'image/png' };
+ var chapter1_image2 = { src: 'http://chapterexample.com/2', sizes: '512x512', type: 'image/png' };
+ var chapter2_image1 = { src: 'http://chapterexample.com/3', sizes: '128x128', type: 'image/png' };
+ var chapter2_image2 = { src: 'http://chapterexample.com/4', sizes: '512x512', type: 'image/png' };
+ var metadata = new MediaMetadata({
+ chapterInfo: [{
+ title: 'Chapter 1',
+ startTime: 0,
+ artwork: [
+ chapter1_image1,
+ chapter1_image2
+ ]
+ }, {
+ title: 'Chapter 2',
+ startTime: 16,
+ artwork: [
+ chapter2_image1,
+ chapter2_image2,
+ ]
+ }]
+ });
+
+ assert_true(Object.isFrozen(metadata.chapterInfo));
+ for (var i = 0; i < metadata.chapterInfo.length; ++i)
+ assert_true(Object.isFrozen(metadata.chapterInfo[i]));
+}, "Test that MediaMetadata.chapterInfo is Frozen");
+
+test(function() {
+ var metadata = new MediaMetadata({ artwork: [
+ { src: 'http://example.com', sizes: '40x40', type: 'image/png' },
+ { src: '../foo', sizes: '40x40', type: 'image/png' },
+ { src: '/foo/bar', sizes: '40x40', type: 'image/png' },
+ ]});
+
+ assert_equals(metadata.artwork[0].src, new URL('http://example.com', document.URL).href)
+ assert_equals(metadata.artwork[1].src, new URL('../foo', document.URL).href)
+ assert_equals(metadata.artwork[2].src, new URL('/foo/bar', document.URL).href)
+}, "Test that MediaMetadata.artwork returns parsed urls");
+
+test(function() {
+ var chapter1_image1 = { src: 'http://chapterexample.com/1', sizes: '128x128', type: 'image/png' };
+ var chapter1_image2 = { src: 'http://chapterexample.com/2', sizes: '512x512', type: 'image/png' };
+ var chapter2_image1 = { src: 'http://chapterexample.com/3', sizes: '128x128', type: 'image/png' };
+ var chapter2_image2 = { src: 'http://chapterexample.com/4', sizes: '512x512', type: 'image/png' };
+ var metadata = new MediaMetadata({
+ chapterInfo: [{
+ title: 'Chapter 1',
+ startTime: 0,
+ artwork: [
+ chapter1_image1,
+ chapter1_image2
+ ]
+ }, {
+ title: 'Chapter 2',
+ startTime: 16,
+ artwork: [
+ chapter2_image1,
+ chapter2_image2,
+ ]
+ }]
+ });
+
+ assert_equals(metadata.chapterInfo[0].artwork[0].src,
+ new URL('http://chapterexample.com/1', document.URL).href)
+ assert_equals(metadata.chapterInfo[0].artwork[1].src,
+ new URL('http://chapterexample.com/2', document.URL).href)
+ assert_equals(metadata.chapterInfo[1].artwork[0].src,
+ new URL('http://chapterexample.com/3', document.URL).href)
+ assert_equals(metadata.chapterInfo[1].artwork[1].src,
+ new URL('http://chapterexample.com/4', document.URL).href)
+}, "Test that MediaMetadata.chapterInfo's artwork returns parsed urls");
+
+test(function() {
+ var metadata = 42;
+
+ assert_throws_js(TypeError, _ => {
+ metadata =
+ new MediaMetadata({ artwork: [ { src: 'http://[example.com]' }] });
+ });
+ assert_equals(metadata, 42);
+
+ metadata = new MediaMetadata();
+ assert_throws_js(TypeError, _ => {
+ metadata.artwork = [
+ // Valid url.
+ { src: 'http://example.com' },
+ // Invalid url.
+ { src: 'http://example.com:demo' },
+ ];
+ });
+ assert_equals(metadata.artwork.length, 0);
+
+ assert_throws_js(TypeError, _ => {
+ metadata =
+ new MediaMetadata({
+ chapterInfo: [{
+ title: 'Chapter 1',
+ startTime: 0,
+ artwork: [
+ // Valid url.
+ { src: 'http://example.com' },
+ // Invalid url.
+ { src: 'http://example.com:demo' },
+ ]
+ }]
+ });
+ });
+ assert_equals(metadata.chapterInfo.length, 0);
+}, "Test that MediaMetadata throws when setting an invalid url");
+
+test(function() {
+ var metadata = new MediaMetadata({ artwork: [ { src: 'foo.jpg' } ] });
+ assert_equals(metadata.artwork[0].type, '');
+ assert_equals(metadata.artwork[0].sizes, '');
+}, "Test MediaImage default values");
+
+test(function() {
+ assert_throws_js(TypeError, _ => {
+ new MediaMetadata({ artwork: [ {} ] })
+ });
+
+ var metadata = new MediaMetadata();
+ assert_throws_js(TypeError, _ => {
+ metadata.artwork = [ { type: 'image/png', sizes: '40x40' } ];
+ });
+
+ assert_throws_js(TypeError, _ => {
+ metadata =
+ new MediaMetadata({
+ chapterInfo: [{
+ title: 'Chapter 1',
+ startTime: 0,
+ artwork: [{ type: 'image/png', sizes: '40x40' }]
+ }]
+ });
+ });
+}, "Test that MediaImage.src is required")
+
+promise_test(async t => {
+ const URLs = [
+ 'http://example.com',
+ '../foo',
+ './foo/bar',
+ '/foo/bar',
+ ];
+ const subframe = await load_iframe('helper/artwork-generator.html');
+ // createArtworkFromURLs is a function in the subframe.
+ const artwork = subframe.contentWindow.createArtworkFromURLs(URLs);
+
+ assert_equals(artwork.length, URLs.length);
+ for (let i = 0 ; i < artwork.length ; ++i) {
+ assert_equals(artwork[i].src, new URL(URLs[i], subframe.contentDocument.URL).href);
+ }
+}, 'Test that the base URL of MediaImage is the base URL of entry setting object');
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/mediasession/playbackstate.html b/Tests/LibWeb/Text/input/wpt-import/mediasession/playbackstate.html
new file mode 100644
index 00000000000..79cacd3d2e9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/mediasession/playbackstate.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<title>MediaSession.playbackState attribute</title>
+<script src=../resources/testharness.js></script>
+<script src="../resources/testharnessreport.js"></script>
+<script>
+
+test(function() {
+ assert_equals(window.navigator.mediaSession.playbackState, "none");
+}, 'Test that playbackState is initialized as "none"');
+
+test(function() {
+ var states = [ "paused", "playing", "none" ];
+ for (let state of states) {
+ window.navigator.mediaSession.playbackState = state;
+ assert_equals(window.navigator.mediaSession.playbackState, state);
+ }
+}, 'Test that playbackState is read/write');
+
+test(function() {
+ var invalidStates = [ "invalid", "" ];
+ for (let state of invalidStates) {
+ window.navigator.mediaSession.playbackState = state;
+ assert_equals(window.navigator.mediaSession.playbackState, "none");
+ }
+}, 'Test that warning is thrown when setting invalid playbackState');
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/mediasession/positionstate.html b/Tests/LibWeb/Text/input/wpt-import/mediasession/positionstate.html
new file mode 100644
index 00000000000..76f1c3ca146
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/mediasession/positionstate.html
@@ -0,0 +1,106 @@
+<!DOCTYPE html>
+<title>MediaSession.setPositionState</title>
+<script src=../resources/testharness.js></script>
+<script src=../resources/testharnessreport.js></script>
+<script>
+test(() => {
+ window.navigator.mediaSession.setPositionState(null);
+}, 'Test setPositionState with a null value');
+
+test(() => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 60.9,
+ position: 10.1,
+ playbackRate: 1.5
+ });
+}, 'Test setPositionState with a valid value for forward playback');
+
+test(() => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 60.9,
+ playbackRate: 1.0
+ });
+}, 'Test setPositionState with optional position');
+
+test(() => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 60.9,
+ position: 10.1
+ });
+}, 'Test setPositionState with optional playback rate');
+
+test(() => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 60.9
+ });
+}, 'Test setPositionState with only duration');
+
+test(() => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 0
+ });
+}, 'Test setPositionState with zero duration');
+
+test(() => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 60.9,
+ position: 10.1,
+ playbackRate: -2.0
+ });
+}, 'Test setPositionState with negative playback rate');
+
+test(() => {
+ assert_throws_js(
+ TypeError,
+ _ => {
+ window.navigator.mediaSession.setPositionState({
+ duration: -1
+ });
+ });
+}, 'Test setPositionState throws a TypeError if duration is negative');
+
+test(() => {
+ assert_throws_js(
+ TypeError,
+ _ => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 10,
+ position: -1
+ });
+ });
+}, 'Test setPositionState throws a TypeError if position is negative');
+
+test(() => {
+ assert_throws_js(
+ TypeError,
+ _ => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 10,
+ position: 20
+ });
+ });
+}, 'Test setPositionState throws a TypeError if duration is less than position');
+
+test(() => {
+ assert_throws_js(
+ TypeError,
+ _ => {
+ window.navigator.mediaSession.setPositionState({
+ duration: 60.9,
+ position: 10.1,
+ playbackRate: 0.0
+ });
+ });
+}, 'Test setPositionState throws a TypeError if playback rate is zero');
+
+test(() => {
+ assert_throws_js(
+ TypeError,
+ _ => {
+ window.navigator.mediaSession.setPositionState({
+ position: 10.1,
+ playbackRate: 1.0
+ });
+ });
+}, 'Test setPositionState throws a TypeError if duration is not specified');
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/mediasession/setactionhandler.html b/Tests/LibWeb/Text/input/wpt-import/mediasession/setactionhandler.html
new file mode 100644
index 00000000000..27376bc57e6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/mediasession/setactionhandler.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<title>Test that setting MediaSession event handler should notify the service</title>
+<link rel="help" href="https://w3c.github.io/mediasession/#media-session-action" />
+<script src=../resources/testharness.js></script>
+<script src="../resources/testharnessreport.js"></script>
+<script>
+
+[
+ "play",
+ "pause",
+ "previoustrack",
+ "nexttrack",
+ "seekbackward",
+ "seekforward",
+ "stop",
+ "seekto",
+ "skipad",
+ "togglemicrophone",
+ "togglecamera",
+ "togglescreenshare",
+ "hangup",
+ "previousslide",
+ "nextslide",
+ "enterpictureinpicture",
+ "voiceactivity"
+].forEach((action) =>
+ test((t) => {
+ window.navigator.mediaSession.setActionHandler(action, null);
+ }, `Test that setActionHandler("${action}") succeeds`)
+);
+
+test(function(t) {
+ assert_throws_js(
+ TypeError,
+ _ => { window.navigator.mediaSession.setActionHandler("invalid", null); });
+}, "Test that setActionHandler() throws exception for unsupported actions");
+
+</script>