Skip to content

Truly independent web browser

LibWeb+LibAudio+AudioServer: Open the microphone in getUserMedia()

Luke Wilde283e79ca8972
diff --git a/Libraries/LibAudio/AudioClient.ipc b/Libraries/LibAudio/AudioClient.ipc
index fb34a5e7222..999673b1ad1 100644
--- a/Libraries/LibAudio/AudioClient.ipc
+++ b/Libraries/LibAudio/AudioClient.ipc
@@ -1,4 +1,5 @@
#include <LibAudio/AudioDevices.h>
+#include <LibAudio/RecordStreamFailure.h>
#include <LibAudio/SampleSpecification.h>
#include <LibAudio/SharedAudioFrameRing.h>
@@ -10,7 +11,7 @@ endpoint AudioClient {
devices_changed(Vector<Audio::AudioDeviceInfo> inputs, Vector<Audio::AudioDeviceInfo> outputs) =|
record_stream_created(u64 stream_id, Audio::SharedAudioFrameRing ring) =|
- record_stream_creation_failed(u64 stream_id) =|
+ record_stream_creation_failed(u64 stream_id, Audio::RecordStreamFailure failure) =|
// The tab's permission to capture is gone, and the stream with it.
record_stream_closed(u64 stream_id) =|
}
diff --git a/Libraries/LibAudio/ClientConnection.cpp b/Libraries/LibAudio/ClientConnection.cpp
index 338354f85a1..cb841482e93 100644
--- a/Libraries/LibAudio/ClientConnection.cpp
+++ b/Libraries/LibAudio/ClientConnection.cpp
@@ -180,7 +180,7 @@ void ClientConnection::record_stream_created(u64 stream_id, SharedAudioFrameRing
// FIXME: Support channel layouts beyond mono and stereo.
if (ring.channel_count() == 0 || ring.channel_count() > 2) {
async_destroy_record_stream(stream_id);
- record_stream_creation_failed(stream_id);
+ record_stream_creation_failed(stream_id, RecordStreamFailure::DeviceUnavailable);
return;
}
SampleSpecification specification(ring.sample_rate(), ring.channel_count() == 1 ? ChannelMap::mono() : ChannelMap::stereo());
@@ -200,13 +200,14 @@ void ClientConnection::record_stream_created(u64 stream_id, SharedAudioFrameRing
pending_stream.promise->resolve(adopt_ref(*new RemoteRecordStream(*this, stream_id, specification, move(pending_stream.callback))));
}
-void ClientConnection::record_stream_creation_failed(u64 stream_id)
+void ClientConnection::record_stream_creation_failed(u64 stream_id, RecordStreamFailure failure)
{
auto source = m_capture_sources.take(stream_id);
if (!source.has_value())
return;
+ auto error_code = failure == RecordStreamFailure::Refused ? EPERM : EIO;
for (auto& pending_stream : source->pending)
- pending_stream.promise->reject(Error::from_string_literal("Audio server could not open the capture device"));
+ pending_stream.promise->reject(Error::from_errno(error_code));
}
void ClientConnection::record_stream_closed(u64 stream_id)
diff --git a/Libraries/LibAudio/ClientConnection.h b/Libraries/LibAudio/ClientConnection.h
index 5b354be8e3d..44b13fa409a 100644
--- a/Libraries/LibAudio/ClientConnection.h
+++ b/Libraries/LibAudio/ClientConnection.h
@@ -21,6 +21,7 @@
#include <LibAudio/PlaybackGroupId.h>
#include <LibAudio/PlaybackStream.h>
#include <LibAudio/RecordStream.h>
+#include <LibAudio/RecordStreamFailure.h>
#include <LibAudio/SharedAudioFrameRing.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Promise.h>
@@ -95,7 +96,7 @@ private:
virtual void stream_request_completed(u64 stream_id, u64 request_id) override;
virtual void devices_changed(Vector<AudioDeviceInfo> inputs, Vector<AudioDeviceInfo> outputs) override;
virtual void record_stream_created(u64 stream_id, SharedAudioFrameRing ring) override;
- virtual void record_stream_creation_failed(u64 stream_id) override;
+ virtual void record_stream_creation_failed(u64 stream_id, RecordStreamFailure) override;
virtual void record_stream_closed(u64 stream_id) override;
void pump_thread_main();
diff --git a/Libraries/LibAudio/RecordStream.h b/Libraries/LibAudio/RecordStream.h
index fdd8403bb2b..2f019bf763b 100644
--- a/Libraries/LibAudio/RecordStream.h
+++ b/Libraries/LibAudio/RecordStream.h
@@ -31,6 +31,7 @@ public:
// passed to the callback is authoritative. A process with no server to reach is refused,
// since only the AudioServer opens devices. The device id is a dom_device_id produced by
// AudioDevices, or an empty string to capture from the default input device.
+ // A stream the Browser refused is rejected with EPERM, and one whose device would not open with EIO.
static NonnullRefPtr<CreatePromise> create(StringView device_id, RecordCallback);
virtual ~RecordStream() = default;
diff --git a/Libraries/LibAudio/RecordStreamFailure.h b/Libraries/LibAudio/RecordStreamFailure.h
new file mode 100644
index 00000000000..c2ffd0aeeea
--- /dev/null
+++ b/Libraries/LibAudio/RecordStreamFailure.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Types.h>
+
+namespace Audio {
+
+// Why the AudioServer could not open a capture stream.
+enum class RecordStreamFailure : u8 {
+ // The Browser refused it: the tab may no longer capture, or the system keeps the microphone from the browser.
+ Refused,
+ DeviceUnavailable,
+};
+
+}
diff --git a/Libraries/LibWeb/MediaCapture/MediaDevices.cpp b/Libraries/LibWeb/MediaCapture/MediaDevices.cpp
index 8f6339bc445..1387114d520 100644
--- a/Libraries/LibWeb/MediaCapture/MediaDevices.cpp
+++ b/Libraries/LibWeb/MediaCapture/MediaDevices.cpp
@@ -393,6 +393,17 @@ GC::RootVector<GC::Ref<MediaDeviceInfo>> MediaDevices::create_list_of_device_inf
return result_list;
}
+static GC::Ref<WebIDL::DOMException> device_access_failure(Error const& error)
+{
+ // AD-HOC: The Browser refuses a capture only once the permission, or the system's consent for the browser, is gone,
+ // which is a failure of permission rather than of the device.
+ if (error.is_errno() && error.code() == EPERM)
+ return WebIDL::NotAllowedError::create("Permission denied"_utf16);
+ if (error.is_errno() && error.code() == EIO)
+ return WebIDL::NotReadableError::create("The audio input device could not be opened"_utf16);
+ return WebIDL::AbortError::create("The audio input device could not be accessed"_utf16);
+}
+
// https://w3c.github.io/mediacapture-main/#dom-mediadevices-getusermedia
void MediaDevices::queue_get_user_media_task(GC::Ref<WebIDL::Promise> promise, Optional<DeviceIdConstraint> device_id_constraint)
{
@@ -535,16 +546,20 @@ void MediaDevices::queue_get_user_media_task(GC::Ref<WebIDL::Promise> promise, O
return;
}
- // 11.9.2 The result of the request is "granted".
- // 11.9.3 Let grantedDevice be finalCandidate's source device.
+ // 11.9.2 The result of the request is "granted". If a hardware error such as an OS/program/webpage lock
+ // prevents access, remove the corresponding candidate from finalSet. If finalSet has no candidates
+ // of type kind, reject p with a new DOMException object whose name attribute has the value
+ // "NotReadableError" and abort these steps. Otherwise, restart these sub steps with the updated
+ // finalSet.
+ // If device access fails for any reason other than those listed above, remove the corresponding
+ // candidate from finalSet. If finalSet has no candidates of type kind, reject p with a new
+ // DOMException object whose name attribute has the value "AbortError" and abort these steps.
+ // Otherwise, restart these sub steps with the updated finalSet.
+ // AD-HOC: The device is accessed through the capture stream of the track it feeds, so the track is created
+ // first, and the page sees it only once access succeeds.
+ // FIXME: Restart these sub steps with the rest of finalSet when the device fails.
Audio::AudioDeviceInfo const& granted_device = final_candidate.value();
-
- // 11.9.4 Using grantedDevice's deviceId, deviceId, set mediaDevices.[[devicesLiveMap]][deviceId] to true, if it isn't already true, and set mediaDevices.[[devicesAccessibleMap]][deviceId] to true, if it isn't already true.
auto granted_device_id = Utf16String::from_utf8_with_replacement_character(granted_device.dom_device_id.view());
- media_devices->m_devices_live_map.set(granted_device_id, true);
- media_devices->m_devices_accessible_map.set(granted_device_id, true);
-
- // 11.9.5 Let track be the result of creating a MediaStreamTrack with grantedDevice and mediaDevices. The source of the MediaStreamTrack MUST NOT change.
GC::Ref<MediaStreamTrack> track = MediaStreamTrack::create(
MediaStreamTrackKind::Audio,
Utf16String::from_utf8_with_replacement_character(granted_device.label.view()));
@@ -554,25 +569,53 @@ void MediaDevices::queue_get_user_media_task(GC::Ref<WebIDL::Promise> promise, O
settings.sample_rate = granted_device.sample_rate_hz;
settings.channel_count = granted_device.channel_count;
track->set_settings(move(settings));
+ track->set_media_devices({}, *media_devices);
- // 11.9.6 Add track to stream's track set.
- stream->append_track(track);
+ track->start_audio_capture(GC::create_function(GC::Heap::the(), [promise, media_devices, stream, track, granted_device_id](ErrorOr<void> access) {
+ auto& realm = WebIDL::promise_realm(*promise);
+ HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
- // FIXME: 11.10 Run the ApplyConstraints algorithm on all tracks in stream with the appropriate constraints.
+ if (access.is_error()) {
+ WebIDL::reject_promise(*promise, device_access_failure(access.error()));
+ return;
+ }
- // 11.11 For each track in stream, tie track source to MediaDevices with track.[[Source]] and mediaDevices.
- media_devices->m_media_stream_track_sources.append(track);
- track->set_media_devices({}, *media_devices);
- track->on_audio_capture_revoked = [media_devices = GC::Weak<MediaDevices>(media_devices), track = GC::Weak<MediaStreamTrack>(track)] {
- if (!media_devices.ptr() || !track.ptr())
+ // AD-HOC: The user may have left the document while the device opened, and capture does not go on
+ // for one they have left.
+ if (!media_devices->m_window->associated_document().is_fully_active()) {
+ track->stop();
+ WebIDL::reject_promise(*promise, WebIDL::InvalidStateError::create("Document is not fully active"_utf16));
return;
- GC::RootVector<GC::Ref<MediaStreamTrack>> tracks;
- tracks.append(*track.ptr());
- media_devices->end_tracks(move(tracks));
- };
+ }
- // 11.12 Resolve p with stream and abort these steps.
- resolve_media_stream_promise(*promise, stream);
+ // AD-HOC: The user may have taken the permission away while the device opened, which ended no track of
+ // this request since none is tied to mediaDevices yet. Another page can keep the process
+ // allowed to capture, so the device opening says nothing of this document.
+ if (PermissionsAPI::permission_state(PermissionsAPI::PermissionDescriptor { "microphone"_utf16 }, HTML::relevant_settings_object(*media_devices->m_window)) != PermissionsAPI::PermissionState::Granted) {
+ track->stop();
+ WebIDL::reject_promise(*promise, WebIDL::NotAllowedError::create("Permission denied"_utf16));
+ return;
+ }
+
+ // 11.9.3 Let grantedDevice be finalCandidate's source device.
+ // 11.9.4 Using grantedDevice's deviceId, deviceId, set mediaDevices.[[devicesLiveMap]][deviceId] to true, if it isn't already true, and set mediaDevices.[[devicesAccessibleMap]][deviceId] to true, if it isn't already true.
+ media_devices->m_devices_live_map.set(granted_device_id, true);
+ media_devices->m_devices_accessible_map.set(granted_device_id, true);
+
+ // 11.9.5 Let track be the result of creating a MediaStreamTrack with grantedDevice and mediaDevices. The source of the MediaStreamTrack MUST NOT change.
+ // NB: The track was created to access the device.
+
+ // 11.9.6 Add track to stream's track set.
+ stream->append_track(track);
+
+ // FIXME: 11.10 Run the ApplyConstraints algorithm on all tracks in stream with the appropriate constraints.
+
+ // 11.11 For each track in stream, tie track source to MediaDevices with track.[[Source]] and mediaDevices.
+ media_devices->m_media_stream_track_sources.append(track);
+
+ // 11.12 Resolve p with stream and abort these steps.
+ resolve_media_stream_promise(*promise, stream);
+ }));
}));
}));
}));
@@ -871,6 +914,13 @@ void MediaDevices::track_was_cloned(Badge<MediaStreamTrack>, MediaStreamTrack& c
m_media_stream_track_sources.append(clone);
}
+void MediaDevices::track_source_ended(Badge<MediaStreamTrack>, MediaStreamTrack& track)
+{
+ GC::RootVector<GC::Ref<MediaStreamTrack>> tracks_to_end;
+ tracks_to_end.append(track);
+ end_tracks(move(tracks_to_end));
+}
+
void MediaDevices::end_tracks(GC::RootVector<GC::Ref<MediaStreamTrack>> tracks_to_end)
{
if (tracks_to_end.is_empty())
diff --git a/Libraries/LibWeb/MediaCapture/MediaDevices.h b/Libraries/LibWeb/MediaCapture/MediaDevices.h
index a601998aa83..e000ad22c93 100644
--- a/Libraries/LibWeb/MediaCapture/MediaDevices.h
+++ b/Libraries/LibWeb/MediaCapture/MediaDevices.h
@@ -46,6 +46,7 @@ public:
// Ends every live track once the document may no longer use the microphone.
void end_tracks_without_permission();
void track_was_cloned(Badge<MediaStreamTrack>, MediaStreamTrack& clone);
+ void track_source_ended(Badge<MediaStreamTrack>, MediaStreamTrack&);
// getUserMedia() waits while the page lacks system focus, and the Window sees no event when that changes.
void system_focus_changed();
diff --git a/Libraries/LibWeb/MediaCapture/MediaStreamTrack.cpp b/Libraries/LibWeb/MediaCapture/MediaStreamTrack.cpp
index 9989f49241a..8a4188ed4fb 100644
--- a/Libraries/LibWeb/MediaCapture/MediaStreamTrack.cpp
+++ b/Libraries/LibWeb/MediaCapture/MediaStreamTrack.cpp
@@ -29,19 +29,17 @@ Atomic<u64> MediaStreamTrack::s_next_provider_id { 1 };
// negotiate it; until then the track source applies unity gain.
static constexpr float TRACK_SOURCE_GAIN = 1.0f;
-bool AudioFrameFanout::add_sink(NonnullRefPtr<AudioFrameSink> sink)
+void AudioFrameFanout::add_sink(NonnullRefPtr<AudioFrameSink> sink)
{
MutexLocker locker(m_mutex);
m_sinks.append(move(sink));
- return m_sinks.size() == 1;
}
-bool AudioFrameFanout::remove_sink(AudioFrameSink const& sink)
+void AudioFrameFanout::remove_sink(AudioFrameSink const& sink)
{
sink.deactivate();
MutexLocker locker(m_mutex);
m_sinks.remove_first_matching([&](auto const& existing) { return existing.ptr() == &sink; });
- return m_sinks.is_empty();
}
void AudioFrameFanout::deliver(float const* samples, size_t frame_count, u8 channel_count, u32 sample_rate)
@@ -155,8 +153,7 @@ void MediaStreamTrack::stop()
return;
// 3. Notify track's source that track is ended.
- // For device-backed audio tracks this releases the capture stream.
- // FIXME: Model track sources properly so tracks sharing a source keep it alive.
+ // NB: Every track of a device holds a stream of it, and the process keeps the device's capture open while any does.
stop_audio_capture();
// 4. Set track's [[ReadyState]] to "ended".
@@ -206,6 +203,8 @@ GC::Ref<MediaStreamTrack> MediaStreamTrack::clone() const
media_devices->track_was_cloned({}, track_clone);
track_clone->m_media_devices = m_media_devices;
}
+ if (track_clone->m_state == MediaStreamTrackState::Live && device_id().has_value())
+ track_clone->start_audio_capture();
// 9. Return trackClone.
return track_clone;
@@ -275,17 +274,12 @@ void MediaStreamTrack::apply_constraints_impl(Optional<MediaTrackConstraints> co
void MediaStreamTrack::add_audio_sink(NonnullRefPtr<AudioFrameSink> sink)
{
- auto was_first_sink = m_audio_fanout->add_sink(move(sink));
-
- // Synthetic tracks have no deviceId and are fed through deliver_audio_frames().
- if (was_first_sink && is_audio() && m_state == MediaStreamTrackState::Live && device_id().has_value())
- ensure_audio_capture_started();
+ m_audio_fanout->add_sink(move(sink));
}
void MediaStreamTrack::remove_audio_sink(AudioFrameSink const& sink)
{
- if (m_audio_fanout->remove_sink(sink))
- stop_audio_capture();
+ m_audio_fanout->remove_sink(sink);
}
void MediaStreamTrack::deliver_audio_frames(float const* samples, size_t frame_count, u8 channel_count, u32 sample_rate)
@@ -293,7 +287,7 @@ void MediaStreamTrack::deliver_audio_frames(float const* samples, size_t frame_c
m_audio_fanout->deliver(samples, frame_count, channel_count, sample_rate);
}
-void MediaStreamTrack::ensure_audio_capture_started()
+void MediaStreamTrack::start_audio_capture(GC::Ptr<GC::Function<void(ErrorOr<void>)>> on_started)
{
if (m_audio_capture_stream || m_audio_capture_start_pending)
return;
@@ -324,7 +318,7 @@ void MediaStreamTrack::ensure_audio_capture_started()
return;
fanout->deliver(reinterpret_cast<float const*>(data.data()), frame_count, channel_count, stream_specification.sample_rate());
});
- stream_promise->when_resolved([track = GC::Ref(*this), capture_request_id](NonnullRefPtr<Audio::RecordStream>& stream) {
+ stream_promise->when_resolved([track = GC::Ref(*this), capture_request_id, on_started = GC::Root(on_started)](NonnullRefPtr<Audio::RecordStream>& stream) {
if (track->m_audio_capture_request_id != capture_request_id)
return;
track->m_audio_capture_start_pending = false;
@@ -337,24 +331,36 @@ void MediaStreamTrack::ensure_audio_capture_started()
if (!track || track->m_audio_capture_request_id != capture_request_id)
return;
track->m_audio_capture_stream = nullptr;
- track->ensure_audio_capture_started();
+ track->start_audio_capture();
};
stream->on_capture_revoked = [weak_track = GC::Weak<MediaStreamTrack>(track), capture_request_id] {
auto track = weak_track.ptr();
if (!track || track->m_audio_capture_request_id != capture_request_id)
return;
- if (track->on_audio_capture_revoked)
- track->on_audio_capture_revoked();
+ track->audio_source_ended();
};
+ if (on_started)
+ on_started->function()({});
});
- stream_promise->when_rejected([track = GC::Ref(*this), capture_request_id](Error& error) {
+ stream_promise->when_rejected([track = GC::Ref(*this), capture_request_id, on_started = GC::Root(on_started)](Error& error) {
if (track->m_audio_capture_request_id != capture_request_id)
return;
track->m_audio_capture_start_pending = false;
- dbgln("MediaStreamTrack: Unable to open a capture stream: {}", error);
+ if (on_started) {
+ on_started->function()(Error::copy(error));
+ return;
+ }
+ // A device the track can't capture from again has permanently ended production of live samples.
+ track->audio_source_ended();
});
}
+void MediaStreamTrack::audio_source_ended()
+{
+ if (auto media_devices = m_media_devices.ptr())
+ media_devices->track_source_ended({}, *this);
+}
+
void MediaStreamTrack::stop_audio_capture()
{
m_audio_capture_start_pending = false;
diff --git a/Libraries/LibWeb/MediaCapture/MediaStreamTrack.h b/Libraries/LibWeb/MediaCapture/MediaStreamTrack.h
index b09b05cb7a8..3494e2f3e20 100644
--- a/Libraries/LibWeb/MediaCapture/MediaStreamTrack.h
+++ b/Libraries/LibWeb/MediaCapture/MediaStreamTrack.h
@@ -19,6 +19,7 @@
#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <AK/Vector.h>
+#include <LibGC/Function.h>
#include <LibGC/Weak.h>
#include <LibWeb/Bindings/MediaStreamConstraints.h>
#include <LibWeb/Bindings/MediaStreamTrack.h>
@@ -70,10 +71,8 @@ struct AudioFrameSink final : public AtomicRefCounted<AudioFrameSink> {
// Atomically ref-counted because backend callbacks may outlive the GC-managed track.
class AudioFrameFanout final : public AtomicRefCounted<AudioFrameFanout> {
public:
- // Returns true when this was the first sink to register.
- bool add_sink(NonnullRefPtr<AudioFrameSink>);
- // Returns true when the last sink was removed.
- bool remove_sink(AudioFrameSink const&);
+ void add_sink(NonnullRefPtr<AudioFrameSink>);
+ void remove_sink(AudioFrameSink const&);
// While a track is muted or disabled it must render silence rather than nothing, so
// consumers keep observing the track's timing and format.
@@ -112,8 +111,9 @@ public:
MediaStreamTrackState track_ready_state() const { return m_state; }
- // The tab's permission to capture is gone; whoever tied the track's source ends it.
- Function<void()> on_audio_capture_revoked;
+ // A device-backed track captures from its device from here until it ends, whether or not anything consumes it.
+ // Without on_started, a device that won't open ends the track.
+ void start_audio_capture(GC::Ptr<GC::Function<void(ErrorOr<void>)>> on_started = {});
void stop();
void end();
@@ -138,7 +138,6 @@ public:
u64 provider_id() const { return m_provider_id; }
- // The first sink starts device capture; removing the last stops it.
void add_audio_sink(NonnullRefPtr<AudioFrameSink>);
void remove_audio_sink(AudioFrameSink const&);
@@ -151,8 +150,8 @@ private:
void apply_constraints_impl(Optional<MediaTrackConstraints> constraints);
- void ensure_audio_capture_started();
void stop_audio_capture();
+ void audio_source_ended();
void update_audio_silence_state() { m_audio_fanout->set_silenced(!m_enabled || m_muted || m_state == MediaStreamTrackState::Ended); }
static Atomic<u64> s_next_provider_id;
diff --git a/Services/AudioServer/ServerConnection.cpp b/Services/AudioServer/ServerConnection.cpp
index 3e45535881e..7e1ddc38348 100644
--- a/Services/AudioServer/ServerConnection.cpp
+++ b/Services/AudioServer/ServerConnection.cpp
@@ -6,6 +6,7 @@
#include <AK/Atomic.h>
#include <AudioServer/ServerConnection.h>
+#include <LibAudio/RecordStreamFailure.h>
#include <math.h>
namespace Audio {
@@ -286,7 +287,7 @@ void ServerConnection::capture_permission_decided(u64 stream_id, ByteString cons
return;
if (!allowed) {
m_record_streams.remove(stream_id);
- async_record_stream_creation_failed(stream_id);
+ async_record_stream_creation_failed(stream_id, RecordStreamFailure::Refused);
return;
}
@@ -310,7 +311,7 @@ void ServerConnection::capture_device_ready(u64 stream_id, CaptureSubscriberId s
auto fail = [&] {
m_capture_devices->unsubscribe(subscriber_id);
m_record_streams.remove(stream_id);
- async_record_stream_creation_failed(stream_id);
+ async_record_stream_creation_failed(stream_id, RecordStreamFailure::DeviceUnavailable);
};
if (result.is_error()) {
fail();
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 42924ff293c..972d0c16cf4 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -17,6 +17,7 @@ Text/input/wpt-import/custom-elements/connected-callbacks.html
; Picture aspect ratios depend on images loaded by root-relative srcset URLs.
Text/input/wpt-import/html/rendering/replaced-elements/attributes-for-embedded-content-and-images/picture-aspect-ratio.html
; Permissions are kept for a site's origin, and a file: page has none.
+Text/input/MediaCapture/
Text/input/PermissionsAPI/
Text/input/WebRTC/audio-loopback.html
Text/input/WebRTC/data-channel-loopback.html
diff --git a/Tests/LibWeb/Text/expected/MediaCapture/getUserMedia-rejects-when-capture-is-refused.txt b/Tests/LibWeb/Text/expected/MediaCapture/getUserMedia-rejects-when-capture-is-refused.txt
new file mode 100644
index 00000000000..5ab95097b77
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/MediaCapture/getUserMedia-rejects-when-capture-is-refused.txt
@@ -0,0 +1 @@
+NotAllowedError
diff --git a/Tests/LibWeb/Text/expected/MediaCapture/getUserMedia-revoked-while-the-system-asks.txt b/Tests/LibWeb/Text/expected/MediaCapture/getUserMedia-revoked-while-the-system-asks.txt
new file mode 100644
index 00000000000..fb3498e55ec
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/MediaCapture/getUserMedia-revoked-while-the-system-asks.txt
@@ -0,0 +1 @@
+the request settles with: NotAllowedError
diff --git a/Tests/LibWeb/Text/expected/MediaCapture/track-ends-when-its-device-cannot-reopen.txt b/Tests/LibWeb/Text/expected/MediaCapture/track-ends-when-its-device-cannot-reopen.txt
new file mode 100644
index 00000000000..3b1d17dbef0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/MediaCapture/track-ends-when-its-device-cannot-reopen.txt
@@ -0,0 +1,2 @@
+track: ended
+clone: ended
diff --git a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txt b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txt
index c402bca208e..704836a23d6 100644
--- a/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txt
+++ b/Tests/LibWeb/Text/expected/PermissionsAPI/microphone-capture-refused-notice-shows-once.txt
@@ -1,3 +1,5 @@
+getUserMedia: NotAllowedError
+getUserMedia: NotAllowedError
capture decisions: 2
capture refusals: 2
notices shown: 1
diff --git a/Tests/LibWeb/Text/input/MediaCapture/getUserMedia-rejects-when-capture-is-refused.html b/Tests/LibWeb/Text/input/MediaCapture/getUserMedia-rejects-when-capture-is-refused.html
new file mode 100644
index 00000000000..124ff19d2c1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/MediaCapture/getUserMedia-rejects-when-capture-is-refused.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ await internals.setPermission("microphone", "granted");
+ internals.setSystemMicrophoneAuthorization("denied");
+ try {
+ await navigator.mediaDevices.getUserMedia({ audio: true });
+ println("resolved");
+ } catch (error) {
+ println(error.name);
+ }
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/MediaCapture/getUserMedia-revoked-while-the-system-asks.html b/Tests/LibWeb/Text/input/MediaCapture/getUserMedia-revoked-while-the-system-asks.html
new file mode 100644
index 00000000000..5aa410c9f4d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/MediaCapture/getUserMedia-revoked-while-the-system-asks.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // The user blocks a site while the system is still asking about its request. The popup stays allowed, so this process
+ // may go on capturing and the AudioServer opens the device, but the blocked site gets no stream of it.
+ promiseTest(async () => {
+ internals.setTestTimeout(30_000);
+ await internals.setPermission("microphone", "granted");
+
+ const url = new URL(
+ await httpTestServer().createEcho("GET", "/getUserMedia-revoked-while-the-system-asks", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>
+ internals.setPermission("microphone", "granted").then(() => opener.postMessage("allowed", "*"));
+ <\/script>`,
+ })
+ );
+ // Another origin of this site, which shares this process.
+ url.hostname = `popup.${location.hostname}`;
+
+ const allowed = new Promise(resolve => addEventListener("message", resolve, { once: true }));
+ const popup = window.open(url.href);
+ await allowed;
+
+ internals.setSystemMicrophoneAuthorization("not-determined", "authorized", true);
+ window.focus();
+ const request = navigator.mediaDevices.getUserMedia({ audio: true });
+ await waitForCondition(() => JSON.parse(internals.microphoneState()).systemRequests === 1);
+
+ await internals.setPermission("microphone", "denied");
+ internals.releaseSystemMicrophoneAnswer();
+ println(`the request settles with: ${await request.then(stream => "a live stream", error => error.name)}`);
+ popup.close();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/MediaCapture/track-ends-when-its-device-cannot-reopen.html b/Tests/LibWeb/Text/input/MediaCapture/track-ends-when-its-device-cannot-reopen.html
new file mode 100644
index 00000000000..1b3edb0570c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/MediaCapture/track-ends-when-its-device-cannot-reopen.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ const track = stream.getTracks()[0];
+ const clone = stream.clone().getTracks()[0];
+ const ended = Promise.all([track, clone].map(t => new Promise(resolve => t.addEventListener("ended", resolve))));
+
+ internals.setSystemMicrophoneAuthorization("denied");
+ internals.disconnectAudioServer();
+ await ended;
+ println(`track: ${track.readyState}`);
+ println(`clone: ${clone.readyState}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.html b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.html
index e99c0875104..9db852571f8 100644
--- a/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.html
+++ b/Tests/LibWeb/Text/input/PermissionsAPI/microphone-capture-refused-notice-shows-once.html
@@ -1,9 +1,9 @@
<!DOCTYPE html>
<script src="../include.js"></script>
<script>
- // A site the user allowed earlier asks the AudioServer to capture once something reads its track. While the system
- // denies the browser the microphone, every such capture is refused, but the user is told only once, and the site's
- // permission is left as it was.
+ // A site the user allowed earlier asks the AudioServer to capture when getUserMedia() opens the microphone. While
+ // the system denies the browser the microphone, every such capture is refused, but the user is told only once, and
+ // the site's permission is left as it was.
asyncTest(async done => {
const state = () => JSON.parse(internals.microphoneState());
// The process counts its capture decisions, and an earlier test may have run in it.
@@ -16,10 +16,13 @@
internals.setSystemMicrophoneAuthorization("denied");
internals.setNextPermissionPromptOutcome("microphone", "dismiss");
- const context = new AudioContext();
for (let i = 1; i <= 2; ++i) {
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- context.createMediaStreamSource(stream);
+ try {
+ await navigator.mediaDevices.getUserMedia({ audio: true });
+ println("getUserMedia: resolved");
+ } catch (error) {
+ println(`getUserMedia: ${error.name}`);
+ }
await captureDecided(i);
// A capture of the same device joins one that waits on the AudioServer, so the next starts once this one's
// refusal has reached this process.