Skip to content

Truly independent web browser

LibMedia: Propagate the Blocked status through the pipeline

Zaggy102422b615ab83be
diff --git a/Documentation/MediaPipelineDesign.md b/Documentation/MediaPipelineDesign.md
index ce6722b0489..e62e78ba629 100644
--- a/Documentation/MediaPipelineDesign.md
+++ b/Documentation/MediaPipelineDesign.md
@@ -34,9 +34,10 @@ being forced to accept data it may have no room for.
`PipelineStatus` is the shared status language between nodes:
-- `Pending`: Data is not available yet, but may become available later.
+- `Pending`: Data is not available yet, but will become available without any new input.
- `HaveData`: A peek exposes data.
-- `Blocked`: Data is not available yet, i.e. we have run out of buffered data from over the network.
+- `Blocked`: Data will remain unavailable until new input arrives.
+ `Blocked` holds nothing that could become output without that input.
- `Suspended`: The upstream node has released its decoding resources and will not produce data until
it receives a seek.
- `EndOfStream`: We have reached the end of the input data.
@@ -51,12 +52,16 @@ that normally polls for upstream input seeing these should sleep until its wake
"waiting" statuses for helper APIs, because no more data is required to decide the seek has
completed.
+A node that combines inputs reports `Blocked` when any input it requires is `Blocked`, since its
+output cannot progress until that input does. A processor reports `Blocked` only when its input is
+`Blocked` and none of the data it holds can be output.
+
## Wake Handlers
Wake handlers do not carry state. A wake means the downstream node should `peek()` again.
-Nodes should dispatch a wake when the downstream node may be waiting, and the status has changed to
-one that resolves a seek: `HaveData`, `EndOfStream`, or `Error`.
+Nodes should dispatch a wake when the downstream node may be waiting, and the status has changed.
+This includes changes between `Pending` and `Blocked`, so that sinks can report both.
Some nodes (i.e. AudioMixer) may also wake when moving away from a previously dispatched
`EndOfStream`, so stale EOS state can be recovered after a seek or after new input becomes
@@ -88,6 +93,10 @@ so it can refill the queue. When the queue is full and no downstream activity oc
timeout, the producer auto-suspends: it drops its decoder, its queue, and any frame pool buffers it
can free, then wakes the consumer with a `Suspended` status.
+A producer reports `Blocked` while its queue is empty, its demuxer read is blocked, and its decoder
+has no decode in progress that could produce output. When the coded data that a blocked read needs
+becomes available, the producer stops reporting `Blocked` immediately.
+
`peek()` and `consume()` defer the idle timeout, but they never resume a suspended producer. When a
downstream node needs new data, it must explicitly `seek()` the suspended node to resume it, so that
the pipeline may insert pre-roll data at any stage where it is needed (i.e. for audio stretching).
diff --git a/Libraries/LibMedia/PlaybackManager.cpp b/Libraries/LibMedia/PlaybackManager.cpp
index b1442f788cd..0cc2c89e56d 100644
--- a/Libraries/LibMedia/PlaybackManager.cpp
+++ b/Libraries/LibMedia/PlaybackManager.cpp
@@ -259,12 +259,6 @@ void PlaybackManager::set_up_producers()
return;
self->dispatch_error(move(error));
});
- video_track_data.producer->set_read_blocked_change_handler([self = weak(), track = video_track_data.track](ReadBlocked read_blocked) {
- if (!self)
- return;
- self->get_video_data_for_track(track).read_blocked = read_blocked == ReadBlocked::Yes;
- self->update_pipeline_state();
- });
}
for (auto const& audio_track_data : m_audio_track_datas) {
@@ -273,12 +267,6 @@ void PlaybackManager::set_up_producers()
return;
self->dispatch_error(move(error));
});
- audio_track_data.producer->set_read_blocked_change_handler([self = weak(), track = audio_track_data.track](ReadBlocked read_blocked) {
- if (!self)
- return;
- self->get_audio_data_for_track(track).read_blocked = read_blocked == ReadBlocked::Yes;
- self->update_pipeline_state();
- });
}
}
@@ -319,18 +307,7 @@ PipelineStatus PlaybackManager::combined_pipeline_status() const
auto status = PipelineStatus::EndOfStream;
if (m_audio_sink != nullptr) {
- auto audio_status = m_audio_sink_status;
- if (audio_status == PipelineStatus::Pending) {
- for (auto const& track_data : m_audio_track_datas) {
- if (!track_data.enabled)
- continue;
- if (!track_data.read_blocked)
- continue;
- audio_status = PipelineStatus::Blocked;
- break;
- }
- }
- status = select_combined_pipeline_status(status, audio_status);
+ status = select_combined_pipeline_status(status, m_audio_sink_status);
} else {
for (auto const& track_data : m_audio_track_datas) {
if (!track_data.enabled)
@@ -352,8 +329,6 @@ PipelineStatus PlaybackManager::combined_pipeline_status() const
if (verified_end_time.has_value() && current_time() >= *verified_end_time)
track_status = PipelineStatus::EndOfStream;
}
- if (track_status == PipelineStatus::Pending && track_data.read_blocked)
- track_status = PipelineStatus::Blocked;
status = select_combined_pipeline_status(status, track_status);
}
@@ -369,9 +344,9 @@ void PlaybackManager::update_pipeline_state()
StringBuilder breakdown;
breakdown.appendff("audio sink {}{}", m_audio_sink_status, m_audio_sink ? "" : " (none)");
for (auto const& track_data : m_audio_track_datas)
- breakdown.appendff(", audio track {} {}{}", track_data.track.identifier(), track_data.enabled ? "enabled" : "disabled", track_data.read_blocked ? " read blocked" : "");
+ breakdown.appendff(", audio track {} {}", track_data.track.identifier(), track_data.enabled ? "enabled" : "disabled");
for (auto const& track_data : m_video_track_datas)
- breakdown.appendff(", video track {} sink {}{}{}", track_data.track.identifier(), track_data.sink_status, track_data.ticking ? "" : " unticked", track_data.read_blocked ? " read blocked" : "");
+ breakdown.appendff(", video track {} sink {}{}", track_data.track.identifier(), track_data.sink_status, track_data.ticking ? "" : " unticked");
dbgln("PlaybackManager({:p}): Combined status {} in {} ({})", this, status, m_handler->state(), breakdown.string_view());
}
}
diff --git a/Libraries/LibMedia/PlaybackManager.h b/Libraries/LibMedia/PlaybackManager.h
index 57c34027ac6..069f578770f 100644
--- a/Libraries/LibMedia/PlaybackManager.h
+++ b/Libraries/LibMedia/PlaybackManager.h
@@ -150,7 +150,6 @@ private:
// While ticking, the sink's dispatched status is live and remains the sole ending
// authority; while unticked, it is stale and the track ends at its verified end time.
bool ticking { true };
- bool read_blocked { false };
Function<void(Gfx::Size<u32>)> on_resize { nullptr };
};
using VideoTrackDatas = Vector<VideoTrackData, EXPECTED_VIDEO_TRACK_COUNT>;
@@ -160,7 +159,6 @@ private:
NonnullRefPtr<Demuxer> demuxer;
NonnullRefPtr<DecodedAudioProducer> producer;
bool enabled { false };
- bool read_blocked { false };
};
using AudioTrackDatas = Vector<AudioTrackData, EXPECTED_AUDIO_TRACK_COUNT>;
diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp b/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp
index 51683219b7b..d587e1ea386 100644
--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp
+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.cpp
@@ -59,11 +59,6 @@ void DecodedAudioProducer::set_error_handler(ErrorHandler&& handler)
m_thread_data->set_error_handler(move(handler));
}
-void DecodedAudioProducer::set_read_blocked_change_handler(ReadBlockedChangeHandler handler)
-{
- m_thread_data->set_read_blocked_change_handler(move(handler));
-}
-
ErrorOr<void> DecodedAudioProducer::set_output_sample_specification(Audio::SampleSpecification sample_specification)
{
return m_thread_data->set_output_sample_specification(sample_specification);
@@ -102,7 +97,11 @@ DecodedAudioProducer::ThreadData::ThreadData(Core::EventLoop& main_thread_event_
, m_auto_suspend_idle_timeout(auto_suspend_idle_timeout)
{
m_demuxer->set_read_blocked_change_handler_for_track(m_track, [this](ReadBlocked blocked) {
- dispatch_read_blocked_change(blocked);
+ m_demuxer_read_is_blocked.store(blocked == ReadBlocked::Yes);
+ m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this)] {
+ auto locker = self->take_lock();
+ self->dispatch_wake_if_needed_while_locked();
+ });
});
}
@@ -116,19 +115,6 @@ void DecodedAudioProducer::ThreadData::set_error_handler(ErrorHandler&& handler)
m_error_handler = move(handler);
}
-void DecodedAudioProducer::ThreadData::set_read_blocked_change_handler(ReadBlockedChangeHandler handler)
-{
- m_read_blocked_change_handler = move(handler);
-}
-
-void DecodedAudioProducer::ThreadData::dispatch_read_blocked_change(ReadBlocked blocked)
-{
- m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this), blocked] {
- if (self->m_read_blocked_change_handler)
- self->m_read_blocked_change_handler(blocked);
- });
-}
-
ErrorOr<void> DecodedAudioProducer::ThreadData::set_output_sample_specification(Audio::SampleSpecification sample_specification)
{
TRY(m_converter->set_output_sample_specification(sample_specification));
@@ -313,10 +299,13 @@ AudioProducerOutput DecodedAudioProducer::ThreadData::peek()
AudioProducerOutput DecodedAudioProducer::ThreadData::peek_while_locked()
{
+ auto read_is_blocked = m_demuxer_read_is_blocked.load();
if (m_last_processed_seek_id != m_seek_id)
- return { nullptr, PipelineStatus::Pending };
+ return { nullptr, read_is_blocked ? PipelineStatus::Blocked : PipelineStatus::Pending };
if (!m_queue.is_empty())
return { &m_queue.head().block, PipelineStatus::HaveData };
+ if (m_current_halting_status == PipelineStatus::Pending && read_is_blocked)
+ return { nullptr, PipelineStatus::Blocked };
return { nullptr, m_current_halting_status };
}
@@ -355,6 +344,8 @@ void DecodedAudioProducer::ThreadData::seek(AK::Duration timestamp)
m_seek_timestamp = timestamp;
m_downstream_needs_wake = true;
m_demuxer->set_blocking_reads_aborted_for_track(m_track);
+ // The aborted read reports that it stopped blocking only once the decode thread wakes.
+ m_demuxer_read_is_blocked.store(false);
wake();
}
diff --git a/Libraries/LibMedia/Producers/DecodedAudioProducer.h b/Libraries/LibMedia/Producers/DecodedAudioProducer.h
index 395609c54d6..b31347be0ca 100644
--- a/Libraries/LibMedia/Producers/DecodedAudioProducer.h
+++ b/Libraries/LibMedia/Producers/DecodedAudioProducer.h
@@ -52,7 +52,6 @@ public:
~DecodedAudioProducer();
void set_error_handler(ErrorHandler&&);
- void set_read_blocked_change_handler(ReadBlockedChangeHandler);
virtual ErrorOr<void> set_output_sample_specification(Audio::SampleSpecification) override;
virtual void start() override;
@@ -70,7 +69,6 @@ private:
~ThreadData();
void set_error_handler(ErrorHandler&&);
- void set_read_blocked_change_handler(ReadBlockedChangeHandler);
ErrorOr<void> set_output_sample_specification(Audio::SampleSpecification);
void set_wake_handler(PipelineWakeHandler);
@@ -132,7 +130,6 @@ private:
ExitDecodeLoop,
};
WaitResult wait_for_queue_space_while_locked();
- void dispatch_read_blocked_change(ReadBlocked blocked);
Core::EventLoop& m_main_thread_event_loop;
@@ -156,8 +153,9 @@ private:
AudioQueue m_queue;
AK::Duration m_consumed_media_time_end;
ErrorHandler m_error_handler;
- ReadBlockedChangeHandler m_read_blocked_change_handler;
PipelineStatus m_current_halting_status { PipelineStatus::Pending };
+ // Set by the demuxer under its own lock, which may be taken while ours is held.
+ Atomic<bool> m_demuxer_read_is_blocked { false };
enum class SeekReason : u8 {
Normal,
diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp
index 8b928830571..0d22620208b 100644
--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp
+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.cpp
@@ -56,11 +56,6 @@ void DecodedVideoProducer::set_error_handler(ErrorHandler&& handler)
m_thread_data->set_error_handler(move(handler));
}
-void DecodedVideoProducer::set_read_blocked_change_handler(ReadBlockedChangeHandler handler)
-{
- m_thread_data->set_read_blocked_change_handler(move(handler));
-}
-
void DecodedVideoProducer::start()
{
m_thread_data->start();
@@ -91,12 +86,19 @@ VideoProducerOutput DecodedVideoProducer::ThreadData::peek()
return output;
}
+bool DecodedVideoProducer::ThreadData::read_is_blocked_while_locked() const
+{
+ return m_demuxer_read_is_blocked.load() && !m_decoder_has_decode_in_progress;
+}
+
VideoProducerOutput DecodedVideoProducer::ThreadData::peek_while_locked()
{
if (m_last_processed_seek_id != m_seek_id)
- return { nullptr, PipelineStatus::Pending };
+ return { nullptr, read_is_blocked_while_locked() ? PipelineStatus::Blocked : PipelineStatus::Pending };
if (!m_queue.is_empty())
return { m_queue.head().frame, PipelineStatus::HaveData };
+ if (m_current_halting_status == PipelineStatus::Pending && read_is_blocked_while_locked())
+ return { nullptr, PipelineStatus::Blocked };
return { nullptr, m_current_halting_status };
}
@@ -163,7 +165,11 @@ DecodedVideoProducer::ThreadData::ThreadData(Core::EventLoop& main_thread_event_
, m_auto_suspend_idle_timeout(auto_suspend_idle_timeout)
{
m_demuxer->set_read_blocked_change_handler_for_track(m_track, [this](ReadBlocked blocked) {
- dispatch_read_blocked_change(blocked);
+ m_demuxer_read_is_blocked.store(blocked == ReadBlocked::Yes);
+ m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this)] {
+ auto locker = self->take_lock();
+ self->dispatch_wake_if_needed_while_locked();
+ });
});
}
@@ -222,10 +228,9 @@ DecoderErrorOr<void> DecodedVideoProducer::ThreadData::create_decoder_for_frame(
wait_state->frame_storage_was_freed = true;
wait_state->condition.broadcast();
});
- // Output that arrives while the decode thread reads coded data is taken as soon as the read returns.
- m_decoder->set_decode_completed_callback([wait_state = m_wait_state, demuxer = m_demuxer, track = m_track](DecodeCompletion completion) {
- if (completion != DecodeCompletion::ProducedOutput)
- return;
+ // A decode that finishes while the decode thread reads coded data is handled as soon as the read returns, either
+ // to take its output or to report that the read has become blocked when output runs out.
+ m_decoder->set_decode_completed_callback([wait_state = m_wait_state, demuxer = m_demuxer, track = m_track](DecodeCompletion) {
if (wait_state->output_should_interrupt_demuxer_reads.load(MemoryOrder::memory_order_relaxed))
demuxer->set_blocking_reads_aborted_for_track(track);
});
@@ -250,6 +255,13 @@ bool DecodedVideoProducer::ThreadData::check_if_seek_is_needed_or_allow_demuxer_
return false;
}
+void DecodedVideoProducer::ThreadData::note_whether_decoder_has_decode_in_progress()
+{
+ VERIFY(m_decode_thread_id.is_current_thread());
+ auto locker = take_lock();
+ m_decoder_has_decode_in_progress = m_decoder != nullptr && m_decoder->has_any_decode_in_progress();
+}
+
DecoderErrorOr<void> DecodedVideoProducer::ThreadData::receive_coded_frame(CodedFrame const& frame, DecodeIntent intent)
{
VERIFY(!m_frame_awaiting_decoder_replacement.has_value());
@@ -301,19 +313,6 @@ void DecodedVideoProducer::ThreadData::set_error_handler(ErrorHandler&& handler)
m_error_handler = move(handler);
}
-void DecodedVideoProducer::ThreadData::set_read_blocked_change_handler(ReadBlockedChangeHandler handler)
-{
- m_read_blocked_change_handler = move(handler);
-}
-
-void DecodedVideoProducer::ThreadData::dispatch_read_blocked_change(ReadBlocked blocked)
-{
- m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this), blocked] {
- if (self->m_read_blocked_change_handler)
- self->m_read_blocked_change_handler(blocked);
- });
-}
-
void DecodedVideoProducer::ThreadData::start()
{
auto locker = take_lock();
@@ -388,6 +387,8 @@ void DecodedVideoProducer::ThreadData::seek(AK::Duration timestamp, InvalidateHe
m_seek_id++;
m_seek_timestamp = timestamp;
m_demuxer->set_blocking_reads_aborted_for_track(m_track);
+ // The aborted read reports that it stopped blocking only once the decode thread wakes.
+ m_demuxer_read_is_blocked.store(false);
wake();
}
@@ -583,6 +584,8 @@ void DecodedVideoProducer::ThreadData::handle_seek()
return;
m_demuxer->reset_blocking_reads_aborted_for_track(m_track);
m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);
+ // Whatever the decoder is still decoding precedes the seek, so it doesn't keep the seek from blocking.
+ m_decoder_has_decode_in_progress = false;
if (seek_reason == SeekReason::Normal) {
if (is_within_available_range_while_locked(timestamp)) {
@@ -749,6 +752,7 @@ void DecodedVideoProducer::ThreadData::handle_seek()
if (new_seek_id != seek_id)
break;
+ note_whether_decoder_has_decode_in_progress();
auto coded_frame_result = m_demuxer->get_next_sample_for_track(m_track);
m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);
if (coded_frame_result.is_error()) {
@@ -894,6 +898,7 @@ void DecodedVideoProducer::ThreadData::push_data_and_decode_some_frames()
if (seek_is_pending())
return;
+ note_whether_decoder_has_decode_in_progress();
auto sample_result = m_demuxer->get_next_sample_for_track(m_track);
m_wait_state->output_should_interrupt_demuxer_reads.store(false, MemoryOrder::memory_order_relaxed);
if (sample_result.is_error()) {
diff --git a/Libraries/LibMedia/Producers/DecodedVideoProducer.h b/Libraries/LibMedia/Producers/DecodedVideoProducer.h
index 6c752ee586e..a9648c04079 100644
--- a/Libraries/LibMedia/Producers/DecodedVideoProducer.h
+++ b/Libraries/LibMedia/Producers/DecodedVideoProducer.h
@@ -53,7 +53,6 @@ public:
~DecodedVideoProducer();
void set_error_handler(ErrorHandler&&);
- void set_read_blocked_change_handler(ReadBlockedChangeHandler);
virtual void start() override;
@@ -71,7 +70,6 @@ private:
~ThreadData();
void set_error_handler(ErrorHandler&&);
- void set_read_blocked_change_handler(ReadBlockedChangeHandler);
void set_wake_handler(PipelineWakeHandler);
void start();
@@ -82,6 +80,7 @@ private:
DecoderErrorOr<void> receive_coded_frame(CodedFrame const&, DecodeIntent);
DecoderErrorOr<bool> replace_drained_decoder();
bool check_if_seek_is_needed_or_allow_demuxer_reads(u32 seek_id);
+ void note_whether_decoder_has_decode_in_progress();
void wait_for_another_seek_or_exit(u32 seek_id);
void release_decoder();
void exit();
@@ -135,7 +134,7 @@ private:
ExitDecodeLoop,
};
WaitResult wait_for_frame_storage_while_locked();
- void dispatch_read_blocked_change(ReadBlocked blocked);
+ bool read_is_blocked_while_locked() const;
Core::EventLoop& m_main_thread_event_loop;
@@ -172,8 +171,10 @@ private:
FrameQueue m_queue;
RefPtr<VideoFrame> m_last_queued_frame;
ErrorHandler m_error_handler;
- ReadBlockedChangeHandler m_read_blocked_change_handler;
PipelineStatus m_current_halting_status { PipelineStatus::Pending };
+ // Set by the demuxer under its own lock, which may be taken while ours is held.
+ Atomic<bool> m_demuxer_read_is_blocked { false };
+ bool m_decoder_has_decode_in_progress { false };
enum class SeekReason : u8 {
Normal,
diff --git a/Libraries/LibMedia/Sinks/AudioPlaybackSink.cpp b/Libraries/LibMedia/Sinks/AudioPlaybackSink.cpp
index 54b79b24300..27f60a60370 100644
--- a/Libraries/LibMedia/Sinks/AudioPlaybackSink.cpp
+++ b/Libraries/LibMedia/Sinks/AudioPlaybackSink.cpp
@@ -45,6 +45,7 @@ public:
ReadonlySpan<float> move_output_to_playback_stream_buffer(Span<float>, MonotonicTime buffer_starts_playing_at);
i64 hold_clock_at_played_frame_while_locked(MediaTimeReader const&);
void dispatch_state_if_changed(PipelineStatus, u32 seek_id);
+ void report_input_status_while_locked(PipelineStatus, u32 seek_id);
void handle_input_suspension_while_locked(u32 seek_id);
void request_resume_from_suspension_while_locked();
void request_played_out_check_if_needed_while_locked();
@@ -120,9 +121,16 @@ ErrorOr<NonnullRefPtr<AudioPlaybackSink>> AudioPlaybackSink::try_create(Pipeline
if (output_thread_data->m_seek_id == seek_id_at_probe) {
if (status == PipelineStatus::Suspended) {
output_thread_data->handle_input_suspension_while_locked(seek_id_at_probe);
- } else if (audio_processor_will_enqueue(status)) {
- output_thread_data->m_last_pull_status = status;
- output_thread_data->m_waiting_for_upstream_data = false;
+ } else {
+ if (audio_processor_will_enqueue(status)) {
+ output_thread_data->m_last_pull_status = status;
+ output_thread_data->m_waiting_for_upstream_data = false;
+ }
+ // Nothing is pulled while the playback rate is zero, so the status is reported here.
+ if (output_thread_data->m_playback_rate == 0.0f && seek_id_at_probe != 0) {
+ output_thread_data->m_last_pull_status = status;
+ output_thread_data->report_input_status_while_locked(status, seek_id_at_probe);
+ }
}
}
}
@@ -158,10 +166,6 @@ ErrorOr<NonnullRefPtr<AudioPlaybackSink>> AudioPlaybackSink::try_create(Pipeline
continue;
}
if (output_thread_data->m_playback_rate == 0.0f) {
- // Buffered input still resolves readiness and seeks while output is stopped. A page may
- // wait for canplay before changing its playback rate from zero.
- if (auto status = output_thread_data->m_last_pull_status; status_change_should_wake(output_thread_data->m_last_dispatched_status, status))
- output_thread_data->dispatch_state_if_changed(status, output_thread_data->m_seek_id);
output_thread_data->m_output_condition.wait();
continue;
}
@@ -236,17 +240,7 @@ ErrorOr<NonnullRefPtr<AudioPlaybackSink>> AudioPlaybackSink::try_create(Pipeline
if (audio_processor_will_enqueue(status))
output_thread_data->m_waiting_for_upstream_data = false;
- if (is_waiting_for_data(status)) {
- // The output may run dry due to the input running slightly behind our playback rate, so we
- // need to start the timer here as well to ensure that it triggers even if the PlaybackStream
- // goes idle due to underrun.
- output_thread_data->request_played_out_check_if_needed_while_locked();
- continue;
- }
- if (!status_change_should_wake(output_thread_data->m_last_dispatched_status, status))
- continue;
-
- output_thread_data->dispatch_state_if_changed(status, seek_id_at_pull);
+ output_thread_data->report_input_status_while_locked(status, seek_id_at_pull);
}
}
@@ -491,6 +485,19 @@ void AudioPlaybackSink::OutputThreadData::request_played_out_check_if_needed_whi
});
}
+void AudioPlaybackSink::OutputThreadData::report_input_status_while_locked(PipelineStatus status, u32 seek_id)
+{
+ if (is_waiting_for_data(status)) {
+ // The output may run dry due to the input running slightly behind our playback rate, so we need to start the
+ // timer here as well to ensure that it triggers even if the PlaybackStream goes idle due to underrun.
+ request_played_out_check_if_needed_while_locked();
+ return;
+ }
+ if (!status_change_should_wake(m_last_dispatched_status, status))
+ return;
+ dispatch_state_if_changed(status, seek_id);
+}
+
void AudioPlaybackSink::OutputThreadData::dispatch_state_if_changed(PipelineStatus status, u32 seek_id)
{
if (status == m_last_dispatched_status)
diff --git a/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp b/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp
index a03825ceb80..38f52d2da23 100644
--- a/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp
+++ b/Libraries/LibMedia/Sinks/DisplayingVideoSink.cpp
@@ -57,12 +57,19 @@ ErrorOr<void> DisplayingVideoSink::connect_input(NonnullRefPtr<VideoProducer> co
update(MonotonicTime::now());
return;
}
+ m_latest_status = PipelineStatus::Suspended;
dispatch_state_if_changed(PipelineStatus::Suspended);
return;
}
- // Update the sink to dispatch a status if we're still resolving a seek. If we're not, avoid the update so that
- // we don't count dropped frames due to the decoder waiting for room while we're not consuming frames.
- if (!m_is_ticking && m_seek_status == SeekStatus::None && !m_seek_resolution_is_pending_frame_at_target)
+ // Update the sink to dispatch a status if we're still resolving a seek or waiting for data. If we're not, avoid
+ // the update so that we don't count dropped frames due to the decoder waiting for room while we're not
+ // consuming frames.
+ auto status_may_change = [&] {
+ if (m_seek_status != SeekStatus::None || m_seek_resolution_is_pending_frame_at_target)
+ return true;
+ return is_waiting_for_data(m_latest_status);
+ }();
+ if (!m_is_ticking && !status_may_change)
return;
update(MonotonicTime::now());
});
@@ -82,6 +89,7 @@ void DisplayingVideoSink::disconnect_input(NonnullRefPtr<VideoProducer> const& i
void DisplayingVideoSink::seek(AK::Duration timestamp, InvalidateHeldData invalidate_held_data)
{
m_seek_id++;
+ m_latest_status = PipelineStatus::Pending;
m_last_dispatched_status = PipelineStatus::Pending;
m_seek_resolution_is_pending_frame_at_target = true;
@@ -254,6 +262,7 @@ DisplayingVideoSinkUpdateResult DisplayingVideoSink::update(MonotonicTime now)
if (new_frame_available && m_on_present_needed)
m_on_present_needed();
+ m_latest_status = status_to_dispatch;
if (status_to_dispatch != m_last_dispatched_status) {
// Dispatch the new state with a deferred invoke to avoid reentrancy. This prevents a seek from resolving while
// an update is being processed.
diff --git a/Libraries/LibMedia/Sinks/DisplayingVideoSink.h b/Libraries/LibMedia/Sinks/DisplayingVideoSink.h
index eb629cab514..67175d3d45b 100644
--- a/Libraries/LibMedia/Sinks/DisplayingVideoSink.h
+++ b/Libraries/LibMedia/Sinks/DisplayingVideoSink.h
@@ -80,6 +80,7 @@ private:
SeekStatus m_seek_status { SeekStatus::None };
PipelineStateChangeHandler m_on_state_changed;
+ PipelineStatus m_latest_status { PipelineStatus::Pending };
PipelineStatus m_last_dispatched_status { PipelineStatus::Pending };
u32 m_seek_id { 0 };
diff --git a/Tests/LibMedia/TestDecodedVideoProducer.cpp b/Tests/LibMedia/TestDecodedVideoProducer.cpp
index b47fa91d469..2ee6b8a8382 100644
--- a/Tests/LibMedia/TestDecodedVideoProducer.cpp
+++ b/Tests/LibMedia/TestDecodedVideoProducer.cpp
@@ -45,9 +45,13 @@ public:
if (m_samples_served >= m_samples_before_blocking) {
m_read_is_blocked = true;
m_state_changed.broadcast();
+ if (m_read_blocked_change_handler)
+ m_read_blocked_change_handler(Media::ReadBlocked::Yes);
while (m_blocks_reads && !m_reads_are_aborted && !m_blocked_samples_are_permanently_unavailable)
m_state_changed.wait();
m_read_is_blocked = false;
+ if (m_read_blocked_change_handler)
+ m_read_blocked_change_handler(Media::ReadBlocked::No);
if (m_reads_are_aborted)
return Media::DecoderError::with_description(Media::DecoderErrorCategory::Aborted, "Blocking read was aborted"sv);
if (m_blocked_samples_are_permanently_unavailable)
@@ -91,7 +95,11 @@ public:
}
m_inner->reset_blocking_reads_aborted_for_track(track);
}
- virtual void set_read_blocked_change_handler_for_track(Media::Track const& track, Media::ReadBlockedChangeHandler handler) override { m_inner->set_read_blocked_change_handler_for_track(track, move(handler)); }
+ virtual void set_read_blocked_change_handler_for_track(Media::Track const&, Media::ReadBlockedChangeHandler handler) override
+ {
+ MutexLocker locker { m_mutex };
+ m_read_blocked_change_handler = move(handler);
+ }
bool wait_until_a_read_blocks(AK::Duration time_limit)
{
@@ -148,6 +156,7 @@ private:
bool m_reads_are_aborted { false };
bool m_blocked_samples_are_permanently_unavailable { false };
bool m_read_is_blocked { false };
+ Media::ReadBlockedChangeHandler m_read_blocked_change_handler;
Atomic<size_t> m_seek_count { 0 };
Atomic<size_t> m_forced_seek_count { 0 };
Atomic<bool> m_seek_is_expected { false };
@@ -654,6 +663,50 @@ TEST_CASE(output_that_arrives_while_the_demuxer_blocks_is_delivered)
demuxer->stop_blocking_reads();
}
+// Output that is still being decoded can arrive without another coded frame, so the producer is only blocked once the
+// decoder has nothing left in progress.
+TEST_CASE(a_blocked_read_reports_blocked_only_once_no_decode_is_in_progress)
+{
+ auto& loop = never_destroyed_event_loop();
+ auto withheld_outputs = make_ref_counted<WithheldOutputs>();
+ WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(withheld_outputs);
+ ScopeGuard stop_withholding = [] { WithholdingVideoDecoder::set_withheld_outputs_for_new_decoders(nullptr); };
+
+ auto sample_timestamps = presentation_timestamps_of_first_samples("./vp9_in_webm.webm"sv, 3);
+ auto [inner_demuxer, track] = demuxer_and_video_track_for("./vp9_in_webm.webm"sv);
+ auto demuxer = BlockingDemuxer::create(inner_demuxer, sample_timestamps.size());
+ auto producer = TRY_OR_FAIL(Media::DecodedVideoProducer::try_create(loop, demuxer, track));
+ producer->set_error_handler([&](Media::DecoderError&& error) {
+ FAIL(ByteString::formatted("An error occurred while decoding: {}", error.description()));
+ });
+ producer->start();
+
+ auto time_limit = AK::Duration::from_seconds(5);
+ if (!demuxer->wait_until_a_read_blocks(time_limit)) {
+ FAIL("Timed out waiting for the decode thread to block on the demuxer");
+ return;
+ }
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Pending);
+
+ for (size_t index = 0; index < sample_timestamps.size(); index++) {
+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Pending);
+ EXPECT(withheld_outputs->release_next());
+ auto frame = take_frame_within_time_limit(*producer, loop, time_limit);
+ if (frame == nullptr) {
+ FAIL("A withheld output was not delivered");
+ return;
+ }
+ }
+
+ auto deadline = MonotonicTime::now_coarse() + time_limit;
+ while (producer->peek().status != Media::PipelineStatus::Blocked && MonotonicTime::now_coarse() < deadline)
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(producer->peek().status, Media::PipelineStatus::Blocked);
+
+ demuxer->stop_blocking_reads();
+}
+
// The frame a seek resolves on can arrive the same way, and must resolve the seek without decoding from its keyframe
// again.
TEST_CASE(a_seek_resolves_on_output_that_arrives_while_the_demuxer_blocks)
diff --git a/Tests/LibMedia/TestDisplayingVideoSink.cpp b/Tests/LibMedia/TestDisplayingVideoSink.cpp
index b25b3dc8312..b328ced0503 100644
--- a/Tests/LibMedia/TestDisplayingVideoSink.cpp
+++ b/Tests/LibMedia/TestDisplayingVideoSink.cpp
@@ -379,6 +379,34 @@ TEST_CASE(resuming_ticking_seeks_past_frames_held_behind_the_clock)
EXPECT_EQ(frame_counts.dropped, 0u);
}
+// A sink reports its status in a deferred task, so a wake can arrive before that report is dispatched. The sink is
+// already presenting a frame by then, and must not take further frames while it is not ticking.
+TEST_CASE(wakes_before_a_status_is_dispatched_leave_frames_held_behind_the_clock)
+{
+ auto& loop = never_destroyed_event_loop();
+
+ auto pool = MUST(Media::VideoFramePool::create());
+ auto clock = MUST(Media::MonotonicMediaClock::try_create());
+ clock->seek(AK::Duration::from_milliseconds(1000));
+
+ auto sink = MUST(Media::DisplayingVideoSink::try_create(clock->time_reader()));
+ auto producer = ScriptedVideoProducer::create();
+ MUST(sink->connect_input(producer));
+
+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(1000), AK::Duration::from_milliseconds(40)));
+ EXPECT(sink->update(MonotonicTime::now()).new_frame_available);
+ EXPECT_EQ(sink->take_frame_counts().presented, 1u);
+
+ sink->set_ticking(false);
+ clock->seek(AK::Duration::from_milliseconds(1200));
+ for (auto timestamp : { 1040, 1080, 1120, 1160 })
+ producer->append_frame(create_test_frame(*pool, AK::Duration::from_milliseconds(timestamp), AK::Duration::from_milliseconds(40)));
+ producer->wake();
+ EXPECT_EQ(sink->current_frame()->timestamp(), AK::Duration::from_milliseconds(1000));
+ EXPECT(sink->take_frame_counts().is_zero());
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+}
+
TEST_CASE(wakes_while_not_ticking_leave_frames_held_behind_the_clock)
{
auto& loop = never_destroyed_event_loop();
diff --git a/Tests/LibMedia/TestPipelineNodes.cpp b/Tests/LibMedia/TestPipelineNodes.cpp
index c01e99fc58c..80d1bb79cda 100644
--- a/Tests/LibMedia/TestPipelineNodes.cpp
+++ b/Tests/LibMedia/TestPipelineNodes.cpp
@@ -292,6 +292,45 @@ private:
}
+// Has no data to hand out, and reports whatever status the test gives it.
+class StatusAudioProducer final : public Media::AudioProducer {
+public:
+ static NonnullRefPtr<StatusAudioProducer> create(Media::PipelineStatus status) { return adopt_ref(*new StatusAudioProducer(status)); }
+
+ virtual void start() override { }
+ virtual ErrorOr<void> set_output_sample_specification(Audio::SampleSpecification) override { return {}; }
+
+ virtual Media::AudioProducerOutput peek() override
+ {
+ MutexLocker locker { m_mutex };
+ return { nullptr, m_status };
+ }
+
+ virtual void consume() override { }
+ virtual void set_wake_handler(Media::PipelineWakeHandler handler) override { m_wake_handler = move(handler); }
+ virtual void seek(AK::Duration) override { }
+
+ void set_status(Media::PipelineStatus status)
+ {
+ {
+ MutexLocker locker { m_mutex };
+ m_status = status;
+ }
+ if (m_wake_handler)
+ m_wake_handler();
+ }
+
+private:
+ explicit StatusAudioProducer(Media::PipelineStatus status)
+ : m_status(status)
+ {
+ }
+
+ Mutex m_mutex;
+ Media::PipelineStatus m_status;
+ Media::PipelineWakeHandler m_wake_handler;
+};
+
TEST_CASE(audio_playback_sink_reseeks_its_input_from_the_written_output_without_moving_the_clock)
{
auto& loop = never_destroyed_event_loop();
@@ -390,6 +429,24 @@ TEST_CASE(audio_playback_sink_reports_readiness_at_zero_rate)
EXPECT(pump_until(loop, [&] { return time_reader.current_time() > seek_target + AK::Duration::from_milliseconds(100); }));
}
+// A sink whose playback rate is zero does not pull from its input, but nothing else reports its input's status, so it
+// must still report that status as it changes.
+TEST_CASE(audio_playback_sink_reports_its_inputs_status_while_its_playback_rate_is_zero)
+{
+ auto& loop = never_destroyed_event_loop();
+
+ Optional<Media::PipelineStatus> last_dispatched_status;
+ auto sink = MUST(Media::AudioPlaybackSink::try_create([&](Media::PipelineStatus status) { last_dispatched_status = status; }, Media::AudioOutputFactory::create_null()));
+ auto producer = StatusAudioProducer::create(Media::PipelineStatus::Blocked);
+ MUST(sink->connect_input(producer));
+ sink->start();
+ EXPECT(pump_until(loop, [&] { return last_dispatched_status == Media::PipelineStatus::Blocked; }));
+
+ sink->set_playback_rate(0.0f);
+ producer->set_status(Media::PipelineStatus::Pending);
+ EXPECT(pump_until(loop, [&] { return last_dispatched_status == Media::PipelineStatus::Pending; }));
+}
+
TEST_CASE(displaying_video_sink_reports_a_suspended_input_while_unticked)
{
auto& loop = never_destroyed_event_loop();