ladybird/Userland/Applications/SoundPlayer/PlaybackManager.h
Nick Miller 9a2c80c791 SoundPlayer: Handle any input file sample rate
This commit addresses two issues:
1. If you play a 96 KHz Wave file, the slider position is incorrect,
   because it is assumed all files are 44.1 KHz.
2. For high-bitrate files, there are audio dropouts due to not
   buffering enough audio data.

Issue 1 is addressed by scaling the number of played samples by the
ratio between the source and destination sample rates.

Issue 2 is addressed by buffering a certain number of milliseconds
worth of audio data (instead of a fixed number of bytes).
This makes the the buffer size independent of the source sample rate.

Some of the code is redesigned to be simpler. The code that did the
book-keeping of which buffers need to be loaded and which have been
already played has been removed. Instead, we enqueue a new buffer based
on a low watermark of samples remaining in the audio server queue.

Other small fixes include:
1. Disable the stop button when playback is finished.
2. Remove hard-coded instances of 44100.
3. Update the GUI every 50 ms (was 100), which improves visualizations.
2021-06-21 03:13:59 +04:30

63 lines
1.9 KiB
C++

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Vector.h>
#include <LibAudio/Buffer.h>
#include <LibAudio/ClientConnection.h>
#include <LibAudio/Loader.h>
#include <LibCore/Timer.h>
class PlaybackManager final {
public:
PlaybackManager(NonnullRefPtr<Audio::ClientConnection>);
~PlaybackManager();
void play();
void stop();
void pause();
void seek(const int position);
void loop(bool);
bool toggle_pause();
void set_loader(NonnullRefPtr<Audio::Loader>&&);
size_t device_sample_rate() const { return m_device_sample_rate; }
int last_seek() const { return m_last_seek; }
bool is_paused() const { return m_paused; }
float total_length() const { return m_total_length; }
RefPtr<Audio::Buffer> current_buffer() const { return m_current_buffer; }
NonnullRefPtr<Audio::ClientConnection> connection() const { return m_connection; }
Function<void()> on_update;
Function<void(Audio::Buffer&)> on_load_sample_buffer;
Function<void()> on_finished_playing;
private:
void next_buffer();
void set_paused(bool);
bool m_paused { true };
bool m_loop = { false };
size_t m_last_seek { 0 };
float m_total_length { 0 };
// FIXME: Get this from the audio server
size_t m_device_sample_rate { 44100 };
size_t m_device_samples_per_buffer { 0 };
size_t m_source_buffer_size_bytes { 0 };
RefPtr<Audio::Loader> m_loader { nullptr };
NonnullRefPtr<Audio::ClientConnection> m_connection;
RefPtr<Audio::Buffer> m_current_buffer;
RefPtr<Core::Timer> m_timer;
// Controls the GUI update rate. A smaller value makes the visualizations nicer.
static constexpr u32 update_rate_ms = 50;
// Number of milliseconds of audio data contained in each audio buffer
static constexpr u32 buffer_size_ms = 100;
};