diff --git a/core/libs/prx/libSceAudioOut/CMakeLists.txt b/core/libs/prx/libSceAudioOut/CMakeLists.txt index e5e5a0685..144dab991 100644 --- a/core/libs/prx/libSceAudioOut/CMakeLists.txt +++ b/core/libs/prx/libSceAudioOut/CMakeLists.txt @@ -72,4 +72,13 @@ if(BUILD_TESTING) set_tests_properties(audio_out2_port_layouts PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test_executable(audio_out2_timing_tests tests/AudioOut2Timing.cpp) + target_include_directories(audio_out2_timing_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(audio_out2_timing_tests PRIVATE libSceAudioOut libc) + configure_windows_unwind(audio_out2_timing_tests) + add_test(NAME audio_out2_timing COMMAND audio_out2_timing_tests) + if(WIN32) + set_tests_properties(audio_out2_timing PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() endif() diff --git a/core/libs/prx/libSceAudioOut/src/AudioOut2Context.cpp b/core/libs/prx/libSceAudioOut/src/AudioOut2Context.cpp index d82a9ae67..9dc8f44d6 100644 --- a/core/libs/prx/libSceAudioOut/src/AudioOut2Context.cpp +++ b/core/libs/prx/libSceAudioOut/src/AudioOut2Context.cpp @@ -14,13 +14,12 @@ #include "prx/libc/include/General.hpp" #include "AudioOut2Internal.hpp" -// An AudioOut2 context is the hardware output queue: every push records the buffers the ports point -// at and appends that grain (num_grains samples) to a queue of queue_depth grains that plays in real -// time. The title paces its mixer on that queue (Demon's Souls polls GetQueueLevel and pushes -// non-blocking whenever a slot is free), so the level must follow the output clock. With an SDL device -// open, the device callback plays the mixed grains behind a cushion and the queue level counts the -// grains beyond that cushion; otherwise a wall-clock model of the queue stands in. A grain's buffers -// are read at the next push: PPSA12544 fills a buffer after pushing it and reuses it two pushes later. +// An AudioOut2 context is the hardware output queue: every push appends a grain (num_grains samples) +// to a queue of queue_depth grains that plays in real time. Titles pace their mixer on that queue, so +// the level must follow the output clock. With an SDL device open, a grain's port buffers are read at +// the next push, the device callback plays the mixed grains behind a cushion and the level counts the +// grains beyond that cushion; otherwise each push is mixed at once and a wall-clock model of the +// queue stands in. using Clock = std::chrono::steady_clock; @@ -37,8 +36,6 @@ static constexpr std::uint32_t MAX_QUEUED_MS = 250; // A blocking push on a full queue gives up after this long. static constexpr std::chrono::milliseconds FULL_WAIT_TIMEOUT{200}; static constexpr std::chrono::milliseconds FULL_WAIT_STEP{1}; -// How long a push waits before it reads the previous grain's buffers: PPSA12544's mixer thread can -// still be writing them when the next push follows within microseconds. static constexpr std::chrono::microseconds READ_DELAY{100}; static constexpr std::uint16_t DEVICE_SAMPLES = 512; // The summed ports (a 7.1 bed folded to stereo plus the object ports) peak above full scale in the @@ -190,7 +187,7 @@ static void QueuePadGrain(AudioOut2Context& context) { const auto frameBytes = static_cast(context.padLayout.channels * sizeof(float)); const auto grainBytes = context.grain * frameBytes; const auto cushionBytes = CUSHION_MS * (AUDIO_OUT2_SAMPLE_RATE / 1000) * frameBytes; - const auto mainQueuedBytes = cushionBytes + context.queueDepth * grainBytes; + const auto mainQueuedBytes = context.device != 0 ? UnplayedGrains(context) * grainBytes : cushionBytes + context.queueDepth * grainBytes; const auto queuedBytes = SDL_GetQueuedAudioSize(context.padDevice); if (queuedBytes > mainQueuedBytes + PAD_SLACK_GRAINS * grainBytes) return; if (queuedBytes == 0) { @@ -333,23 +330,31 @@ int APS5_VABI sceAudioOut2ContextPush(AudioOut2ContextHandle ctx, uint32_t block } context->queued++; context->playHead += GrainDuration(*context); - context->pendingGrains.push_back(AudioOut2CaptureGrain(*context)); UpdatePadDevice(*context, now); - const auto mixed = static_cast(context->pendingGrains.back().size()); - const std::size_t unread = context->device == 0 ? context->queueDepth : 2; - if (context->pendingGrains.size() >= unread) { - const auto readAt = Clock::now() + READ_DELAY; - while (Clock::now() < readAt) std::this_thread::yield(); - } - while (context->pendingGrains.size() >= unread) { - Render(*context, context->pendingGrains.front()); - context->pendingGrains.pop_front(); - if (context->device == 0) continue; - if (PendingMs(*context) > MAX_QUEUED_MS) { - context->dropped++; - continue; + auto grain = AudioOut2CaptureGrain(*context); + const auto mixed = static_cast(grain.size()); + if (context->device == 0) { + Render(*context, grain); + } else { + context->pendingGrains.push_back(std::move(grain)); + context->pendingSince.push_back(Clock::now()); + while (context->pendingGrains.size() >= 2) { + const auto readAt = context->pendingSince.front() + READ_DELAY; + if (Clock::now() < readAt) { + lock.unlock(); + while (Clock::now() < readAt) std::this_thread::yield(); + lock.lock(); + continue; + } + Render(*context, context->pendingGrains.front()); + context->pendingGrains.pop_front(); + context->pendingSince.pop_front(); + if (PendingMs(*context) > MAX_QUEUED_MS) { + context->dropped++; + continue; + } + context->output.insert(context->output.end(), context->mix.begin(), context->mix.end()); } - context->output.insert(context->output.end(), context->mix.begin(), context->mix.end()); } context->pushes++; context->summaryPushes++; diff --git a/core/libs/prx/libSceAudioOut/src/AudioOut2Internal.hpp b/core/libs/prx/libSceAudioOut/src/AudioOut2Internal.hpp index f5e38e833..2b7a8aa0a 100644 --- a/core/libs/prx/libSceAudioOut/src/AudioOut2Internal.hpp +++ b/core/libs/prx/libSceAudioOut/src/AudioOut2Internal.hpp @@ -77,6 +77,7 @@ struct AudioOut2Context { std::deque output; bool priming = true; std::deque pendingGrains; + std::deque pendingSince; SDL_AudioDeviceID padDevice = 0; std::chrono::steady_clock::time_point nextPadProbe; AudioOut2PadLayout padLayout; diff --git a/core/libs/prx/libSceAudioOut/tests/AudioOut2Timing.cpp b/core/libs/prx/libSceAudioOut/tests/AudioOut2Timing.cpp new file mode 100644 index 000000000..14e3f1744 --- /dev/null +++ b/core/libs/prx/libSceAudioOut/tests/AudioOut2Timing.cpp @@ -0,0 +1,172 @@ +#include "SceTypes.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +int APS5_VABI sceAudioOut2ContextResetParam(AudioOut2ContextParam*); +int APS5_VABI sceAudioOut2ContextCreate(const AudioOut2ContextParam*, void*, std::size_t, AudioOut2ContextHandle*); +int APS5_VABI sceAudioOut2ContextDestroy(AudioOut2ContextHandle); +int APS5_VABI sceAudioOut2ContextPush(AudioOut2ContextHandle, std::uint32_t); +int APS5_VABI sceAudioOut2ContextGetQueueLevel(AudioOut2ContextHandle, std::uint32_t*, std::uint32_t*); +int APS5_VABI sceAudioOut2PortCreate(AudioOut2ContextHandle, const AudioOut2PortParam*, AudioOut2PortHandle*); +int APS5_VABI sceAudioOut2PortDestroy(AudioOut2PortHandle); +int APS5_VABI sceAudioOut2PortSetAttributes(AudioOut2PortHandle, const AudioOut2Attribute*, std::uint32_t); +} + +static void Require(bool value) { if (!value) std::abort(); } + +static void SetEnvironment(const char* name, const std::string& value) { +#ifdef _WIN32 + _putenv_s(name, value.c_str()); +#else + setenv(name, value.c_str(), 1); +#endif +} + +namespace { + +constexpr std::uint32_t grain = 256; +constexpr std::uint32_t queueDepth = 2; +constexpr std::uint32_t cushionGrains = 8; +constexpr std::uint32_t frequency = 48000; +constexpr std::uint32_t formatStereoFloat = 2u << 8; +constexpr std::uint32_t attributeData = 0; +constexpr int queueFull = static_cast(0x80260507); +constexpr float masterGain = 0.5f; +constexpr float tolerance = 1e-5f; + +struct Session { + std::filesystem::path path; + AudioOut2ContextHandle context = 0; + AudioOut2PortHandle port = 0; + std::vector buffer = std::vector(static_cast(grain) * 2, 0.0f); + + explicit Session(const char* name) : path(std::filesystem::temp_directory_path() / name) { + std::filesystem::remove(path); + SetEnvironment("SDL_DISKAUDIOFILE", path.string()); + AudioOut2ContextParam params{}; + Require(sceAudioOut2ContextResetParam(¶ms) == 0); + params.num_grains = grain; + params.queue_depth = queueDepth; + Require(sceAudioOut2ContextCreate(¶ms, nullptr, 0, &context) == 0); + AudioOut2PortParam port{}; + port.port_type = 0; + port.data_format = formatStereoFloat; + port.sampling_freq = frequency; + Require(sceAudioOut2PortCreate(context, &port, &this->port) == 0); + } + + void Point(const void* data) { + const AudioOut2Attribute attribute{attributeData, 0, &data, sizeof(data)}; + Require(sceAudioOut2PortSetAttributes(port, &attribute, 1) == 0); + } + + void Fill(float value) { + for (float& sample : buffer) sample = value; + } + + std::vector Close() { + Require(sceAudioOut2PortDestroy(port) == 0); + Require(sceAudioOut2ContextDestroy(context) == 0); + std::ifstream file(path, std::ios::binary); + const std::vector bytes{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + file.close(); + std::filesystem::remove(path); + Require(bytes.size() % sizeof(float) == 0); + const auto* samples = reinterpret_cast(bytes.data()); + return {samples, samples + bytes.size() / sizeof(float)}; + } +}; + +std::size_t FirstNonZero(const std::vector& played, std::size_t from = 0) { + while (from < played.size() && played[from] == 0.0f) from++; + return from; +} + +bool Constant(const std::vector& played, std::size_t first, std::size_t count, float value) { + if (first + count > played.size()) return false; + for (std::size_t index = first; index < first + count; index++) { + if (std::fabs(played[index] - value) > tolerance) return false; + } + return true; +} + +void TestReadAtNextPush() { + Session session("anyps5_audio_out2_next_push.raw"); + session.Fill(0.25f); + session.Point(session.buffer.data()); + Require(sceAudioOut2ContextPush(session.context, 1) == 0); + session.Fill(0.5f); + Require(sceAudioOut2ContextPush(session.context, 1) == 0); + session.Fill(0.75f); + Require(sceAudioOut2ContextPush(session.context, 1) == 0); + session.Fill(0.0f); + session.Point(nullptr); + for (std::uint32_t push = 0; push < cushionGrains * 4; push++) Require(sceAudioOut2ContextPush(session.context, 1) == 0); + const auto played = session.Close(); + const auto first = FirstNonZero(played); + const std::size_t samples = static_cast(grain) * 2; + Require(Constant(played, first, samples, 0.5f * masterGain)); + Require(Constant(played, first + samples, samples, 0.75f * masterGain)); + Require(FirstNonZero(played, first + 2 * samples) == played.size()); +} + +void TestLevelExcludesCushion() { + Session session("anyps5_audio_out2_level.raw"); + session.Point(nullptr); + std::uint32_t level = 99; + std::uint32_t available = 99; + Require(sceAudioOut2ContextGetQueueLevel(session.context, &level, &available) == 0); + Require(level == 0 && available == queueDepth); + std::uint32_t accepted = 0; + int result = 0; + while ((result = sceAudioOut2ContextPush(session.context, 0)) == 0) { + accepted++; + Require(accepted < 1000); + } + Require(result == queueFull); + Require(accepted >= cushionGrains + queueDepth); + session.Close(); +} + +void TestPrimingAfterRunningDry() { + Session session("anyps5_audio_out2_priming.raw"); + session.Fill(0.5f); + session.Point(session.buffer.data()); + for (std::uint32_t push = 0; push < 12; push++) Require(sceAudioOut2ContextPush(session.context, 1) == 0); + session.Point(nullptr); + Require(sceAudioOut2ContextPush(session.context, 1) == 0); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + session.Fill(-0.5f); + session.Point(session.buffer.data()); + for (std::uint32_t push = 0; push < 12; push++) Require(sceAudioOut2ContextPush(session.context, 1) == 0); + session.Point(nullptr); + for (std::uint32_t push = 0; push < cushionGrains * 4; push++) Require(sceAudioOut2ContextPush(session.context, 1) == 0); + const auto played = session.Close(); + const std::size_t burst = static_cast(grain) * 2 * 12; + const auto first = FirstNonZero(played); + Require(Constant(played, first, burst, 0.5f * masterGain)); + const auto second = FirstNonZero(played, first + burst); + Require(second < played.size() && second - (first + burst) >= static_cast(grain) * 2); + Require(Constant(played, second, burst, -0.5f * masterGain)); +} + +} + +int main() { + SetEnvironment("SDL_AUDIODRIVER", "disk"); + TestReadAtNextPush(); + TestLevelExcludesCushion(); + TestPrimingAfterRunningDry(); + return 0; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index b8b01fa24..43239a6cc 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -249,7 +249,7 @@ Throughout the project, every function at every stage either **does exactly what - [sceKeyboardGetKey2Char](../../core/libs/prx/libSceKeyboard/src/keyboard_impl.cpp) (libSceKeyboard) translates the 101-key (US) arrangement and the alphanumeric layer of the 106-key (Japanese) one, which follows the JIS layout of the HID usages: the Yen (0x89) and Ro (0x87) keys return `\` (0x5C) unshifted, as JIS X 0201 places the yen sign there; whether the console returns U+00A5 instead is unverified. With the Kana LED (bit 4, the HID position) set the 106-key arrangement throws, as the kana the console returns are unknown. Ctrl and Alt do not change the character. - [sceAudioOut2Set3DLatency](../../core/libs/prx/libSceAudioOut/src/AudioOut2System.cpp) and [sceAudioOut2MasteringInit](../../core/libs/prx/libSceAudioOut/src/AudioOut2Mastering.cpp) (libSceAudioOut) have no effect: there is no 3D rendering or mastering stage. - [sceImeKeyboardGetInfo](../../core/libs/prx/libSceIme/Export.cpp) (libSceIme) returns `0x80bc0023` (no resource id) for every id while a keyboard is open, since the IME keyboard never reports a connected device. [sceImeKeyboardSetMode](../../core/libs/prx/libSceIme/Export.cpp) validates the mode bits but the mode has no effect, as no IME keyboard events are delivered. -- [AudioOut2 contexts](../../core/libs/prx/libSceAudioOut/src/AudioOut2Context.cpp) (libSceAudioOut) read a grain's port buffers at the next push, 100 us after it, and play the mix behind a 40 ms cushion that the queue level leaves out. Both follow PPSA12544's FMOD output, measured by recording its four 256-frame buffers at every push: it fills a buffer after pushing it, reuses it two pushes later, and its mixer thread can still be writing when the next push follows within microseconds. Reading at the push, or two pushes later, breaks 27% or 59% of grain boundaries. When the hardware reads the buffers is not known. +- [AudioOut2 contexts](../../core/libs/prx/libSceAudioOut/src/AudioOut2Context.cpp) (libSceAudioOut) with an SDL device read a grain's port buffers at the next push, at least 100 us after the grain was pushed, and play the mix behind a 40 ms cushion that the queue level leaves out. When the hardware reads the buffers is not known. The timing follows a title whose mixer fills a buffer after pushing it, reuses it two pushes later, and may still be writing it when the next push follows within microseconds - [libSceAudiodec](../../core/libs/prx/libSceAudiodec/Export.cpp) throws for the 24-bit PCM word size (`iBwPcm` 0): its sample layout is unknown. ATRAC9 decoding is covered only by configuration and error tests, as no ATRAC9 encoder is available for a fixture. - [sceAjmDecMp3ParseFrame](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native) throws when the original file length is requested (`parse_ofl` non-zero) for a layer other than III, for a CRC-protected frame, or for a VBRI header outside MPEG-1 stereo: shadPS4 looks for the tag after the CRC and after the side information, while LAME and FFmpeg place it without the CRC and VBRI always at byte 36. - The [output modifier](../../core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp) (`mul:2`, `mul:4`, `div:2`) follows the hardware with the IEEE mode off and f32 denormals flushed, the LLVM graphics default; the shader's MODE register is not read, and the hardware ignores the modifier in the other modes. On f16 results it is ignored, as on the hardware while f16 denormals are enabled; with them flushed the hardware applies it.