Optimize audio output a bit

This commit is contained in:
wheremyfoodat 2024-02-23 23:49:10 +02:00
parent 53746e0511
commit 921250bcd2
4 changed files with 113 additions and 124 deletions

View file

@ -1,4 +1,6 @@
#pragma once #pragma once
#include <array>
#include "audio/dsp_core.hpp" #include "audio/dsp_core.hpp"
#include "memory.hpp" #include "memory.hpp"
#include "swap.hpp" #include "swap.hpp"
@ -10,6 +12,11 @@ namespace Audio {
u32 pipeBaseAddr; u32 pipeBaseAddr;
bool running; // Is the DSP running? bool running; // Is the DSP running?
bool loaded; // Have we finished loading a binary with LoadComponent? bool loaded; // Have we finished loading a binary with LoadComponent?
bool signalledData;
bool signalledSemaphore;
uint audioFrameIndex = 0; // Index in our audio frame
std::array<s16, 160 * 2> audioFrame;
// Get a pointer to a data memory address // Get a pointer to a data memory address
u8* getDataPointer(u32 address) { return getDspMemory() + Memory::DSP_DATA_MEMORY_OFFSET + address; } u8* getDataPointer(u32 address) { return getDspMemory() + Memory::DSP_DATA_MEMORY_OFFSET + address; }
@ -62,10 +69,6 @@ namespace Audio {
std::memcpy(statusAddress + 6, &status.writePointer, sizeof(u16)); std::memcpy(statusAddress + 6, &status.writePointer, sizeof(u16));
} }
} }
bool signalledData;
bool signalledSemaphore;
// Run 1 slice of DSP instructions // Run 1 slice of DSP instructions
void runSlice() { void runSlice() {
if (running) { if (running) {

View file

@ -1,117 +1,110 @@
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project /*
// SPDX-License-Identifier: GPL-2.0-or-later
MIT License
Copyright (c) 2021 PCSX-Redux authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once #pragma once
#include <memory.h>
#include <algorithm> #include <algorithm>
#include <array> #include <chrono>
#include <atomic> #include <condition_variable>
#include <cstddef> #include <mutex>
#include <cstring> #include <stdexcept>
#include <new>
#include <span>
#include <type_traits>
#include <vector>
namespace Common { namespace Common {
/// SPSC ring buffer template <typename T, size_t BS = 1024>
/// @tparam T Element type class RingBuffer {
/// @tparam capacity Number of slots in ring buffer
template <typename T, std::size_t capacity>
class RingBuffer {
/// A "slot" is made of a single `T`.
static constexpr std::size_t slot_size = sizeof(T);
// T must be safely memcpy-able and have a trivial default constructor.
static_assert(std::is_trivial_v<T>);
// Ensure capacity is sensible.
static_assert(capacity < std::numeric_limits<std::size_t>::max() / 2);
static_assert((capacity & (capacity - 1)) == 0, "capacity must be a power of two");
// Ensure lock-free.
static_assert(std::atomic_size_t::is_always_lock_free);
public: public:
/// Pushes slots into the ring buffer static constexpr size_t BUFFER_SIZE = BS;
/// @param new_slots Pointer to the slots to push size_t available() {
/// @param slot_count Number of slots to push std::unique_lock<std::mutex> l(m_mu);
/// @returns The number of slots actually pushed return availableLocked();
std::size_t push(const void* new_slots, std::size_t slot_count) { }
const std::size_t write_index = m_write_index.load(); size_t buffered() {
const std::size_t slots_free = capacity + m_read_index.load() - write_index; std::unique_lock<std::mutex> l(m_mu);
const std::size_t push_count = std::min(slot_count, slots_free); return bufferedLocked();
const std::size_t pos = write_index % capacity;
const std::size_t first_copy = std::min(capacity - pos, push_count);
const std::size_t second_copy = push_count - first_copy;
const char* in = static_cast<const char*>(new_slots);
std::memcpy(m_data.data() + pos, in, first_copy * slot_size);
in += first_copy * slot_size;
std::memcpy(m_data.data(), in, second_copy * slot_size);
m_write_index.store(write_index + push_count);
return push_count;
} }
std::size_t push(std::span<const T> input) { bool push(const T* data, size_t N) {
return push(input.data(), input.size()); if (N > BUFFER_SIZE) {
throw std::runtime_error("Trying to enqueue too much data");
}
std::unique_lock<std::mutex> l(m_mu);
using namespace std::chrono_literals;
bool safe = m_cv.wait_for(l, 20ms, [this, N]() -> bool { return N < availableLocked(); });
if (safe) enqueueSafe(data, N);
return safe;
}
size_t pop(T* data, size_t N) {
std::unique_lock<std::mutex> l(m_mu);
N = std::min(N, bufferedLocked());
dequeueSafe(data, N);
return N;
} }
/// Pops slots from the ring buffer private:
/// @param output Where to store the popped slots size_t availableLocked() const { return BUFFER_SIZE - m_size; }
/// @param max_slots Maximum number of slots to pop size_t bufferedLocked() const { return m_size; }
/// @returns The number of slots actually popped void enqueueSafe(const T* data, size_t N) {
std::size_t pop(void* output, std::size_t max_slots = ~std::size_t(0)) { size_t end = m_end;
const std::size_t read_index = m_read_index.load(); const size_t subLen = BUFFER_SIZE - end;
const std::size_t slots_filled = m_write_index.load() - read_index; if (N > subLen) {
const std::size_t pop_count = std::min(slots_filled, max_slots); enqueueSafe(data, subLen);
enqueueSafe(data + subLen, N - subLen);
const std::size_t pos = read_index % capacity; } else {
const std::size_t first_copy = std::min(capacity - pos, pop_count); memcpy(m_buffer + end, data, N * sizeof(T));
const std::size_t second_copy = pop_count - first_copy; end += N;
if (end == BUFFER_SIZE) end = 0;
char* out = static_cast<char*>(output); m_end = end;
std::memcpy(out, m_data.data() + pos, first_copy * slot_size); m_size += N;
out += first_copy * slot_size; }
std::memcpy(out, m_data.data(), second_copy * slot_size); }
void dequeueSafe(T* data, size_t N) {
m_read_index.store(read_index + pop_count); size_t begin = m_begin;
const size_t subLen = BUFFER_SIZE - begin;
return pop_count; if (N > subLen) {
dequeueSafe(data, subLen);
dequeueSafe(data + subLen, N - subLen);
} else {
memcpy(data, m_buffer + begin, N * sizeof(T));
begin += N;
if (begin == BUFFER_SIZE) begin = 0;
m_begin = begin;
m_size -= N;
m_cv.notify_one();
}
} }
std::vector<T> pop(std::size_t max_slots = ~std::size_t(0)) { size_t m_begin = 0, m_end = 0, m_size = 0;
std::vector<T> out(std::min(max_slots, capacity)); T m_buffer[BUFFER_SIZE];
const std::size_t count = Pop(out.data(), out.size());
out.resize(count);
return out;
}
/// @returns Number of slots used
[[nodiscard]] std::size_t size() const {
return m_write_index.load() - m_read_index.load();
}
/// @returns Maximum size of ring buffer
[[nodiscard]] constexpr std::size_t Capacity() const {
return capacity;
}
private:
// It is important to align the below variables for performance reasons:
// Having them on the same cache-line would result in false-sharing between them.
// TODO: Remove this ifdef whenever clang and GCC support
// std::hardware_destructive_interference_size.
#ifdef __cpp_lib_hardware_interference_size
alignas(std::hardware_destructive_interference_size) std::atomic_size_t m_read_index{0};
alignas(std::hardware_destructive_interference_size) std::atomic_size_t m_write_index{0};
#else
alignas(128) std::atomic_size_t m_read_index{0};
alignas(128) std::atomic_size_t m_write_index{0};
#endif
std::array<T, capacity> m_data;
};
std::mutex m_mu;
std::condition_variable m_cv;
};
} // namespace Common } // namespace Common

View file

@ -92,15 +92,6 @@ void MiniAudioDevice::init(Samples& samples, bool safe) {
auto self = reinterpret_cast<MiniAudioDevice*>(device->pUserData); auto self = reinterpret_cast<MiniAudioDevice*>(device->pUserData);
s16* output = reinterpret_cast<ma_int16*>(out); s16* output = reinterpret_cast<ma_int16*>(out);
// Wait until there's enough samples to pop
while (self->samples->size() < frameCount * channelCount) {
printf("Waiting\n");
// If audio output is disabled from the emulator thread, make sure that this callback will return and not hang
if (!self->running) {
return;
}
}
self->samples->pop(output, frameCount * channelCount); self->samples->pop(output, frameCount * channelCount);
}; };

View file

@ -6,10 +6,6 @@
#include "services/dsp.hpp" #include "services/dsp.hpp"
using namespace Audio; using namespace Audio;
static constexpr u32 sampleRate = 32768;
static constexpr u32 duration = 30;
static s16 samples[sampleRate * duration * 2];
static uint sampleIndex = 0;
struct Dsp1 { struct Dsp1 {
// All sizes are in bytes unless otherwise specified // All sizes are in bytes unless otherwise specified
@ -115,6 +111,8 @@ void TeakraDSP::reset() {
running = false; running = false;
loaded = false; loaded = false;
signalledData = signalledSemaphore = false; signalledData = signalledSemaphore = false;
audioFrameIndex = 0;
} }
void TeakraDSP::setAudioEnabled(bool enable) { void TeakraDSP::setAudioEnabled(bool enable) {
@ -124,10 +122,14 @@ void TeakraDSP::setAudioEnabled(bool enable) {
// Set the appropriate audio callback for Teakra // Set the appropriate audio callback for Teakra
if (audioEnabled) { if (audioEnabled) {
teakra.SetAudioCallback([=](std::array<s16, 2> sample) { teakra.SetAudioCallback([=](std::array<s16, 2> sample) {
// Wait until we can push our samples audioFrame[audioFrameIndex++] = sample[0];
while (sampleBuffer.size() + 2 > sampleBuffer.Capacity()) { audioFrame[audioFrameIndex++] = sample[1];
// Push our samples at the end of an audio frame
if (audioFrameIndex >= audioFrame.size()) {
audioFrameIndex -= audioFrame.size();
sampleBuffer.push(audioFrame.data(), audioFrame.size());
} }
sampleBuffer.push(sample.data(), 2);
}); });
} else { } else {
teakra.SetAudioCallback([=](std::array<s16, 2> sample) { /* Do nothing */ }); teakra.SetAudioCallback([=](std::array<s16, 2> sample) { /* Do nothing */ });