Skip to content

Truly independent web browser

LibWeb: Play MediaStreams assigned to a media element's srcObject

Ali Mohammad Pur02b93ad15ea8
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index a57cb7a4842..ed89ffe5963 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -576,6 +576,7 @@ set(SOURCES
HTML/LocalTraversableNavigable.cpp
HTML/Location.cpp
HTML/MediaError.cpp
+ HTML/MediaStreamPlayback.cpp
HTML/MediaTrackBase.cpp
HTML/MessageEvent.cpp
HTML/MessagePort.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index f7dfa51b998..88d968cf2d2 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -798,6 +798,7 @@ class LocalNavigable;
class LocalTraversableNavigable;
class Location;
class MediaError;
+class MediaStreamPlayback;
class MessageEvent;
class MessagePort;
class MimeType;
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index 86fc67800b9..86f80e340ef 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -15,6 +15,7 @@
#include <LibJS/Runtime/Date.h>
#include <LibJS/Runtime/Promise.h>
#include <LibMedia/MediaSupport.h>
+#include <LibMedia/Sinks/AudioOutputFactory.h>
#include <LibMedia/Track.h>
#include <LibMediaClient/Client.h>
#include <LibMediaClient/RemoteMediaStream.h>
@@ -46,6 +47,7 @@
#include <LibWeb/HTML/HTMLVideoElement.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/MediaError.h>
+#include <LibWeb/HTML/MediaStreamPlayback.h>
#include <LibWeb/HTML/PotentialCORSRequest.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
@@ -660,6 +662,8 @@ void HTMLMediaElement::seek_from_media_controls(double time)
// https://html.spec.whatwg.org/multipage/media.html#current-playback-position
double HTMLMediaElement::current_playback_position() const
{
+ if (m_media_stream_playback)
+ return m_media_stream_playback->current_time();
if (!m_playback_manager)
return 0;
return m_playback_manager->current_time().to_seconds_f64();
@@ -854,6 +858,8 @@ void HTMLMediaElement::update_volume()
{
if (m_playback_manager)
m_playback_manager->set_volume(effective_media_volume());
+ if (m_media_stream_playback)
+ m_media_stream_playback->set_volume(effective_media_volume());
}
// https://html.spec.whatwg.org/multipage/media.html#dom-media-addtexttrack
@@ -1886,9 +1892,21 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,
// the demuxers that our PlaybackManager is given.
}
},
- [&](GC::Ref<MediaCapture::MediaStream>) {
- // FIXME: Route MediaStream tracks into media-element playback.
- // Accept srcObject assignments while RTC audio uses direct playback.
+ [&](GC::Ref<MediaCapture::MediaStream> stream) {
+ // https://w3c.github.io/mediacapture-main/#mediastreams-in-media-elements
+ // FIXME: Reflect the stream's tracks in audioTracks and videoTracks, follow tracks added to or removed
+ // from the stream after assignment, and render video tracks.
+ m_media_stream_playback = MediaStreamPlayback::create(document().page().client().create_audio_output_factory());
+ m_media_stream_playback->set_tracks(stream->get_audio_tracks());
+ update_volume();
+
+ // A MediaStream is live and unbounded, so its duration is infinite and its data is always as complete as it
+ // will get.
+ set_duration(AK::Infinity<double>);
+ set_ready_state(ReadyState::HaveMetadata);
+ set_ready_state(ReadyState::HaveEnoughData);
+ set_network_state(NetworkState::Idle);
+ set_delaying_the_load_event(false);
},
[&](GC::Ref<FileAPI::Blob>) {
// FIXME: Support File objects.
@@ -2716,6 +2734,10 @@ void HTMLMediaElement::forget_media_resource_specific_tracks()
m_video_tracks->remove_all_tracks();
update_audio_play_state();
m_playback_manager.clear();
+ if (m_media_stream_playback) {
+ m_media_stream_playback->set_tracks({});
+ m_media_stream_playback.clear();
+ }
m_last_known_current_playback_position = {};
start_or_stop_playback_position_update_timer();
update_screen_wake_lock();
@@ -3323,6 +3345,8 @@ void HTMLMediaElement::notify_about_playing()
if (m_playback_manager)
m_playback_manager->play();
+ if (m_media_stream_playback)
+ m_media_stream_playback->play();
m_has_started_playback = true;
update_audio_play_state();
@@ -3367,6 +3391,8 @@ void HTMLMediaElement::set_paused(bool paused)
if (m_playback_manager)
m_playback_manager->pause();
+ if (m_media_stream_playback)
+ m_media_stream_playback->pause();
update_audio_play_state();
}
@@ -3589,6 +3615,12 @@ bool HTMLMediaElement::has_ended_playback(IgnoreLoopAttribute ignore_loop_attrib
if (m_ready_state < ReadyState::HaveMetadata)
return false;
+ // NB: A MediaStream is unbounded, so playback never reaches its end and it has no earliest position to go back to.
+ // FIXME: Report ended playback once the MediaStream becomes inactive.
+ // https://w3c.github.io/mediacapture-main/#mediastreams-in-media-elements
+ if (m_media_stream_playback)
+ return false;
+
VERIFY(m_playback_manager != nullptr);
// Either:
if (
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.h
index 5583c16068b..43a3d16a6a9 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h
@@ -492,6 +492,7 @@ private:
bool m_current_resource_selection_is_explicit { false };
OwnPtr<MediaClient::RemotePlaybackManager> m_playback_manager;
+ OwnPtr<MediaStreamPlayback> m_media_stream_playback;
Function<void(Utf16String)> m_playback_manager_failure_callback;
RefPtr<Core::Timer> m_playback_position_update_timer;
diff --git a/Libraries/LibWeb/HTML/MediaStreamPlayback.cpp b/Libraries/LibWeb/HTML/MediaStreamPlayback.cpp
new file mode 100644
index 00000000000..4c63b563e26
--- /dev/null
+++ b/Libraries/LibWeb/HTML/MediaStreamPlayback.cpp
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Atomic.h>
+#include <AK/Mutex.h>
+#include <LibMedia/FFmpeg/FFmpegAudioConverter.h>
+#include <LibMedia/Sinks/AudioOutputFactory.h>
+#include <LibMediaCodecs/AudioBlock.h>
+#include <LibWeb/HTML/MediaStreamPlayback.h>
+
+namespace Web::HTML {
+
+static constexpr u32 TARGET_LATENCY_MS = 100;
+
+// Live audio that the output can't keep up with is dropped rather than played late.
+static constexpr u32 MAXIMUM_QUEUED_MILLISECONDS = 200;
+
+// Fed on whichever thread produces the track's audio, drained on the audio output's thread.
+struct MediaStreamPlayback::TrackInput final : public AtomicRefCounted<TrackInput> {
+ Mutex mutex;
+ OwnPtr<Media::FFmpeg::FFmpegAudioConverter> converter;
+ Audio::SampleSpecification converter_output_specification;
+ i64 frames_received { 0 };
+ // Interleaved, in the output's sample specification.
+ Vector<float> samples;
+};
+
+struct MediaStreamPlayback::Mixer final : public AtomicRefCounted<Mixer> {
+ Mutex mutex;
+ Vector<NonnullRefPtr<TrackInput>> inputs;
+ Audio::SampleSpecification output_specification;
+ Atomic<bool> playing { false };
+};
+
+static void receive_frames(MediaStreamPlayback::Mixer& mixer, MediaStreamPlayback::TrackInput& input, float const* samples, size_t frame_count, u8 channel_count, u32 sample_rate)
+{
+ if (!mixer.playing.load(AK::MemoryOrder::memory_order_relaxed) || frame_count == 0 || channel_count == 0 || sample_rate == 0)
+ return;
+
+ Audio::SampleSpecification output_specification;
+ {
+ MutexLocker locker(mixer.mutex);
+ output_specification = mixer.output_specification;
+ }
+ if (!output_specification.is_valid())
+ return;
+
+ MutexLocker locker(input.mutex);
+ if (!input.converter || input.converter_output_specification != output_specification) {
+ auto converter_or_error = Media::FFmpeg::FFmpegAudioConverter::try_create();
+ if (converter_or_error.is_error())
+ return;
+ auto converter = converter_or_error.release_value();
+ if (converter->set_output_sample_specification(output_specification).is_error())
+ return;
+ input.converter = move(converter);
+ input.converter_output_specification = output_specification;
+ input.samples.clear();
+ }
+
+ // FIXME: Downmix sources with more than two channels instead of keeping the first two.
+ auto used_channel_count = min<size_t>(channel_count, 2);
+ auto channel_map = used_channel_count == 1 ? Audio::ChannelMap::mono() : Audio::ChannelMap::stereo();
+ Media::AudioBlock block;
+ block.initialize(Audio::SampleSpecification(sample_rate, channel_map), input.frames_received, frame_count);
+ input.frames_received += static_cast<i64>(frame_count);
+ for (size_t channel = 0; channel < used_channel_count; ++channel) {
+ auto destination = block.channel_data(channel);
+ for (size_t frame = 0; frame < frame_count; ++frame)
+ destination[frame] = samples[(frame * channel_count) + channel];
+ }
+ if (input.converter->push_block(block).is_error())
+ return;
+
+ while (true) {
+ Media::AudioBlock converted;
+ if (input.converter->retrieve_block(converted).is_error() || converted.is_empty())
+ break;
+ auto offset = input.samples.size();
+ input.samples.resize(offset + converted.sample_count());
+ converted.copy_to_interleaved(input.samples.span().slice(offset));
+ }
+
+ auto maximum_samples = static_cast<size_t>(output_specification.sample_rate()) * output_specification.channel_count() * MAXIMUM_QUEUED_MILLISECONDS / 1000;
+ if (input.samples.size() > maximum_samples)
+ input.samples.remove(0, input.samples.size() - maximum_samples);
+}
+
+NonnullOwnPtr<MediaStreamPlayback> MediaStreamPlayback::create(NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
+{
+ return adopt_own(*new MediaStreamPlayback(move(audio_output_factory)));
+}
+
+MediaStreamPlayback::MediaStreamPlayback(NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
+ : m_mixer(adopt_ref(*new Mixer))
+ , m_audio_output_factory(move(audio_output_factory))
+{
+}
+
+MediaStreamPlayback::~MediaStreamPlayback()
+{
+ m_mixer->playing.store(false);
+ // This can run while the garbage collector is sweeping, when the tracks may already be gone, so the sinks
+ // are only switched off here. Callers stop playback properly through set_tracks({}) beforehand.
+ for (auto& subscription : m_subscriptions)
+ subscription.sink->deactivate();
+}
+
+void MediaStreamPlayback::set_tracks(ReadonlySpan<GC::Ref<MediaCapture::MediaStreamTrack>> tracks)
+{
+ for (size_t index = m_subscriptions.size(); index-- > 0;) {
+ auto track = m_subscriptions[index].track.ptr();
+ auto still_present = track && any_of(tracks, [&](auto const& candidate) { return candidate.ptr() == track.ptr(); });
+ if (!still_present)
+ remove_input(index);
+ }
+
+ for (auto const& track : tracks) {
+ if (!track->is_audio())
+ continue;
+ if (any_of(m_subscriptions, [&](auto const& subscription) { return subscription.track.ptr().ptr() == track.ptr(); }))
+ continue;
+
+ auto input = adopt_ref(*new TrackInput);
+ auto sink = adopt_ref(*new MediaCapture::AudioFrameSink);
+ sink->on_frames = [mixer = m_mixer, input](float const* samples, size_t frame_count, u8 channel_count, u32 sample_rate) {
+ receive_frames(*mixer, *input, samples, frame_count, channel_count, sample_rate);
+ };
+ {
+ MutexLocker locker(m_mixer->mutex);
+ m_mixer->inputs.append(input);
+ }
+ m_subscriptions.append({ track, sink, input });
+ track->add_audio_sink(sink);
+ }
+}
+
+void MediaStreamPlayback::remove_input(size_t index)
+{
+ auto subscription = m_subscriptions.take(index);
+ if (auto track = subscription.track.ptr())
+ track->remove_audio_sink(*subscription.sink);
+ else
+ subscription.sink->deactivate();
+
+ MutexLocker locker(m_mixer->mutex);
+ m_mixer->inputs.remove_first_matching([&](auto const& input) { return input.ptr() == subscription.input.ptr(); });
+}
+
+void MediaStreamPlayback::play()
+{
+ if (m_playing)
+ return;
+ m_playing = true;
+ m_playing_since = MonotonicTime::now();
+ m_mixer->playing.store(true);
+
+ if (m_output) {
+ (void)m_output->resume();
+ return;
+ }
+ if (m_creating_output)
+ return;
+ m_creating_output = true;
+
+ auto data_callback = [mixer = m_mixer](Span<float> buffer, MonotonicTime) -> ReadonlySpan<float> {
+ buffer.fill(0.0f);
+ MutexLocker mixer_locker(mixer->mutex);
+ for (auto& input : mixer->inputs) {
+ MutexLocker input_locker(input->mutex);
+ auto sample_count = min(input->samples.size(), buffer.size());
+ for (size_t index = 0; index < sample_count; ++index)
+ buffer[index] += input->samples[index];
+ input->samples.remove(0, sample_count);
+ }
+ // A short read is padded with silence, so the output keeps asking for more instead of treating the
+ // stream as finished.
+ return buffer;
+ };
+
+ auto promise = m_audio_output_factory->open_output(Audio::OutputState::Suspended, TARGET_LATENCY_MS, move(data_callback));
+ promise->when_resolved([weak_self = make_weak_ptr()](auto& stream) {
+ if (!weak_self)
+ return;
+ auto& self = *weak_self;
+ self.m_creating_output = false;
+ self.m_output = stream;
+ {
+ MutexLocker locker(self.m_mixer->mutex);
+ self.m_mixer->output_specification = stream->sample_specification();
+ }
+ (void)stream->set_volume(self.m_volume);
+ if (self.m_playing)
+ (void)stream->resume();
+ });
+ promise->when_rejected([weak_self = make_weak_ptr()](auto& error) {
+ dbgln("MediaStreamPlayback: Unable to open an audio output: {}", error);
+ if (weak_self)
+ weak_self->m_creating_output = false;
+ });
+}
+
+void MediaStreamPlayback::pause()
+{
+ if (!m_playing)
+ return;
+ m_playing = false;
+ if (m_playing_since.has_value())
+ m_time_played += MonotonicTime::now() - m_playing_since.release_value();
+ m_mixer->playing.store(false);
+
+ if (m_output)
+ (void)m_output->discard_buffer_and_suspend();
+
+ // A paused live stream skips what arrived in the meantime rather than resuming from where it stopped.
+ MutexLocker locker(m_mixer->mutex);
+ for (auto& input : m_mixer->inputs) {
+ MutexLocker input_locker(input->mutex);
+ input->samples.clear();
+ }
+}
+
+void MediaStreamPlayback::set_volume(double volume)
+{
+ m_volume = volume;
+ if (m_output)
+ (void)m_output->set_volume(volume);
+}
+
+double MediaStreamPlayback::current_time() const
+{
+ auto time = m_time_played;
+ if (m_playing_since.has_value())
+ time += MonotonicTime::now() - *m_playing_since;
+ return time.to_seconds_f64();
+}
+
+}
diff --git a/Libraries/LibWeb/HTML/MediaStreamPlayback.h b/Libraries/LibWeb/HTML/MediaStreamPlayback.h
new file mode 100644
index 00000000000..caf719f3c50
--- /dev/null
+++ b/Libraries/LibWeb/HTML/MediaStreamPlayback.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/NonnullOwnPtr.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/RefPtr.h>
+#include <AK/Time.h>
+#include <AK/Vector.h>
+#include <AK/WeakPtr.h>
+#include <AK/Weakable.h>
+#include <LibAudio/Forward.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/Weak.h>
+#include <LibMedia/Forward.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/MediaCapture/MediaStreamTrack.h>
+
+namespace Web::HTML {
+
+// Plays the audio tracks of a MediaStream assigned to a media element's srcObject, mixed into one output stream.
+// https://w3c.github.io/mediacapture-main/#mediastreams-in-media-elements
+class MediaStreamPlayback final : public Weakable<MediaStreamPlayback> {
+ AK_MAKE_NONCOPYABLE(MediaStreamPlayback);
+ AK_MAKE_NONMOVABLE(MediaStreamPlayback);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ static NonnullOwnPtr<MediaStreamPlayback> create(NonnullRefPtr<Media::AudioOutputFactory>);
+ ~MediaStreamPlayback();
+
+ void set_tracks(ReadonlySpan<GC::Ref<MediaCapture::MediaStreamTrack>>);
+
+ void play();
+ void pause();
+ void set_volume(double);
+
+ // A MediaStream has no timeline of its own, so the position is the time spent playing.
+ double current_time() const;
+
+ struct Mixer;
+ struct TrackInput;
+
+private:
+ explicit MediaStreamPlayback(NonnullRefPtr<Media::AudioOutputFactory>);
+
+ void remove_input(size_t index);
+
+ NonnullRefPtr<Mixer> m_mixer;
+ NonnullRefPtr<Media::AudioOutputFactory> m_audio_output_factory;
+
+ struct Subscription {
+ GC::Weak<MediaCapture::MediaStreamTrack> track;
+ NonnullRefPtr<MediaCapture::AudioFrameSink> sink;
+ NonnullRefPtr<TrackInput> input;
+ };
+ Vector<Subscription> m_subscriptions;
+
+ RefPtr<Audio::PlaybackStream> m_output;
+ bool m_creating_output { false };
+ bool m_playing { false };
+ double m_volume { 1.0 };
+
+ AK::Duration m_time_played;
+ Optional<MonotonicTime> m_playing_since;
+};
+
+}
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp b/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp
index c37e7413cfd..22454793a0e 100644
--- a/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp
@@ -7,7 +7,6 @@
#include <AK/Debug.h>
#include <AK/JsonArray.h>
#include <AK/JsonObject.h>
-#include <LibAudio/PlaybackStream.h>
#include <LibCore/EventLoop.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/Map.h>
@@ -225,11 +224,7 @@ void RTCPeerConnection::close_the_connection_algorithm(bool disappear)
m_pending_description_requests.clear();
m_pending_description_payloads.clear();
m_held_ice_events.clear();
- for (auto& [_, playback] : m_receiver_audio_playbacks) {
- if (playback->playback_stream)
- (void)playback->playback_stream->discard_buffer_and_suspend();
- }
- m_receiver_audio_playbacks.clear();
+ m_receiver_audio_decoders.clear();
agent.unregister_peer_connection(m_pc_id);
// 6. If connection.[[SctpTransport]] is not null...
if (m_sctp) {
@@ -1527,9 +1522,7 @@ void RTCPeerConnection::on_remote_track_ended(u64 receiver_id)
HTML::TemporaryExecutionContext context(relevant_realm());
if (auto receiver = m_remote_receivers_by_id.get(receiver_id); receiver.has_value())
(*receiver)->track()->end();
- auto playback = m_receiver_audio_playbacks.take(receiver_id);
- if (playback.has_value() && (*playback)->playback_stream)
- (void)(*playback)->playback_stream->discard_buffer_and_suspend();
+ m_receiver_audio_decoders.remove(receiver_id);
}
void RTCPeerConnection::on_encoded_audio_frame_received(u64 receiver_id, u32 ssrc, u32 rtp_timestamp, u16 sequence_number, u8 payload_type, ByteBuffer payload)
@@ -1557,114 +1550,41 @@ void RTCPeerConnection::on_encoded_audio_frame_received(u64 receiver_id, u32 ssr
script_transform.enqueue_encoded_audio_frame(move(payload), ssrc, payload_type, rtp_timestamp, sequence_number);
}
-// Decode one decrypted opus packet and push PCM into the receiver's playback stream.
-// FIXME: this is a shortcut around the spec — the right path is for MediaStreamTrack to
-// carry the audio data and HTMLMediaElement.srcObject playback to drain it.
+// Decode one decrypted Opus packet and deliver the PCM through the receiver's track.
void RTCPeerConnection::feed_decoded_audio(u64 receiver_id, ByteBuffer payload, u32 rtp_timestamp)
{
if (m_is_closed)
return;
- auto playback_iter = m_receiver_audio_playbacks.find(receiver_id);
- auto* playback = playback_iter == m_receiver_audio_playbacks.end() ? nullptr : playback_iter->value.ptr();
- if (!playback) {
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: setting up audio playback for receiver={}", receiver_id);
- // Opus is fundamentally 48 kHz; channel count comes out of the first decoded block.
- auto sample_spec = Audio::SampleSpecification(48000, Audio::ChannelMap::stereo());
- auto decoder_or_err = Media::FFmpeg::FFmpegAudioDecoder::try_create(Media::CodecID::Opus, sample_spec, {});
- if (decoder_or_err.is_error()) {
- dbgln("RTCPeerConnection: opus decoder init failed for receiver={}: {}", receiver_id, decoder_or_err.error().description());
+ auto receiver = m_remote_receivers_by_id.get(receiver_id);
+ if (!receiver.has_value())
+ return;
+
+ if (!m_receiver_audio_decoders.contains(receiver_id)) {
+ // Opus always runs at 48 kHz; the channel count comes from the stream.
+ auto sample_specification = Audio::SampleSpecification(48000, Audio::ChannelMap::stereo());
+ auto decoder_or_error = Media::FFmpeg::FFmpegAudioDecoder::try_create(Media::CodecID::Opus, sample_specification, {});
+ if (decoder_or_error.is_error()) {
+ dbgln("RTCPeerConnection: Opus decoder init failed for receiver={}: {}", receiver_id, decoder_or_error.error().description());
return;
}
- auto fresh = make<ReceiverAudioPlayback>();
- fresh->decoder = decoder_or_err.release_value();
- auto* fresh_ptr = fresh.ptr();
- m_receiver_audio_playbacks.set(receiver_id, move(fresh));
- playback = fresh_ptr;
-
- auto data_callback = [buffer_state = playback->buffer](Span<float> buffer, MonotonicTime) -> ReadonlySpan<float> {
- MutexLocker locker(buffer_state->mutex);
- auto available = buffer_state->samples.size();
- auto take = AK::min(available, buffer.size());
- memcpy(buffer.data(), buffer_state->samples.data(), take * sizeof(float));
- buffer_state->samples.remove(0, take);
- // Pad the rest of the buffer with silence so the output keeps requesting
- // data instead of treating a short span as the end of the stream.
- if (take < buffer.size())
- memset(buffer.data() + take, 0, (buffer.size() - take) * sizeof(float));
- return buffer;
- };
- constexpr u32 target_latency_ms = 100;
- auto promise = Audio::PlaybackStream::create(Audio::OutputState::Suspended, target_latency_ms, move(data_callback));
- promise->when_resolved([self = GC::Weak { *this }, receiver_id](auto& stream) {
- if (!self || self->m_is_closed)
- return;
- auto entry = self->m_receiver_audio_playbacks.find(receiver_id);
- if (entry == self->m_receiver_audio_playbacks.end())
- return;
- auto* playback = entry->value.ptr();
- playback->playback_stream = stream;
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: playback stream resolved receiver={} spec={}", receiver_id, stream->sample_specification());
- auto converter_or_err = Media::FFmpeg::FFmpegAudioConverter::try_create();
- if (converter_or_err.is_error()) {
- dbgln("RTCPeerConnection: audio converter init failed for receiver={}: {}", receiver_id, converter_or_err.error());
- } else {
- auto converter = converter_or_err.release_value();
- if (auto rc = converter->set_output_sample_specification(stream->sample_specification()); rc.is_error())
- dbgln("RTCPeerConnection: converter set_output failed for receiver={}: {}", receiver_id, rc.error());
- else
- playback->converter = move(converter);
- }
- (void)stream->resume();
- });
- promise->when_rejected([receiver_id](auto& error) {
- dbgln("RTCPeerConnection: playback stream init failed for receiver={}: {}", receiver_id, error);
- });
+ m_receiver_audio_decoders.set(receiver_id, decoder_or_error.release_value());
}
-
- if (!playback->decoder)
- return;
+ auto& decoder = **m_receiver_audio_decoders.get(receiver_id);
auto timestamp = AK::Duration::from_milliseconds(static_cast<i64>(rtp_timestamp / 48));
Media::CodedFrame coded_frame { Media::CodecID::Opus, timestamp, timestamp, {}, Media::FrameFlags::Keyframe, MUST(FixedArray<u8>::create(payload.bytes())) };
- if (auto result = playback->decoder->receive_coded_data(coded_frame); result.is_error()) {
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: opus receive_coded_data failed: {}", result.error().description());
+ if (auto result = decoder.receive_coded_data(coded_frame); result.is_error()) {
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: Opus receive_coded_data failed: {}", result.error().description());
return;
}
Media::AudioBlock block;
- if (auto result = playback->decoder->write_next_block(block); result.is_error()) {
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: write_next_block failed: {}", result.error().description());
- return;
- }
- if (block.is_empty()) {
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: write_next_block produced empty block");
+ if (auto result = decoder.write_next_block(block); result.is_error() || block.is_empty())
return;
- }
- // Drop frames until the playback stream is up — we need its sample-spec to set up the
- // resampler, and feeding mismatched-rate samples in the meantime would just stretch.
- if (!playback->converter)
- return;
- if (auto rc = playback->converter->push_block(block); rc.is_error()) {
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: audio convert failed: {}", rc.error());
- return;
- }
- while (true) {
- Media::AudioBlock converted;
- if (auto rc = playback->converter->retrieve_block(converted); rc.is_error()) {
- break;
- }
- if (converted.is_empty())
- continue;
- MutexLocker locker(playback->buffer->mutex);
- playback->channel_count = converted.channel_count();
- auto max_samples = static_cast<size_t>(converted.sample_specification().sample_rate()) * converted.channel_count() / 5;
- if (playback->buffer->samples.size() > max_samples)
- playback->buffer->samples.remove(0, playback->buffer->samples.size() - max_samples);
- auto base = playback->buffer->samples.size();
- playback->buffer->samples.resize(base + converted.sample_count());
- converted.copy_to_interleaved(playback->buffer->samples.span().slice(base));
- dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: feed_decoded_audio receiver={} samples={} channels={} spec={} buffer_total={}",
- receiver_id, converted.sample_count(), converted.channel_count(), converted.sample_specification(), playback->buffer->samples.size());
- }
+
+ m_decoded_audio_scratch.resize(block.sample_count());
+ block.copy_to_interleaved(m_decoded_audio_scratch.span());
+ dbgln_if(WEBRTC_DEBUG, "RTCPeerConnection: decoded audio receiver={} frames={} spec={}", receiver_id, block.frame_count(), block.sample_specification());
+ (*receiver)->track()->deliver_audio_frames(m_decoded_audio_scratch.data(), block.frame_count(), block.channel_count(), block.sample_specification().sample_rate());
}
static Bindings::RTCSdpType parse_sdp_type(StringView s)
diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnection.h b/Libraries/LibWeb/WebRTC/RTCPeerConnection.h
index a60f4a199c5..3e1a475a71c 100644
--- a/Libraries/LibWeb/WebRTC/RTCPeerConnection.h
+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnection.h
@@ -217,24 +217,10 @@ private:
// [[PendingRemoteDescription]]
GC::Ptr<RTCSessionDescription> m_pending_remote_description;
- // Per-remote-receiver playback stack. We bypass the spec's MediaStream → audio-element
- // path entirely and just opus-decode + push PCM straight to libmedia's audio output.
- // Once we wire MediaStreamTrack as a real audio source, this should go away.
- struct PlaybackBuffer : public AtomicRefCounted<PlaybackBuffer> {
- Mutex mutex;
- Vector<float> samples;
- };
- struct ReceiverAudioPlayback {
- AK_ALLOC_WITH_KMALLOC;
-
- OwnPtr<Media::AudioDecoder> decoder;
- OwnPtr<Media::FFmpeg::FFmpegAudioConverter> converter;
- RefPtr<Audio::PlaybackStream> playback_stream;
- NonnullRefPtr<PlaybackBuffer> buffer = adopt_ref(*new PlaybackBuffer);
- u8 channel_count { 0 };
- bool started { false };
- };
- HashMap<u64, NonnullOwnPtr<ReceiverAudioPlayback>> m_receiver_audio_playbacks;
+ // Decoded audio goes to the receiver's track, and from there to whatever consumes it: media elements,
+ // WebAudio, or another peer connection.
+ HashMap<u64, NonnullOwnPtr<Media::AudioDecoder>> m_receiver_audio_decoders;
+ Vector<float> m_decoded_audio_scratch;
void feed_decoded_audio(u64 receiver_id, ByteBuffer payload, u32 rtp_timestamp);
// The track may outlive this connection, so its producer callback owns this state independently.
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 33fd332f59d..79e2bb69c3f 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -10,6 +10,7 @@ Text/input/wpt-import/html/rendering/replaced-elements/attributes-for-embedded-c
Text/input/PermissionsAPI/
Text/input/WebRTC/audio-loopback.html
Text/input/WebRTC/data-channel-loopback.html
+Text/input/WebRTC/media-element-playback.html
Text/input/WebRTC/script-transform-roundtrip.html
Text/input/WebRTC/track-event-transceiver.html
Text/input/wpt-import/geolocation/
diff --git a/Tests/LibWeb/Text/expected/WebRTC/media-element-gc.txt b/Tests/LibWeb/Text/expected/WebRTC/media-element-gc.txt
new file mode 100644
index 00000000000..469ca10828b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/media-element-gc.txt
@@ -0,0 +1,3 @@
+network idle: true
+paused: true
+audio collected: true
diff --git a/Tests/LibWeb/Text/expected/WebRTC/media-element-playback.txt b/Tests/LibWeb/Text/expected/WebRTC/media-element-playback.txt
new file mode 100644
index 00000000000..4bf363044d3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebRTC/media-element-playback.txt
@@ -0,0 +1,7 @@
+readyState: 4
+duration: Infinity
+paused after play(): false
+remote track carries audio: true
+currentTime advanced: true
+paused after pause(): true
+paused after playing again: false
diff --git a/Tests/LibWeb/Text/input/WebRTC/media-element-gc.html b/Tests/LibWeb/Text/input/WebRTC/media-element-gc.html
new file mode 100644
index 00000000000..144a7f42198
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/media-element-gc.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+function attachStream(stream, onLoaded) {
+ const audio = new Audio();
+ audio.srcObject = stream;
+ audio.addEventListener("loadeddata", () => {
+ println(`network idle: ${audio.networkState === HTMLMediaElement.NETWORK_IDLE}`);
+ println(`paused: ${audio.paused}`);
+ onLoaded();
+ }, { once: true });
+ audio.gcSentinel = true;
+ return new WeakRef(audio);
+}
+
+asyncTest(async done => {
+ const context = new AudioContext();
+ const destination = context.createMediaStreamDestination();
+ let weakAudio;
+ await new Promise(resolve => weakAudio = attachStream(destination.stream, resolve));
+ await collectGarbageUntilCleared([weakAudio]);
+ println(`audio collected: ${weakAudio.deref() === undefined}`);
+ await context.close();
+ done();
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/WebRTC/media-element-playback.html b/Tests/LibWeb/Text/input/WebRTC/media-element-playback.html
new file mode 100644
index 00000000000..7d97c4020ac
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebRTC/media-element-playback.html
@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<script>internals.setAutoplayPolicy("allow-audio-and-video");</script>
+<script src="../include.js"></script>
+<script>
+asyncTest(async done => {
+ // Use numeric host candidates so this loopback test does not depend on mDNS multicast.
+ await internals.setPermission("microphone", "granted");
+ const a = new RTCPeerConnection();
+ const b = new RTCPeerConnection();
+ a.onicecandidate = event => event.candidate && b.addIceCandidate(event.candidate).catch(() => {});
+ b.onicecandidate = event => event.candidate && a.addIceCandidate(event.candidate).catch(() => {});
+ const context = new AudioContext();
+ const oscillator = context.createOscillator();
+ const destination = context.createMediaStreamDestination();
+ oscillator.connect(destination);
+ oscillator.start();
+ const remote = new Promise(resolve => b.ontrack = event => resolve(event));
+ try {
+ a.addTrack(destination.stream.getAudioTracks()[0], destination.stream);
+ await a.setLocalDescription(await a.createOffer());
+ await b.setRemoteDescription(a.localDescription);
+ await b.setLocalDescription(await b.createAnswer());
+ await a.setRemoteDescription(b.localDescription);
+ const { track, streams } = await remote;
+
+ const audio = new Audio();
+ const loadedMetadata = new Promise(resolve => audio.onloadedmetadata = resolve);
+ audio.srcObject = streams[0];
+ await audio.play();
+ await loadedMetadata;
+ println(`readyState: ${audio.readyState}`);
+ println(`duration: ${audio.duration}`);
+ println(`paused after play(): ${audio.paused}`);
+
+ // The decoded audio reaches the remote track itself, so WebAudio can listen to it too.
+ const analyser = context.createAnalyser();
+ context.createMediaStreamSource(new MediaStream([track])).connect(analyser);
+ const samples = new Float32Array(analyser.fftSize);
+ let peak = 0;
+ for (let attempt = 0; attempt < 100 && peak < 0.1; ++attempt) {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ analyser.getFloatTimeDomainData(samples);
+ peak = samples.reduce((max, sample) => Math.max(max, Math.abs(sample)), 0);
+ }
+ println(`remote track carries audio: ${peak >= 0.1}`);
+ println(`currentTime advanced: ${audio.currentTime > 0}`);
+
+ audio.volume = 0.5;
+ audio.muted = true;
+ audio.pause();
+ println(`paused after pause(): ${audio.paused}`);
+ await audio.play();
+ println(`paused after playing again: ${audio.paused}`);
+ } catch (error) {
+ println(`FAIL: ${error.name}: ${error.message}`);
+ } finally {
+ oscillator.stop();
+ a.close(); b.close(); context.close(); done();
+ }
+});
+</script>