diff options
Diffstat (limited to '')
30 files changed, 512 insertions, 124 deletions
diff --git a/src/android/app/src/main/res/values/arrays.xml b/src/android/app/src/main/res/values/arrays.xml index ab435dce9..e3915ef4f 100644 --- a/src/android/app/src/main/res/values/arrays.xml +++ b/src/android/app/src/main/res/values/arrays.xml @@ -256,11 +256,13 @@ <string-array name="outputEngineEntries"> <item>@string/auto</item> + <item>@string/oboe</item> <item>@string/cubeb</item> <item>@string/string_null</item> </string-array> <integer-array name="outputEngineValues"> <item>0</item> + <item>4</item> <item>1</item> <item>3</item> </integer-array> diff --git a/src/android/app/src/main/res/values/strings.xml b/src/android/app/src/main/res/values/strings.xml index c86c43df2..0b80b04a4 100644 --- a/src/android/app/src/main/res/values/strings.xml +++ b/src/android/app/src/main/res/values/strings.xml @@ -503,6 +503,7 @@ <string name="theme_mode_dark">Dark</string> <!-- Audio output engines --> + <string name="oboe">oboe</string> <string name="cubeb">cubeb</string> <!-- Black backgrounds theme --> diff --git a/src/audio_core/CMakeLists.txt b/src/audio_core/CMakeLists.txt index 400988c5f..e982d03be 100644 --- a/src/audio_core/CMakeLists.txt +++ b/src/audio_core/CMakeLists.txt @@ -253,6 +253,17 @@ if (ENABLE_SDL2) target_compile_definitions(audio_core PRIVATE HAVE_SDL2) endif() +if (ANDROID) + target_sources(audio_core PRIVATE + sink/oboe_sink.cpp + sink/oboe_sink.h + ) + + # FIXME: this port seems broken, it cannot be imported with find_package(oboe REQUIRED) + target_link_libraries(audio_core PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/liboboe.a") + target_compile_definitions(audio_core PRIVATE HAVE_OBOE) +endif() + if (YUZU_USE_PRECOMPILED_HEADERS) target_precompile_headers(audio_core PRIVATE precompiled_headers.h) endif() diff --git a/src/audio_core/sink/cubeb_sink.cpp b/src/audio_core/sink/cubeb_sink.cpp index 51a23fe15..d97ca2a40 100644 --- a/src/audio_core/sink/cubeb_sink.cpp +++ b/src/audio_core/sink/cubeb_sink.cpp @@ -253,8 +253,9 @@ CubebSink::~CubebSink() { #endif } -SinkStream* CubebSink::AcquireSinkStream(Core::System& system, u32 system_channels, +SinkStream* CubebSink::AcquireSinkStream(Core::System& system, u32 system_channels_, const std::string& name, StreamType type) { + system_channels = system_channels_; SinkStreamPtr& stream = sink_streams.emplace_back(std::make_unique<CubebSinkStream>( ctx, device_channels, system_channels, output_device, input_device, name, type, system)); diff --git a/src/audio_core/sink/oboe_sink.cpp b/src/audio_core/sink/oboe_sink.cpp new file mode 100644 index 000000000..e61841172 --- /dev/null +++ b/src/audio_core/sink/oboe_sink.cpp @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include <span> +#include <vector> + +#include <oboe/Oboe.h> + +#include "audio_core/common/common.h" +#include "audio_core/sink/oboe_sink.h" +#include "audio_core/sink/sink_stream.h" +#include "common/logging/log.h" +#include "common/scope_exit.h" +#include "core/core.h" + +namespace AudioCore::Sink { + +class OboeSinkStream final : public SinkStream, + public oboe::AudioStreamDataCallback, + public oboe::AudioStreamErrorCallback { +public: + explicit OboeSinkStream(Core::System& system_, StreamType type_, const std::string& name_, + u32 system_channels_) + : SinkStream(system_, type_) { + name = name_; + system_channels = system_channels_; + + this->OpenStream(); + } + + ~OboeSinkStream() override { + LOG_INFO(Audio_Sink, "Destroyed Oboe stream"); + } + + void Finalize() override { + this->Stop(); + m_stream.reset(); + } + + void Start(bool resume = false) override { + if (!m_stream || !paused) { + return; + } + + paused = false; + + if (m_stream->start() != oboe::Result::OK) { + LOG_CRITICAL(Audio_Sink, "Error starting Oboe stream"); + } + } + + void Stop() override { + if (!m_stream || paused) { + return; + } + + this->SignalPause(); + + if (m_stream->stop() != oboe::Result::OK) { + LOG_CRITICAL(Audio_Sink, "Error stopping Oboe stream"); + } + } + +public: + static s32 QueryChannelCount(oboe::Direction direction) { + std::shared_ptr<oboe::AudioStream> temp_stream; + oboe::AudioStreamBuilder builder; + + const auto result = ConfigureBuilder(builder, direction)->openStream(temp_stream); + ASSERT(result == oboe::Result::OK); + + return temp_stream->getChannelCount() >= 6 ? 6 : 2; + } + +protected: + oboe::DataCallbackResult onAudioReady(oboe::AudioStream*, void* audio_data, + s32 num_buffer_frames) override { + const size_t num_channels = this->GetDeviceChannels(); + const size_t frame_size = num_channels; + const size_t num_frames = static_cast<size_t>(num_buffer_frames); + + if (type == StreamType::In) { + std::span<const s16> input_buffer{reinterpret_cast<const s16*>(audio_data), + num_frames * frame_size}; + this->ProcessAudioIn(input_buffer, num_frames); + } else { + std::span<s16> output_buffer{reinterpret_cast<s16*>(audio_data), + num_frames * frame_size}; + this->ProcessAudioOutAndRender(output_buffer, num_frames); + } + + return oboe::DataCallbackResult::Continue; + } + + void onErrorAfterClose(oboe::AudioStream*, oboe::Result) override { + LOG_INFO(Audio_Sink, "Audio stream closed, reinitializing"); + + if (this->OpenStream()) { + m_stream->start(); + } + } + +private: + static oboe::AudioStreamBuilder* ConfigureBuilder(oboe::AudioStreamBuilder& builder, + oboe::Direction direction) { + // TODO: investigate callback delay issues when using AAudio + return builder.setPerformanceMode(oboe::PerformanceMode::LowLatency) + ->setAudioApi(oboe::AudioApi::OpenSLES) + ->setDirection(direction) + ->setSampleRate(TargetSampleRate) + ->setSampleRateConversionQuality(oboe::SampleRateConversionQuality::High) + ->setFormat(oboe::AudioFormat::I16) + ->setFormatConversionAllowed(true) + ->setUsage(oboe::Usage::Game) + ->setBufferCapacityInFrames(TargetSampleCount * 2); + } + + bool OpenStream() { + const auto direction = [&]() { + switch (type) { + case StreamType::In: + return oboe::Direction::Input; + case StreamType::Out: + case StreamType::Render: + return oboe::Direction::Output; + default: + ASSERT(false); + return oboe::Direction::Output; + } + }(); + + const auto expected_channels = QueryChannelCount(direction); + const auto expected_mask = [&]() { + switch (expected_channels) { + case 1: + return oboe::ChannelMask::Mono; + case 2: + return oboe::ChannelMask::Stereo; + case 6: + return oboe::ChannelMask::CM5Point1; + default: + ASSERT(false); + return oboe::ChannelMask::Unspecified; + } + }(); + + oboe::AudioStreamBuilder builder; + const auto result = ConfigureBuilder(builder, direction) + ->setChannelCount(expected_channels) + ->setChannelMask(expected_mask) + ->setChannelConversionAllowed(true) + ->setDataCallback(this) + ->setErrorCallback(this) + ->openStream(m_stream); + ASSERT(result == oboe::Result::OK); + return result == oboe::Result::OK && this->SetStreamProperties(); + } + + bool SetStreamProperties() { + ASSERT(m_stream); + + m_stream->setBufferSizeInFrames(TargetSampleCount * 2); + device_channels = m_stream->getChannelCount(); + + const auto sample_rate = m_stream->getSampleRate(); + const auto buffer_capacity = m_stream->getBufferCapacityInFrames(); + const auto stream_backend = + m_stream->getAudioApi() == oboe::AudioApi::AAudio ? "AAudio" : "OpenSLES"; + + LOG_INFO(Audio_Sink, "Opened Oboe {} stream with {} channels sample rate {} capacity {}", + stream_backend, device_channels, sample_rate, buffer_capacity); + + return true; + } + + std::shared_ptr<oboe::AudioStream> m_stream{}; +}; + +OboeSink::OboeSink() { + // TODO: This is not generally knowable + // The channel count is distinct based on direction and can change + device_channels = OboeSinkStream::QueryChannelCount(oboe::Direction::Output); +} + +OboeSink::~OboeSink() = default; + +SinkStream* OboeSink::AcquireSinkStream(Core::System& system, u32 system_channels, + const std::string& name, StreamType type) { + SinkStreamPtr& stream = sink_streams.emplace_back( + std::make_unique<OboeSinkStream>(system, type, name, system_channels)); + + return stream.get(); +} + +void OboeSink::CloseStream(SinkStream* to_remove) { + sink_streams.remove_if([&](auto& stream) { return stream.get() == to_remove; }); +} + +void OboeSink::CloseStreams() { + sink_streams.clear(); +} + +f32 OboeSink::GetDeviceVolume() const { + if (sink_streams.empty()) { + return 1.0f; + } + + return sink_streams.front()->GetDeviceVolume(); +} + +void OboeSink::SetDeviceVolume(f32 volume) { + for (auto& stream : sink_streams) { + stream->SetDeviceVolume(volume); + } +} + +void OboeSink::SetSystemVolume(f32 volume) { + for (auto& stream : sink_streams) { + stream->SetSystemVolume(volume); + } +} + +} // namespace AudioCore::Sink diff --git a/src/audio_core/sink/oboe_sink.h b/src/audio_core/sink/oboe_sink.h new file mode 100644 index 000000000..8f6f54ab5 --- /dev/null +++ b/src/audio_core/sink/oboe_sink.h @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include <list> +#include <string> + +#include "audio_core/sink/sink.h" + +namespace Core { +class System; +} + +namespace AudioCore::Sink { +class SinkStream; + +class OboeSink final : public Sink { +public: + explicit OboeSink(); + ~OboeSink() override; + + /** + * Create a new sink stream. + * + * @param system - Core system. + * @param system_channels - Number of channels the audio system expects. + * May differ from the device's channel count. + * @param name - Name of this stream. + * @param type - Type of this stream, render/in/out. + * + * @return A pointer to the created SinkStream + */ + SinkStream* AcquireSinkStream(Core::System& system, u32 system_channels, + const std::string& name, StreamType type) override; + + /** + * Close a given stream. + * + * @param stream - The stream to close. + */ + void CloseStream(SinkStream* stream) override; + + /** + * Close all streams. + */ + void CloseStreams() override; + + /** + * Get the device volume. Set from calls to the IAudioDevice service. + * + * @return Volume of the device. + */ + f32 GetDeviceVolume() const override; + + /** + * Set the device volume. Set from calls to the IAudioDevice service. + * + * @param volume - New volume of the device. + */ + void SetDeviceVolume(f32 volume) override; + + /** + * Set the system volume. Comes from the audio system using this stream. + * + * @param volume - New volume of the system. + */ + void SetSystemVolume(f32 volume) override; + +private: + /// List of streams managed by this sink + std::list<SinkStreamPtr> sink_streams{}; +}; + +} // namespace AudioCore::Sink diff --git a/src/audio_core/sink/sdl2_sink.cpp b/src/audio_core/sink/sdl2_sink.cpp index 96e0efce2..7dd155ff0 100644 --- a/src/audio_core/sink/sdl2_sink.cpp +++ b/src/audio_core/sink/sdl2_sink.cpp @@ -168,8 +168,9 @@ SDLSink::SDLSink(std::string_view target_device_name) { SDLSink::~SDLSink() = default; -SinkStream* SDLSink::AcquireSinkStream(Core::System& system, u32 system_channels, +SinkStream* SDLSink::AcquireSinkStream(Core::System& system, u32 system_channels_, const std::string&, StreamType type) { + system_channels = system_channels_; SinkStreamPtr& stream = sink_streams.emplace_back(std::make_unique<SDLSinkStream>( device_channels, system_channels, output_device, input_device, type, system)); return stream.get(); diff --git a/src/audio_core/sink/sink.h b/src/audio_core/sink/sink.h index f28c6d126..e22e8c3e5 100644 --- a/src/audio_core/sink/sink.h +++ b/src/audio_core/sink/sink.h @@ -85,9 +85,21 @@ public: */ virtual void SetSystemVolume(f32 volume) = 0; + /** + * Get the number of channels the game has set, can be different to the host hardware's support. + * Either 2 or 6. + * + * @return Number of device channels. + */ + u32 GetSystemChannels() const { + return system_channels; + } + protected: /// Number of device channels supported by the hardware u32 device_channels{2}; + /// Number of channels the game is sending + u32 system_channels{2}; }; using SinkPtr = std::unique_ptr<Sink>; diff --git a/src/audio_core/sink/sink_details.cpp b/src/audio_core/sink/sink_details.cpp index 7c9a4e3ac..449af659d 100644 --- a/src/audio_core/sink/sink_details.cpp +++ b/src/audio_core/sink/sink_details.cpp @@ -7,6 +7,9 @@ #include <vector> #include "audio_core/sink/sink_details.h" +#ifdef HAVE_OBOE +#include "audio_core/sink/oboe_sink.h" +#endif #ifdef HAVE_CUBEB #include "audio_core/sink/cubeb_sink.h" #endif @@ -36,6 +39,16 @@ struct SinkDetails { // sink_details is ordered in terms of desirability, with the best choice at the top. constexpr SinkDetails sink_details[] = { +#ifdef HAVE_OBOE + SinkDetails{ + Settings::AudioEngine::Oboe, + [](std::string_view device_id) -> std::unique_ptr<Sink> { + return std::make_unique<OboeSink>(); + }, + [](bool capture) { return std::vector<std::string>{"Default"}; }, + []() { return true; }, + }, +#endif #ifdef HAVE_CUBEB SinkDetails{ Settings::AudioEngine::Cubeb, diff --git a/src/audio_core/sink/sink_stream.cpp b/src/audio_core/sink/sink_stream.cpp index 2a09db599..c047b0668 100644 --- a/src/audio_core/sink/sink_stream.cpp +++ b/src/audio_core/sink/sink_stream.cpp @@ -40,29 +40,36 @@ void SinkStream::AppendBuffer(SinkBuffer& buffer, std::span<s16> samples) { if (system_channels == 6 && device_channels == 2) { // We're given 6 channels, but our device only outputs 2, so downmix. - static constexpr std::array<f32, 4> down_mix_coeff{1.0f, 0.707f, 0.251f, 0.707f}; + // Front = 1.0 + // Center = 0.596 + // LFE = 0.354 + // Back = 0.707 + static constexpr std::array<f32, 4> down_mix_coeff{1.0, 0.596f, 0.354f, 0.707f}; for (u32 read_index = 0, write_index = 0; read_index < samples.size(); read_index += system_channels, write_index += device_channels) { + const auto fl = + static_cast<f32>(samples[read_index + static_cast<u32>(Channels::FrontLeft)]); + const auto fr = + static_cast<f32>(samples[read_index + static_cast<u32>(Channels::FrontRight)]); + const auto c = + static_cast<f32>(samples[read_index + static_cast<u32>(Channels::Center)]); + const auto lfe = + static_cast<f32>(samples[read_index + static_cast<u32>(Channels::LFE)]); + const auto bl = + static_cast<f32>(samples[read_index + static_cast<u32>(Channels::BackLeft)]); + const auto br = + static_cast<f32>(samples[read_index + static_cast<u32>(Channels::BackRight)]); + const auto left_sample{ - ((Common::FixedPoint<49, 15>( - samples[read_index + static_cast<u32>(Channels::FrontLeft)]) * - down_mix_coeff[0] + - samples[read_index + static_cast<u32>(Channels::Center)] * down_mix_coeff[1] + - samples[read_index + static_cast<u32>(Channels::LFE)] * down_mix_coeff[2] + - samples[read_index + static_cast<u32>(Channels::BackLeft)] * down_mix_coeff[3]) * - volume) - .to_int()}; + static_cast<s32>((fl * down_mix_coeff[0] + c * down_mix_coeff[1] + + lfe * down_mix_coeff[2] + bl * down_mix_coeff[3]) * + volume)}; const auto right_sample{ - ((Common::FixedPoint<49, 15>( - samples[read_index + static_cast<u32>(Channels::FrontRight)]) * - down_mix_coeff[0] + - samples[read_index + static_cast<u32>(Channels::Center)] * down_mix_coeff[1] + - samples[read_index + static_cast<u32>(Channels::LFE)] * down_mix_coeff[2] + - samples[read_index + static_cast<u32>(Channels::BackRight)] * down_mix_coeff[3]) * - volume) - .to_int()}; + static_cast<s32>((fr * down_mix_coeff[0] + c * down_mix_coeff[1] + + lfe * down_mix_coeff[2] + br * down_mix_coeff[3]) * + volume)}; samples[write_index + static_cast<u32>(Channels::FrontLeft)] = static_cast<s16>(std::clamp(left_sample, min, max)); diff --git a/src/common/fs/path_util.cpp b/src/common/fs/path_util.cpp index d2f50432a..4f69db6f5 100644 --- a/src/common/fs/path_util.cpp +++ b/src/common/fs/path_util.cpp @@ -418,9 +418,9 @@ std::string SanitizePath(std::string_view path_, DirectorySeparator directory_se return std::string(RemoveTrailingSlash(path)); } -std::string_view GetParentPath(std::string_view path) { +std::string GetParentPath(std::string_view path) { if (path.empty()) { - return path; + return std::string(path); } #ifdef ANDROID @@ -439,7 +439,7 @@ std::string_view GetParentPath(std::string_view path) { name_index = std::max(name_bck_index, name_fwd_index); } - return path.substr(0, name_index); + return std::string(path.substr(0, name_index)); } std::string_view GetPathWithoutTop(std::string_view path) { diff --git a/src/common/fs/path_util.h b/src/common/fs/path_util.h index 23c8b1359..59301e7ed 100644 --- a/src/common/fs/path_util.h +++ b/src/common/fs/path_util.h @@ -302,7 +302,7 @@ enum class DirectorySeparator { DirectorySeparator directory_separator = DirectorySeparator::ForwardSlash); // Gets all of the text up to the last '/' or '\' in the path. -[[nodiscard]] std::string_view GetParentPath(std::string_view path); +[[nodiscard]] std::string GetParentPath(std::string_view path); // Gets all of the text after the first '/' or '\' in the path. [[nodiscard]] std::string_view GetPathWithoutTop(std::string_view path); diff --git a/src/common/settings_enums.h b/src/common/settings_enums.h index d6351e57e..617036588 100644 --- a/src/common/settings_enums.h +++ b/src/common/settings_enums.h @@ -82,16 +82,15 @@ enum class AudioEngine : u32 { Cubeb, Sdl2, Null, + Oboe, }; template <> inline std::vector<std::pair<std::string, AudioEngine>> EnumMetadata<AudioEngine>::Canonicalizations() { return { - {"auto", AudioEngine::Auto}, - {"cubeb", AudioEngine::Cubeb}, - {"sdl2", AudioEngine::Sdl2}, - {"null", AudioEngine::Null}, + {"auto", AudioEngine::Auto}, {"cubeb", AudioEngine::Cubeb}, {"sdl2", AudioEngine::Sdl2}, + {"null", AudioEngine::Null}, {"oboe", AudioEngine::Oboe}, }; } diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp index 2f09cade5..23e56c77a 100644 --- a/src/core/hle/service/audio/audren_u.cpp +++ b/src/core/hle/service/audio/audren_u.cpp @@ -359,7 +359,7 @@ private: void GetActiveChannelCount(HLERequestContext& ctx) { const auto& sink{system.AudioCore().GetOutputSink()}; - u32 channel_count{sink.GetDeviceChannels()}; + u32 channel_count{sink.GetSystemChannels()}; LOG_DEBUG(Service_Audio, "(STUBBED) called. Channels={}", channel_count); diff --git a/src/core/hle/service/filesystem/filesystem.h b/src/core/hle/service/filesystem/filesystem.h index e7e7c4c28..276d264e1 100644 --- a/src/core/hle/service/filesystem/filesystem.h +++ b/src/core/hle/service/filesystem/filesystem.h @@ -54,6 +54,13 @@ enum class ImageDirectoryId : u32 { SdCard, }; +enum class OpenDirectoryMode : u64 { + Directory = (1 << 0), + File = (1 << 1), + All = Directory | File +}; +DECLARE_ENUM_FLAG_OPERATORS(OpenDirectoryMode); + class FileSystemController { public: explicit FileSystemController(Core::System& system_); diff --git a/src/core/hle/service/filesystem/fsp_srv.cpp b/src/core/hle/service/filesystem/fsp_srv.cpp index b1310d6e4..82ecc1b90 100644 --- a/src/core/hle/service/filesystem/fsp_srv.cpp +++ b/src/core/hle/service/filesystem/fsp_srv.cpp @@ -259,7 +259,7 @@ static void BuildEntryIndex(std::vector<FileSys::Entry>& entries, const std::vec class IDirectory final : public ServiceFramework<IDirectory> { public: - explicit IDirectory(Core::System& system_, FileSys::VirtualDir backend_) + explicit IDirectory(Core::System& system_, FileSys::VirtualDir backend_, OpenDirectoryMode mode) : ServiceFramework{system_, "IDirectory"}, backend(std::move(backend_)) { static const FunctionInfo functions[] = { {0, &IDirectory::Read, "Read"}, @@ -269,8 +269,12 @@ public: // TODO(DarkLordZach): Verify that this is the correct behavior. // Build entry index now to save time later. - BuildEntryIndex(entries, backend->GetFiles(), FileSys::EntryType::File); - BuildEntryIndex(entries, backend->GetSubdirectories(), FileSys::EntryType::Directory); + if (True(mode & OpenDirectoryMode::Directory)) { + BuildEntryIndex(entries, backend->GetSubdirectories(), FileSys::EntryType::Directory); + } + if (True(mode & OpenDirectoryMode::File)) { + BuildEntryIndex(entries, backend->GetFiles(), FileSys::EntryType::File); + } } private: @@ -446,11 +450,9 @@ public: const auto file_buffer = ctx.ReadBuffer(); const std::string name = Common::StringFromBuffer(file_buffer); + const auto mode = rp.PopRaw<OpenDirectoryMode>(); - // TODO(Subv): Implement this filter. - const u32 filter_flags = rp.Pop<u32>(); - - LOG_DEBUG(Service_FS, "called. directory={}, filter={}", name, filter_flags); + LOG_DEBUG(Service_FS, "called. directory={}, mode={}", name, mode); FileSys::VirtualDir vfs_dir{}; auto result = backend.OpenDirectory(&vfs_dir, name); @@ -460,7 +462,7 @@ public: return; } - auto directory = std::make_shared<IDirectory>(system, vfs_dir); + auto directory = std::make_shared<IDirectory>(system, vfs_dir, mode); IPC::ResponseBuilder rb{ctx, 2, 0, 1}; rb.Push(ResultSuccess); diff --git a/src/core/hle/service/nvnflinger/buffer_queue_consumer.cpp b/src/core/hle/service/nvnflinger/buffer_queue_consumer.cpp index d91886bed..bbe8e06d4 100644 --- a/src/core/hle/service/nvnflinger/buffer_queue_consumer.cpp +++ b/src/core/hle/service/nvnflinger/buffer_queue_consumer.cpp @@ -90,6 +90,18 @@ Status BufferQueueConsumer::AcquireBuffer(BufferItem* out_buffer, LOG_DEBUG(Service_Nvnflinger, "acquiring slot={}", slot); + // If the front buffer is still being tracked, update its slot state + if (core->StillTracking(*front)) { + slots[slot].acquire_called = true; + slots[slot].needs_cleanup_on_release = false; + slots[slot].buffer_state = BufferState::Acquired; + + // TODO: for now, avoid resetting the fence, so that when we next return this + // slot to the producer, it will wait for the fence to pass. We should fix this + // by properly waiting for the fence in the BufferItemConsumer. + // slots[slot].fence = Fence::NoFence(); + } + // If the buffer has previously been acquired by the consumer, set graphic_buffer to nullptr to // avoid unnecessarily remapping this buffer on the consumer side. if (out_buffer->acquire_called) { @@ -132,11 +144,28 @@ Status BufferQueueConsumer::ReleaseBuffer(s32 slot, u64 frame_number, const Fenc ++current; } - slots[slot].buffer_state = BufferState::Free; + if (slots[slot].buffer_state == BufferState::Acquired) { + // TODO: for now, avoid resetting the fence, so that when we next return this + // slot to the producer, it can wait for its own fence to pass. We should fix this + // by properly waiting for the fence in the BufferItemConsumer. + // slots[slot].fence = release_fence; + slots[slot].buffer_state = BufferState::Free; - listener = core->connected_producer_listener; + listener = core->connected_producer_listener; - LOG_DEBUG(Service_Nvnflinger, "releasing slot {}", slot); + LOG_DEBUG(Service_Nvnflinger, "releasing slot {}", slot); + } else if (slots[slot].needs_cleanup_on_release) { + LOG_DEBUG(Service_Nvnflinger, "releasing a stale buffer slot {} (state = {})", slot, + slots[slot].buffer_state); + slots[slot].needs_cleanup_on_release = false; + return Status::StaleBufferSlot; + } else { + LOG_ERROR(Service_Nvnflinger, + "attempted to release buffer slot {} but its state was {}", slot, + slots[slot].buffer_state); + + return Status::BadValue; + } core->SignalDequeueCondition(); } diff --git a/src/core/hle/service/nvnflinger/buffer_queue_core.cpp b/src/core/hle/service/nvnflinger/buffer_queue_core.cpp index 4ed5e5978..5d8c861fa 100644 --- a/src/core/hle/service/nvnflinger/buffer_queue_core.cpp +++ b/src/core/hle/service/nvnflinger/buffer_queue_core.cpp @@ -74,6 +74,10 @@ void BufferQueueCore::FreeBufferLocked(s32 slot) { slots[slot].graphic_buffer.reset(); + if (slots[slot].buffer_state == BufferState::Acquired) { + slots[slot].needs_cleanup_on_release = true; + } + slots[slot].buffer_state = BufferState::Free; slots[slot].frame_number = UINT32_MAX; slots[slot].acquire_called = false; diff --git a/src/core/hle/service/nvnflinger/buffer_slot.h b/src/core/hle/service/nvnflinger/buffer_slot.h index d25bca049..37daca78b 100644 --- a/src/core/hle/service/nvnflinger/buffer_slot.h +++ b/src/core/hle/service/nvnflinger/buffer_slot.h @@ -31,6 +31,7 @@ struct BufferSlot final { u64 frame_number{}; Fence fence; bool acquire_called{}; + bool needs_cleanup_on_release{}; bool attached_by_consumer{}; bool is_preallocated{}; }; diff --git a/src/tests/video_core/memory_tracker.cpp b/src/tests/video_core/memory_tracker.cpp index 2dbff21af..618793668 100644 --- a/src/tests/video_core/memory_tracker.cpp +++ b/src/tests/video_core/memory_tracker.cpp @@ -23,13 +23,13 @@ constexpr VAddr c = 16 * HIGH_PAGE_SIZE; class RasterizerInterface { public: - void UpdatePagesCachedCount(VAddr addr, u64 size, bool cache) { + void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) { const u64 page_start{addr >> Core::Memory::YUZU_PAGEBITS}; const u64 page_end{(addr + size + Core::Memory::YUZU_PAGESIZE - 1) >> Core::Memory::YUZU_PAGEBITS}; for (u64 page = page_start; page < page_end; ++page) { int& value = page_table[page]; - value += (cache ? 1 : -1); + value += delta; if (value < 0) { throw std::logic_error{"negative page"}; } @@ -546,4 +546,4 @@ TEST_CASE("MemoryTracker: Cached write downloads") { REQUIRE(!memory_track->IsRegionGpuModified(c + PAGE, PAGE)); memory_track->MarkRegionAsCpuModified(c, WORD); REQUIRE(rasterizer.Count() == 0); -} +}
\ No newline at end of file diff --git a/src/video_core/buffer_cache/word_manager.h b/src/video_core/buffer_cache/word_manager.h index 95b752055..a336bde41 100644 --- a/src/video_core/buffer_cache/word_manager.h +++ b/src/video_core/buffer_cache/word_manager.h @@ -473,7 +473,7 @@ private: VAddr addr = cpu_addr + word_index * BYTES_PER_WORD; IteratePages(changed_bits, [&](size_t offset, size_t size) { rasterizer->UpdatePagesCachedCount(addr + offset * BYTES_PER_PAGE, - size * BYTES_PER_PAGE, add_to_rasterizer); + size * BYTES_PER_PAGE, add_to_rasterizer ? 1 : -1); }); } diff --git a/src/video_core/rasterizer_accelerated.cpp b/src/video_core/rasterizer_accelerated.cpp index 3c9477f6e..f200a650f 100644 --- a/src/video_core/rasterizer_accelerated.cpp +++ b/src/video_core/rasterizer_accelerated.cpp @@ -3,7 +3,6 @@ #include <atomic> -#include "common/alignment.h" #include "common/assert.h" #include "common/common_types.h" #include "common/div_ceil.h" @@ -12,65 +11,61 @@ namespace VideoCore { -static constexpr u16 IdentityValue = 1; - using namespace Core::Memory; -RasterizerAccelerated::RasterizerAccelerated(Memory& cpu_memory_) : map{}, cpu_memory{cpu_memory_} { - // We are tracking CPU memory, which cannot map more than 39 bits. - const VAddr start_address = 0; - const VAddr end_address = (1ULL << 39); - const IntervalType address_space_interval(start_address, end_address); - const auto value = std::make_pair(address_space_interval, IdentityValue); - - map.add(value); -} +RasterizerAccelerated::RasterizerAccelerated(Memory& cpu_memory_) + : cached_pages(std::make_unique<CachedPages>()), cpu_memory{cpu_memory_} {} RasterizerAccelerated::~RasterizerAccelerated() = default; -void RasterizerAccelerated::UpdatePagesCachedCount(VAddr addr, u64 size, bool cache) { - std::scoped_lock lk{map_lock}; - - // Align sizes. - addr = Common::AlignDown(addr, YUZU_PAGESIZE); - size = Common::AlignUp(size, YUZU_PAGESIZE); - - // Declare the overall interval we are going to operate on. - const VAddr start_address = addr; - const VAddr end_address = addr + size; - const IntervalType modification_range(start_address, end_address); - - // Find the boundaries of where to iterate. - const auto lower = map.lower_bound(modification_range); - const auto upper = map.upper_bound(modification_range); - - // Iterate over the contained intervals. - for (auto it = lower; it != upper; it++) { - // Intersect interval range with modification range. - const auto current_range = modification_range & it->first; - - // Calculate the address and size to operate over. - const auto current_addr = current_range.lower(); - const auto current_size = current_range.upper() - current_addr; - - // Get the current value of the range. - const auto value = it->second; +void RasterizerAccelerated::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) { + u64 uncache_begin = 0; + u64 cache_begin = 0; + u64 uncache_bytes = 0; + u64 cache_bytes = 0; + + std::atomic_thread_fence(std::memory_order_acquire); + const u64 page_end = Common::DivCeil(addr + size, YUZU_PAGESIZE); + for (u64 page = addr >> YUZU_PAGEBITS; page != page_end; ++page) { + std::atomic_uint16_t& count = cached_pages->at(page >> 2).Count(page); + + if (delta > 0) { + ASSERT_MSG(count.load(std::memory_order::relaxed) < UINT16_MAX, "Count may overflow!"); + } else if (delta < 0) { + ASSERT_MSG(count.load(std::memory_order::relaxed) > 0, "Count may underflow!"); + } else { + ASSERT_MSG(false, "Delta must be non-zero!"); + } - if (cache && value == IdentityValue) { - // If we are going to cache, and the value is not yet referenced, then cache this range. - cpu_memory.RasterizerMarkRegionCached(current_addr, current_size, true); - } else if (!cache && value == IdentityValue + 1) { - // If we are going to uncache, and this is the last reference, then uncache this range. - cpu_memory.RasterizerMarkRegionCached(current_addr, current_size, false); + // Adds or subtracts 1, as count is a unsigned 8-bit value + count.fetch_add(static_cast<u16>(delta), std::memory_order_release); + + // Assume delta is either -1 or 1 + if (count.load(std::memory_order::relaxed) == 0) { + if (uncache_bytes == 0) { + uncache_begin = page; + } + uncache_bytes += YUZU_PAGESIZE; + } else if (uncache_bytes > 0) { + cpu_memory.RasterizerMarkRegionCached(uncache_begin << YUZU_PAGEBITS, uncache_bytes, + false); + uncache_bytes = 0; + } + if (count.load(std::memory_order::relaxed) == 1 && delta > 0) { + if (cache_bytes == 0) { + cache_begin = page; + } + cache_bytes += YUZU_PAGESIZE; + } else if (cache_bytes > 0) { + cpu_memory.RasterizerMarkRegionCached(cache_begin << YUZU_PAGEBITS, cache_bytes, true); + cache_bytes = 0; } } - - // Update the set. - const auto value = std::make_pair(modification_range, IdentityValue); - if (cache) { - map.add(value); - } else { - map.subtract(value); + if (uncache_bytes > 0) { + cpu_memory.RasterizerMarkRegionCached(uncache_begin << YUZU_PAGEBITS, uncache_bytes, false); + } + if (cache_bytes > 0) { + cpu_memory.RasterizerMarkRegionCached(cache_begin << YUZU_PAGEBITS, cache_bytes, true); } } diff --git a/src/video_core/rasterizer_accelerated.h b/src/video_core/rasterizer_accelerated.h index f1968f186..e6c0ea87a 100644 --- a/src/video_core/rasterizer_accelerated.h +++ b/src/video_core/rasterizer_accelerated.h @@ -3,8 +3,8 @@ #pragma once -#include <mutex> -#include <boost/icl/interval_map.hpp> +#include <array> +#include <atomic> #include "common/common_types.h" #include "video_core/rasterizer_interface.h" @@ -21,17 +21,28 @@ public: explicit RasterizerAccelerated(Core::Memory::Memory& cpu_memory_); ~RasterizerAccelerated() override; - void UpdatePagesCachedCount(VAddr addr, u64 size, bool cache) override; + void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) override; private: - using PageIndex = VAddr; - using PageReferenceCount = u16; + class CacheEntry final { + public: + CacheEntry() = default; - using IntervalMap = boost::icl::interval_map<PageIndex, PageReferenceCount>; - using IntervalType = IntervalMap::interval_type; + std::atomic_uint16_t& Count(std::size_t page) { + return values[page & 3]; + } - IntervalMap map; - std::mutex map_lock; + const std::atomic_uint16_t& Count(std::size_t page) const { + return values[page & 3]; + } + + private: + std::array<std::atomic_uint16_t, 4> values{}; + }; + static_assert(sizeof(CacheEntry) == 8, "CacheEntry should be 8 bytes!"); + + using CachedPages = std::array<CacheEntry, 0x2000000>; + std::unique_ptr<CachedPages> cached_pages; Core::Memory::Memory& cpu_memory; }; diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h index fd42d26b5..af1469147 100644 --- a/src/video_core/rasterizer_interface.h +++ b/src/video_core/rasterizer_interface.h @@ -162,7 +162,7 @@ public: } /// Increase/decrease the number of object in pages touching the specified region - virtual void UpdatePagesCachedCount(VAddr addr, u64 size, bool cache) {} + virtual void UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {} /// Initialize disk cached resources for the game being emulated virtual void LoadDiskResources(u64 title_id, std::stop_token stop_loading, diff --git a/src/video_core/shader_cache.cpp b/src/video_core/shader_cache.cpp index a109f9cbe..e81cd031b 100644 --- a/src/video_core/shader_cache.cpp +++ b/src/video_core/shader_cache.cpp @@ -132,7 +132,7 @@ void ShaderCache::Register(std::unique_ptr<ShaderInfo> data, VAddr addr, size_t storage.push_back(std::move(data)); - rasterizer.UpdatePagesCachedCount(addr, size, true); + rasterizer.UpdatePagesCachedCount(addr, size, 1); } void ShaderCache::InvalidatePagesInRegion(VAddr addr, size_t size) { @@ -209,7 +209,7 @@ void ShaderCache::UnmarkMemory(Entry* entry) { const VAddr addr = entry->addr_start; const size_t size = entry->addr_end - addr; - rasterizer.UpdatePagesCachedCount(addr, size, false); + rasterizer.UpdatePagesCachedCount(addr, size, -1); } void ShaderCache::RemoveShadersFromStorage(std::span<ShaderInfo*> removed_shaders) { diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h index d7941f6a4..0d5a1709f 100644 --- a/src/video_core/texture_cache/texture_cache.h +++ b/src/video_core/texture_cache/texture_cache.h @@ -2080,7 +2080,7 @@ void TextureCache<P>::TrackImage(ImageBase& image, ImageId image_id) { ASSERT(False(image.flags & ImageFlagBits::Tracked)); image.flags |= ImageFlagBits::Tracked; if (False(image.flags & ImageFlagBits::Sparse)) { - rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, true); + rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, 1); return; } if (True(image.flags & ImageFlagBits::Registered)) { @@ -2091,13 +2091,13 @@ void TextureCache<P>::TrackImage(ImageBase& image, ImageId image_id) { const auto& map = slot_map_views[map_view_id]; const VAddr cpu_addr = map.cpu_addr; const std::size_t size = map.size; - rasterizer.UpdatePagesCachedCount(cpu_addr, size, true); + rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1); } return; } ForEachSparseSegment(image, [this]([[maybe_unused]] GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) { - rasterizer.UpdatePagesCachedCount(cpu_addr, size, true); + rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1); }); } @@ -2106,7 +2106,7 @@ void TextureCache<P>::UntrackImage(ImageBase& image, ImageId image_id) { ASSERT(True(image.flags & ImageFlagBits::Tracked)); image.flags &= ~ImageFlagBits::Tracked; if (False(image.flags & ImageFlagBits::Sparse)) { - rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, false); + rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, -1); return; } ASSERT(True(image.flags & ImageFlagBits::Registered)); @@ -2117,7 +2117,7 @@ void TextureCache<P>::UntrackImage(ImageBase& image, ImageId image_id) { const auto& map = slot_map_views[map_view_id]; const VAddr cpu_addr = map.cpu_addr; const std::size_t size = map.size; - rasterizer.UpdatePagesCachedCount(cpu_addr, size, false); + rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1); } } diff --git a/src/yuzu/configuration/configure_ui.cpp b/src/yuzu/configuration/configure_ui.cpp index dd43f0a0e..c8e871151 100644 --- a/src/yuzu/configuration/configure_ui.cpp +++ b/src/yuzu/configuration/configure_ui.cpp @@ -193,8 +193,8 @@ void ConfigureUi::RequestGameListUpdate() { void ConfigureUi::SetConfiguration() { ui->theme_combobox->setCurrentIndex( ui->theme_combobox->findData(QString::fromStdString(UISettings::values.theme))); - ui->language_combobox->setCurrentIndex( - ui->language_combobox->findData(QString::fromStdString(UISettings::values.language))); + ui->language_combobox->setCurrentIndex(ui->language_combobox->findData( + QString::fromStdString(UISettings::values.language.GetValue()))); ui->show_add_ons->setChecked(UISettings::values.show_add_ons.GetValue()); ui->show_compat->setChecked(UISettings::values.show_compat.GetValue()); ui->show_size->setChecked(UISettings::values.show_size.GetValue()); diff --git a/src/yuzu/configuration/qt_config.cpp b/src/yuzu/configuration/qt_config.cpp index 636c5e640..417a43ec5 100644 --- a/src/yuzu/configuration/qt_config.cpp +++ b/src/yuzu/configuration/qt_config.cpp @@ -187,7 +187,6 @@ void QtConfig::ReadPathValues() { BeginGroup(Settings::TranslateCategory(Settings::Category::Paths)); UISettings::values.roms_path = ReadStringSetting(std::string("romsPath")); - UISettings::values.symbols_path = ReadStringSetting(std::string("symbolsPath")); UISettings::values.game_dir_deprecated = ReadStringSetting(std::string("gameListRootDir"), std::string(".")); UISettings::values.game_dir_deprecated_deepscan = @@ -225,8 +224,6 @@ void QtConfig::ReadPathValues() { UISettings::values.recent_files = QString::fromStdString(ReadStringSetting(std::string("recentFiles"))) .split(QStringLiteral(", "), Qt::SkipEmptyParts, Qt::CaseSensitive); - UISettings::values.language = - ReadStringSetting(std::string("language"), std::make_optional(std::string(""))); EndGroup(); } @@ -409,7 +406,6 @@ void QtConfig::SavePathValues() { BeginGroup(Settings::TranslateCategory(Settings::Category::Paths)); WriteSetting(std::string("romsPath"), UISettings::values.roms_path); - WriteSetting(std::string("symbolsPath"), UISettings::values.symbols_path); BeginArray(std::string("gamedirs")); for (int i = 0; i < UISettings::values.game_dirs.size(); ++i) { SetArrayIndex(i); @@ -422,7 +418,6 @@ void QtConfig::SavePathValues() { WriteSetting(std::string("recentFiles"), UISettings::values.recent_files.join(QStringLiteral(", ")).toStdString()); - WriteSetting(std::string("language"), UISettings::values.language); EndGroup(); } diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index f31ed7ebb..059fcf041 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -5147,12 +5147,12 @@ void GMainWindow::UpdateUITheme() { void GMainWindow::LoadTranslation() { bool loaded; - if (UISettings::values.language.empty()) { + if (UISettings::values.language.GetValue().empty()) { // If the selected language is empty, use system locale loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/")); } else { // Otherwise load from the specified file - loaded = translator.load(QString::fromStdString(UISettings::values.language), + loaded = translator.load(QString::fromStdString(UISettings::values.language.GetValue()), QStringLiteral(":/languages/")); } @@ -5164,7 +5164,7 @@ void GMainWindow::LoadTranslation() { } void GMainWindow::OnLanguageChanged(const QString& locale) { - if (UISettings::values.language != std::string("en")) { + if (UISettings::values.language.GetValue() != std::string("en")) { qApp->removeTranslator(&translator); } diff --git a/src/yuzu/uisettings.h b/src/yuzu/uisettings.h index 549a39e1b..f9906be33 100644 --- a/src/yuzu/uisettings.h +++ b/src/yuzu/uisettings.h @@ -154,12 +154,11 @@ struct Values { Setting<u32> screenshot_height{linkage, 0, "screenshot_height", Category::Screenshots}; std::string roms_path; - std::string symbols_path; std::string game_dir_deprecated; bool game_dir_deprecated_deepscan; QVector<GameDir> game_dirs; QStringList recent_files; - std::string language; + Setting<std::string> language{linkage, {}, "language", Category::Paths}; std::string theme; |