From ac6c06e23595e284426e5d691d367ed141fbaf55 Mon Sep 17 00:00:00 2001 From: Zaggy1024 Date: Wed, 9 Aug 2023 04:22:15 -0500 Subject: [PATCH] LibAudio: Don't count buffered samples in `Loader::loaded_samples()` The `Loader` uses a `Vector` to store any samples that the actual audio decoder returned that the loader client did not request yet. However, it did not take that buffer into account when those clients asked for the number of samples loaded. The buffer is an internal implementation detail, and should not be reflected on the external API. This allows LibWeb to keep better track of audio position without any desync caused by the buffer. When using the Serenity `PlaybackStream` implementation as the back end for an `HTMLAudioElement`, this allows us to perfectly stop on the exact last sample of the audio file, so it will not stop before the media element can see that it has finished playback. Note that `Loader::get_more_samples()` also calls `loaded_samples()` to determine how many samples are remaining to load into the output buffer. However, this change appears to be correct even there, given that the samples copied from the internal sample buffer are included in that count. --- Userland/Libraries/LibAudio/Loader.cpp | 2 +- Userland/Libraries/LibAudio/Loader.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Userland/Libraries/LibAudio/Loader.cpp b/Userland/Libraries/LibAudio/Loader.cpp index c3080a9842..62933e600b 100644 --- a/Userland/Libraries/LibAudio/Loader.cpp +++ b/Userland/Libraries/LibAudio/Loader.cpp @@ -69,7 +69,7 @@ ErrorOr, LoaderError> Loader::create_plugin(NonnullO LoaderSamples Loader::get_more_samples(size_t samples_to_read_from_input) { - if (m_plugin_at_end_of_stream) + if (m_plugin_at_end_of_stream && m_buffer.is_empty()) return FixedArray {}; size_t remaining_samples = total_samples() - loaded_samples(); diff --git a/Userland/Libraries/LibAudio/Loader.h b/Userland/Libraries/LibAudio/Loader.h index d6d5b9e3e8..e1f0d80679 100644 --- a/Userland/Libraries/LibAudio/Loader.h +++ b/Userland/Libraries/LibAudio/Loader.h @@ -103,7 +103,7 @@ public: return m_plugin->seek(position); } - int loaded_samples() const { return m_plugin->loaded_samples(); } + int loaded_samples() const { return m_plugin->loaded_samples() - (int)m_buffer.size(); } int total_samples() const { return m_plugin->total_samples(); } u32 sample_rate() const { return m_plugin->sample_rate(); } u16 num_channels() const { return m_plugin->num_channels(); }