diff options
author | James Rowe <jroweboy@gmail.com> | 2018-01-12 03:21:20 +0100 |
---|---|---|
committer | James Rowe <jroweboy@gmail.com> | 2018-01-13 03:11:03 +0100 |
commit | ebf9a784a9f7f4148a669dbb39e7cd50df779a14 (patch) | |
tree | d585685a1c0a34b903af1d086d62560bf56bb29f /src | |
parent | config: Default CPU core to Unicorn. (diff) | |
download | yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.tar yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.tar.gz yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.tar.bz2 yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.tar.lz yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.tar.xz yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.tar.zst yuzu-ebf9a784a9f7f4148a669dbb39e7cd50df779a14.zip |
Diffstat (limited to '')
-rw-r--r-- | src/CMakeLists.txt | 9 | ||||
-rw-r--r-- | src/audio_core/CMakeLists.txt | 44 | ||||
-rw-r--r-- | src/audio_core/audio_core.cpp | 61 | ||||
-rw-r--r-- | src/audio_core/audio_core.h | 31 | ||||
-rw-r--r-- | src/audio_core/codec.cpp | 127 | ||||
-rw-r--r-- | src/audio_core/codec.h | 51 | ||||
-rw-r--r-- | src/audio_core/hle/common.h | 34 | ||||
-rw-r--r-- | src/audio_core/hle/dsp.cpp | 172 | ||||
-rw-r--r-- | src/audio_core/hle/dsp.h | 595 | ||||
-rw-r--r-- | src/audio_core/hle/filter.cpp | 117 | ||||
-rw-r--r-- | src/audio_core/hle/filter.h | 117 | ||||
-rw-r--r-- | src/audio_core/hle/mixers.cpp | 210 | ||||
-rw-r--r-- | src/audio_core/hle/mixers.h | 61 | ||||
-rw-r--r-- | src/audio_core/hle/pipe.cpp | 177 | ||||
-rw-r--r-- | src/audio_core/hle/pipe.h | 63 | ||||
-rw-r--r-- | src/audio_core/hle/source.cpp | 349 | ||||
-rw-r--r-- | src/audio_core/hle/source.h | 149 | ||||
-rw-r--r-- | src/audio_core/interpolate.cpp | 76 | ||||
-rw-r--r-- | src/audio_core/interpolate.h | 49 | ||||
-rw-r--r-- | src/audio_core/null_sink.h | 34 | ||||
-rw-r--r-- | src/audio_core/sdl2_sink.cpp | 147 | ||||
-rw-r--r-- | src/audio_core/sdl2_sink.h | 34 | ||||
-rw-r--r-- | src/audio_core/sink.h | 45 | ||||
-rw-r--r-- | src/audio_core/sink_details.cpp | 42 | ||||
-rw-r--r-- | src/audio_core/sink_details.h | 29 | ||||
-rw-r--r-- | src/audio_core/time_stretch.cpp | 143 | ||||
-rw-r--r-- | src/audio_core/time_stretch.h | 60 | ||||
-rw-r--r-- | src/network/CMakeLists.txt | 18 | ||||
-rw-r--r-- | src/network/network.cpp | 50 | ||||
-rw-r--r-- | src/network/network.h | 25 | ||||
-rw-r--r-- | src/network/packet.cpp | 263 | ||||
-rw-r--r-- | src/network/packet.h | 166 | ||||
-rw-r--r-- | src/network/room.cpp | 497 | ||||
-rw-r--r-- | src/network/room.h | 101 | ||||
-rw-r--r-- | src/network/room_member.cpp | 490 | ||||
-rw-r--r-- | src/network/room_member.h | 182 | ||||
-rw-r--r-- | src/web_service/CMakeLists.txt | 16 | ||||
-rw-r--r-- | src/web_service/telemetry_json.cpp | 86 | ||||
-rw-r--r-- | src/web_service/telemetry_json.h | 59 | ||||
-rw-r--r-- | src/web_service/verify_login.cpp | 28 | ||||
-rw-r--r-- | src/web_service/verify_login.h | 24 | ||||
-rw-r--r-- | src/web_service/web_backend.cpp | 140 | ||||
-rw-r--r-- | src/web_service/web_backend.h | 39 | ||||
-rw-r--r-- | src/yuzu/CMakeLists.txt (renamed from src/citra_qt/CMakeLists.txt) | 22 | ||||
-rw-r--r-- | src/yuzu/Info.plist (renamed from src/citra_qt/Info.plist) | 0 | ||||
-rw-r--r-- | src/yuzu/bootmanager.cpp (renamed from src/citra_qt/bootmanager.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/bootmanager.h (renamed from src/citra_qt/bootmanager.h) | 0 | ||||
-rw-r--r-- | src/yuzu/citra-qt.rc (renamed from src/citra_qt/citra-qt.rc) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/config.cpp (renamed from src/citra_qt/configuration/config.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/config.h (renamed from src/citra_qt/configuration/config.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure.ui (renamed from src/citra_qt/configuration/configure.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_audio.cpp (renamed from src/citra_qt/configuration/configure_audio.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_audio.h (renamed from src/citra_qt/configuration/configure_audio.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_audio.ui (renamed from src/citra_qt/configuration/configure_audio.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_debug.cpp (renamed from src/citra_qt/configuration/configure_debug.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_debug.h (renamed from src/citra_qt/configuration/configure_debug.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_debug.ui (renamed from src/citra_qt/configuration/configure_debug.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_dialog.cpp (renamed from src/citra_qt/configuration/configure_dialog.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_dialog.h (renamed from src/citra_qt/configuration/configure_dialog.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_general.cpp (renamed from src/citra_qt/configuration/configure_general.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_general.h (renamed from src/citra_qt/configuration/configure_general.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_general.ui (renamed from src/citra_qt/configuration/configure_general.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_graphics.cpp (renamed from src/citra_qt/configuration/configure_graphics.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_graphics.h (renamed from src/citra_qt/configuration/configure_graphics.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_graphics.ui (renamed from src/citra_qt/configuration/configure_graphics.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_input.cpp (renamed from src/citra_qt/configuration/configure_input.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_input.h (renamed from src/citra_qt/configuration/configure_input.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_input.ui (renamed from src/citra_qt/configuration/configure_input.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_system.cpp (renamed from src/citra_qt/configuration/configure_system.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_system.h (renamed from src/citra_qt/configuration/configure_system.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_system.ui (renamed from src/citra_qt/configuration/configure_system.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_web.cpp (renamed from src/citra_qt/configuration/configure_web.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_web.h (renamed from src/citra_qt/configuration/configure_web.h) | 0 | ||||
-rw-r--r-- | src/yuzu/configuration/configure_web.ui (renamed from src/citra_qt/configuration/configure_web.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics.cpp (renamed from src/citra_qt/debugger/graphics/graphics.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics.h (renamed from src/citra_qt/debugger/graphics/graphics.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_breakpoint_observer.cpp (renamed from src/citra_qt/debugger/graphics/graphics_breakpoint_observer.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_breakpoint_observer.h (renamed from src/citra_qt/debugger/graphics/graphics_breakpoint_observer.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_breakpoints.cpp (renamed from src/citra_qt/debugger/graphics/graphics_breakpoints.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_breakpoints.h (renamed from src/citra_qt/debugger/graphics/graphics_breakpoints.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_breakpoints_p.h (renamed from src/citra_qt/debugger/graphics/graphics_breakpoints_p.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_cmdlists.cpp (renamed from src/citra_qt/debugger/graphics/graphics_cmdlists.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_cmdlists.h (renamed from src/citra_qt/debugger/graphics/graphics_cmdlists.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_surface.cpp (renamed from src/citra_qt/debugger/graphics/graphics_surface.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_surface.h (renamed from src/citra_qt/debugger/graphics/graphics_surface.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_tracing.cpp (renamed from src/citra_qt/debugger/graphics/graphics_tracing.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_tracing.h (renamed from src/citra_qt/debugger/graphics/graphics_tracing.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_vertex_shader.cpp (renamed from src/citra_qt/debugger/graphics/graphics_vertex_shader.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/graphics/graphics_vertex_shader.h (renamed from src/citra_qt/debugger/graphics/graphics_vertex_shader.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/profiler.cpp (renamed from src/citra_qt/debugger/profiler.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/profiler.h (renamed from src/citra_qt/debugger/profiler.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/registers.cpp (renamed from src/citra_qt/debugger/registers.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/registers.h (renamed from src/citra_qt/debugger/registers.h) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/registers.ui (renamed from src/citra_qt/debugger/registers.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/wait_tree.cpp (renamed from src/citra_qt/debugger/wait_tree.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/debugger/wait_tree.h (renamed from src/citra_qt/debugger/wait_tree.h) | 0 | ||||
-rw-r--r-- | src/yuzu/game_list.cpp (renamed from src/citra_qt/game_list.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/game_list.h (renamed from src/citra_qt/game_list.h) | 0 | ||||
-rw-r--r-- | src/yuzu/game_list_p.h (renamed from src/citra_qt/game_list_p.h) | 0 | ||||
-rw-r--r-- | src/yuzu/hotkeys.cpp (renamed from src/citra_qt/hotkeys.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/hotkeys.h (renamed from src/citra_qt/hotkeys.h) | 0 | ||||
-rw-r--r-- | src/yuzu/hotkeys.ui (renamed from src/citra_qt/hotkeys.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/main.cpp (renamed from src/citra_qt/main.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/main.h (renamed from src/citra_qt/main.h) | 0 | ||||
-rw-r--r-- | src/yuzu/main.ui (renamed from src/citra_qt/main.ui) | 0 | ||||
-rw-r--r-- | src/yuzu/ui_settings.cpp (renamed from src/citra_qt/ui_settings.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/ui_settings.h (renamed from src/citra_qt/ui_settings.h) | 0 | ||||
-rw-r--r-- | src/yuzu/util/spinbox.cpp (renamed from src/citra_qt/util/spinbox.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/util/spinbox.h (renamed from src/citra_qt/util/spinbox.h) | 0 | ||||
-rw-r--r-- | src/yuzu/util/util.cpp (renamed from src/citra_qt/util/util.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu/util/util.h (renamed from src/citra_qt/util/util.h) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/CMakeLists.txt (renamed from src/citra/CMakeLists.txt) | 16 | ||||
-rw-r--r-- | src/yuzu_cmd/citra.cpp (renamed from src/citra/citra.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/citra.rc (renamed from src/citra/citra.rc) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/config.cpp (renamed from src/citra/config.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/config.h (renamed from src/citra/config.h) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/default_ini.h (renamed from src/citra/default_ini.h) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/emu_window/emu_window_sdl2.cpp (renamed from src/citra/emu_window/emu_window_sdl2.cpp) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/emu_window/emu_window_sdl2.h (renamed from src/citra/emu_window/emu_window_sdl2.h) | 0 | ||||
-rw-r--r-- | src/yuzu_cmd/resource.h (renamed from src/citra/resource.h) | 0 |
120 files changed, 21 insertions, 5227 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e11940f59..85354f43e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,16 +4,11 @@ include_directories(.) add_subdirectory(common) add_subdirectory(core) add_subdirectory(video_core) -add_subdirectory(audio_core) -add_subdirectory(network) add_subdirectory(input_common) add_subdirectory(tests) if (ENABLE_SDL2) - add_subdirectory(citra) + add_subdirectory(yuzu_cmd) endif() if (ENABLE_QT) - add_subdirectory(citra_qt) -endif() -if (ENABLE_WEB_SERVICE) - add_subdirectory(web_service) + add_subdirectory(yuzu) endif() diff --git a/src/audio_core/CMakeLists.txt b/src/audio_core/CMakeLists.txt deleted file mode 100644 index 0ad86bb7a..000000000 --- a/src/audio_core/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -set(SRCS - audio_core.cpp - codec.cpp - hle/dsp.cpp - hle/filter.cpp - hle/mixers.cpp - hle/pipe.cpp - hle/source.cpp - interpolate.cpp - sink_details.cpp - time_stretch.cpp - ) - -set(HEADERS - audio_core.h - codec.h - hle/common.h - hle/dsp.h - hle/filter.h - hle/mixers.h - hle/pipe.h - hle/source.h - interpolate.h - null_sink.h - sink.h - sink_details.h - time_stretch.h - ) - -if(SDL2_FOUND) - set(SRCS ${SRCS} sdl2_sink.cpp) - set(HEADERS ${HEADERS} sdl2_sink.h) -endif() - -create_directory_groups(${SRCS} ${HEADERS}) - -add_library(audio_core STATIC ${SRCS} ${HEADERS}) -target_link_libraries(audio_core PUBLIC common core) -target_link_libraries(audio_core PRIVATE SoundTouch) - -if(SDL2_FOUND) - target_link_libraries(audio_core PRIVATE SDL2) - target_compile_definitions(audio_core PRIVATE HAVE_SDL2) -endif() diff --git a/src/audio_core/audio_core.cpp b/src/audio_core/audio_core.cpp deleted file mode 100644 index ae2b68f9c..000000000 --- a/src/audio_core/audio_core.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <array> -#include <memory> -#include <string> -#include "audio_core/audio_core.h" -#include "audio_core/hle/dsp.h" -#include "audio_core/hle/pipe.h" -#include "audio_core/null_sink.h" -#include "audio_core/sink.h" -#include "audio_core/sink_details.h" -#include "common/common_types.h" -#include "core/core_timing.h" -#include "core/hle/service/dsp_dsp.h" - -namespace AudioCore { - -// Audio Ticks occur about every 5 miliseconds. -static CoreTiming::EventType* tick_event; ///< CoreTiming event -static constexpr u64 audio_frame_ticks = 1310252ull; ///< Units: ARM11 cycles - -static void AudioTickCallback(u64 /*userdata*/, int cycles_late) { - if (DSP::HLE::Tick()) { - // TODO(merry): Signal all the other interrupts as appropriate. - Service::DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Audio); - // HACK(merry): Added to prevent regressions. Will remove soon. - Service::DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Binary); - } - - // Reschedule recurrent event - CoreTiming::ScheduleEvent(audio_frame_ticks - cycles_late, tick_event); -} - -void Init() { - DSP::HLE::Init(); - - tick_event = CoreTiming::RegisterEvent("AudioCore::tick_event", AudioTickCallback); - CoreTiming::ScheduleEvent(audio_frame_ticks, tick_event); -} - -std::array<u8, Memory::DSP_RAM_SIZE>& GetDspMemory() { - return DSP::HLE::g_dsp_memory.raw_memory; -} - -void SelectSink(std::string sink_id) { - const SinkDetails& sink_details = GetSinkDetails(sink_id); - DSP::HLE::SetSink(sink_details.factory()); -} - -void EnableStretching(bool enable) { - DSP::HLE::EnableStretching(enable); -} - -void Shutdown() { - CoreTiming::UnscheduleEvent(tick_event, 0); - DSP::HLE::Shutdown(); -} - -} // namespace AudioCore diff --git a/src/audio_core/audio_core.h b/src/audio_core/audio_core.h deleted file mode 100644 index ab323ce1f..000000000 --- a/src/audio_core/audio_core.h +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <string> -#include "common/common_types.h" -#include "core/memory.h" - -namespace AudioCore { - -constexpr int native_sample_rate = 32728; ///< 32kHz - -/// Initialise Audio Core -void Init(); - -/// Returns a reference to the array backing DSP memory -std::array<u8, Memory::DSP_RAM_SIZE>& GetDspMemory(); - -/// Select the sink to use based on sink id. -void SelectSink(std::string sink_id); - -/// Enable/Disable stretching. -void EnableStretching(bool enable); - -/// Shutdown Audio Core -void Shutdown(); - -} // namespace AudioCore diff --git a/src/audio_core/codec.cpp b/src/audio_core/codec.cpp deleted file mode 100644 index 6fba9fdae..000000000 --- a/src/audio_core/codec.cpp +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <array> -#include <cstddef> -#include <cstring> -#include <vector> -#include "audio_core/codec.h" -#include "common/assert.h" -#include "common/common_types.h" -#include "common/math_util.h" - -namespace Codec { - -StereoBuffer16 DecodeADPCM(const u8* const data, const size_t sample_count, - const std::array<s16, 16>& adpcm_coeff, ADPCMState& state) { - // GC-ADPCM with scale factor and variable coefficients. - // Frames are 8 bytes long containing 14 samples each. - // Samples are 4 bits (one nibble) long. - - constexpr size_t FRAME_LEN = 8; - constexpr size_t SAMPLES_PER_FRAME = 14; - constexpr std::array<int, 16> SIGNED_NIBBLES = { - {0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1}}; - - const size_t ret_size = - sample_count % 2 == 0 ? sample_count : sample_count + 1; // Ensure multiple of two. - StereoBuffer16 ret(ret_size); - - int yn1 = state.yn1, yn2 = state.yn2; - - const size_t NUM_FRAMES = - (sample_count + (SAMPLES_PER_FRAME - 1)) / SAMPLES_PER_FRAME; // Round up. - for (size_t framei = 0; framei < NUM_FRAMES; framei++) { - const int frame_header = data[framei * FRAME_LEN]; - const int scale = 1 << (frame_header & 0xF); - const int idx = (frame_header >> 4) & 0x7; - - // Coefficients are fixed point with 11 bits fractional part. - const int coef1 = adpcm_coeff[idx * 2 + 0]; - const int coef2 = adpcm_coeff[idx * 2 + 1]; - - // Decodes an audio sample. One nibble produces one sample. - const auto decode_sample = [&](const int nibble) -> s16 { - const int xn = nibble * scale; - // We first transform everything into 11 bit fixed point, perform the second order - // digital filter, then transform back. - // 0x400 == 0.5 in 11 bit fixed point. - // Filter: y[n] = x[n] + 0.5 + c1 * y[n-1] + c2 * y[n-2] - int val = ((xn << 11) + 0x400 + coef1 * yn1 + coef2 * yn2) >> 11; - // Clamp to output range. - val = MathUtil::Clamp(val, -32768, 32767); - // Advance output feedback. - yn2 = yn1; - yn1 = val; - return (s16)val; - }; - - size_t outputi = framei * SAMPLES_PER_FRAME; - size_t datai = framei * FRAME_LEN + 1; - for (size_t i = 0; i < SAMPLES_PER_FRAME && outputi < sample_count; i += 2) { - const s16 sample1 = decode_sample(SIGNED_NIBBLES[data[datai] >> 4]); - ret[outputi].fill(sample1); - outputi++; - - const s16 sample2 = decode_sample(SIGNED_NIBBLES[data[datai] & 0xF]); - ret[outputi].fill(sample2); - outputi++; - - datai++; - } - } - - state.yn1 = yn1; - state.yn2 = yn2; - - return ret; -} - -static s16 SignExtendS8(u8 x) { - // The data is actually signed PCM8. - // We sign extend this to signed PCM16. - return static_cast<s16>(static_cast<s8>(x)); -} - -StereoBuffer16 DecodePCM8(const unsigned num_channels, const u8* const data, - const size_t sample_count) { - ASSERT(num_channels == 1 || num_channels == 2); - - StereoBuffer16 ret(sample_count); - - if (num_channels == 1) { - for (size_t i = 0; i < sample_count; i++) { - ret[i].fill(SignExtendS8(data[i])); - } - } else { - for (size_t i = 0; i < sample_count; i++) { - ret[i][0] = SignExtendS8(data[i * 2 + 0]); - ret[i][1] = SignExtendS8(data[i * 2 + 1]); - } - } - - return ret; -} - -StereoBuffer16 DecodePCM16(const unsigned num_channels, const u8* const data, - const size_t sample_count) { - ASSERT(num_channels == 1 || num_channels == 2); - - StereoBuffer16 ret(sample_count); - - if (num_channels == 1) { - for (size_t i = 0; i < sample_count; i++) { - s16 sample; - std::memcpy(&sample, data + i * sizeof(s16), sizeof(s16)); - ret[i].fill(sample); - } - } else { - for (size_t i = 0; i < sample_count; ++i) { - std::memcpy(&ret[i], data + i * sizeof(s16) * 2, 2 * sizeof(s16)); - } - } - - return ret; -} -}; diff --git a/src/audio_core/codec.h b/src/audio_core/codec.h deleted file mode 100644 index 877b2202d..000000000 --- a/src/audio_core/codec.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <deque> -#include "common/common_types.h" - -namespace Codec { - -/// A variable length buffer of signed PCM16 stereo samples. -using StereoBuffer16 = std::deque<std::array<s16, 2>>; - -/// See: Codec::DecodeADPCM -struct ADPCMState { - // Two historical samples from previous processed buffer, - // required for ADPCM decoding - s16 yn1; ///< y[n-1] - s16 yn2; ///< y[n-2] -}; - -/** - * @param data Pointer to buffer that contains ADPCM data to decode - * @param sample_count Length of buffer in terms of number of samples - * @param adpcm_coeff ADPCM coefficients - * @param state ADPCM state, this is updated with new state - * @return Decoded stereo signed PCM16 data, sample_count in length - */ -StereoBuffer16 DecodeADPCM(const u8* const data, const size_t sample_count, - const std::array<s16, 16>& adpcm_coeff, ADPCMState& state); - -/** - * @param num_channels Number of channels - * @param data Pointer to buffer that contains PCM8 data to decode - * @param sample_count Length of buffer in terms of number of samples - * @return Decoded stereo signed PCM16 data, sample_count in length - */ -StereoBuffer16 DecodePCM8(const unsigned num_channels, const u8* const data, - const size_t sample_count); - -/** - * @param num_channels Number of channels - * @param data Pointer to buffer that contains PCM16 data to decode - * @param sample_count Length of buffer in terms of number of samples - * @return Decoded stereo signed PCM16 data, sample_count in length - */ -StereoBuffer16 DecodePCM16(const unsigned num_channels, const u8* const data, - const size_t sample_count); -}; diff --git a/src/audio_core/hle/common.h b/src/audio_core/hle/common.h deleted file mode 100644 index 7fbc3ad9a..000000000 --- a/src/audio_core/hle/common.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <algorithm> -#include <array> -#include "common/common_types.h" - -namespace DSP { -namespace HLE { - -constexpr int num_sources = 24; -constexpr int samples_per_frame = 160; ///< Samples per audio frame at native sample rate - -/// The final output to the speakers is stereo. Preprocessing output in Source is also stereo. -using StereoFrame16 = std::array<std::array<s16, 2>, samples_per_frame>; - -/// The DSP is quadraphonic internally. -using QuadFrame32 = std::array<std::array<s32, 4>, samples_per_frame>; - -/** - * This performs the filter operation defined by FilterT::ProcessSample on the frame in-place. - * FilterT::ProcessSample is called sequentially on the samples. - */ -template <typename FrameT, typename FilterT> -void FilterFrame(FrameT& frame, FilterT& filter) { - std::transform(frame.begin(), frame.end(), frame.begin(), - [&filter](const auto& sample) { return filter.ProcessSample(sample); }); -} - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/dsp.cpp b/src/audio_core/hle/dsp.cpp deleted file mode 100644 index 260b182ed..000000000 --- a/src/audio_core/hle/dsp.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <array> -#include <memory> -#include "audio_core/hle/dsp.h" -#include "audio_core/hle/mixers.h" -#include "audio_core/hle/pipe.h" -#include "audio_core/hle/source.h" -#include "audio_core/sink.h" -#include "audio_core/time_stretch.h" - -namespace DSP { -namespace HLE { - -// Region management - -DspMemory g_dsp_memory; - -static size_t CurrentRegionIndex() { - // The region with the higher frame counter is chosen unless there is wraparound. - // This function only returns a 0 or 1. - u16 frame_counter_0 = g_dsp_memory.region_0.frame_counter; - u16 frame_counter_1 = g_dsp_memory.region_1.frame_counter; - - if (frame_counter_0 == 0xFFFFu && frame_counter_1 != 0xFFFEu) { - // Wraparound has occurred. - return 1; - } - - if (frame_counter_1 == 0xFFFFu && frame_counter_0 != 0xFFFEu) { - // Wraparound has occurred. - return 0; - } - - return (frame_counter_0 > frame_counter_1) ? 0 : 1; -} - -static SharedMemory& ReadRegion() { - return CurrentRegionIndex() == 0 ? g_dsp_memory.region_0 : g_dsp_memory.region_1; -} - -static SharedMemory& WriteRegion() { - return CurrentRegionIndex() != 0 ? g_dsp_memory.region_0 : g_dsp_memory.region_1; -} - -// Audio processing and mixing - -static std::array<Source, num_sources> sources = { - Source(0), Source(1), Source(2), Source(3), Source(4), Source(5), Source(6), Source(7), - Source(8), Source(9), Source(10), Source(11), Source(12), Source(13), Source(14), Source(15), - Source(16), Source(17), Source(18), Source(19), Source(20), Source(21), Source(22), Source(23), -}; -static Mixers mixers; - -static StereoFrame16 GenerateCurrentFrame() { - SharedMemory& read = ReadRegion(); - SharedMemory& write = WriteRegion(); - - std::array<QuadFrame32, 3> intermediate_mixes = {}; - - // Generate intermediate mixes - for (size_t i = 0; i < num_sources; i++) { - write.source_statuses.status[i] = - sources[i].Tick(read.source_configurations.config[i], read.adpcm_coefficients.coeff[i]); - for (size_t mix = 0; mix < 3; mix++) { - sources[i].MixInto(intermediate_mixes[mix], mix); - } - } - - // Generate final mix - write.dsp_status = mixers.Tick(read.dsp_configuration, read.intermediate_mix_samples, - write.intermediate_mix_samples, intermediate_mixes); - - StereoFrame16 output_frame = mixers.GetOutput(); - - // Write current output frame to the shared memory region - for (size_t samplei = 0; samplei < output_frame.size(); samplei++) { - for (size_t channeli = 0; channeli < output_frame[0].size(); channeli++) { - write.final_samples.pcm16[samplei][channeli] = s16_le(output_frame[samplei][channeli]); - } - } - - return output_frame; -} - -// Audio output - -static bool perform_time_stretching = true; -static std::unique_ptr<AudioCore::Sink> sink; -static AudioCore::TimeStretcher time_stretcher; - -static void FlushResidualStretcherAudio() { - time_stretcher.Flush(); - while (true) { - std::vector<s16> residual_audio = time_stretcher.Process(sink->SamplesInQueue()); - if (residual_audio.empty()) - break; - sink->EnqueueSamples(residual_audio.data(), residual_audio.size() / 2); - } -} - -static void OutputCurrentFrame(const StereoFrame16& frame) { - if (perform_time_stretching) { - time_stretcher.AddSamples(&frame[0][0], frame.size()); - std::vector<s16> stretched_samples = time_stretcher.Process(sink->SamplesInQueue()); - sink->EnqueueSamples(stretched_samples.data(), stretched_samples.size() / 2); - } else { - constexpr size_t maximum_sample_latency = 2048; // about 64 miliseconds - if (sink->SamplesInQueue() > maximum_sample_latency) { - // This can occur if we're running too fast and samples are starting to back up. - // Just drop the samples. - return; - } - - sink->EnqueueSamples(&frame[0][0], frame.size()); - } -} - -void EnableStretching(bool enable) { - if (perform_time_stretching == enable) - return; - - if (!enable) { - FlushResidualStretcherAudio(); - } - perform_time_stretching = enable; -} - -// Public Interface - -void Init() { - DSP::HLE::ResetPipes(); - - for (auto& source : sources) { - source.Reset(); - } - - mixers.Reset(); - - time_stretcher.Reset(); - if (sink) { - time_stretcher.SetOutputSampleRate(sink->GetNativeSampleRate()); - } -} - -void Shutdown() { - if (perform_time_stretching) { - FlushResidualStretcherAudio(); - } -} - -bool Tick() { - StereoFrame16 current_frame = {}; - - // TODO: Check dsp::DSP semaphore (which indicates emulated application has finished writing to - // shared memory region) - current_frame = GenerateCurrentFrame(); - - OutputCurrentFrame(current_frame); - - return true; -} - -void SetSink(std::unique_ptr<AudioCore::Sink> sink_) { - sink = std::move(sink_); - time_stretcher.SetOutputSampleRate(sink->GetNativeSampleRate()); -} - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/dsp.h b/src/audio_core/hle/dsp.h deleted file mode 100644 index 94ce48863..000000000 --- a/src/audio_core/hle/dsp.h +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <cstddef> -#include <memory> -#include <type_traits> -#include "audio_core/hle/common.h" -#include "common/bit_field.h" -#include "common/common_funcs.h" -#include "common/common_types.h" -#include "common/swap.h" - -namespace AudioCore { -class Sink; -} - -namespace DSP { -namespace HLE { - -// The application-accessible region of DSP memory consists of two parts. Both are marked as IO and -// have Read/Write permissions. -// -// First Region: 0x1FF50000 (Size: 0x8000) -// Second Region: 0x1FF70000 (Size: 0x8000) -// -// The DSP reads from each region alternately based on the frame counter for each region much like a -// double-buffer. The frame counter is located as the very last u16 of each region and is -// incremented each audio tick. - -constexpr u32 region0_offset = 0x50000; -constexpr u32 region1_offset = 0x70000; - -/** - * The DSP is native 16-bit. The DSP also appears to be big-endian. When reading 32-bit numbers from - * its memory regions, the higher and lower 16-bit halves are swapped compared to the little-endian - * layout of the ARM11. Hence from the ARM11's point of view the memory space appears to be - * middle-endian. - * - * Unusually this does not appear to be an issue for floating point numbers. The DSP makes the more - * sensible choice of keeping that little-endian. There are also some exceptions such as the - * IntermediateMixSamples structure, which is little-endian. - * - * This struct implements the conversion to and from this middle-endianness. - */ -struct u32_dsp { - u32_dsp() = default; - operator u32() const { - return Convert(storage); - } - void operator=(u32 new_value) { - storage = Convert(new_value); - } - -private: - static constexpr u32 Convert(u32 value) { - return (value << 16) | (value >> 16); - } - u32_le storage; -}; -#if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER) -static_assert(std::is_trivially_copyable<u32_dsp>::value, "u32_dsp isn't trivially copyable"); -#endif - -// There are 15 structures in each memory region. A table of them in the order they appear in memory -// is presented below: -// -// # First Region DSP Address Purpose Control -// 5 0x8400 DSP Status DSP -// 9 0x8410 DSP Debug Info DSP -// 6 0x8540 Final Mix Samples DSP -// 2 0x8680 Source Status [24] DSP -// 8 0x8710 Compressor Table Application -// 4 0x9430 DSP Configuration Application -// 7 0x9492 Intermediate Mix Samples DSP + App -// 1 0x9E92 Source Configuration [24] Application -// 3 0xA792 Source ADPCM Coefficients [24] Application -// 10 0xA912 Surround Sound Related -// 11 0xAA12 Surround Sound Related -// 12 0xAAD2 Surround Sound Related -// 13 0xAC52 Surround Sound Related -// 14 0xAC5C Surround Sound Related -// 0 0xBFFF Frame Counter Application -// -// #: This refers to the order in which they appear in the DspPipe::Audio DSP pipe. -// See also: DSP::HLE::PipeRead. -// -// Note that the above addresses do vary slightly between audio firmwares observed; the addresses -// are not fixed in stone. The addresses above are only an examplar; they're what this -// implementation does and provides to applications. -// -// Application requests the DSP service to convert DSP addresses into ARM11 virtual addresses using -// the ConvertProcessAddressFromDspDram service call. Applications seem to derive the addresses for -// the second region via: -// second_region_dsp_addr = first_region_dsp_addr | 0x10000 -// -// Applications maintain most of its own audio state, the memory region is used mainly for -// communication and not storage of state. -// -// In the documentation below, filter and effect transfer functions are specified in the z domain. -// (If you are more familiar with the Laplace transform, z = exp(sT). The z domain is the digital -// frequency domain, just like how the s domain is the analog frequency domain.) - -#define INSERT_PADDING_DSPWORDS(num_words) INSERT_PADDING_BYTES(2 * (num_words)) - -// GCC versions < 5.0 do not implement std::is_trivially_copyable. -// Excluding MSVC because it has weird behaviour for std::is_trivially_copyable. -#if (__GNUC__ >= 5) || defined(__clang__) -#define ASSERT_DSP_STRUCT(name, size) \ - static_assert(std::is_standard_layout<name>::value, \ - "DSP structure " #name " doesn't use standard layout"); \ - static_assert(std::is_trivially_copyable<name>::value, \ - "DSP structure " #name " isn't trivially copyable"); \ - static_assert(sizeof(name) == (size), "Unexpected struct size for DSP structure " #name) -#else -#define ASSERT_DSP_STRUCT(name, size) \ - static_assert(std::is_standard_layout<name>::value, \ - "DSP structure " #name " doesn't use standard layout"); \ - static_assert(sizeof(name) == (size), "Unexpected struct size for DSP structure " #name) -#endif - -struct SourceConfiguration { - struct Configuration { - /// These dirty flags are set by the application when it updates the fields in this struct. - /// The DSP clears these each audio frame. - union { - u32_le dirty_raw; - - BitField<0, 1, u32_le> format_dirty; - BitField<1, 1, u32_le> mono_or_stereo_dirty; - BitField<2, 1, u32_le> adpcm_coefficients_dirty; - /// Tends to be set when a looped buffer is queued. - BitField<3, 1, u32_le> partial_embedded_buffer_dirty; - BitField<4, 1, u32_le> partial_reset_flag; - - BitField<16, 1, u32_le> enable_dirty; - BitField<17, 1, u32_le> interpolation_dirty; - BitField<18, 1, u32_le> rate_multiplier_dirty; - BitField<19, 1, u32_le> buffer_queue_dirty; - BitField<20, 1, u32_le> loop_related_dirty; - /// Tends to also be set when embedded buffer is updated. - BitField<21, 1, u32_le> play_position_dirty; - BitField<22, 1, u32_le> filters_enabled_dirty; - BitField<23, 1, u32_le> simple_filter_dirty; - BitField<24, 1, u32_le> biquad_filter_dirty; - BitField<25, 1, u32_le> gain_0_dirty; - BitField<26, 1, u32_le> gain_1_dirty; - BitField<27, 1, u32_le> gain_2_dirty; - BitField<28, 1, u32_le> sync_dirty; - BitField<29, 1, u32_le> reset_flag; - BitField<30, 1, u32_le> embedded_buffer_dirty; - }; - - // Gain control - - /** - * Gain is between 0.0-1.0. This determines how much will this source appear on each of the - * 12 channels that feed into the intermediate mixers. Each of the three intermediate mixers - * is fed two left and two right channels. - */ - float_le gain[3][4]; - - // Interpolation - - /// Multiplier for sample rate. Resampling occurs with the selected interpolation method. - float_le rate_multiplier; - - enum class InterpolationMode : u8 { - Polyphase = 0, - Linear = 1, - None = 2, - }; - - InterpolationMode interpolation_mode; - INSERT_PADDING_BYTES(1); ///< Interpolation related - - // Filters - - /** - * This is the simplest normalized first-order digital recursive filter. - * The transfer function of this filter is: - * H(z) = b0 / (1 - a1 z^-1) - * Note the feedbackward coefficient is negated. - * Values are signed fixed point with 15 fractional bits. - */ - struct SimpleFilter { - s16_le b0; - s16_le a1; - }; - - /** - * This is a normalised biquad filter (second-order). - * The transfer function of this filter is: - * H(z) = (b0 + b1 z^-1 + b2 z^-2) / (1 - a1 z^-1 - a2 z^-2) - * Nintendo chose to negate the feedbackward coefficients. This differs from standard - * notation as in: https://ccrma.stanford.edu/~jos/filters/Direct_Form_I.html - * Values are signed fixed point with 14 fractional bits. - */ - struct BiquadFilter { - s16_le a2; - s16_le a1; - s16_le b2; - s16_le b1; - s16_le b0; - }; - - union { - u16_le filters_enabled; - BitField<0, 1, u16_le> simple_filter_enabled; - BitField<1, 1, u16_le> biquad_filter_enabled; - }; - - SimpleFilter simple_filter; - BiquadFilter biquad_filter; - - // Buffer Queue - - /// A buffer of audio data from the application, along with metadata about it. - struct Buffer { - /// Physical memory address of the start of the buffer - u32_dsp physical_address; - - /// This is length in terms of samples. - /// Note that in different buffer formats a sample takes up different number of bytes. - u32_dsp length; - - /// ADPCM Predictor (4 bits) and Scale (4 bits) - union { - u16_le adpcm_ps; - BitField<0, 4, u16_le> adpcm_scale; - BitField<4, 4, u16_le> adpcm_predictor; - }; - - /// ADPCM Historical Samples (y[n-1] and y[n-2]) - u16_le adpcm_yn[2]; - - /// This is non-zero when the ADPCM values above are to be updated. - u8 adpcm_dirty; - - /// Is a looping buffer. - u8 is_looping; - - /// This value is shown in SourceStatus::previous_buffer_id when this buffer has - /// finished. This allows the emulated application to tell what buffer is currently - /// playing. - u16_le buffer_id; - - INSERT_PADDING_DSPWORDS(1); - }; - - u16_le buffers_dirty; ///< Bitmap indicating which buffers are dirty (bit i -> buffers[i]) - Buffer buffers[4]; ///< Queued Buffers - - // Playback controls - - u32_dsp loop_related; - u8 enable; - INSERT_PADDING_BYTES(1); - u16_le sync; ///< Application-side sync (See also: SourceStatus::sync) - u32_dsp play_position; ///< Position. (Units: number of samples) - INSERT_PADDING_DSPWORDS(2); - - // Embedded Buffer - // This buffer is often the first buffer to be used when initiating audio playback, - // after which the buffer queue is used. - - u32_dsp physical_address; - - /// This is length in terms of samples. - /// Note a sample takes up different number of bytes in different buffer formats. - u32_dsp length; - - enum class MonoOrStereo : u16_le { - Mono = 1, - Stereo = 2, - }; - - enum class Format : u16_le { - PCM8 = 0, - PCM16 = 1, - ADPCM = 2, - }; - - union { - u16_le flags1_raw; - BitField<0, 2, MonoOrStereo> mono_or_stereo; - BitField<2, 2, Format> format; - BitField<5, 1, u16_le> fade_in; - }; - - /// ADPCM Predictor (4 bit) and Scale (4 bit) - union { - u16_le adpcm_ps; - BitField<0, 4, u16_le> adpcm_scale; - BitField<4, 4, u16_le> adpcm_predictor; - }; - - /// ADPCM Historical Samples (y[n-1] and y[n-2]) - u16_le adpcm_yn[2]; - - union { - u16_le flags2_raw; - BitField<0, 1, u16_le> adpcm_dirty; ///< Has the ADPCM info above been changed? - BitField<1, 1, u16_le> is_looping; ///< Is this a looping buffer? - }; - - /// Buffer id of embedded buffer (used as a buffer id in SourceStatus to reference this - /// buffer). - u16_le buffer_id; - }; - - Configuration config[num_sources]; -}; -ASSERT_DSP_STRUCT(SourceConfiguration::Configuration, 192); -ASSERT_DSP_STRUCT(SourceConfiguration::Configuration::Buffer, 20); - -struct SourceStatus { - struct Status { - u8 is_enabled; ///< Is this channel enabled? (Doesn't have to be playing anything.) - u8 current_buffer_id_dirty; ///< Non-zero when current_buffer_id changes - u16_le sync; ///< Is set by the DSP to the value of SourceConfiguration::sync - u32_dsp buffer_position; ///< Number of samples into the current buffer - u16_le current_buffer_id; ///< Updated when a buffer finishes playing - INSERT_PADDING_DSPWORDS(1); - }; - - Status status[num_sources]; -}; -ASSERT_DSP_STRUCT(SourceStatus::Status, 12); - -struct DspConfiguration { - /// These dirty flags are set by the application when it updates the fields in this struct. - /// The DSP clears these each audio frame. - union { - u32_le dirty_raw; - - BitField<8, 1, u32_le> mixer1_enabled_dirty; - BitField<9, 1, u32_le> mixer2_enabled_dirty; - BitField<10, 1, u32_le> delay_effect_0_dirty; - BitField<11, 1, u32_le> delay_effect_1_dirty; - BitField<12, 1, u32_le> reverb_effect_0_dirty; - BitField<13, 1, u32_le> reverb_effect_1_dirty; - - BitField<16, 1, u32_le> volume_0_dirty; - - BitField<24, 1, u32_le> volume_1_dirty; - BitField<25, 1, u32_le> volume_2_dirty; - BitField<26, 1, u32_le> output_format_dirty; - BitField<27, 1, u32_le> limiter_enabled_dirty; - BitField<28, 1, u32_le> headphones_connected_dirty; - }; - - /// The DSP has three intermediate audio mixers. This controls the volume level (0.0-1.0) for - /// each at the final mixer. - float_le volume[3]; - - INSERT_PADDING_DSPWORDS(3); - - enum class OutputFormat : u16_le { - Mono = 0, - Stereo = 1, - Surround = 2, - }; - - OutputFormat output_format; - - u16_le limiter_enabled; ///< Not sure of the exact gain equation for the limiter. - u16_le headphones_connected; ///< Application updates the DSP on headphone status. - INSERT_PADDING_DSPWORDS(4); ///< TODO: Surround sound related - INSERT_PADDING_DSPWORDS(2); ///< TODO: Intermediate mixer 1/2 related - u16_le mixer1_enabled; - u16_le mixer2_enabled; - - /** - * This is delay with feedback. - * Transfer function: - * H(z) = a z^-N / (1 - b z^-1 + a g z^-N) - * where - * N = frame_count * samples_per_frame - * g, a and b are fixed point with 7 fractional bits - */ - struct DelayEffect { - /// These dirty flags are set by the application when it updates the fields in this struct. - /// The DSP clears these each audio frame. - union { - u16_le dirty_raw; - BitField<0, 1, u16_le> enable_dirty; - BitField<1, 1, u16_le> work_buffer_address_dirty; - BitField<2, 1, u16_le> other_dirty; ///< Set when anything else has been changed - }; - - u16_le enable; - INSERT_PADDING_DSPWORDS(1); - u16_le outputs; - /// The application allocates a block of memory for the DSP to use as a work buffer. - u32_dsp work_buffer_address; - /// Frames to delay by - u16_le frame_count; - - // Coefficients - s16_le g; ///< Fixed point with 7 fractional bits - s16_le a; ///< Fixed point with 7 fractional bits - s16_le b; ///< Fixed point with 7 fractional bits - }; - - DelayEffect delay_effect[2]; - - struct ReverbEffect { - INSERT_PADDING_DSPWORDS(26); ///< TODO - }; - - ReverbEffect reverb_effect[2]; - - INSERT_PADDING_DSPWORDS(4); -}; -ASSERT_DSP_STRUCT(DspConfiguration, 196); -ASSERT_DSP_STRUCT(DspConfiguration::DelayEffect, 20); -ASSERT_DSP_STRUCT(DspConfiguration::ReverbEffect, 52); - -struct AdpcmCoefficients { - /// Coefficients are signed fixed point with 11 fractional bits. - /// Each source has 16 coefficients associated with it. - s16_le coeff[num_sources][16]; -}; -ASSERT_DSP_STRUCT(AdpcmCoefficients, 768); - -struct DspStatus { - u16_le unknown; - u16_le dropped_frames; - INSERT_PADDING_DSPWORDS(0xE); -}; -ASSERT_DSP_STRUCT(DspStatus, 32); - -/// Final mixed output in PCM16 stereo format, what you hear out of the speakers. -/// When the application writes to this region it has no effect. -struct FinalMixSamples { - s16_le pcm16[samples_per_frame][2]; -}; -ASSERT_DSP_STRUCT(FinalMixSamples, 640); - -/// DSP writes output of intermediate mixers 1 and 2 here. -/// Writes to this region by the application edits the output of the intermediate mixers. -/// This seems to be intended to allow the application to do custom effects on the ARM11. -/// Values that exceed s16 range will be clipped by the DSP after further processing. -struct IntermediateMixSamples { - struct Samples { - s32_le pcm32[4][samples_per_frame]; ///< Little-endian as opposed to DSP middle-endian. - }; - - Samples mix1; - Samples mix2; -}; -ASSERT_DSP_STRUCT(IntermediateMixSamples, 5120); - -/// Compressor table -struct Compressor { - INSERT_PADDING_DSPWORDS(0xD20); ///< TODO -}; - -/// There is no easy way to implement this in a HLE implementation. -struct DspDebug { - INSERT_PADDING_DSPWORDS(0x130); -}; -ASSERT_DSP_STRUCT(DspDebug, 0x260); - -struct SharedMemory { - /// Padding - INSERT_PADDING_DSPWORDS(0x400); - - DspStatus dsp_status; - - DspDebug dsp_debug; - - FinalMixSamples final_samples; - - SourceStatus source_statuses; - - Compressor compressor; - - DspConfiguration dsp_configuration; - - IntermediateMixSamples intermediate_mix_samples; - - SourceConfiguration source_configurations; - - AdpcmCoefficients adpcm_coefficients; - - struct { - INSERT_PADDING_DSPWORDS(0x100); - } unknown10; - - struct { - INSERT_PADDING_DSPWORDS(0xC0); - } unknown11; - - struct { - INSERT_PADDING_DSPWORDS(0x180); - } unknown12; - - struct { - INSERT_PADDING_DSPWORDS(0xA); - } unknown13; - - struct { - INSERT_PADDING_DSPWORDS(0x13A3); - } unknown14; - - u16_le frame_counter; -}; -ASSERT_DSP_STRUCT(SharedMemory, 0x8000); - -union DspMemory { - std::array<u8, 0x80000> raw_memory; - struct { - u8 unused_0[0x50000]; - SharedMemory region_0; - u8 unused_1[0x18000]; - SharedMemory region_1; - u8 unused_2[0x8000]; - }; -}; -static_assert(offsetof(DspMemory, region_0) == region0_offset, - "DSP region 0 is at the wrong offset"); -static_assert(offsetof(DspMemory, region_1) == region1_offset, - "DSP region 1 is at the wrong offset"); - -extern DspMemory g_dsp_memory; - -// Structures must have an offset that is a multiple of two. -static_assert(offsetof(SharedMemory, frame_counter) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, source_configurations) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, source_statuses) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, adpcm_coefficients) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, dsp_configuration) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, dsp_status) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, final_samples) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, intermediate_mix_samples) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, compressor) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, dsp_debug) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, unknown10) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, unknown11) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, unknown12) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, unknown13) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); -static_assert(offsetof(SharedMemory, unknown14) % 2 == 0, - "Structures in DSP::HLE::SharedMemory must be 2-byte aligned"); - -#undef INSERT_PADDING_DSPWORDS -#undef ASSERT_DSP_STRUCT - -/// Initialize DSP hardware -void Init(); - -/// Shutdown DSP hardware -void Shutdown(); - -/** - * Perform processing and updates state of current shared memory buffer. - * This function is called every audio tick before triggering the audio interrupt. - * @return Whether an audio interrupt should be triggered this frame. - */ -bool Tick(); - -/** - * Set the output sink. This must be called before calling Tick(). - * @param sink The sink to which audio will be output to. - */ -void SetSink(std::unique_ptr<AudioCore::Sink> sink); - -/** - * Enables/Disables audio-stretching. - * Audio stretching is an enhancement that stretches audio to match emulation - * speed to prevent stuttering at the cost of some audio latency. - * @param enable true to enable, false to disable. - */ -void EnableStretching(bool enable); - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/filter.cpp b/src/audio_core/hle/filter.cpp deleted file mode 100644 index b24a79b89..000000000 --- a/src/audio_core/hle/filter.cpp +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <array> -#include <cstddef> -#include "audio_core/hle/common.h" -#include "audio_core/hle/dsp.h" -#include "audio_core/hle/filter.h" -#include "common/common_types.h" -#include "common/math_util.h" - -namespace DSP { -namespace HLE { - -void SourceFilters::Reset() { - Enable(false, false); -} - -void SourceFilters::Enable(bool simple, bool biquad) { - simple_filter_enabled = simple; - biquad_filter_enabled = biquad; - - if (!simple) - simple_filter.Reset(); - if (!biquad) - biquad_filter.Reset(); -} - -void SourceFilters::Configure(SourceConfiguration::Configuration::SimpleFilter config) { - simple_filter.Configure(config); -} - -void SourceFilters::Configure(SourceConfiguration::Configuration::BiquadFilter config) { - biquad_filter.Configure(config); -} - -void SourceFilters::ProcessFrame(StereoFrame16& frame) { - if (!simple_filter_enabled && !biquad_filter_enabled) - return; - - if (simple_filter_enabled) { - FilterFrame(frame, simple_filter); - } - - if (biquad_filter_enabled) { - FilterFrame(frame, biquad_filter); - } -} - -// SimpleFilter - -void SourceFilters::SimpleFilter::Reset() { - y1.fill(0); - // Configure as passthrough. - a1 = 0; - b0 = 1 << 15; -} - -void SourceFilters::SimpleFilter::Configure( - SourceConfiguration::Configuration::SimpleFilter config) { - - a1 = config.a1; - b0 = config.b0; -} - -std::array<s16, 2> SourceFilters::SimpleFilter::ProcessSample(const std::array<s16, 2>& x0) { - std::array<s16, 2> y0; - for (size_t i = 0; i < 2; i++) { - const s32 tmp = (b0 * x0[i] + a1 * y1[i]) >> 15; - y0[i] = MathUtil::Clamp(tmp, -32768, 32767); - } - - y1 = y0; - - return y0; -} - -// BiquadFilter - -void SourceFilters::BiquadFilter::Reset() { - x1.fill(0); - x2.fill(0); - y1.fill(0); - y2.fill(0); - // Configure as passthrough. - a1 = a2 = b1 = b2 = 0; - b0 = 1 << 14; -} - -void SourceFilters::BiquadFilter::Configure( - SourceConfiguration::Configuration::BiquadFilter config) { - - a1 = config.a1; - a2 = config.a2; - b0 = config.b0; - b1 = config.b1; - b2 = config.b2; -} - -std::array<s16, 2> SourceFilters::BiquadFilter::ProcessSample(const std::array<s16, 2>& x0) { - std::array<s16, 2> y0; - for (size_t i = 0; i < 2; i++) { - const s32 tmp = (b0 * x0[i] + b1 * x1[i] + b2 * x2[i] + a1 * y1[i] + a2 * y2[i]) >> 14; - y0[i] = MathUtil::Clamp(tmp, -32768, 32767); - } - - x2 = x1; - x1 = x0; - y2 = y1; - y1 = y0; - - return y0; -} - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/filter.h b/src/audio_core/hle/filter.h deleted file mode 100644 index 5350e2857..000000000 --- a/src/audio_core/hle/filter.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include "audio_core/hle/common.h" -#include "audio_core/hle/dsp.h" -#include "common/common_types.h" - -namespace DSP { -namespace HLE { - -/// Preprocessing filters. There is an independent set of filters for each Source. -class SourceFilters final { -public: - SourceFilters() { - Reset(); - } - - /// Reset internal state. - void Reset(); - - /** - * Enable/Disable filters - * See also: SourceConfiguration::Configuration::simple_filter_enabled, - * SourceConfiguration::Configuration::biquad_filter_enabled. - * @param simple If true, enables the simple filter. If false, disables it. - * @param biquad If true, enables the biquad filter. If false, disables it. - */ - void Enable(bool simple, bool biquad); - - /** - * Configure simple filter. - * @param config Configuration from DSP shared memory. - */ - void Configure(SourceConfiguration::Configuration::SimpleFilter config); - - /** - * Configure biquad filter. - * @param config Configuration from DSP shared memory. - */ - void Configure(SourceConfiguration::Configuration::BiquadFilter config); - - /** - * Processes a frame in-place. - * @param frame Audio samples to process. Modified in-place. - */ - void ProcessFrame(StereoFrame16& frame); - -private: - bool simple_filter_enabled; - bool biquad_filter_enabled; - - struct SimpleFilter { - SimpleFilter() { - Reset(); - } - - /// Resets internal state. - void Reset(); - - /** - * Configures this filter with application settings. - * @param config Configuration from DSP shared memory. - */ - void Configure(SourceConfiguration::Configuration::SimpleFilter config); - - /** - * Processes a single stereo PCM16 sample. - * @param x0 Input sample - * @return Output sample - */ - std::array<s16, 2> ProcessSample(const std::array<s16, 2>& x0); - - private: - // Configuration - s32 a1, b0; - // Internal state - std::array<s16, 2> y1; - } simple_filter; - - struct BiquadFilter { - BiquadFilter() { - Reset(); - } - - /// Resets internal state. - void Reset(); - - /** - * Configures this filter with application settings. - * @param config Configuration from DSP shared memory. - */ - void Configure(SourceConfiguration::Configuration::BiquadFilter config); - - /** - * Processes a single stereo PCM16 sample. - * @param x0 Input sample - * @return Output sample - */ - std::array<s16, 2> ProcessSample(const std::array<s16, 2>& x0); - - private: - // Configuration - s32 a1, a2, b0, b1, b2; - // Internal state - std::array<s16, 2> x1; - std::array<s16, 2> x2; - std::array<s16, 2> y1; - std::array<s16, 2> y2; - } biquad_filter; -}; - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/mixers.cpp b/src/audio_core/hle/mixers.cpp deleted file mode 100644 index 6cc81dfca..000000000 --- a/src/audio_core/hle/mixers.cpp +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <cstddef> - -#include "audio_core/hle/common.h" -#include "audio_core/hle/dsp.h" -#include "audio_core/hle/mixers.h" -#include "common/assert.h" -#include "common/logging/log.h" -#include "common/math_util.h" - -namespace DSP { -namespace HLE { - -void Mixers::Reset() { - current_frame.fill({}); - state = {}; -} - -DspStatus Mixers::Tick(DspConfiguration& config, const IntermediateMixSamples& read_samples, - IntermediateMixSamples& write_samples, - const std::array<QuadFrame32, 3>& input) { - ParseConfig(config); - - AuxReturn(read_samples); - AuxSend(write_samples, input); - - MixCurrentFrame(); - - return GetCurrentStatus(); -} - -void Mixers::ParseConfig(DspConfiguration& config) { - if (!config.dirty_raw) { - return; - } - - if (config.mixer1_enabled_dirty) { - config.mixer1_enabled_dirty.Assign(0); - state.mixer1_enabled = config.mixer1_enabled != 0; - LOG_TRACE(Audio_DSP, "mixers mixer1_enabled = %hu", config.mixer1_enabled); - } - - if (config.mixer2_enabled_dirty) { - config.mixer2_enabled_dirty.Assign(0); - state.mixer2_enabled = config.mixer2_enabled != 0; - LOG_TRACE(Audio_DSP, "mixers mixer2_enabled = %hu", config.mixer2_enabled); - } - - if (config.volume_0_dirty) { - config.volume_0_dirty.Assign(0); - state.intermediate_mixer_volume[0] = config.volume[0]; - LOG_TRACE(Audio_DSP, "mixers volume[0] = %f", config.volume[0]); - } - - if (config.volume_1_dirty) { - config.volume_1_dirty.Assign(0); - state.intermediate_mixer_volume[1] = config.volume[1]; - LOG_TRACE(Audio_DSP, "mixers volume[1] = %f", config.volume[1]); - } - - if (config.volume_2_dirty) { - config.volume_2_dirty.Assign(0); - state.intermediate_mixer_volume[2] = config.volume[2]; - LOG_TRACE(Audio_DSP, "mixers volume[2] = %f", config.volume[2]); - } - - if (config.output_format_dirty) { - config.output_format_dirty.Assign(0); - state.output_format = config.output_format; - LOG_TRACE(Audio_DSP, "mixers output_format = %zu", - static_cast<size_t>(config.output_format)); - } - - if (config.headphones_connected_dirty) { - config.headphones_connected_dirty.Assign(0); - // Do nothing. (Note: Whether headphones are connected does affect coefficients used for - // surround sound.) - LOG_TRACE(Audio_DSP, "mixers headphones_connected=%hu", config.headphones_connected); - } - - if (config.dirty_raw) { - LOG_DEBUG(Audio_DSP, "mixers remaining_dirty=%x", config.dirty_raw); - } - - config.dirty_raw = 0; -} - -static s16 ClampToS16(s32 value) { - return static_cast<s16>(MathUtil::Clamp(value, -32768, 32767)); -} - -static std::array<s16, 2> AddAndClampToS16(const std::array<s16, 2>& a, - const std::array<s16, 2>& b) { - return {ClampToS16(static_cast<s32>(a[0]) + static_cast<s32>(b[0])), - ClampToS16(static_cast<s32>(a[1]) + static_cast<s32>(b[1]))}; -} - -void Mixers::DownmixAndMixIntoCurrentFrame(float gain, const QuadFrame32& samples) { - // TODO(merry): Limiter. (Currently we're performing final mixing assuming a disabled limiter.) - - switch (state.output_format) { - case OutputFormat::Mono: - std::transform( - current_frame.begin(), current_frame.end(), samples.begin(), current_frame.begin(), - [gain](const std::array<s16, 2>& accumulator, - const std::array<s32, 4>& sample) -> std::array<s16, 2> { - // Downmix to mono - s16 mono = ClampToS16(static_cast<s32>( - (gain * sample[0] + gain * sample[1] + gain * sample[2] + gain * sample[3]) / - 2)); - // Mix into current frame - return AddAndClampToS16(accumulator, {mono, mono}); - }); - return; - - case OutputFormat::Surround: - // TODO(merry): Implement surround sound. - // fallthrough - - case OutputFormat::Stereo: - std::transform( - current_frame.begin(), current_frame.end(), samples.begin(), current_frame.begin(), - [gain](const std::array<s16, 2>& accumulator, - const std::array<s32, 4>& sample) -> std::array<s16, 2> { - // Downmix to stereo - s16 left = ClampToS16(static_cast<s32>(gain * sample[0] + gain * sample[2])); - s16 right = ClampToS16(static_cast<s32>(gain * sample[1] + gain * sample[3])); - // Mix into current frame - return AddAndClampToS16(accumulator, {left, right}); - }); - return; - } - - UNREACHABLE_MSG("Invalid output_format %zu", static_cast<size_t>(state.output_format)); -} - -void Mixers::AuxReturn(const IntermediateMixSamples& read_samples) { - // NOTE: read_samples.mix{1,2}.pcm32 annoyingly have their dimensions in reverse order to - // QuadFrame32. - - if (state.mixer1_enabled) { - for (size_t sample = 0; sample < samples_per_frame; sample++) { - for (size_t channel = 0; channel < 4; channel++) { - state.intermediate_mix_buffer[1][sample][channel] = - read_samples.mix1.pcm32[channel][sample]; - } - } - } - - if (state.mixer2_enabled) { - for (size_t sample = 0; sample < samples_per_frame; sample++) { - for (size_t channel = 0; channel < 4; channel++) { - state.intermediate_mix_buffer[2][sample][channel] = - read_samples.mix2.pcm32[channel][sample]; - } - } - } -} - -void Mixers::AuxSend(IntermediateMixSamples& write_samples, - const std::array<QuadFrame32, 3>& input) { - // NOTE: read_samples.mix{1,2}.pcm32 annoyingly have their dimensions in reverse order to - // QuadFrame32. - - state.intermediate_mix_buffer[0] = input[0]; - - if (state.mixer1_enabled) { - for (size_t sample = 0; sample < samples_per_frame; sample++) { - for (size_t channel = 0; channel < 4; channel++) { - write_samples.mix1.pcm32[channel][sample] = input[1][sample][channel]; - } - } - } else { - state.intermediate_mix_buffer[1] = input[1]; - } - - if (state.mixer2_enabled) { - for (size_t sample = 0; sample < samples_per_frame; sample++) { - for (size_t channel = 0; channel < 4; channel++) { - write_samples.mix2.pcm32[channel][sample] = input[2][sample][channel]; - } - } - } else { - state.intermediate_mix_buffer[2] = input[2]; - } -} - -void Mixers::MixCurrentFrame() { - current_frame.fill({}); - - for (size_t mix = 0; mix < 3; mix++) { - DownmixAndMixIntoCurrentFrame(state.intermediate_mixer_volume[mix], - state.intermediate_mix_buffer[mix]); - } - - // TODO(merry): Compressor. (We currently assume a disabled compressor.) -} - -DspStatus Mixers::GetCurrentStatus() const { - DspStatus status; - status.unknown = 0; - status.dropped_frames = 0; - return status; -} - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/mixers.h b/src/audio_core/hle/mixers.h deleted file mode 100644 index bf4e865ae..000000000 --- a/src/audio_core/hle/mixers.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include "audio_core/hle/common.h" -#include "audio_core/hle/dsp.h" - -namespace DSP { -namespace HLE { - -class Mixers final { -public: - Mixers() { - Reset(); - } - - void Reset(); - - DspStatus Tick(DspConfiguration& config, const IntermediateMixSamples& read_samples, - IntermediateMixSamples& write_samples, const std::array<QuadFrame32, 3>& input); - - StereoFrame16 GetOutput() const { - return current_frame; - } - -private: - StereoFrame16 current_frame = {}; - - using OutputFormat = DspConfiguration::OutputFormat; - - struct { - std::array<float, 3> intermediate_mixer_volume = {}; - - bool mixer1_enabled = false; - bool mixer2_enabled = false; - std::array<QuadFrame32, 3> intermediate_mix_buffer = {}; - - OutputFormat output_format = OutputFormat::Stereo; - - } state; - - /// INTERNAL: Update our internal state based on the current config. - void ParseConfig(DspConfiguration& config); - /// INTERNAL: Read samples from shared memory that have been modified by the ARM11. - void AuxReturn(const IntermediateMixSamples& read_samples); - /// INTERNAL: Write samples to shared memory for the ARM11 to modify. - void AuxSend(IntermediateMixSamples& write_samples, const std::array<QuadFrame32, 3>& input); - /// INTERNAL: Mix current_frame. - void MixCurrentFrame(); - /// INTERNAL: Downmix from quadraphonic to stereo based on status.output_format and accumulate - /// into current_frame. - void DownmixAndMixIntoCurrentFrame(float gain, const QuadFrame32& samples); - /// INTERNAL: Generate DspStatus based on internal state. - DspStatus GetCurrentStatus() const; -}; - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/pipe.cpp b/src/audio_core/hle/pipe.cpp deleted file mode 100644 index 24074a514..000000000 --- a/src/audio_core/hle/pipe.cpp +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <array> -#include <vector> -#include "audio_core/hle/dsp.h" -#include "audio_core/hle/pipe.h" -#include "common/assert.h" -#include "common/common_types.h" -#include "common/logging/log.h" -#include "core/hle/service/dsp_dsp.h" - -namespace DSP { -namespace HLE { - -static DspState dsp_state = DspState::Off; - -static std::array<std::vector<u8>, NUM_DSP_PIPE> pipe_data; - -void ResetPipes() { - for (auto& data : pipe_data) { - data.clear(); - } - dsp_state = DspState::Off; -} - -std::vector<u8> PipeRead(DspPipe pipe_number, u32 length) { - const size_t pipe_index = static_cast<size_t>(pipe_number); - - if (pipe_index >= NUM_DSP_PIPE) { - LOG_ERROR(Audio_DSP, "pipe_number = %zu invalid", pipe_index); - return {}; - } - - if (length > UINT16_MAX) { // Can only read at most UINT16_MAX from the pipe - LOG_ERROR(Audio_DSP, "length of %u greater than max of %u", length, UINT16_MAX); - return {}; - } - - std::vector<u8>& data = pipe_data[pipe_index]; - - if (length > data.size()) { - LOG_WARNING( - Audio_DSP, - "pipe_number = %zu is out of data, application requested read of %u but %zu remain", - pipe_index, length, data.size()); - length = static_cast<u32>(data.size()); - } - - if (length == 0) - return {}; - - std::vector<u8> ret(data.begin(), data.begin() + length); - data.erase(data.begin(), data.begin() + length); - return ret; -} - -size_t GetPipeReadableSize(DspPipe pipe_number) { - const size_t pipe_index = static_cast<size_t>(pipe_number); - - if (pipe_index >= NUM_DSP_PIPE) { - LOG_ERROR(Audio_DSP, "pipe_number = %zu invalid", pipe_index); - return 0; - } - - return pipe_data[pipe_index].size(); -} - -static void WriteU16(DspPipe pipe_number, u16 value) { - const size_t pipe_index = static_cast<size_t>(pipe_number); - - std::vector<u8>& data = pipe_data.at(pipe_index); - // Little endian - data.emplace_back(value & 0xFF); - data.emplace_back(value >> 8); -} - -static void AudioPipeWriteStructAddresses() { - // These struct addresses are DSP dram addresses. - // See also: DSP_DSP::ConvertProcessAddressFromDspDram - static const std::array<u16, 15> struct_addresses = { - 0x8000 + offsetof(SharedMemory, frame_counter) / 2, - 0x8000 + offsetof(SharedMemory, source_configurations) / 2, - 0x8000 + offsetof(SharedMemory, source_statuses) / 2, - 0x8000 + offsetof(SharedMemory, adpcm_coefficients) / 2, - 0x8000 + offsetof(SharedMemory, dsp_configuration) / 2, - 0x8000 + offsetof(SharedMemory, dsp_status) / 2, - 0x8000 + offsetof(SharedMemory, final_samples) / 2, - 0x8000 + offsetof(SharedMemory, intermediate_mix_samples) / 2, - 0x8000 + offsetof(SharedMemory, compressor) / 2, - 0x8000 + offsetof(SharedMemory, dsp_debug) / 2, - 0x8000 + offsetof(SharedMemory, unknown10) / 2, - 0x8000 + offsetof(SharedMemory, unknown11) / 2, - 0x8000 + offsetof(SharedMemory, unknown12) / 2, - 0x8000 + offsetof(SharedMemory, unknown13) / 2, - 0x8000 + offsetof(SharedMemory, unknown14) / 2, - }; - - // Begin with a u16 denoting the number of structs. - WriteU16(DspPipe::Audio, static_cast<u16>(struct_addresses.size())); - // Then write the struct addresses. - for (u16 addr : struct_addresses) { - WriteU16(DspPipe::Audio, addr); - } - // Signal that we have data on this pipe. - Service::DSP_DSP::SignalPipeInterrupt(DspPipe::Audio); -} - -void PipeWrite(DspPipe pipe_number, const std::vector<u8>& buffer) { - switch (pipe_number) { - case DspPipe::Audio: { - if (buffer.size() != 4) { - LOG_ERROR(Audio_DSP, "DspPipe::Audio: Unexpected buffer length %zu was written", - buffer.size()); - return; - } - - enum class StateChange { - Initialize = 0, - Shutdown = 1, - Wakeup = 2, - Sleep = 3, - }; - - // The difference between Initialize and Wakeup is that Input state is maintained - // when sleeping but isn't when turning it off and on again. (TODO: Implement this.) - // Waking up from sleep garbles some of the structs in the memory region. (TODO: - // Implement this.) Applications store away the state of these structs before - // sleeping and reset it back after wakeup on behalf of the DSP. - - switch (static_cast<StateChange>(buffer[0])) { - case StateChange::Initialize: - LOG_INFO(Audio_DSP, "Application has requested initialization of DSP hardware"); - ResetPipes(); - AudioPipeWriteStructAddresses(); - dsp_state = DspState::On; - break; - case StateChange::Shutdown: - LOG_INFO(Audio_DSP, "Application has requested shutdown of DSP hardware"); - dsp_state = DspState::Off; - break; - case StateChange::Wakeup: - LOG_INFO(Audio_DSP, "Application has requested wakeup of DSP hardware"); - ResetPipes(); - AudioPipeWriteStructAddresses(); - dsp_state = DspState::On; - break; - case StateChange::Sleep: - LOG_INFO(Audio_DSP, "Application has requested sleep of DSP hardware"); - UNIMPLEMENTED(); - dsp_state = DspState::Sleeping; - break; - default: - LOG_ERROR(Audio_DSP, - "Application has requested unknown state transition of DSP hardware %hhu", - buffer[0]); - dsp_state = DspState::Off; - break; - } - - return; - } - default: - LOG_CRITICAL(Audio_DSP, "pipe_number = %zu unimplemented", - static_cast<size_t>(pipe_number)); - UNIMPLEMENTED(); - return; - } -} - -DspState GetDspState() { - return dsp_state; -} - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/pipe.h b/src/audio_core/hle/pipe.h deleted file mode 100644 index ac053c029..000000000 --- a/src/audio_core/hle/pipe.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <cstddef> -#include <vector> -#include "common/common_types.h" - -namespace DSP { -namespace HLE { - -/// Reset the pipes by setting pipe positions back to the beginning. -void ResetPipes(); - -enum class DspPipe { - Debug = 0, - Dma = 1, - Audio = 2, - Binary = 3, -}; -constexpr size_t NUM_DSP_PIPE = 8; - -/** - * Reads `length` bytes from the DSP pipe identified with `pipe_number`. - * @note Can read up to the maximum value of a u16 in bytes (65,535). - * @note IF an error is encoutered with either an invalid `pipe_number` or `length` value, an empty - * vector will be returned. - * @note IF `length` is set to 0, an empty vector will be returned. - * @note IF `length` is greater than the amount of data available, this function will only read the - * available amount. - * @param pipe_number a `DspPipe` - * @param length the number of bytes to read. The max is 65,535 (max of u16). - * @returns a vector of bytes from the specified pipe. On error, will be empty. - */ -std::vector<u8> PipeRead(DspPipe pipe_number, u32 length); - -/** - * How much data is left in pipe - * @param pipe_number The Pipe ID - * @return The amount of data remaning in the pipe. This is the maximum length PipeRead will return. - */ -size_t GetPipeReadableSize(DspPipe pipe_number); - -/** - * Write to a DSP pipe. - * @param pipe_number The Pipe ID - * @param buffer The data to write to the pipe. - */ -void PipeWrite(DspPipe pipe_number, const std::vector<u8>& buffer); - -enum class DspState { - Off, - On, - Sleeping, -}; - -/// Get the state of the DSP -DspState GetDspState(); - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/source.cpp b/src/audio_core/hle/source.cpp deleted file mode 100644 index c12287700..000000000 --- a/src/audio_core/hle/source.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <algorithm> -#include <array> -#include "audio_core/codec.h" -#include "audio_core/hle/common.h" -#include "audio_core/hle/source.h" -#include "audio_core/interpolate.h" -#include "common/assert.h" -#include "common/logging/log.h" -#include "core/memory.h" - -namespace DSP { -namespace HLE { - -SourceStatus::Status Source::Tick(SourceConfiguration::Configuration& config, - const s16_le (&adpcm_coeffs)[16]) { - ParseConfig(config, adpcm_coeffs); - - if (state.enabled) { - GenerateFrame(); - } - - return GetCurrentStatus(); -} - -void Source::MixInto(QuadFrame32& dest, size_t intermediate_mix_id) const { - if (!state.enabled) - return; - - const std::array<float, 4>& gains = state.gain.at(intermediate_mix_id); - for (size_t samplei = 0; samplei < samples_per_frame; samplei++) { - // Conversion from stereo (current_frame) to quadraphonic (dest) occurs here. - dest[samplei][0] += static_cast<s32>(gains[0] * current_frame[samplei][0]); - dest[samplei][1] += static_cast<s32>(gains[1] * current_frame[samplei][1]); - dest[samplei][2] += static_cast<s32>(gains[2] * current_frame[samplei][0]); - dest[samplei][3] += static_cast<s32>(gains[3] * current_frame[samplei][1]); - } -} - -void Source::Reset() { - current_frame.fill({}); - state = {}; -} - -void Source::ParseConfig(SourceConfiguration::Configuration& config, - const s16_le (&adpcm_coeffs)[16]) { - if (!config.dirty_raw) { - return; - } - - if (config.reset_flag) { - config.reset_flag.Assign(0); - Reset(); - LOG_TRACE(Audio_DSP, "source_id=%zu reset", source_id); - } - - if (config.partial_reset_flag) { - config.partial_reset_flag.Assign(0); - state.input_queue = std::priority_queue<Buffer, std::vector<Buffer>, BufferOrder>{}; - LOG_TRACE(Audio_DSP, "source_id=%zu partial_reset", source_id); - } - - if (config.enable_dirty) { - config.enable_dirty.Assign(0); - state.enabled = config.enable != 0; - LOG_TRACE(Audio_DSP, "source_id=%zu enable=%d", source_id, state.enabled); - } - - if (config.sync_dirty) { - config.sync_dirty.Assign(0); - state.sync = config.sync; - LOG_TRACE(Audio_DSP, "source_id=%zu sync=%u", source_id, state.sync); - } - - if (config.rate_multiplier_dirty) { - config.rate_multiplier_dirty.Assign(0); - state.rate_multiplier = config.rate_multiplier; - LOG_TRACE(Audio_DSP, "source_id=%zu rate=%f", source_id, state.rate_multiplier); - - if (state.rate_multiplier <= 0) { - LOG_ERROR(Audio_DSP, "Was given an invalid rate multiplier: source_id=%zu rate=%f", - source_id, state.rate_multiplier); - state.rate_multiplier = 1.0f; - // Note: Actual firmware starts producing garbage if this occurs. - } - } - - if (config.adpcm_coefficients_dirty) { - config.adpcm_coefficients_dirty.Assign(0); - std::transform(adpcm_coeffs, adpcm_coeffs + state.adpcm_coeffs.size(), - state.adpcm_coeffs.begin(), - [](const auto& coeff) { return static_cast<s16>(coeff); }); - LOG_TRACE(Audio_DSP, "source_id=%zu adpcm update", source_id); - } - - if (config.gain_0_dirty) { - config.gain_0_dirty.Assign(0); - std::transform(config.gain[0], config.gain[0] + state.gain[0].size(), state.gain[0].begin(), - [](const auto& coeff) { return static_cast<float>(coeff); }); - LOG_TRACE(Audio_DSP, "source_id=%zu gain 0 update", source_id); - } - - if (config.gain_1_dirty) { - config.gain_1_dirty.Assign(0); - std::transform(config.gain[1], config.gain[1] + state.gain[1].size(), state.gain[1].begin(), - [](const auto& coeff) { return static_cast<float>(coeff); }); - LOG_TRACE(Audio_DSP, "source_id=%zu gain 1 update", source_id); - } - - if (config.gain_2_dirty) { - config.gain_2_dirty.Assign(0); - std::transform(config.gain[2], config.gain[2] + state.gain[2].size(), state.gain[2].begin(), - [](const auto& coeff) { return static_cast<float>(coeff); }); - LOG_TRACE(Audio_DSP, "source_id=%zu gain 2 update", source_id); - } - - if (config.filters_enabled_dirty) { - config.filters_enabled_dirty.Assign(0); - state.filters.Enable(config.simple_filter_enabled.ToBool(), - config.biquad_filter_enabled.ToBool()); - LOG_TRACE(Audio_DSP, "source_id=%zu enable_simple=%hu enable_biquad=%hu", source_id, - config.simple_filter_enabled.Value(), config.biquad_filter_enabled.Value()); - } - - if (config.simple_filter_dirty) { - config.simple_filter_dirty.Assign(0); - state.filters.Configure(config.simple_filter); - LOG_TRACE(Audio_DSP, "source_id=%zu simple filter update", source_id); - } - - if (config.biquad_filter_dirty) { - config.biquad_filter_dirty.Assign(0); - state.filters.Configure(config.biquad_filter); - LOG_TRACE(Audio_DSP, "source_id=%zu biquad filter update", source_id); - } - - if (config.interpolation_dirty) { - config.interpolation_dirty.Assign(0); - state.interpolation_mode = config.interpolation_mode; - LOG_TRACE(Audio_DSP, "source_id=%zu interpolation_mode=%zu", source_id, - static_cast<size_t>(state.interpolation_mode)); - } - - if (config.format_dirty || config.embedded_buffer_dirty) { - config.format_dirty.Assign(0); - state.format = config.format; - LOG_TRACE(Audio_DSP, "source_id=%zu format=%zu", source_id, - static_cast<size_t>(state.format)); - } - - if (config.mono_or_stereo_dirty || config.embedded_buffer_dirty) { - config.mono_or_stereo_dirty.Assign(0); - state.mono_or_stereo = config.mono_or_stereo; - LOG_TRACE(Audio_DSP, "source_id=%zu mono_or_stereo=%zu", source_id, - static_cast<size_t>(state.mono_or_stereo)); - } - - u32_dsp play_position = {}; - if (config.play_position_dirty && config.play_position != 0) { - config.play_position_dirty.Assign(0); - play_position = config.play_position; - // play_position applies only to the embedded buffer, and defaults to 0 w/o a dirty bit - // This will be the starting sample for the first time the buffer is played. - } - - if (config.embedded_buffer_dirty) { - config.embedded_buffer_dirty.Assign(0); - state.input_queue.emplace(Buffer{ - config.physical_address, - config.length, - static_cast<u8>(config.adpcm_ps), - {config.adpcm_yn[0], config.adpcm_yn[1]}, - config.adpcm_dirty.ToBool(), - config.is_looping.ToBool(), - config.buffer_id, - state.mono_or_stereo, - state.format, - false, - play_position, - false, - }); - LOG_TRACE(Audio_DSP, "enqueuing embedded addr=0x%08x len=%u id=%hu start=%u", - config.physical_address, config.length, config.buffer_id, - static_cast<u32>(config.play_position)); - } - - if (config.loop_related_dirty && config.loop_related != 0) { - config.loop_related_dirty.Assign(0); - LOG_WARNING(Audio_DSP, "Unhandled complex loop with loop_related=0x%08x", - static_cast<u32>(config.loop_related)); - } - - if (config.buffer_queue_dirty) { - config.buffer_queue_dirty.Assign(0); - for (size_t i = 0; i < 4; i++) { - if (config.buffers_dirty & (1 << i)) { - const auto& b = config.buffers[i]; - state.input_queue.emplace(Buffer{ - b.physical_address, - b.length, - static_cast<u8>(b.adpcm_ps), - {b.adpcm_yn[0], b.adpcm_yn[1]}, - b.adpcm_dirty != 0, - b.is_looping != 0, - b.buffer_id, - state.mono_or_stereo, - state.format, - true, - {}, // 0 in u32_dsp - false, - }); - LOG_TRACE(Audio_DSP, "enqueuing queued %zu addr=0x%08x len=%u id=%hu", i, - b.physical_address, b.length, b.buffer_id); - } - } - config.buffers_dirty = 0; - } - - if (config.dirty_raw) { - LOG_DEBUG(Audio_DSP, "source_id=%zu remaining_dirty=%x", source_id, config.dirty_raw); - } - - config.dirty_raw = 0; -} - -void Source::GenerateFrame() { - current_frame.fill({}); - - if (state.current_buffer.empty() && !DequeueBuffer()) { - state.enabled = false; - state.buffer_update = true; - state.current_buffer_id = 0; - return; - } - - size_t frame_position = 0; - - state.current_sample_number = state.next_sample_number; - while (frame_position < current_frame.size()) { - if (state.current_buffer.empty() && !DequeueBuffer()) { - break; - } - - switch (state.interpolation_mode) { - case InterpolationMode::None: - AudioInterp::None(state.interp_state, state.current_buffer, state.rate_multiplier, - current_frame, frame_position); - break; - case InterpolationMode::Linear: - AudioInterp::Linear(state.interp_state, state.current_buffer, state.rate_multiplier, - current_frame, frame_position); - break; - case InterpolationMode::Polyphase: - // TODO(merry): Implement polyphase interpolation - LOG_DEBUG(Audio_DSP, "Polyphase interpolation unimplemented; falling back to linear"); - AudioInterp::Linear(state.interp_state, state.current_buffer, state.rate_multiplier, - current_frame, frame_position); - break; - default: - UNIMPLEMENTED(); - break; - } - } - state.next_sample_number += static_cast<u32>(frame_position); - - state.filters.ProcessFrame(current_frame); -} - -bool Source::DequeueBuffer() { - ASSERT_MSG(state.current_buffer.empty(), - "Shouldn't dequeue; we still have data in current_buffer"); - - if (state.input_queue.empty()) - return false; - - Buffer buf = state.input_queue.top(); - - // if we're in a loop, the current sound keeps playing afterwards, so leave the queue alone - if (!buf.is_looping) { - state.input_queue.pop(); - } - - if (buf.adpcm_dirty) { - state.adpcm_state.yn1 = buf.adpcm_yn[0]; - state.adpcm_state.yn2 = buf.adpcm_yn[1]; - } - - const u8* const memory = Memory::GetPhysicalPointer(buf.physical_address); - if (memory) { - const unsigned num_channels = buf.mono_or_stereo == MonoOrStereo::Stereo ? 2 : 1; - switch (buf.format) { - case Format::PCM8: - state.current_buffer = Codec::DecodePCM8(num_channels, memory, buf.length); - break; - case Format::PCM16: - state.current_buffer = Codec::DecodePCM16(num_channels, memory, buf.length); - break; - case Format::ADPCM: - DEBUG_ASSERT(num_channels == 1); - state.current_buffer = - Codec::DecodeADPCM(memory, buf.length, state.adpcm_coeffs, state.adpcm_state); - break; - default: - UNIMPLEMENTED(); - break; - } - } else { - LOG_WARNING(Audio_DSP, - "source_id=%zu buffer_id=%hu length=%u: Invalid physical address 0x%08X", - source_id, buf.buffer_id, buf.length, buf.physical_address); - state.current_buffer.clear(); - return true; - } - - // the first playthrough starts at play_position, loops start at the beginning of the buffer - state.current_sample_number = (!buf.has_played) ? buf.play_position : 0; - state.next_sample_number = state.current_sample_number; - state.current_buffer_id = buf.buffer_id; - state.buffer_update = buf.from_queue && !buf.has_played; - - buf.has_played = true; - - LOG_TRACE(Audio_DSP, "source_id=%zu buffer_id=%hu from_queue=%s current_buffer.size()=%zu", - source_id, buf.buffer_id, buf.from_queue ? "true" : "false", - state.current_buffer.size()); - return true; -} - -SourceStatus::Status Source::GetCurrentStatus() { - SourceStatus::Status ret; - - // Applications depend on the correct emulation of - // current_buffer_id_dirty and current_buffer_id to synchronise - // audio with video. - ret.is_enabled = state.enabled; - ret.current_buffer_id_dirty = state.buffer_update ? 1 : 0; - state.buffer_update = false; - ret.current_buffer_id = state.current_buffer_id; - ret.buffer_position = state.current_sample_number; - ret.sync = state.sync; - - return ret; -} - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/hle/source.h b/src/audio_core/hle/source.h deleted file mode 100644 index c4d2debc2..000000000 --- a/src/audio_core/hle/source.h +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <queue> -#include <vector> -#include "audio_core/codec.h" -#include "audio_core/hle/common.h" -#include "audio_core/hle/dsp.h" -#include "audio_core/hle/filter.h" -#include "audio_core/interpolate.h" -#include "common/common_types.h" - -namespace DSP { -namespace HLE { - -/** - * This module performs: - * - Buffer management - * - Decoding of buffers - * - Buffer resampling and interpolation - * - Per-source filtering (SimpleFilter, BiquadFilter) - * - Per-source gain - * - Other per-source processing - */ -class Source final { -public: - explicit Source(size_t source_id_) : source_id(source_id_) { - Reset(); - } - - /// Resets internal state. - void Reset(); - - /** - * This is called once every audio frame. This performs per-source processing every frame. - * @param config The new configuration we've got for this Source from the application. - * @param adpcm_coeffs ADPCM coefficients to use if config tells us to use them (may contain - * invalid values otherwise). - * @return The current status of this Source. This is given back to the emulated application via - * SharedMemory. - */ - SourceStatus::Status Tick(SourceConfiguration::Configuration& config, - const s16_le (&adpcm_coeffs)[16]); - - /** - * Mix this source's output into dest, using the gains for the `intermediate_mix_id`-th - * intermediate mixer. - * @param dest The QuadFrame32 to mix into. - * @param intermediate_mix_id The id of the intermediate mix whose gains we are using. - */ - void MixInto(QuadFrame32& dest, size_t intermediate_mix_id) const; - -private: - const size_t source_id; - StereoFrame16 current_frame; - - using Format = SourceConfiguration::Configuration::Format; - using InterpolationMode = SourceConfiguration::Configuration::InterpolationMode; - using MonoOrStereo = SourceConfiguration::Configuration::MonoOrStereo; - - /// Internal representation of a buffer for our buffer queue - struct Buffer { - PAddr physical_address; - u32 length; - u8 adpcm_ps; - std::array<u16, 2> adpcm_yn; - bool adpcm_dirty; - bool is_looping; - u16 buffer_id; - - MonoOrStereo mono_or_stereo; - Format format; - - bool from_queue; - u32_dsp play_position; // = 0; - bool has_played; // = false; - }; - - struct BufferOrder { - bool operator()(const Buffer& a, const Buffer& b) const { - // Lower buffer_id comes first. - return a.buffer_id > b.buffer_id; - } - }; - - struct { - - // State variables - - bool enabled = false; - u16 sync = 0; - - // Mixing - - std::array<std::array<float, 4>, 3> gain = {}; - - // Buffer queue - - std::priority_queue<Buffer, std::vector<Buffer>, BufferOrder> input_queue; - MonoOrStereo mono_or_stereo = MonoOrStereo::Mono; - Format format = Format::ADPCM; - - // Current buffer - - u32 current_sample_number = 0; - u32 next_sample_number = 0; - AudioInterp::StereoBuffer16 current_buffer; - - // buffer_id state - - bool buffer_update = false; - u32 current_buffer_id = 0; - - // Decoding state - - std::array<s16, 16> adpcm_coeffs = {}; - Codec::ADPCMState adpcm_state = {}; - - // Resampling state - - float rate_multiplier = 1.0; - InterpolationMode interpolation_mode = InterpolationMode::Polyphase; - AudioInterp::State interp_state = {}; - - // Filter state - - SourceFilters filters; - - } state; - - // Internal functions - - /// INTERNAL: Update our internal state based on the current config. - void ParseConfig(SourceConfiguration::Configuration& config, const s16_le (&adpcm_coeffs)[16]); - /// INTERNAL: Generate the current audio output for this frame based on our internal state. - void GenerateFrame(); - /// INTERNAL: Dequeues a buffer and does preprocessing on it (decoding, resampling). Puts it - /// into current_buffer. - bool DequeueBuffer(); - /// INTERNAL: Generates a SourceStatus::Status based on our internal state. - SourceStatus::Status GetCurrentStatus(); -}; - -} // namespace HLE -} // namespace DSP diff --git a/src/audio_core/interpolate.cpp b/src/audio_core/interpolate.cpp deleted file mode 100644 index 83573d772..000000000 --- a/src/audio_core/interpolate.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include "audio_core/interpolate.h" -#include "common/assert.h" -#include "common/math_util.h" - -namespace AudioInterp { - -// Calculations are done in fixed point with 24 fractional bits. -// (This is not verified. This was chosen for minimal error.) -constexpr u64 scale_factor = 1 << 24; -constexpr u64 scale_mask = scale_factor - 1; - -/// Here we step over the input in steps of rate, until we consume all of the input. -/// Three adjacent samples are passed to fn each step. -template <typename Function> -static void StepOverSamples(State& state, StereoBuffer16& input, float rate, - DSP::HLE::StereoFrame16& output, size_t& outputi, Function fn) { - ASSERT(rate > 0); - - if (input.empty()) - return; - - input.insert(input.begin(), {state.xn2, state.xn1}); - - const u64 step_size = static_cast<u64>(rate * scale_factor); - u64 fposition = state.fposition; - size_t inputi = 0; - - while (outputi < output.size()) { - inputi = static_cast<size_t>(fposition / scale_factor); - - if (inputi + 2 >= input.size()) { - inputi = input.size() - 2; - break; - } - - u64 fraction = fposition & scale_mask; - output[outputi++] = fn(fraction, input[inputi], input[inputi + 1], input[inputi + 2]); - - fposition += step_size; - } - - state.xn2 = input[inputi]; - state.xn1 = input[inputi + 1]; - state.fposition = fposition - inputi * scale_factor; - - input.erase(input.begin(), std::next(input.begin(), inputi + 2)); -} - -void None(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output, - size_t& outputi) { - StepOverSamples( - state, input, rate, output, outputi, - [](u64 fraction, const auto& x0, const auto& x1, const auto& x2) { return x0; }); -} - -void Linear(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output, - size_t& outputi) { - // Note on accuracy: Some values that this produces are +/- 1 from the actual firmware. - StepOverSamples(state, input, rate, output, outputi, - [](u64 fraction, const auto& x0, const auto& x1, const auto& x2) { - // This is a saturated subtraction. (Verified by black-box fuzzing.) - s64 delta0 = MathUtil::Clamp<s64>(x1[0] - x0[0], -32768, 32767); - s64 delta1 = MathUtil::Clamp<s64>(x1[1] - x0[1], -32768, 32767); - - return std::array<s16, 2>{ - static_cast<s16>(x0[0] + fraction * delta0 / scale_factor), - static_cast<s16>(x0[1] + fraction * delta1 / scale_factor), - }; - }); -} - -} // namespace AudioInterp diff --git a/src/audio_core/interpolate.h b/src/audio_core/interpolate.h deleted file mode 100644 index 8dff6111a..000000000 --- a/src/audio_core/interpolate.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <deque> -#include "audio_core/hle/common.h" -#include "common/common_types.h" - -namespace AudioInterp { - -/// A variable length buffer of signed PCM16 stereo samples. -using StereoBuffer16 = std::deque<std::array<s16, 2>>; - -struct State { - /// Two historical samples. - std::array<s16, 2> xn1 = {}; ///< x[n-1] - std::array<s16, 2> xn2 = {}; ///< x[n-2] - /// Current fractional position. - u64 fposition = 0; -}; - -/** - * No interpolation. This is equivalent to a zero-order hold. There is a two-sample predelay. - * @param state Interpolation state. - * @param input Input buffer. - * @param rate Stretch factor. Must be a positive non-zero value. - * rate > 1.0 performs decimation and rate < 1.0 performs upsampling. - * @param output The resampled audio buffer. - * @param outputi The index of output to start writing to. - */ -void None(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output, - size_t& outputi); - -/** - * Linear interpolation. This is equivalent to a first-order hold. There is a two-sample predelay. - * @param state Interpolation state. - * @param input Input buffer. - * @param rate Stretch factor. Must be a positive non-zero value. - * rate > 1.0 performs decimation and rate < 1.0 performs upsampling. - * @param output The resampled audio buffer. - * @param outputi The index of output to start writing to. - */ -void Linear(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output, - size_t& outputi); - -} // namespace AudioInterp diff --git a/src/audio_core/null_sink.h b/src/audio_core/null_sink.h deleted file mode 100644 index c732926a2..000000000 --- a/src/audio_core/null_sink.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <cstddef> -#include "audio_core/audio_core.h" -#include "audio_core/sink.h" - -namespace AudioCore { - -class NullSink final : public Sink { -public: - ~NullSink() override = default; - - unsigned int GetNativeSampleRate() const override { - return native_sample_rate; - } - - void EnqueueSamples(const s16*, size_t) override {} - - size_t SamplesInQueue() const override { - return 0; - } - - void SetDevice(int device_id) override {} - - std::vector<std::string> GetDeviceList() const override { - return {}; - } -}; - -} // namespace AudioCore diff --git a/src/audio_core/sdl2_sink.cpp b/src/audio_core/sdl2_sink.cpp deleted file mode 100644 index 933c5f16d..000000000 --- a/src/audio_core/sdl2_sink.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <list> -#include <numeric> -#include <SDL.h> -#include "audio_core/audio_core.h" -#include "audio_core/sdl2_sink.h" -#include "common/assert.h" -#include "common/logging/log.h" -#include "core/settings.h" - -namespace AudioCore { - -struct SDL2Sink::Impl { - unsigned int sample_rate = 0; - - SDL_AudioDeviceID audio_device_id = 0; - - std::list<std::vector<s16>> queue; - - static void Callback(void* impl_, u8* buffer, int buffer_size_in_bytes); -}; - -SDL2Sink::SDL2Sink() : impl(std::make_unique<Impl>()) { - if (SDL_Init(SDL_INIT_AUDIO) < 0) { - LOG_CRITICAL(Audio_Sink, "SDL_Init(SDL_INIT_AUDIO) failed with: %s", SDL_GetError()); - impl->audio_device_id = 0; - return; - } - - SDL_AudioSpec desired_audiospec; - SDL_zero(desired_audiospec); - desired_audiospec.format = AUDIO_S16; - desired_audiospec.channels = 2; - desired_audiospec.freq = native_sample_rate; - desired_audiospec.samples = 512; - desired_audiospec.userdata = impl.get(); - desired_audiospec.callback = &Impl::Callback; - - SDL_AudioSpec obtained_audiospec; - SDL_zero(obtained_audiospec); - - int device_count = SDL_GetNumAudioDevices(0); - device_list.clear(); - for (int i = 0; i < device_count; ++i) { - device_list.push_back(SDL_GetAudioDeviceName(i, 0)); - } - - const char* device = nullptr; - - if (device_count >= 1 && Settings::values.audio_device_id != "auto" && - !Settings::values.audio_device_id.empty()) { - device = Settings::values.audio_device_id.c_str(); - } - - impl->audio_device_id = SDL_OpenAudioDevice(device, false, &desired_audiospec, - &obtained_audiospec, SDL_AUDIO_ALLOW_ANY_CHANGE); - if (impl->audio_device_id <= 0) { - LOG_CRITICAL(Audio_Sink, "SDL_OpenAudioDevice failed with code %d for device \"%s\"", - impl->audio_device_id, Settings::values.audio_device_id.c_str()); - return; - } - - impl->sample_rate = obtained_audiospec.freq; - - // SDL2 audio devices start out paused, unpause it: - SDL_PauseAudioDevice(impl->audio_device_id, 0); -} - -SDL2Sink::~SDL2Sink() { - if (impl->audio_device_id <= 0) - return; - - SDL_CloseAudioDevice(impl->audio_device_id); -} - -unsigned int SDL2Sink::GetNativeSampleRate() const { - if (impl->audio_device_id <= 0) - return native_sample_rate; - - return impl->sample_rate; -} - -std::vector<std::string> SDL2Sink::GetDeviceList() const { - return device_list; -} - -void SDL2Sink::EnqueueSamples(const s16* samples, size_t sample_count) { - if (impl->audio_device_id <= 0) - return; - - SDL_LockAudioDevice(impl->audio_device_id); - impl->queue.emplace_back(samples, samples + sample_count * 2); - SDL_UnlockAudioDevice(impl->audio_device_id); -} - -size_t SDL2Sink::SamplesInQueue() const { - if (impl->audio_device_id <= 0) - return 0; - - SDL_LockAudioDevice(impl->audio_device_id); - - size_t total_size = std::accumulate(impl->queue.begin(), impl->queue.end(), - static_cast<size_t>(0), [](size_t sum, const auto& buffer) { - // Division by two because each stereo sample is made of - // two s16. - return sum + buffer.size() / 2; - }); - - SDL_UnlockAudioDevice(impl->audio_device_id); - - return total_size; -} - -void SDL2Sink::SetDevice(int device_id) { - this->device_id = device_id; -} - -void SDL2Sink::Impl::Callback(void* impl_, u8* buffer, int buffer_size_in_bytes) { - Impl* impl = reinterpret_cast<Impl*>(impl_); - - size_t remaining_size = static_cast<size_t>(buffer_size_in_bytes) / - sizeof(s16); // Keep track of size in 16-bit increments. - - while (remaining_size > 0 && !impl->queue.empty()) { - if (impl->queue.front().size() <= remaining_size) { - memcpy(buffer, impl->queue.front().data(), impl->queue.front().size() * sizeof(s16)); - buffer += impl->queue.front().size() * sizeof(s16); - remaining_size -= impl->queue.front().size(); - impl->queue.pop_front(); - } else { - memcpy(buffer, impl->queue.front().data(), remaining_size * sizeof(s16)); - buffer += remaining_size * sizeof(s16); - impl->queue.front().erase(impl->queue.front().begin(), - impl->queue.front().begin() + remaining_size); - remaining_size = 0; - } - } - - if (remaining_size > 0) { - memset(buffer, 0, remaining_size * sizeof(s16)); - } -} - -} // namespace AudioCore diff --git a/src/audio_core/sdl2_sink.h b/src/audio_core/sdl2_sink.h deleted file mode 100644 index bcc725369..000000000 --- a/src/audio_core/sdl2_sink.h +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <cstddef> -#include <memory> -#include "audio_core/sink.h" - -namespace AudioCore { - -class SDL2Sink final : public Sink { -public: - SDL2Sink(); - ~SDL2Sink() override; - - unsigned int GetNativeSampleRate() const override; - - void EnqueueSamples(const s16* samples, size_t sample_count) override; - - size_t SamplesInQueue() const override; - - std::vector<std::string> GetDeviceList() const override; - void SetDevice(int device_id) override; - -private: - struct Impl; - std::unique_ptr<Impl> impl; - int device_id; - std::vector<std::string> device_list; -}; - -} // namespace AudioCore diff --git a/src/audio_core/sink.h b/src/audio_core/sink.h deleted file mode 100644 index c69cb2c74..000000000 --- a/src/audio_core/sink.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <vector> -#include "common/common_types.h" - -namespace AudioCore { - -/** - * This class is an interface for an audio sink. An audio sink accepts samples in stereo signed - * PCM16 format to be output. Sinks *do not* handle resampling and expect the correct sample rate. - * They are dumb outputs. - */ -class Sink { -public: - virtual ~Sink() = default; - - /// The native rate of this sink. The sink expects to be fed samples that respect this. (Units: - /// samples/sec) - virtual unsigned int GetNativeSampleRate() const = 0; - - /** - * Feed stereo samples to sink. - * @param samples Samples in interleaved stereo PCM16 format. - * @param sample_count Number of samples. - */ - virtual void EnqueueSamples(const s16* samples, size_t sample_count) = 0; - - /// Samples enqueued that have not been played yet. - virtual std::size_t SamplesInQueue() const = 0; - - /** - * Sets the desired output device. - * @param device_id ID of the desired device. - */ - virtual void SetDevice(int device_id) = 0; - - /// Returns the list of available devices. - virtual std::vector<std::string> GetDeviceList() const = 0; -}; - -} // namespace diff --git a/src/audio_core/sink_details.cpp b/src/audio_core/sink_details.cpp deleted file mode 100644 index 6972395af..000000000 --- a/src/audio_core/sink_details.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <algorithm> -#include <memory> -#include <vector> -#include "audio_core/null_sink.h" -#include "audio_core/sink_details.h" -#ifdef HAVE_SDL2 -#include "audio_core/sdl2_sink.h" -#endif -#include "common/logging/log.h" - -namespace AudioCore { - -// g_sink_details is ordered in terms of desirability, with the best choice at the top. -const std::vector<SinkDetails> g_sink_details = { -#ifdef HAVE_SDL2 - {"sdl2", []() { return std::make_unique<SDL2Sink>(); }}, -#endif - {"null", []() { return std::make_unique<NullSink>(); }}, -}; - -const SinkDetails& GetSinkDetails(std::string sink_id) { - auto iter = - std::find_if(g_sink_details.begin(), g_sink_details.end(), - [sink_id](const auto& sink_detail) { return sink_detail.id == sink_id; }); - - if (sink_id == "auto" || iter == g_sink_details.end()) { - if (sink_id != "auto") { - LOG_ERROR(Audio, "AudioCore::SelectSink given invalid sink_id %s", sink_id.c_str()); - } - // Auto-select. - // g_sink_details is ordered in terms of desirability, with the best choice at the front. - iter = g_sink_details.begin(); - } - - return *iter; -} - -} // namespace AudioCore diff --git a/src/audio_core/sink_details.h b/src/audio_core/sink_details.h deleted file mode 100644 index 9d3735171..000000000 --- a/src/audio_core/sink_details.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <functional> -#include <memory> -#include <vector> - -namespace AudioCore { - -class Sink; - -struct SinkDetails { - SinkDetails(const char* id_, std::function<std::unique_ptr<Sink>()> factory_) - : id(id_), factory(factory_) {} - - /// Name for this sink. - const char* id; - /// A method to call to construct an instance of this type of sink. - std::function<std::unique_ptr<Sink>()> factory; -}; - -extern const std::vector<SinkDetails> g_sink_details; - -const SinkDetails& GetSinkDetails(std::string sink_id); - -} // namespace AudioCore diff --git a/src/audio_core/time_stretch.cpp b/src/audio_core/time_stretch.cpp deleted file mode 100644 index 437cf9752..000000000 --- a/src/audio_core/time_stretch.cpp +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <chrono> -#include <cmath> -#include <vector> -#include <SoundTouch.h> -#include "audio_core/audio_core.h" -#include "audio_core/time_stretch.h" -#include "common/common_types.h" -#include "common/logging/log.h" -#include "common/math_util.h" - -using steady_clock = std::chrono::steady_clock; - -namespace AudioCore { - -constexpr double MIN_RATIO = 0.1; -constexpr double MAX_RATIO = 100.0; - -static double ClampRatio(double ratio) { - return MathUtil::Clamp(ratio, MIN_RATIO, MAX_RATIO); -} - -constexpr double MIN_DELAY_TIME = 0.05; // Units: seconds -constexpr double MAX_DELAY_TIME = 0.25; // Units: seconds -constexpr size_t DROP_FRAMES_SAMPLE_DELAY = 16000; // Units: samples - -constexpr double SMOOTHING_FACTOR = 0.007; - -struct TimeStretcher::Impl { - soundtouch::SoundTouch soundtouch; - - steady_clock::time_point frame_timer = steady_clock::now(); - size_t samples_queued = 0; - - double smoothed_ratio = 1.0; - - double sample_rate = static_cast<double>(native_sample_rate); -}; - -std::vector<s16> TimeStretcher::Process(size_t samples_in_queue) { - // This is a very simple algorithm without any fancy control theory. It works and is stable. - - double ratio = CalculateCurrentRatio(); - ratio = CorrectForUnderAndOverflow(ratio, samples_in_queue); - impl->smoothed_ratio = - (1.0 - SMOOTHING_FACTOR) * impl->smoothed_ratio + SMOOTHING_FACTOR * ratio; - impl->smoothed_ratio = ClampRatio(impl->smoothed_ratio); - - // SoundTouch's tempo definition the inverse of our ratio definition. - impl->soundtouch.setTempo(1.0 / impl->smoothed_ratio); - - std::vector<s16> samples = GetSamples(); - if (samples_in_queue >= DROP_FRAMES_SAMPLE_DELAY) { - samples.clear(); - LOG_TRACE(Audio, "Dropping frames!"); - } - return samples; -} - -TimeStretcher::TimeStretcher() : impl(std::make_unique<Impl>()) { - impl->soundtouch.setPitch(1.0); - impl->soundtouch.setChannels(2); - impl->soundtouch.setSampleRate(native_sample_rate); - Reset(); -} - -TimeStretcher::~TimeStretcher() { - impl->soundtouch.clear(); -} - -void TimeStretcher::SetOutputSampleRate(unsigned int sample_rate) { - impl->sample_rate = static_cast<double>(sample_rate); - impl->soundtouch.setRate(static_cast<double>(native_sample_rate) / impl->sample_rate); -} - -void TimeStretcher::AddSamples(const s16* buffer, size_t num_samples) { - impl->soundtouch.putSamples(buffer, static_cast<uint>(num_samples)); - impl->samples_queued += num_samples; -} - -void TimeStretcher::Flush() { - impl->soundtouch.flush(); -} - -void TimeStretcher::Reset() { - impl->soundtouch.setTempo(1.0); - impl->soundtouch.clear(); - impl->smoothed_ratio = 1.0; - impl->frame_timer = steady_clock::now(); - impl->samples_queued = 0; - SetOutputSampleRate(native_sample_rate); -} - -double TimeStretcher::CalculateCurrentRatio() { - const steady_clock::time_point now = steady_clock::now(); - const std::chrono::duration<double> duration = now - impl->frame_timer; - - const double expected_time = - static_cast<double>(impl->samples_queued) / static_cast<double>(native_sample_rate); - const double actual_time = duration.count(); - - double ratio; - if (expected_time != 0) { - ratio = ClampRatio(actual_time / expected_time); - } else { - ratio = impl->smoothed_ratio; - } - - impl->frame_timer = now; - impl->samples_queued = 0; - - return ratio; -} - -double TimeStretcher::CorrectForUnderAndOverflow(double ratio, size_t sample_delay) const { - const size_t min_sample_delay = static_cast<size_t>(MIN_DELAY_TIME * impl->sample_rate); - const size_t max_sample_delay = static_cast<size_t>(MAX_DELAY_TIME * impl->sample_rate); - - if (sample_delay < min_sample_delay) { - // Make the ratio bigger. - ratio = ratio > 1.0 ? ratio * ratio : sqrt(ratio); - } else if (sample_delay > max_sample_delay) { - // Make the ratio smaller. - ratio = ratio > 1.0 ? sqrt(ratio) : ratio * ratio; - } - - return ClampRatio(ratio); -} - -std::vector<s16> TimeStretcher::GetSamples() { - uint available = impl->soundtouch.numSamples(); - - std::vector<s16> output(static_cast<size_t>(available) * 2); - - impl->soundtouch.receiveSamples(output.data(), available); - - return output; -} - -} // namespace AudioCore diff --git a/src/audio_core/time_stretch.h b/src/audio_core/time_stretch.h deleted file mode 100644 index c98b16705..000000000 --- a/src/audio_core/time_stretch.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2016 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <cstddef> -#include <memory> -#include <vector> -#include "common/common_types.h" - -namespace AudioCore { - -class TimeStretcher final { -public: - TimeStretcher(); - ~TimeStretcher(); - - /** - * Set sample rate for the samples that Process returns. - * @param sample_rate The sample rate. - */ - void SetOutputSampleRate(unsigned int sample_rate); - - /** - * Add samples to be processed. - * @param sample_buffer Buffer of samples in interleaved stereo PCM16 format. - * @param num_samples Number of samples. - */ - void AddSamples(const s16* sample_buffer, size_t num_samples); - - /// Flush audio remaining in internal buffers. - void Flush(); - - /// Resets internal state and clears buffers. - void Reset(); - - /** - * Does audio stretching and produces the time-stretched samples. - * Timer calculations use sample_delay to determine how much of a margin we have. - * @param sample_delay How many samples are buffered downstream of this module and haven't been - * played yet. - * @return Samples to play in interleaved stereo PCM16 format. - */ - std::vector<s16> Process(size_t sample_delay); - -private: - struct Impl; - std::unique_ptr<Impl> impl; - - /// INTERNAL: ratio = wallclock time / emulated time - double CalculateCurrentRatio(); - /// INTERNAL: If we have too many or too few samples downstream, nudge ratio in the appropriate - /// direction. - double CorrectForUnderAndOverflow(double ratio, size_t sample_delay) const; - /// INTERNAL: Gets the time-stretched samples from SoundTouch. - std::vector<s16> GetSamples(); -}; - -} // namespace AudioCore diff --git a/src/network/CMakeLists.txt b/src/network/CMakeLists.txt deleted file mode 100644 index ac9d028da..000000000 --- a/src/network/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -set(SRCS - network.cpp - packet.cpp - room.cpp - room_member.cpp - ) - -set(HEADERS - network.h - packet.h - room.h - room_member.h - ) - -create_directory_groups(${SRCS} ${HEADERS}) - -add_library(network STATIC ${SRCS} ${HEADERS}) -target_link_libraries(network PRIVATE common enet) diff --git a/src/network/network.cpp b/src/network/network.cpp deleted file mode 100644 index 51b5d6a9f..000000000 --- a/src/network/network.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include "common/assert.h" -#include "common/logging/log.h" -#include "enet/enet.h" -#include "network/network.h" - -namespace Network { - -static std::shared_ptr<RoomMember> g_room_member; ///< RoomMember (Client) for network games -static std::shared_ptr<Room> g_room; ///< Room (Server) for network games -// TODO(B3N30): Put these globals into a networking class - -bool Init() { - if (enet_initialize() != 0) { - LOG_ERROR(Network, "Error initalizing ENet"); - return false; - } - g_room = std::make_shared<Room>(); - g_room_member = std::make_shared<RoomMember>(); - LOG_DEBUG(Network, "initialized OK"); - return true; -} - -std::weak_ptr<Room> GetRoom() { - return g_room; -} - -std::weak_ptr<RoomMember> GetRoomMember() { - return g_room_member; -} - -void Shutdown() { - if (g_room_member) { - if (g_room_member->IsConnected()) - g_room_member->Leave(); - g_room_member.reset(); - } - if (g_room) { - if (g_room->GetState() == Room::State::Open) - g_room->Destroy(); - g_room.reset(); - } - enet_deinitialize(); - LOG_DEBUG(Network, "shutdown OK"); -} - -} // namespace Network diff --git a/src/network/network.h b/src/network/network.h deleted file mode 100644 index 6d002d693..000000000 --- a/src/network/network.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <memory> -#include "network/room.h" -#include "network/room_member.h" - -namespace Network { - -/// Initializes and registers the network device, the room, and the room member. -bool Init(); - -/// Returns a pointer to the room handle -std::weak_ptr<Room> GetRoom(); - -/// Returns a pointer to the room member handle -std::weak_ptr<RoomMember> GetRoomMember(); - -/// Unregisters the network device, the room, and the room member and shut them down. -void Shutdown(); - -} // namespace Network diff --git a/src/network/packet.cpp b/src/network/packet.cpp deleted file mode 100644 index 7e1a812f3..000000000 --- a/src/network/packet.cpp +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#ifdef _WIN32 -#include <winsock2.h> -#else -#include <arpa/inet.h> -#endif -#include <cstring> -#include <string> -#include "network/packet.h" - -namespace Network { - -#ifndef htonll -u64 htonll(u64 x) { - return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32)); -} -#endif - -#ifndef ntohll -u64 ntohll(u64 x) { - return ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x)&0xFFFFFFFF) << 32) | ntohl((x) >> 32)); -} -#endif - -void Packet::Append(const void* in_data, std::size_t size_in_bytes) { - if (in_data && (size_in_bytes > 0)) { - std::size_t start = data.size(); - data.resize(start + size_in_bytes); - std::memcpy(&data[start], in_data, size_in_bytes); - } -} - -void Packet::Read(void* out_data, std::size_t size_in_bytes) { - if (out_data && CheckSize(size_in_bytes)) { - std::memcpy(out_data, &data[read_pos], size_in_bytes); - read_pos += size_in_bytes; - } -} - -void Packet::Clear() { - data.clear(); - read_pos = 0; - is_valid = true; -} - -const void* Packet::GetData() const { - return !data.empty() ? &data[0] : nullptr; -} - -void Packet::IgnoreBytes(u32 length) { - read_pos += length; -} - -std::size_t Packet::GetDataSize() const { - return data.size(); -} - -bool Packet::EndOfPacket() const { - return read_pos >= data.size(); -} - -Packet::operator bool() const { - return is_valid ? &Packet::CheckSize : nullptr; -} - -Packet& Packet::operator>>(bool& out_data) { - u8 value; - if (*this >> value) { - out_data = (value != 0); - } - return *this; -} - -Packet& Packet::operator>>(s8& out_data) { - Read(&out_data, sizeof(out_data)); - return *this; -} - -Packet& Packet::operator>>(u8& out_data) { - Read(&out_data, sizeof(out_data)); - return *this; -} - -Packet& Packet::operator>>(s16& out_data) { - s16 value; - Read(&value, sizeof(value)); - out_data = ntohs(value); - return *this; -} - -Packet& Packet::operator>>(u16& out_data) { - u16 value; - Read(&value, sizeof(value)); - out_data = ntohs(value); - return *this; -} - -Packet& Packet::operator>>(s32& out_data) { - s32 value; - Read(&value, sizeof(value)); - out_data = ntohl(value); - return *this; -} - -Packet& Packet::operator>>(u32& out_data) { - u32 value; - Read(&value, sizeof(value)); - out_data = ntohl(value); - return *this; -} - -Packet& Packet::operator>>(s64& out_data) { - s64 value; - Read(&value, sizeof(value)); - out_data = ntohll(value); - return *this; -} - -Packet& Packet::operator>>(u64& out_data) { - u64 value; - Read(&value, sizeof(value)); - out_data = ntohll(value); - return *this; -} - -Packet& Packet::operator>>(float& out_data) { - Read(&out_data, sizeof(out_data)); - return *this; -} - -Packet& Packet::operator>>(double& out_data) { - Read(&out_data, sizeof(out_data)); - return *this; -} - -Packet& Packet::operator>>(char* out_data) { - // First extract string length - u32 length = 0; - *this >> length; - - if ((length > 0) && CheckSize(length)) { - // Then extract characters - std::memcpy(out_data, &data[read_pos], length); - out_data[length] = '\0'; - - // Update reading position - read_pos += length; - } - - return *this; -} - -Packet& Packet::operator>>(std::string& out_data) { - // First extract string length - u32 length = 0; - *this >> length; - - out_data.clear(); - if ((length > 0) && CheckSize(length)) { - // Then extract characters - out_data.assign(&data[read_pos], length); - - // Update reading position - read_pos += length; - } - - return *this; -} - -Packet& Packet::operator<<(bool in_data) { - *this << static_cast<u8>(in_data); - return *this; -} - -Packet& Packet::operator<<(s8 in_data) { - Append(&in_data, sizeof(in_data)); - return *this; -} - -Packet& Packet::operator<<(u8 in_data) { - Append(&in_data, sizeof(in_data)); - return *this; -} - -Packet& Packet::operator<<(s16 in_data) { - s16 toWrite = htons(in_data); - Append(&toWrite, sizeof(toWrite)); - return *this; -} - -Packet& Packet::operator<<(u16 in_data) { - u16 toWrite = htons(in_data); - Append(&toWrite, sizeof(toWrite)); - return *this; -} - -Packet& Packet::operator<<(s32 in_data) { - s32 toWrite = htonl(in_data); - Append(&toWrite, sizeof(toWrite)); - return *this; -} - -Packet& Packet::operator<<(u32 in_data) { - u32 toWrite = htonl(in_data); - Append(&toWrite, sizeof(toWrite)); - return *this; -} - -Packet& Packet::operator<<(s64 in_data) { - s64 toWrite = htonll(in_data); - Append(&toWrite, sizeof(toWrite)); - return *this; -} - -Packet& Packet::operator<<(u64 in_data) { - u64 toWrite = htonll(in_data); - Append(&toWrite, sizeof(toWrite)); - return *this; -} - -Packet& Packet::operator<<(float in_data) { - Append(&in_data, sizeof(in_data)); - return *this; -} - -Packet& Packet::operator<<(double in_data) { - Append(&in_data, sizeof(in_data)); - return *this; -} - -Packet& Packet::operator<<(const char* in_data) { - // First insert string length - u32 length = static_cast<u32>(std::strlen(in_data)); - *this << length; - - // Then insert characters - Append(in_data, length * sizeof(char)); - - return *this; -} - -Packet& Packet::operator<<(const std::string& in_data) { - // First insert string length - u32 length = static_cast<u32>(in_data.size()); - *this << length; - - // Then insert characters - if (length > 0) - Append(in_data.c_str(), length * sizeof(std::string::value_type)); - - return *this; -} - -bool Packet::CheckSize(std::size_t size) { - is_valid = is_valid && (read_pos + size <= data.size()); - - return is_valid; -} - -} // namespace Network diff --git a/src/network/packet.h b/src/network/packet.h deleted file mode 100644 index 5a2e58dc2..000000000 --- a/src/network/packet.h +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <vector> -#include "common/common_types.h" - -namespace Network { - -/// A class that serializes data for network transfer. It also handles endianess -class Packet { -public: - Packet() = default; - ~Packet() = default; - - /** - * Append data to the end of the packet - * @param data Pointer to the sequence of bytes to append - * @param size_in_bytes Number of bytes to append - */ - void Append(const void* data, std::size_t size_in_bytes); - - /** - * Reads data from the current read position of the packet - * @param out_data Pointer where the data should get written to - * @param size_in_bytes Number of bytes to read - */ - void Read(void* out_data, std::size_t size_in_bytes); - - /** - * Clear the packet - * After calling Clear, the packet is empty. - */ - void Clear(); - - /** - * Ignores bytes while reading - * @param length THe number of bytes to ignore - */ - void IgnoreBytes(u32 length); - - /** - * Get a pointer to the data contained in the packet - * @return Pointer to the data - */ - const void* GetData() const; - - /** - * This function returns the number of bytes pointed to by - * what getData returns. - * @return Data size, in bytes - */ - std::size_t GetDataSize() const; - - /** - * This function is useful to know if there is some data - * left to be read, without actually reading it. - * @return True if all data was read, false otherwise - */ - bool EndOfPacket() const; - - explicit operator bool() const; - - /// Overloads of operator >> to read data from the packet - Packet& operator>>(bool& out_data); - Packet& operator>>(s8& out_data); - Packet& operator>>(u8& out_data); - Packet& operator>>(s16& out_data); - Packet& operator>>(u16& out_data); - Packet& operator>>(s32& out_data); - Packet& operator>>(u32& out_data); - Packet& operator>>(s64& out_data); - Packet& operator>>(u64& out_data); - Packet& operator>>(float& out_data); - Packet& operator>>(double& out_data); - Packet& operator>>(char* out_data); - Packet& operator>>(std::string& out_data); - template <typename T> - Packet& operator>>(std::vector<T>& out_data); - template <typename T, std::size_t S> - Packet& operator>>(std::array<T, S>& out_data); - - /// Overloads of operator << to write data into the packet - Packet& operator<<(bool in_data); - Packet& operator<<(s8 in_data); - Packet& operator<<(u8 in_data); - Packet& operator<<(s16 in_data); - Packet& operator<<(u16 in_data); - Packet& operator<<(s32 in_data); - Packet& operator<<(u32 in_data); - Packet& operator<<(s64 in_data); - Packet& operator<<(u64 in_data); - Packet& operator<<(float in_data); - Packet& operator<<(double in_data); - Packet& operator<<(const char* in_data); - Packet& operator<<(const std::string& in_data); - template <typename T> - Packet& operator<<(const std::vector<T>& in_data); - template <typename T, std::size_t S> - Packet& operator<<(const std::array<T, S>& data); - -private: - /** - * Check if the packet can extract a given number of bytes - * This function updates accordingly the state of the packet. - * @param size Size to check - * @return True if size bytes can be read from the packet - */ - bool CheckSize(std::size_t size); - - // Member data - std::vector<char> data; ///< Data stored in the packet - std::size_t read_pos = 0; ///< Current reading position in the packet - bool is_valid = true; ///< Reading state of the packet -}; - -template <typename T> -Packet& Packet::operator>>(std::vector<T>& out_data) { - // First extract the size - u32 size = 0; - *this >> size; - out_data.resize(size); - - // Then extract the data - for (std::size_t i = 0; i < out_data.size(); ++i) { - T character = 0; - *this >> character; - out_data[i] = character; - } - return *this; -} - -template <typename T, std::size_t S> -Packet& Packet::operator>>(std::array<T, S>& out_data) { - for (std::size_t i = 0; i < out_data.size(); ++i) { - T character = 0; - *this >> character; - out_data[i] = character; - } - return *this; -} - -template <typename T> -Packet& Packet::operator<<(const std::vector<T>& in_data) { - // First insert the size - *this << static_cast<u32>(in_data.size()); - - // Then insert the data - for (std::size_t i = 0; i < in_data.size(); ++i) { - *this << in_data[i]; - } - return *this; -} - -template <typename T, std::size_t S> -Packet& Packet::operator<<(const std::array<T, S>& in_data) { - for (std::size_t i = 0; i < in_data.size(); ++i) { - *this << in_data[i]; - } - return *this; -} - -} // namespace Network diff --git a/src/network/room.cpp b/src/network/room.cpp deleted file mode 100644 index 261049ab0..000000000 --- a/src/network/room.cpp +++ /dev/null @@ -1,497 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <algorithm> -#include <atomic> -#include <mutex> -#include <random> -#include <thread> -#include "enet/enet.h" -#include "network/packet.h" -#include "network/room.h" - -namespace Network { - -/// Maximum number of concurrent connections allowed to this room. -static constexpr u32 MaxConcurrentConnections = 10; - -class Room::RoomImpl { -public: - // This MAC address is used to generate a 'Nintendo' like Mac address. - const MacAddress NintendoOUI; - std::mt19937 random_gen; ///< Random number generator. Used for GenerateMacAddress - - ENetHost* server = nullptr; ///< Network interface. - - std::atomic<State> state{State::Closed}; ///< Current state of the room. - RoomInformation room_information; ///< Information about this room. - - struct Member { - std::string nickname; ///< The nickname of the member. - GameInfo game_info; ///< The current game of the member - MacAddress mac_address; ///< The assigned mac address of the member. - ENetPeer* peer; ///< The remote peer. - }; - using MemberList = std::vector<Member>; - MemberList members; ///< Information about the members of this room - mutable std::mutex member_mutex; ///< Mutex for locking the members list - /// This should be a std::shared_mutex as soon as C++17 is supported - - RoomImpl() - : random_gen(std::random_device()()), NintendoOUI{0x00, 0x1F, 0x32, 0x00, 0x00, 0x00} {} - - /// Thread that receives and dispatches network packets - std::unique_ptr<std::thread> room_thread; - - /// Thread function that will receive and dispatch messages until the room is destroyed. - void ServerLoop(); - void StartLoop(); - - /** - * Parses and answers a room join request from a client. - * Validates the uniqueness of the username and assigns the MAC address - * that the client will use for the remainder of the connection. - */ - void HandleJoinRequest(const ENetEvent* event); - - /** - * Returns whether the nickname is valid, ie. isn't already taken by someone else in the room. - */ - bool IsValidNickname(const std::string& nickname) const; - - /** - * Returns whether the MAC address is valid, ie. isn't already taken by someone else in the - * room. - */ - bool IsValidMacAddress(const MacAddress& address) const; - - /** - * Sends a ID_ROOM_NAME_COLLISION message telling the client that the name is invalid. - */ - void SendNameCollision(ENetPeer* client); - - /** - * Sends a ID_ROOM_MAC_COLLISION message telling the client that the MAC is invalid. - */ - void SendMacCollision(ENetPeer* client); - - /** - * Sends a ID_ROOM_VERSION_MISMATCH message telling the client that the version is invalid. - */ - void SendVersionMismatch(ENetPeer* client); - - /** - * Notifies the member that its connection attempt was successful, - * and it is now part of the room. - */ - void SendJoinSuccess(ENetPeer* client, MacAddress mac_address); - - /** - * Notifies the members that the room is closed, - */ - void SendCloseMessage(); - - /** - * Sends the information about the room, along with the list of members - * to every connected client in the room. - * The packet has the structure: - * <MessageID>ID_ROOM_INFORMATION - * <String> room_name - * <u32> member_slots: The max number of clients allowed in this room - * <u32> num_members: the number of currently joined clients - * This is followed by the following three values for each member: - * <String> nickname of that member - * <MacAddress> mac_address of that member - * <String> game_name of that member - */ - void BroadcastRoomInformation(); - - /** - * Generates a free MAC address to assign to a new client. - * The first 3 bytes are the NintendoOUI 0x00, 0x1F, 0x32 - */ - MacAddress GenerateMacAddress(); - - /** - * Broadcasts this packet to all members except the sender. - * @param event The ENet event containing the data - */ - void HandleWifiPacket(const ENetEvent* event); - - /** - * Extracts a chat entry from a received ENet packet and adds it to the chat queue. - * @param event The ENet event that was received. - */ - void HandleChatPacket(const ENetEvent* event); - - /** - * Extracts the game name from a received ENet packet and broadcasts it. - * @param event The ENet event that was received. - */ - void HandleGameNamePacket(const ENetEvent* event); - - /** - * Removes the client from the members list if it was in it and announces the change - * to all other clients. - */ - void HandleClientDisconnection(ENetPeer* client); -}; - -// RoomImpl -void Room::RoomImpl::ServerLoop() { - while (state != State::Closed) { - ENetEvent event; - if (enet_host_service(server, &event, 100) > 0) { - switch (event.type) { - case ENET_EVENT_TYPE_RECEIVE: - switch (event.packet->data[0]) { - case IdJoinRequest: - HandleJoinRequest(&event); - break; - case IdSetGameInfo: - HandleGameNamePacket(&event); - break; - case IdWifiPacket: - HandleWifiPacket(&event); - break; - case IdChatMessage: - HandleChatPacket(&event); - break; - } - enet_packet_destroy(event.packet); - break; - case ENET_EVENT_TYPE_DISCONNECT: - HandleClientDisconnection(event.peer); - break; - } - } - } - // Close the connection to all members: - SendCloseMessage(); -} - -void Room::RoomImpl::StartLoop() { - room_thread = std::make_unique<std::thread>(&Room::RoomImpl::ServerLoop, this); -} - -void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) { - Packet packet; - packet.Append(event->packet->data, event->packet->dataLength); - packet.IgnoreBytes(sizeof(u8)); // Igonore the message type - std::string nickname; - packet >> nickname; - - MacAddress preferred_mac; - packet >> preferred_mac; - - u32 client_version; - packet >> client_version; - - if (!IsValidNickname(nickname)) { - SendNameCollision(event->peer); - return; - } - - if (preferred_mac != NoPreferredMac) { - // Verify if the preferred mac is available - if (!IsValidMacAddress(preferred_mac)) { - SendMacCollision(event->peer); - return; - } - } else { - // Assign a MAC address of this client automatically - preferred_mac = GenerateMacAddress(); - } - - if (client_version != network_version) { - SendVersionMismatch(event->peer); - return; - } - - // At this point the client is ready to be added to the room. - Member member{}; - member.mac_address = preferred_mac; - member.nickname = nickname; - member.peer = event->peer; - - { - std::lock_guard<std::mutex> lock(member_mutex); - members.push_back(std::move(member)); - } - - // Notify everyone that the room information has changed. - BroadcastRoomInformation(); - SendJoinSuccess(event->peer, preferred_mac); -} - -bool Room::RoomImpl::IsValidNickname(const std::string& nickname) const { - // A nickname is valid if it is not already taken by anybody else in the room. - // TODO(B3N30): Check for empty names, spaces, etc. - std::lock_guard<std::mutex> lock(member_mutex); - return std::all_of(members.begin(), members.end(), - [&nickname](const auto& member) { return member.nickname != nickname; }); -} - -bool Room::RoomImpl::IsValidMacAddress(const MacAddress& address) const { - // A MAC address is valid if it is not already taken by anybody else in the room. - std::lock_guard<std::mutex> lock(member_mutex); - return std::all_of(members.begin(), members.end(), - [&address](const auto& member) { return member.mac_address != address; }); -} - -void Room::RoomImpl::SendNameCollision(ENetPeer* client) { - Packet packet; - packet << static_cast<u8>(IdNameCollision); - - ENetPacket* enet_packet = - enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); - enet_peer_send(client, 0, enet_packet); - enet_host_flush(server); -} - -void Room::RoomImpl::SendMacCollision(ENetPeer* client) { - Packet packet; - packet << static_cast<u8>(IdMacCollision); - - ENetPacket* enet_packet = - enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); - enet_peer_send(client, 0, enet_packet); - enet_host_flush(server); -} - -void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) { - Packet packet; - packet << static_cast<u8>(IdVersionMismatch); - packet << network_version; - - ENetPacket* enet_packet = - enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); - enet_peer_send(client, 0, enet_packet); - enet_host_flush(server); -} - -void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) { - Packet packet; - packet << static_cast<u8>(IdJoinSuccess); - packet << mac_address; - ENetPacket* enet_packet = - enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); - enet_peer_send(client, 0, enet_packet); - enet_host_flush(server); -} - -void Room::RoomImpl::SendCloseMessage() { - Packet packet; - packet << static_cast<u8>(IdCloseRoom); - ENetPacket* enet_packet = - enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); - std::lock_guard<std::mutex> lock(member_mutex); - for (auto& member : members) { - enet_peer_send(member.peer, 0, enet_packet); - } - enet_host_flush(server); - for (auto& member : members) { - enet_peer_disconnect(member.peer, 0); - } -} - -void Room::RoomImpl::BroadcastRoomInformation() { - Packet packet; - packet << static_cast<u8>(IdRoomInformation); - packet << room_information.name; - packet << room_information.member_slots; - - packet << static_cast<u32>(members.size()); - { - std::lock_guard<std::mutex> lock(member_mutex); - for (const auto& member : members) { - packet << member.nickname; - packet << member.mac_address; - packet << member.game_info.name; - packet << member.game_info.id; - } - } - - ENetPacket* enet_packet = - enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); - enet_host_broadcast(server, 0, enet_packet); - enet_host_flush(server); -} - -MacAddress Room::RoomImpl::GenerateMacAddress() { - MacAddress result_mac = - NintendoOUI; // The first three bytes of each MAC address will be the NintendoOUI - std::uniform_int_distribution<> dis(0x00, 0xFF); // Random byte between 0 and 0xFF - do { - for (size_t i = 3; i < result_mac.size(); ++i) { - result_mac[i] = dis(random_gen); - } - } while (!IsValidMacAddress(result_mac)); - return result_mac; -} - -void Room::RoomImpl::HandleWifiPacket(const ENetEvent* event) { - Packet in_packet; - in_packet.Append(event->packet->data, event->packet->dataLength); - in_packet.IgnoreBytes(sizeof(u8)); // Message type - in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Type - in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Channel - in_packet.IgnoreBytes(sizeof(MacAddress)); // WifiPacket Transmitter Address - MacAddress destination_address; - in_packet >> destination_address; - - Packet out_packet; - out_packet.Append(event->packet->data, event->packet->dataLength); - ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), - ENET_PACKET_FLAG_RELIABLE); - - if (destination_address == BroadcastMac) { // Send the data to everyone except the sender - std::lock_guard<std::mutex> lock(member_mutex); - for (const auto& member : members) { - if (member.peer != event->peer) - enet_peer_send(member.peer, 0, enet_packet); - } - } else { // Send the data only to the destination client - std::lock_guard<std::mutex> lock(member_mutex); - auto member = std::find_if(members.begin(), members.end(), - [destination_address](const Member& member) -> bool { - return member.mac_address == destination_address; - }); - if (member != members.end()) { - enet_peer_send(member->peer, 0, enet_packet); - } - } - enet_host_flush(server); -} - -void Room::RoomImpl::HandleChatPacket(const ENetEvent* event) { - Packet in_packet; - in_packet.Append(event->packet->data, event->packet->dataLength); - - in_packet.IgnoreBytes(sizeof(u8)); // Igonore the message type - std::string message; - in_packet >> message; - auto CompareNetworkAddress = [event](const Member member) -> bool { - return member.peer == event->peer; - }; - - std::lock_guard<std::mutex> lock(member_mutex); - const auto sending_member = std::find_if(members.begin(), members.end(), CompareNetworkAddress); - if (sending_member == members.end()) { - return; // Received a chat message from a unknown sender - } - - Packet out_packet; - out_packet << static_cast<u8>(IdChatMessage); - out_packet << sending_member->nickname; - out_packet << message; - - ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), - ENET_PACKET_FLAG_RELIABLE); - for (const auto& member : members) { - if (member.peer != event->peer) - enet_peer_send(member.peer, 0, enet_packet); - } - enet_host_flush(server); -} - -void Room::RoomImpl::HandleGameNamePacket(const ENetEvent* event) { - Packet in_packet; - in_packet.Append(event->packet->data, event->packet->dataLength); - - in_packet.IgnoreBytes(sizeof(u8)); // Igonore the message type - GameInfo game_info; - in_packet >> game_info.name; - in_packet >> game_info.id; - - { - std::lock_guard<std::mutex> lock(member_mutex); - auto member = - std::find_if(members.begin(), members.end(), [event](const Member& member) -> bool { - return member.peer == event->peer; - }); - if (member != members.end()) { - member->game_info = game_info; - } - } - BroadcastRoomInformation(); -} - -void Room::RoomImpl::HandleClientDisconnection(ENetPeer* client) { - // Remove the client from the members list. - { - std::lock_guard<std::mutex> lock(member_mutex); - members.erase( - std::remove_if(members.begin(), members.end(), - [client](const Member& member) { return member.peer == client; }), - members.end()); - } - - // Announce the change to all clients. - enet_peer_disconnect(client, 0); - BroadcastRoomInformation(); -} - -// Room -Room::Room() : room_impl{std::make_unique<RoomImpl>()} {} - -Room::~Room() = default; - -void Room::Create(const std::string& name, const std::string& server_address, u16 server_port) { - ENetAddress address; - address.host = ENET_HOST_ANY; - if (!server_address.empty()) { - enet_address_set_host(&address, server_address.c_str()); - } - address.port = server_port; - - room_impl->server = enet_host_create(&address, MaxConcurrentConnections, NumChannels, 0, 0); - // TODO(B3N30): Allow specifying the maximum number of concurrent connections. - room_impl->state = State::Open; - - room_impl->room_information.name = name; - room_impl->room_information.member_slots = MaxConcurrentConnections; - room_impl->StartLoop(); -} - -Room::State Room::GetState() const { - return room_impl->state; -} - -const RoomInformation& Room::GetRoomInformation() const { - return room_impl->room_information; -} - -std::vector<Room::Member> Room::GetRoomMemberList() const { - std::vector<Room::Member> member_list; - std::lock_guard<std::mutex> lock(room_impl->member_mutex); - for (const auto& member_impl : room_impl->members) { - Member member; - member.nickname = member_impl.nickname; - member.mac_address = member_impl.mac_address; - member.game_info = member_impl.game_info; - member_list.push_back(member); - } - return member_list; -}; - -void Room::Destroy() { - room_impl->state = State::Closed; - room_impl->room_thread->join(); - room_impl->room_thread.reset(); - - if (room_impl->server) { - enet_host_destroy(room_impl->server); - } - room_impl->room_information = {}; - room_impl->server = nullptr; - { - std::lock_guard<std::mutex> lock(room_impl->member_mutex); - room_impl->members.clear(); - } - room_impl->room_information.member_slots = 0; - room_impl->room_information.name.clear(); -} - -} // namespace Network diff --git a/src/network/room.h b/src/network/room.h deleted file mode 100644 index 8285a4d0c..000000000 --- a/src/network/room.h +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <memory> -#include <string> -#include <vector> -#include "common/common_types.h" - -namespace Network { - -constexpr u32 network_version = 1; ///< The version of this Room and RoomMember - -constexpr u16 DefaultRoomPort = 1234; -constexpr size_t NumChannels = 1; // Number of channels used for the connection - -struct RoomInformation { - std::string name; ///< Name of the server - u32 member_slots; ///< Maximum number of members in this room -}; - -struct GameInfo { - std::string name{""}; - u64 id{0}; -}; - -using MacAddress = std::array<u8, 6>; -/// A special MAC address that tells the room we're joining to assign us a MAC address -/// automatically. -constexpr MacAddress NoPreferredMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - -// 802.11 broadcast MAC address -constexpr MacAddress BroadcastMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - -// The different types of messages that can be sent. The first byte of each packet defines the type -enum RoomMessageTypes : u8 { - IdJoinRequest = 1, - IdJoinSuccess, - IdRoomInformation, - IdSetGameInfo, - IdWifiPacket, - IdChatMessage, - IdNameCollision, - IdMacCollision, - IdVersionMismatch, - IdCloseRoom -}; - -/// This is what a server [person creating a server] would use. -class Room final { -public: - enum class State : u8 { - Open, ///< The room is open and ready to accept connections. - Closed, ///< The room is not opened and can not accept connections. - }; - - struct Member { - std::string nickname; ///< The nickname of the member. - GameInfo game_info; ///< The current game of the member - MacAddress mac_address; ///< The assigned mac address of the member. - }; - - Room(); - ~Room(); - - /** - * Gets the current state of the room. - */ - State GetState() const; - - /** - * Gets the room information of the room. - */ - const RoomInformation& GetRoomInformation() const; - - /** - * Gets a list of the mbmers connected to the room. - */ - std::vector<Member> GetRoomMemberList() const; - - /** - * Creates the socket for this room. Will bind to default address if - * server is empty string. - */ - void Create(const std::string& name, const std::string& server = "", - u16 server_port = DefaultRoomPort); - - /** - * Destroys the socket - */ - void Destroy(); - -private: - class RoomImpl; - std::unique_ptr<RoomImpl> room_impl; -}; - -} // namespace Network diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp deleted file mode 100644 index f229ec6fd..000000000 --- a/src/network/room_member.cpp +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <atomic> -#include <list> -#include <mutex> -#include <set> -#include <thread> -#include "common/assert.h" -#include "enet/enet.h" -#include "network/packet.h" -#include "network/room_member.h" - -namespace Network { - -constexpr u32 ConnectionTimeoutMs = 5000; - -class RoomMember::RoomMemberImpl { -public: - ENetHost* client = nullptr; ///< ENet network interface. - ENetPeer* server = nullptr; ///< The server peer the client is connected to - - /// Information about the clients connected to the same room as us. - MemberList member_information; - /// Information about the room we're connected to. - RoomInformation room_information; - - /// The current game name, id and version - GameInfo current_game_info; - - std::atomic<State> state{State::Idle}; ///< Current state of the RoomMember. - void SetState(const State new_state); - bool IsConnected() const; - - std::string nickname; ///< The nickname of this member. - MacAddress mac_address; ///< The mac_address of this member. - - std::mutex network_mutex; ///< Mutex that controls access to the `client` variable. - /// Thread that receives and dispatches network packets - std::unique_ptr<std::thread> loop_thread; - std::mutex send_list_mutex; ///< Mutex that controls access to the `send_list` variable. - std::list<Packet> send_list; ///< A list that stores all packets to send the async - - template <typename T> - using CallbackSet = std::set<CallbackHandle<T>>; - std::mutex callback_mutex; ///< The mutex used for handling callbacks - - class Callbacks { - public: - template <typename T> - CallbackSet<T>& Get(); - - private: - CallbackSet<WifiPacket> callback_set_wifi_packet; - CallbackSet<ChatEntry> callback_set_chat_messages; - CallbackSet<RoomInformation> callback_set_room_information; - CallbackSet<State> callback_set_state; - }; - Callbacks callbacks; ///< All CallbackSets to all events - - void MemberLoop(); - - void StartLoop(); - - /** - * Sends data to the room. It will be send on channel 0 with flag RELIABLE - * @param packet The data to send - */ - void Send(Packet&& packet); - - /** - * Sends a request to the server, asking for permission to join a room with the specified - * nickname and preferred mac. - * @params nickname The desired nickname. - * @params preferred_mac The preferred MAC address to use in the room, the NoPreferredMac tells - * the server to assign one for us. - */ - void SendJoinRequest(const std::string& nickname, - const MacAddress& preferred_mac = NoPreferredMac); - - /** - * Extracts a MAC Address from a received ENet packet. - * @param event The ENet event that was received. - */ - void HandleJoinPacket(const ENetEvent* event); - /** - * Extracts RoomInformation and MemberInformation from a received RakNet packet. - * @param event The ENet event that was received. - */ - void HandleRoomInformationPacket(const ENetEvent* event); - - /** - * Extracts a WifiPacket from a received ENet packet. - * @param event The ENet event that was received. - */ - void HandleWifiPackets(const ENetEvent* event); - - /** - * Extracts a chat entry from a received ENet packet and adds it to the chat queue. - * @param event The ENet event that was received. - */ - void HandleChatPacket(const ENetEvent* event); - - /** - * Disconnects the RoomMember from the Room - */ - void Disconnect(); - - template <typename T> - void Invoke(const T& data); - - template <typename T> - CallbackHandle<T> Bind(std::function<void(const T&)> callback); -}; - -// RoomMemberImpl -void RoomMember::RoomMemberImpl::SetState(const State new_state) { - if (state != new_state) { - state = new_state; - Invoke<State>(state); - } -} - -bool RoomMember::RoomMemberImpl::IsConnected() const { - return state == State::Joining || state == State::Joined; -} - -void RoomMember::RoomMemberImpl::MemberLoop() { - // Receive packets while the connection is open - while (IsConnected()) { - std::lock_guard<std::mutex> lock(network_mutex); - ENetEvent event; - if (enet_host_service(client, &event, 100) > 0) { - switch (event.type) { - case ENET_EVENT_TYPE_RECEIVE: - switch (event.packet->data[0]) { - case IdWifiPacket: - HandleWifiPackets(&event); - break; - case IdChatMessage: - HandleChatPacket(&event); - break; - case IdRoomInformation: - HandleRoomInformationPacket(&event); - break; - case IdJoinSuccess: - // The join request was successful, we are now in the room. - // If we joined successfully, there must be at least one client in the room: us. - ASSERT_MSG(member_information.size() > 0, - "We have not yet received member information."); - HandleJoinPacket(&event); // Get the MAC Address for the client - SetState(State::Joined); - break; - case IdNameCollision: - SetState(State::NameCollision); - break; - case IdMacCollision: - SetState(State::MacCollision); - break; - case IdVersionMismatch: - SetState(State::WrongVersion); - break; - case IdCloseRoom: - SetState(State::LostConnection); - break; - } - enet_packet_destroy(event.packet); - break; - case ENET_EVENT_TYPE_DISCONNECT: - SetState(State::LostConnection); - break; - } - } - { - std::lock_guard<std::mutex> lock(send_list_mutex); - for (const auto& packet : send_list) { - ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetDataSize(), - ENET_PACKET_FLAG_RELIABLE); - enet_peer_send(server, 0, enetPacket); - } - enet_host_flush(client); - send_list.clear(); - } - } - Disconnect(); -}; - -void RoomMember::RoomMemberImpl::StartLoop() { - loop_thread = std::make_unique<std::thread>(&RoomMember::RoomMemberImpl::MemberLoop, this); -} - -void RoomMember::RoomMemberImpl::Send(Packet&& packet) { - std::lock_guard<std::mutex> lock(send_list_mutex); - send_list.push_back(std::move(packet)); -} - -void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname, - const MacAddress& preferred_mac) { - Packet packet; - packet << static_cast<u8>(IdJoinRequest); - packet << nickname; - packet << preferred_mac; - packet << network_version; - Send(std::move(packet)); -} - -void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* event) { - Packet packet; - packet.Append(event->packet->data, event->packet->dataLength); - - // Ignore the first byte, which is the message id. - packet.IgnoreBytes(sizeof(u8)); // Igonore the message type - - RoomInformation info{}; - packet >> info.name; - packet >> info.member_slots; - room_information.name = info.name; - room_information.member_slots = info.member_slots; - - u32 num_members; - packet >> num_members; - member_information.resize(num_members); - - for (auto& member : member_information) { - packet >> member.nickname; - packet >> member.mac_address; - packet >> member.game_info.name; - packet >> member.game_info.id; - } - Invoke(room_information); -} - -void RoomMember::RoomMemberImpl::HandleJoinPacket(const ENetEvent* event) { - Packet packet; - packet.Append(event->packet->data, event->packet->dataLength); - - // Ignore the first byte, which is the message id. - packet.IgnoreBytes(sizeof(u8)); // Igonore the message type - - // Parse the MAC Address from the packet - packet >> mac_address; - SetState(State::Joined); -} - -void RoomMember::RoomMemberImpl::HandleWifiPackets(const ENetEvent* event) { - WifiPacket wifi_packet{}; - Packet packet; - packet.Append(event->packet->data, event->packet->dataLength); - - // Ignore the first byte, which is the message id. - packet.IgnoreBytes(sizeof(u8)); // Igonore the message type - - // Parse the WifiPacket from the packet - u8 frame_type; - packet >> frame_type; - WifiPacket::PacketType type = static_cast<WifiPacket::PacketType>(frame_type); - - wifi_packet.type = type; - packet >> wifi_packet.channel; - packet >> wifi_packet.transmitter_address; - packet >> wifi_packet.destination_address; - - u32 data_length; - packet >> data_length; - - packet >> wifi_packet.data; - - Invoke<WifiPacket>(wifi_packet); -} - -void RoomMember::RoomMemberImpl::HandleChatPacket(const ENetEvent* event) { - Packet packet; - packet.Append(event->packet->data, event->packet->dataLength); - - // Ignore the first byte, which is the message id. - packet.IgnoreBytes(sizeof(u8)); - - ChatEntry chat_entry{}; - packet >> chat_entry.nickname; - packet >> chat_entry.message; - Invoke<ChatEntry>(chat_entry); -} - -void RoomMember::RoomMemberImpl::Disconnect() { - member_information.clear(); - room_information.member_slots = 0; - room_information.name.clear(); - - if (!server) - return; - enet_peer_disconnect(server, 0); - - ENetEvent event; - while (enet_host_service(client, &event, ConnectionTimeoutMs) > 0) { - switch (event.type) { - case ENET_EVENT_TYPE_RECEIVE: - enet_packet_destroy(event.packet); // Ignore all incoming data - break; - case ENET_EVENT_TYPE_DISCONNECT: - server = nullptr; - return; - } - } - // didn't disconnect gracefully force disconnect - enet_peer_reset(server); - server = nullptr; -} - -template <> -RoomMember::RoomMemberImpl::CallbackSet<WifiPacket>& RoomMember::RoomMemberImpl::Callbacks::Get() { - return callback_set_wifi_packet; -} - -template <> -RoomMember::RoomMemberImpl::CallbackSet<RoomMember::State>& -RoomMember::RoomMemberImpl::Callbacks::Get() { - return callback_set_state; -} - -template <> -RoomMember::RoomMemberImpl::CallbackSet<RoomInformation>& -RoomMember::RoomMemberImpl::Callbacks::Get() { - return callback_set_room_information; -} - -template <> -RoomMember::RoomMemberImpl::CallbackSet<ChatEntry>& RoomMember::RoomMemberImpl::Callbacks::Get() { - return callback_set_chat_messages; -} - -template <typename T> -void RoomMember::RoomMemberImpl::Invoke(const T& data) { - std::lock_guard<std::mutex> lock(callback_mutex); - CallbackSet<T> callback_set = callbacks.Get<T>(); - for (auto const& callback : callback_set) - (*callback)(data); -} - -template <typename T> -RoomMember::CallbackHandle<T> RoomMember::RoomMemberImpl::Bind( - std::function<void(const T&)> callback) { - std::lock_guard<std::mutex> lock(callback_mutex); - CallbackHandle<T> handle; - handle = std::make_shared<std::function<void(const T&)>>(callback); - callbacks.Get<T>().insert(handle); - return handle; -} - -// RoomMember -RoomMember::RoomMember() : room_member_impl{std::make_unique<RoomMemberImpl>()} { - room_member_impl->client = enet_host_create(nullptr, 1, NumChannels, 0, 0); - ASSERT_MSG(room_member_impl->client != nullptr, "Could not create client"); -} - -RoomMember::~RoomMember() { - ASSERT_MSG(!IsConnected(), "RoomMember is being destroyed while connected"); - enet_host_destroy(room_member_impl->client); -} - -RoomMember::State RoomMember::GetState() const { - return room_member_impl->state; -} - -const RoomMember::MemberList& RoomMember::GetMemberInformation() const { - return room_member_impl->member_information; -} - -const std::string& RoomMember::GetNickname() const { - return room_member_impl->nickname; -} - -const MacAddress& RoomMember::GetMacAddress() const { - ASSERT_MSG(IsConnected(), "Tried to get MAC address while not connected"); - return room_member_impl->mac_address; -} - -RoomInformation RoomMember::GetRoomInformation() const { - return room_member_impl->room_information; -} - -void RoomMember::Join(const std::string& nick, const char* server_addr, u16 server_port, - u16 client_port, const MacAddress& preferred_mac) { - // If the member is connected, kill the connection first - if (room_member_impl->loop_thread && room_member_impl->loop_thread->joinable()) { - room_member_impl->SetState(State::Error); - room_member_impl->loop_thread->join(); - room_member_impl->loop_thread.reset(); - } - // If the thread isn't running but the ptr still exists, reset it - else if (room_member_impl->loop_thread) { - room_member_impl->loop_thread.reset(); - } - - ENetAddress address{}; - enet_address_set_host(&address, server_addr); - address.port = server_port; - room_member_impl->server = - enet_host_connect(room_member_impl->client, &address, NumChannels, 0); - - if (!room_member_impl->server) { - room_member_impl->SetState(State::Error); - return; - } - - ENetEvent event{}; - int net = enet_host_service(room_member_impl->client, &event, ConnectionTimeoutMs); - if (net > 0 && event.type == ENET_EVENT_TYPE_CONNECT) { - room_member_impl->nickname = nick; - room_member_impl->SetState(State::Joining); - room_member_impl->StartLoop(); - room_member_impl->SendJoinRequest(nick, preferred_mac); - SendGameInfo(room_member_impl->current_game_info); - } else { - room_member_impl->SetState(State::CouldNotConnect); - } -} - -bool RoomMember::IsConnected() const { - return room_member_impl->IsConnected(); -} - -void RoomMember::SendWifiPacket(const WifiPacket& wifi_packet) { - Packet packet; - packet << static_cast<u8>(IdWifiPacket); - packet << static_cast<u8>(wifi_packet.type); - packet << wifi_packet.channel; - packet << wifi_packet.transmitter_address; - packet << wifi_packet.destination_address; - packet << wifi_packet.data; - room_member_impl->Send(std::move(packet)); -} - -void RoomMember::SendChatMessage(const std::string& message) { - Packet packet; - packet << static_cast<u8>(IdChatMessage); - packet << message; - room_member_impl->Send(std::move(packet)); -} - -void RoomMember::SendGameInfo(const GameInfo& game_info) { - room_member_impl->current_game_info = game_info; - if (!IsConnected()) - return; - - Packet packet; - packet << static_cast<u8>(IdSetGameInfo); - packet << game_info.name; - packet << game_info.id; - room_member_impl->Send(std::move(packet)); -} - -RoomMember::CallbackHandle<RoomMember::State> RoomMember::BindOnStateChanged( - std::function<void(const RoomMember::State&)> callback) { - return room_member_impl->Bind(callback); -} - -RoomMember::CallbackHandle<WifiPacket> RoomMember::BindOnWifiPacketReceived( - std::function<void(const WifiPacket&)> callback) { - return room_member_impl->Bind(callback); -} - -RoomMember::CallbackHandle<RoomInformation> RoomMember::BindOnRoomInformationChanged( - std::function<void(const RoomInformation&)> callback) { - return room_member_impl->Bind(callback); -} - -RoomMember::CallbackHandle<ChatEntry> RoomMember::BindOnChatMessageRecieved( - std::function<void(const ChatEntry&)> callback) { - return room_member_impl->Bind(callback); -} - -template <typename T> -void RoomMember::Unbind(CallbackHandle<T> handle) { - std::lock_guard<std::mutex> lock(room_member_impl->callback_mutex); - room_member_impl->callbacks.Get<T>().erase(handle); -} - -void RoomMember::Leave() { - room_member_impl->SetState(State::Idle); - room_member_impl->loop_thread->join(); - room_member_impl->loop_thread.reset(); -} - -template void RoomMember::Unbind(CallbackHandle<WifiPacket>); -template void RoomMember::Unbind(CallbackHandle<RoomMember::State>); -template void RoomMember::Unbind(CallbackHandle<RoomInformation>); -template void RoomMember::Unbind(CallbackHandle<ChatEntry>); - -} // namespace Network diff --git a/src/network/room_member.h b/src/network/room_member.h deleted file mode 100644 index 98770a234..000000000 --- a/src/network/room_member.h +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <functional> -#include <memory> -#include <string> -#include <vector> -#include "common/common_types.h" -#include "network/room.h" - -namespace Network { - -/// Information about the received WiFi packets. -/// Acts as our own 802.11 header. -struct WifiPacket { - enum class PacketType : u8 { Beacon, Data, Authentication, AssociationResponse }; - PacketType type; ///< The type of 802.11 frame. - std::vector<u8> data; ///< Raw 802.11 frame data, starting at the management frame header - /// for management frames. - MacAddress transmitter_address; ///< Mac address of the transmitter. - MacAddress destination_address; ///< Mac address of the receiver. - u8 channel; ///< WiFi channel where this frame was transmitted. -}; - -/// Represents a chat message. -struct ChatEntry { - std::string nickname; ///< Nickname of the client who sent this message. - std::string message; ///< Body of the message. -}; - -/** - * This is what a client [person joining a server] would use. - * It also has to be used if you host a game yourself (You'd create both, a Room and a - * RoomMembership for yourself) - */ -class RoomMember final { -public: - enum class State : u8 { - Idle, ///< Default state - Error, ///< Some error [permissions to network device missing or something] - Joining, ///< The client is attempting to join a room. - Joined, ///< The client is connected to the room and is ready to send/receive packets. - LostConnection, ///< Connection closed - - // Reasons why connection was rejected - NameCollision, ///< Somebody is already using this name - MacCollision, ///< Somebody is already using that mac-address - WrongVersion, ///< The room version is not the same as for this RoomMember - CouldNotConnect ///< The room is not responding to a connection attempt - }; - - struct MemberInformation { - std::string nickname; ///< Nickname of the member. - GameInfo game_info; ///< Name of the game they're currently playing, or empty if they're - /// not playing anything. - MacAddress mac_address; ///< MAC address associated with this member. - }; - using MemberList = std::vector<MemberInformation>; - - // The handle for the callback functions - template <typename T> - using CallbackHandle = std::shared_ptr<std::function<void(const T&)>>; - - /** - * Unbinds a callback function from the events. - * @param handle The connection handle to disconnect - */ - template <typename T> - void Unbind(CallbackHandle<T> handle); - - RoomMember(); - ~RoomMember(); - - /** - * Returns the status of our connection to the room. - */ - State GetState() const; - - /** - * Returns information about the members in the room we're currently connected to. - */ - const MemberList& GetMemberInformation() const; - - /** - * Returns the nickname of the RoomMember. - */ - const std::string& GetNickname() const; - - /** - * Returns the MAC address of the RoomMember. - */ - const MacAddress& GetMacAddress() const; - - /** - * Returns information about the room we're currently connected to. - */ - RoomInformation GetRoomInformation() const; - - /** - * Returns whether we're connected to a server or not. - */ - bool IsConnected() const; - - /** - * Attempts to join a room at the specified address and port, using the specified nickname. - * This may fail if the username is already taken. - */ - void Join(const std::string& nickname, const char* server_addr = "127.0.0.1", - const u16 serverPort = DefaultRoomPort, const u16 clientPort = 0, - const MacAddress& preferred_mac = NoPreferredMac); - - /** - * Sends a WiFi packet to the room. - * @param packet The WiFi packet to send. - */ - void SendWifiPacket(const WifiPacket& packet); - - /** - * Sends a chat message to the room. - * @param message The contents of the message. - */ - void SendChatMessage(const std::string& message); - - /** - * Sends the current game info to the room. - * @param game_info The game information. - */ - void SendGameInfo(const GameInfo& game_info); - - /** - * Binds a function to an event that will be triggered every time the State of the member - * changed. The function wil be called every time the event is triggered. The callback function - * must not bind or unbind a function. Doing so will cause a deadlock - * @param callback The function to call - * @return A handle used for removing the function from the registered list - */ - CallbackHandle<State> BindOnStateChanged(std::function<void(const State&)> callback); - - /** - * Binds a function to an event that will be triggered every time a WifiPacket is received. - * The function wil be called everytime the event is triggered. - * The callback function must not bind or unbind a function. Doing so will cause a deadlock - * @param callback The function to call - * @return A handle used for removing the function from the registered list - */ - CallbackHandle<WifiPacket> BindOnWifiPacketReceived( - std::function<void(const WifiPacket&)> callback); - - /** - * Binds a function to an event that will be triggered every time the RoomInformation changes. - * The function wil be called every time the event is triggered. - * The callback function must not bind or unbind a function. Doing so will cause a deadlock - * @param callback The function to call - * @return A handle used for removing the function from the registered list - */ - CallbackHandle<RoomInformation> BindOnRoomInformationChanged( - std::function<void(const RoomInformation&)> callback); - - /** - * Binds a function to an event that will be triggered every time a ChatMessage is received. - * The function wil be called every time the event is triggered. - * The callback function must not bind or unbind a function. Doing so will cause a deadlock - * @param callback The function to call - * @return A handle used for removing the function from the registered list - */ - CallbackHandle<ChatEntry> BindOnChatMessageRecieved( - std::function<void(const ChatEntry&)> callback); - - /** - * Leaves the current room. - */ - void Leave(); - -private: - class RoomMemberImpl; - std::unique_ptr<RoomMemberImpl> room_member_impl; -}; - -} // namespace Network diff --git a/src/web_service/CMakeLists.txt b/src/web_service/CMakeLists.txt deleted file mode 100644 index c93811892..000000000 --- a/src/web_service/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -set(SRCS - telemetry_json.cpp - verify_login.cpp - web_backend.cpp - ) - -set(HEADERS - telemetry_json.h - verify_login.h - web_backend.h - ) - -create_directory_groups(${SRCS} ${HEADERS}) - -add_library(web_service STATIC ${SRCS} ${HEADERS}) -target_link_libraries(web_service PUBLIC common cpr json-headers) diff --git a/src/web_service/telemetry_json.cpp b/src/web_service/telemetry_json.cpp deleted file mode 100644 index 6ad2ffcd4..000000000 --- a/src/web_service/telemetry_json.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include "common/assert.h" -#include "web_service/telemetry_json.h" -#include "web_service/web_backend.h" - -namespace WebService { - -template <class T> -void TelemetryJson::Serialize(Telemetry::FieldType type, const std::string& name, T value) { - sections[static_cast<u8>(type)][name] = value; -} - -void TelemetryJson::SerializeSection(Telemetry::FieldType type, const std::string& name) { - TopSection()[name] = sections[static_cast<unsigned>(type)]; -} - -void TelemetryJson::Visit(const Telemetry::Field<bool>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<double>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<float>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<u8>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<u16>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<u32>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<u64>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<s8>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<s16>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<s32>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<s64>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<std::string>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue()); -} - -void TelemetryJson::Visit(const Telemetry::Field<const char*>& field) { - Serialize(field.GetType(), field.GetName(), std::string(field.GetValue())); -} - -void TelemetryJson::Visit(const Telemetry::Field<std::chrono::microseconds>& field) { - Serialize(field.GetType(), field.GetName(), field.GetValue().count()); -} - -void TelemetryJson::Complete() { - SerializeSection(Telemetry::FieldType::App, "App"); - SerializeSection(Telemetry::FieldType::Session, "Session"); - SerializeSection(Telemetry::FieldType::Performance, "Performance"); - SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback"); - SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig"); - SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem"); - PostJson(endpoint_url, TopSection().dump(), true, username, token); -} - -} // namespace WebService diff --git a/src/web_service/telemetry_json.h b/src/web_service/telemetry_json.h deleted file mode 100644 index 9e78c6803..000000000 --- a/src/web_service/telemetry_json.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <array> -#include <string> -#include <json.hpp> -#include "common/telemetry.h" - -namespace WebService { - -/** - * Implementation of VisitorInterface that serialized telemetry into JSON, and submits it to the - * Citra web service - */ -class TelemetryJson : public Telemetry::VisitorInterface { -public: - TelemetryJson(const std::string& endpoint_url, const std::string& username, - const std::string& token) - : endpoint_url(endpoint_url), username(username), token(token) {} - ~TelemetryJson() = default; - - void Visit(const Telemetry::Field<bool>& field) override; - void Visit(const Telemetry::Field<double>& field) override; - void Visit(const Telemetry::Field<float>& field) override; - void Visit(const Telemetry::Field<u8>& field) override; - void Visit(const Telemetry::Field<u16>& field) override; - void Visit(const Telemetry::Field<u32>& field) override; - void Visit(const Telemetry::Field<u64>& field) override; - void Visit(const Telemetry::Field<s8>& field) override; - void Visit(const Telemetry::Field<s16>& field) override; - void Visit(const Telemetry::Field<s32>& field) override; - void Visit(const Telemetry::Field<s64>& field) override; - void Visit(const Telemetry::Field<std::string>& field) override; - void Visit(const Telemetry::Field<const char*>& field) override; - void Visit(const Telemetry::Field<std::chrono::microseconds>& field) override; - - void Complete() override; - -private: - nlohmann::json& TopSection() { - return sections[static_cast<u8>(Telemetry::FieldType::None)]; - } - - template <class T> - void Serialize(Telemetry::FieldType type, const std::string& name, T value); - - void SerializeSection(Telemetry::FieldType type, const std::string& name); - - nlohmann::json output; - std::array<nlohmann::json, 7> sections; - std::string endpoint_url; - std::string username; - std::string token; -}; - -} // namespace WebService diff --git a/src/web_service/verify_login.cpp b/src/web_service/verify_login.cpp deleted file mode 100644 index 1bc3b5afe..000000000 --- a/src/web_service/verify_login.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include <json.hpp> -#include "web_service/verify_login.h" -#include "web_service/web_backend.h" - -namespace WebService { - -std::future<bool> VerifyLogin(std::string& username, std::string& token, - const std::string& endpoint_url, std::function<void()> func) { - auto get_func = [func, username](const std::string& reply) -> bool { - func(); - if (reply.empty()) - return false; - nlohmann::json json = nlohmann::json::parse(reply); - std::string result; - try { - result = json["username"]; - } catch (const nlohmann::detail::out_of_range&) { - } - return result == username; - }; - return GetJson<bool>(get_func, endpoint_url, false, username, token); -} - -} // namespace WebService diff --git a/src/web_service/verify_login.h b/src/web_service/verify_login.h deleted file mode 100644 index 303f5dbbc..000000000 --- a/src/web_service/verify_login.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <functional> -#include <future> -#include <string> - -namespace WebService { - -/** - * Checks if username and token is valid - * @param username Citra username to use for authentication. - * @param token Citra token to use for authentication. - * @param endpoint_url URL of the services.citra-emu.org endpoint. - * @param func A function that gets exectued when the verification is finished - * @returns Future with bool indicating whether the verification succeeded - */ -std::future<bool> VerifyLogin(std::string& username, std::string& token, - const std::string& endpoint_url, std::function<void()> func); - -} // namespace WebService diff --git a/src/web_service/web_backend.cpp b/src/web_service/web_backend.cpp deleted file mode 100644 index b17d82f9c..000000000 --- a/src/web_service/web_backend.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#ifdef _WIN32 -#include <winsock.h> -#endif - -#include <cstdlib> -#include <thread> -#include <cpr/cpr.h> -#include "common/logging/log.h" -#include "web_service/web_backend.h" - -namespace WebService { - -static constexpr char API_VERSION[]{"1"}; - -static std::unique_ptr<cpr::Session> g_session; - -void Win32WSAStartup() { -#ifdef _WIN32 - // On Windows, CPR/libcurl does not properly initialize Winsock. The below code is used to - // initialize Winsock globally, which fixes this problem. Without this, only the first CPR - // session will properly be created, and subsequent ones will fail. - WSADATA wsa_data; - const int wsa_result{WSAStartup(MAKEWORD(2, 2), &wsa_data)}; - if (wsa_result) { - LOG_CRITICAL(WebService, "WSAStartup failed: %d", wsa_result); - } -#endif -} - -void PostJson(const std::string& url, const std::string& data, bool allow_anonymous, - const std::string& username, const std::string& token) { - if (url.empty()) { - LOG_ERROR(WebService, "URL is invalid"); - return; - } - - const bool are_credentials_provided{!token.empty() && !username.empty()}; - if (!allow_anonymous && !are_credentials_provided) { - LOG_ERROR(WebService, "Credentials must be provided for authenticated requests"); - return; - } - - Win32WSAStartup(); - - // Built request header - cpr::Header header; - if (are_credentials_provided) { - // Authenticated request if credentials are provided - header = {{"Content-Type", "application/json"}, - {"x-username", username.c_str()}, - {"x-token", token.c_str()}, - {"api-version", API_VERSION}}; - } else { - // Otherwise, anonymous request - header = cpr::Header{{"Content-Type", "application/json"}, {"api-version", API_VERSION}}; - } - - // Post JSON asynchronously - static std::future<void> future; - future = cpr::PostCallback( - [](cpr::Response r) { - if (r.error) { - LOG_ERROR(WebService, "POST returned cpr error: %u:%s", - static_cast<u32>(r.error.code), r.error.message.c_str()); - return; - } - if (r.status_code >= 400) { - LOG_ERROR(WebService, "POST returned error status code: %u", r.status_code); - return; - } - if (r.header["content-type"].find("application/json") == std::string::npos) { - LOG_ERROR(WebService, "POST returned wrong content: %s", - r.header["content-type"].c_str()); - return; - } - }, - cpr::Url{url}, cpr::Body{data}, header); -} - -template <typename T> -std::future<T> GetJson(std::function<T(const std::string&)> func, const std::string& url, - bool allow_anonymous, const std::string& username, - const std::string& token) { - if (url.empty()) { - LOG_ERROR(WebService, "URL is invalid"); - return std::async(std::launch::async, [func{std::move(func)}]() { return func(""); }); - } - - const bool are_credentials_provided{!token.empty() && !username.empty()}; - if (!allow_anonymous && !are_credentials_provided) { - LOG_ERROR(WebService, "Credentials must be provided for authenticated requests"); - return std::async(std::launch::async, [func{std::move(func)}]() { return func(""); }); - } - - Win32WSAStartup(); - - // Built request header - cpr::Header header; - if (are_credentials_provided) { - // Authenticated request if credentials are provided - header = {{"Content-Type", "application/json"}, - {"x-username", username.c_str()}, - {"x-token", token.c_str()}, - {"api-version", API_VERSION}}; - } else { - // Otherwise, anonymous request - header = cpr::Header{{"Content-Type", "application/json"}, {"api-version", API_VERSION}}; - } - - // Get JSON asynchronously - return cpr::GetCallback( - [func{std::move(func)}](cpr::Response r) { - if (r.error) { - LOG_ERROR(WebService, "GET returned cpr error: %u:%s", - static_cast<u32>(r.error.code), r.error.message.c_str()); - return func(""); - } - if (r.status_code >= 400) { - LOG_ERROR(WebService, "GET returned error code: %u", r.status_code); - return func(""); - } - if (r.header["content-type"].find("application/json") == std::string::npos) { - LOG_ERROR(WebService, "GET returned wrong content: %s", - r.header["content-type"].c_str()); - return func(""); - } - return func(r.text); - }, - cpr::Url{url}, header); -} - -template std::future<bool> GetJson(std::function<bool(const std::string&)> func, - const std::string& url, bool allow_anonymous, - const std::string& username, const std::string& token); - -} // namespace WebService diff --git a/src/web_service/web_backend.h b/src/web_service/web_backend.h deleted file mode 100644 index a63c75d13..000000000 --- a/src/web_service/web_backend.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include <functional> -#include <future> -#include <string> -#include "common/common_types.h" - -namespace WebService { - -/** - * Posts JSON to services.citra-emu.org. - * @param url URL of the services.citra-emu.org endpoint to post data to. - * @param data String of JSON data to use for the body of the POST request. - * @param allow_anonymous If true, allow anonymous unauthenticated requests. - * @param username Citra username to use for authentication. - * @param token Citra token to use for authentication. - */ -void PostJson(const std::string& url, const std::string& data, bool allow_anonymous, - const std::string& username = {}, const std::string& token = {}); - -/** - * Gets JSON from services.citra-emu.org. - * @param func A function that gets exectued when the json as a string is received - * @param url URL of the services.citra-emu.org endpoint to post data to. - * @param allow_anonymous If true, allow anonymous unauthenticated requests. - * @param username Citra username to use for authentication. - * @param token Citra token to use for authentication. - * @return future that holds the return value T of the func - */ -template <typename T> -std::future<T> GetJson(std::function<T(const std::string&)> func, const std::string& url, - bool allow_anonymous, const std::string& username = {}, - const std::string& token = {}); - -} // namespace WebService diff --git a/src/citra_qt/CMakeLists.txt b/src/yuzu/CMakeLists.txt index e2fa33081..38bbc0043 100644 --- a/src/citra_qt/CMakeLists.txt +++ b/src/yuzu/CMakeLists.txt @@ -79,7 +79,7 @@ set(UIS main.ui ) -file(GLOB_RECURSE ICONS ${CMAKE_SOURCE_DIR}/dist/icons/*) +# file(GLOB_RECURSE ICONS ${CMAKE_SOURCE_DIR}/dist/icons/*) file(GLOB_RECURSE THEMES ${CMAKE_SOURCE_DIR}/dist/qt_themes/*) create_directory_groups(${SRCS} ${HEADERS} ${UIS}) @@ -93,24 +93,24 @@ endif() if (APPLE) set(MACOSX_ICON "../../dist/citra.icns") set_source_files_properties(${MACOSX_ICON} PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - add_executable(citra-qt MACOSX_BUNDLE ${SRCS} ${HEADERS} ${UI_HDRS} ${ICONS} ${THEMES} ${MACOSX_ICON}) - set_target_properties(citra-qt PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) + add_executable(yuzu MACOSX_BUNDLE ${SRCS} ${HEADERS} ${UI_HDRS} ${MACOSX_ICON}) + set_target_properties(yuzu PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) else() - add_executable(citra-qt ${SRCS} ${HEADERS} ${UI_HDRS} ${ICONS} ${THEMES}) + add_executable(yuzu ${SRCS} ${HEADERS} ${UI_HDRS}) endif() -target_link_libraries(citra-qt PRIVATE audio_core common core input_common network video_core) -target_link_libraries(citra-qt PRIVATE Boost::boost glad nihstro-headers Qt5::OpenGL Qt5::Widgets) -target_link_libraries(citra-qt PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) +target_link_libraries(yuzu PRIVATE common core input_common video_core) +target_link_libraries(yuzu PRIVATE Boost::boost glad Qt5::OpenGL Qt5::Widgets) +target_link_libraries(yuzu PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) if(UNIX AND NOT APPLE) - install(TARGETS citra-qt RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") + install(TARGETS yuzu RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") endif() if (MSVC) include(CopyCitraQt5Deps) include(CopyCitraSDLDeps) include(CopyYuzuUnicornDeps) - copy_citra_Qt5_deps(citra-qt) - copy_citra_SDL_deps(citra-qt) - copy_yuzu_unicorn_deps(citra-qt) + copy_citra_Qt5_deps(yuzu) + copy_citra_SDL_deps(yuzu) + copy_yuzu_unicorn_deps(yuzu) endif() diff --git a/src/citra_qt/Info.plist b/src/yuzu/Info.plist index 7d46b39d1..7d46b39d1 100644 --- a/src/citra_qt/Info.plist +++ b/src/yuzu/Info.plist diff --git a/src/citra_qt/bootmanager.cpp b/src/yuzu/bootmanager.cpp index eb542ad4e..eb542ad4e 100644 --- a/src/citra_qt/bootmanager.cpp +++ b/src/yuzu/bootmanager.cpp diff --git a/src/citra_qt/bootmanager.h b/src/yuzu/bootmanager.h index 6974edcbb..6974edcbb 100644 --- a/src/citra_qt/bootmanager.h +++ b/src/yuzu/bootmanager.h diff --git a/src/citra_qt/citra-qt.rc b/src/yuzu/citra-qt.rc index a48a9440d..a48a9440d 100644 --- a/src/citra_qt/citra-qt.rc +++ b/src/yuzu/citra-qt.rc diff --git a/src/citra_qt/configuration/config.cpp b/src/yuzu/configuration/config.cpp index fd884db7a..fd884db7a 100644 --- a/src/citra_qt/configuration/config.cpp +++ b/src/yuzu/configuration/config.cpp diff --git a/src/citra_qt/configuration/config.h b/src/yuzu/configuration/config.h index cbf745ea2..cbf745ea2 100644 --- a/src/citra_qt/configuration/config.h +++ b/src/yuzu/configuration/config.h diff --git a/src/citra_qt/configuration/configure.ui b/src/yuzu/configuration/configure.ui index 6abd1917e..6abd1917e 100644 --- a/src/citra_qt/configuration/configure.ui +++ b/src/yuzu/configuration/configure.ui diff --git a/src/citra_qt/configuration/configure_audio.cpp b/src/yuzu/configuration/configure_audio.cpp index 3fd1d127a..3fd1d127a 100644 --- a/src/citra_qt/configuration/configure_audio.cpp +++ b/src/yuzu/configuration/configure_audio.cpp diff --git a/src/citra_qt/configuration/configure_audio.h b/src/yuzu/configuration/configure_audio.h index 8190e694f..8190e694f 100644 --- a/src/citra_qt/configuration/configure_audio.h +++ b/src/yuzu/configuration/configure_audio.h diff --git a/src/citra_qt/configuration/configure_audio.ui b/src/yuzu/configuration/configure_audio.ui index dd870eb61..dd870eb61 100644 --- a/src/citra_qt/configuration/configure_audio.ui +++ b/src/yuzu/configuration/configure_audio.ui diff --git a/src/citra_qt/configuration/configure_debug.cpp b/src/yuzu/configuration/configure_debug.cpp index 263f73f38..263f73f38 100644 --- a/src/citra_qt/configuration/configure_debug.cpp +++ b/src/yuzu/configuration/configure_debug.cpp diff --git a/src/citra_qt/configuration/configure_debug.h b/src/yuzu/configuration/configure_debug.h index d167eb996..d167eb996 100644 --- a/src/citra_qt/configuration/configure_debug.h +++ b/src/yuzu/configuration/configure_debug.h diff --git a/src/citra_qt/configuration/configure_debug.ui b/src/yuzu/configuration/configure_debug.ui index 96638ebdb..96638ebdb 100644 --- a/src/citra_qt/configuration/configure_debug.ui +++ b/src/yuzu/configuration/configure_debug.ui diff --git a/src/citra_qt/configuration/configure_dialog.cpp b/src/yuzu/configuration/configure_dialog.cpp index b87dc0e6c..b87dc0e6c 100644 --- a/src/citra_qt/configuration/configure_dialog.cpp +++ b/src/yuzu/configuration/configure_dialog.cpp diff --git a/src/citra_qt/configuration/configure_dialog.h b/src/yuzu/configuration/configure_dialog.h index 21fa1f501..21fa1f501 100644 --- a/src/citra_qt/configuration/configure_dialog.h +++ b/src/yuzu/configuration/configure_dialog.h diff --git a/src/citra_qt/configuration/configure_general.cpp b/src/yuzu/configuration/configure_general.cpp index 0de27aa8b..0de27aa8b 100644 --- a/src/citra_qt/configuration/configure_general.cpp +++ b/src/yuzu/configuration/configure_general.cpp diff --git a/src/citra_qt/configuration/configure_general.h b/src/yuzu/configuration/configure_general.h index 447552d8c..447552d8c 100644 --- a/src/citra_qt/configuration/configure_general.h +++ b/src/yuzu/configuration/configure_general.h diff --git a/src/citra_qt/configuration/configure_general.ui b/src/yuzu/configuration/configure_general.ui index e88c37936..e88c37936 100644 --- a/src/citra_qt/configuration/configure_general.ui +++ b/src/yuzu/configuration/configure_general.ui diff --git a/src/citra_qt/configuration/configure_graphics.cpp b/src/yuzu/configuration/configure_graphics.cpp index b5a5ab1e1..b5a5ab1e1 100644 --- a/src/citra_qt/configuration/configure_graphics.cpp +++ b/src/yuzu/configuration/configure_graphics.cpp diff --git a/src/citra_qt/configuration/configure_graphics.h b/src/yuzu/configuration/configure_graphics.h index 5497a55f7..5497a55f7 100644 --- a/src/citra_qt/configuration/configure_graphics.h +++ b/src/yuzu/configuration/configure_graphics.h diff --git a/src/citra_qt/configuration/configure_graphics.ui b/src/yuzu/configuration/configure_graphics.ui index 5667b14b6..5667b14b6 100644 --- a/src/citra_qt/configuration/configure_graphics.ui +++ b/src/yuzu/configuration/configure_graphics.ui diff --git a/src/citra_qt/configuration/configure_input.cpp b/src/yuzu/configuration/configure_input.cpp index 116a6330f..116a6330f 100644 --- a/src/citra_qt/configuration/configure_input.cpp +++ b/src/yuzu/configuration/configure_input.cpp diff --git a/src/citra_qt/configuration/configure_input.h b/src/yuzu/configuration/configure_input.h index c950fbcb4..c950fbcb4 100644 --- a/src/citra_qt/configuration/configure_input.h +++ b/src/yuzu/configuration/configure_input.h diff --git a/src/citra_qt/configuration/configure_input.ui b/src/yuzu/configuration/configure_input.ui index 2760787e5..2760787e5 100644 --- a/src/citra_qt/configuration/configure_input.ui +++ b/src/yuzu/configuration/configure_input.ui diff --git a/src/citra_qt/configuration/configure_system.cpp b/src/yuzu/configuration/configure_system.cpp index d83c2db23..d83c2db23 100644 --- a/src/citra_qt/configuration/configure_system.cpp +++ b/src/yuzu/configuration/configure_system.cpp diff --git a/src/citra_qt/configuration/configure_system.h b/src/yuzu/configuration/configure_system.h index f13de17d4..f13de17d4 100644 --- a/src/citra_qt/configuration/configure_system.h +++ b/src/yuzu/configuration/configure_system.h diff --git a/src/citra_qt/configuration/configure_system.ui b/src/yuzu/configuration/configure_system.ui index 8caf49623..8caf49623 100644 --- a/src/citra_qt/configuration/configure_system.ui +++ b/src/yuzu/configuration/configure_system.ui diff --git a/src/citra_qt/configuration/configure_web.cpp b/src/yuzu/configuration/configure_web.cpp index bf8c21ac7..bf8c21ac7 100644 --- a/src/citra_qt/configuration/configure_web.cpp +++ b/src/yuzu/configuration/configure_web.cpp diff --git a/src/citra_qt/configuration/configure_web.h b/src/yuzu/configuration/configure_web.h index ad2d58f6e..ad2d58f6e 100644 --- a/src/citra_qt/configuration/configure_web.h +++ b/src/yuzu/configuration/configure_web.h diff --git a/src/citra_qt/configuration/configure_web.ui b/src/yuzu/configuration/configure_web.ui index dd996ab62..dd996ab62 100644 --- a/src/citra_qt/configuration/configure_web.ui +++ b/src/yuzu/configuration/configure_web.ui diff --git a/src/citra_qt/debugger/graphics/graphics.cpp b/src/yuzu/debugger/graphics/graphics.cpp index 8154363a2..8154363a2 100644 --- a/src/citra_qt/debugger/graphics/graphics.cpp +++ b/src/yuzu/debugger/graphics/graphics.cpp diff --git a/src/citra_qt/debugger/graphics/graphics.h b/src/yuzu/debugger/graphics/graphics.h index 8837fb792..8837fb792 100644 --- a/src/citra_qt/debugger/graphics/graphics.h +++ b/src/yuzu/debugger/graphics/graphics.h diff --git a/src/citra_qt/debugger/graphics/graphics_breakpoint_observer.cpp b/src/yuzu/debugger/graphics/graphics_breakpoint_observer.cpp index dc6070dea..dc6070dea 100644 --- a/src/citra_qt/debugger/graphics/graphics_breakpoint_observer.cpp +++ b/src/yuzu/debugger/graphics/graphics_breakpoint_observer.cpp diff --git a/src/citra_qt/debugger/graphics/graphics_breakpoint_observer.h b/src/yuzu/debugger/graphics/graphics_breakpoint_observer.h index e77df4f5b..e77df4f5b 100644 --- a/src/citra_qt/debugger/graphics/graphics_breakpoint_observer.h +++ b/src/yuzu/debugger/graphics/graphics_breakpoint_observer.h diff --git a/src/citra_qt/debugger/graphics/graphics_breakpoints.cpp b/src/yuzu/debugger/graphics/graphics_breakpoints.cpp index 030828ba8..030828ba8 100644 --- a/src/citra_qt/debugger/graphics/graphics_breakpoints.cpp +++ b/src/yuzu/debugger/graphics/graphics_breakpoints.cpp diff --git a/src/citra_qt/debugger/graphics/graphics_breakpoints.h b/src/yuzu/debugger/graphics/graphics_breakpoints.h index bec72a2db..bec72a2db 100644 --- a/src/citra_qt/debugger/graphics/graphics_breakpoints.h +++ b/src/yuzu/debugger/graphics/graphics_breakpoints.h diff --git a/src/citra_qt/debugger/graphics/graphics_breakpoints_p.h b/src/yuzu/debugger/graphics/graphics_breakpoints_p.h index dc64706bd..dc64706bd 100644 --- a/src/citra_qt/debugger/graphics/graphics_breakpoints_p.h +++ b/src/yuzu/debugger/graphics/graphics_breakpoints_p.h diff --git a/src/citra_qt/debugger/graphics/graphics_cmdlists.cpp b/src/yuzu/debugger/graphics/graphics_cmdlists.cpp index ce2b9fa50..ce2b9fa50 100644 --- a/src/citra_qt/debugger/graphics/graphics_cmdlists.cpp +++ b/src/yuzu/debugger/graphics/graphics_cmdlists.cpp diff --git a/src/citra_qt/debugger/graphics/graphics_cmdlists.h b/src/yuzu/debugger/graphics/graphics_cmdlists.h index 8f40b94c5..8f40b94c5 100644 --- a/src/citra_qt/debugger/graphics/graphics_cmdlists.h +++ b/src/yuzu/debugger/graphics/graphics_cmdlists.h diff --git a/src/citra_qt/debugger/graphics/graphics_surface.cpp b/src/yuzu/debugger/graphics/graphics_surface.cpp index c974545ef..c974545ef 100644 --- a/src/citra_qt/debugger/graphics/graphics_surface.cpp +++ b/src/yuzu/debugger/graphics/graphics_surface.cpp diff --git a/src/citra_qt/debugger/graphics/graphics_surface.h b/src/yuzu/debugger/graphics/graphics_surface.h index 28f5650a7..28f5650a7 100644 --- a/src/citra_qt/debugger/graphics/graphics_surface.h +++ b/src/yuzu/debugger/graphics/graphics_surface.h diff --git a/src/citra_qt/debugger/graphics/graphics_tracing.cpp b/src/yuzu/debugger/graphics/graphics_tracing.cpp index 40d5bed51..40d5bed51 100644 --- a/src/citra_qt/debugger/graphics/graphics_tracing.cpp +++ b/src/yuzu/debugger/graphics/graphics_tracing.cpp diff --git a/src/citra_qt/debugger/graphics/graphics_tracing.h b/src/yuzu/debugger/graphics/graphics_tracing.h index eb1292c29..eb1292c29 100644 --- a/src/citra_qt/debugger/graphics/graphics_tracing.h +++ b/src/yuzu/debugger/graphics/graphics_tracing.h diff --git a/src/citra_qt/debugger/graphics/graphics_vertex_shader.cpp b/src/yuzu/debugger/graphics/graphics_vertex_shader.cpp index 7f4ec0c52..7f4ec0c52 100644 --- a/src/citra_qt/debugger/graphics/graphics_vertex_shader.cpp +++ b/src/yuzu/debugger/graphics/graphics_vertex_shader.cpp diff --git a/src/citra_qt/debugger/graphics/graphics_vertex_shader.h b/src/yuzu/debugger/graphics/graphics_vertex_shader.h index c249a2ff8..c249a2ff8 100644 --- a/src/citra_qt/debugger/graphics/graphics_vertex_shader.h +++ b/src/yuzu/debugger/graphics/graphics_vertex_shader.h diff --git a/src/citra_qt/debugger/profiler.cpp b/src/yuzu/debugger/profiler.cpp index f060bbe08..f060bbe08 100644 --- a/src/citra_qt/debugger/profiler.cpp +++ b/src/yuzu/debugger/profiler.cpp diff --git a/src/citra_qt/debugger/profiler.h b/src/yuzu/debugger/profiler.h index eae1e9e3c..eae1e9e3c 100644 --- a/src/citra_qt/debugger/profiler.h +++ b/src/yuzu/debugger/profiler.h diff --git a/src/citra_qt/debugger/registers.cpp b/src/yuzu/debugger/registers.cpp index f9345c9f6..f9345c9f6 100644 --- a/src/citra_qt/debugger/registers.cpp +++ b/src/yuzu/debugger/registers.cpp diff --git a/src/citra_qt/debugger/registers.h b/src/yuzu/debugger/registers.h index 55bda5b59..55bda5b59 100644 --- a/src/citra_qt/debugger/registers.h +++ b/src/yuzu/debugger/registers.h diff --git a/src/citra_qt/debugger/registers.ui b/src/yuzu/debugger/registers.ui index c81ae03f9..c81ae03f9 100644 --- a/src/citra_qt/debugger/registers.ui +++ b/src/yuzu/debugger/registers.ui diff --git a/src/citra_qt/debugger/wait_tree.cpp b/src/yuzu/debugger/wait_tree.cpp index eefbcb9f1..eefbcb9f1 100644 --- a/src/citra_qt/debugger/wait_tree.cpp +++ b/src/yuzu/debugger/wait_tree.cpp diff --git a/src/citra_qt/debugger/wait_tree.h b/src/yuzu/debugger/wait_tree.h index 4034e909b..4034e909b 100644 --- a/src/citra_qt/debugger/wait_tree.h +++ b/src/yuzu/debugger/wait_tree.h diff --git a/src/citra_qt/game_list.cpp b/src/yuzu/game_list.cpp index a8e3541cd..a8e3541cd 100644 --- a/src/citra_qt/game_list.cpp +++ b/src/yuzu/game_list.cpp diff --git a/src/citra_qt/game_list.h b/src/yuzu/game_list.h index 4823a1296..4823a1296 100644 --- a/src/citra_qt/game_list.h +++ b/src/yuzu/game_list.h diff --git a/src/citra_qt/game_list_p.h b/src/yuzu/game_list_p.h index 9881296d9..9881296d9 100644 --- a/src/citra_qt/game_list_p.h +++ b/src/yuzu/game_list_p.h diff --git a/src/citra_qt/hotkeys.cpp b/src/yuzu/hotkeys.cpp index 158ed506f..158ed506f 100644 --- a/src/citra_qt/hotkeys.cpp +++ b/src/yuzu/hotkeys.cpp diff --git a/src/citra_qt/hotkeys.h b/src/yuzu/hotkeys.h index a4ccc193b..a4ccc193b 100644 --- a/src/citra_qt/hotkeys.h +++ b/src/yuzu/hotkeys.h diff --git a/src/citra_qt/hotkeys.ui b/src/yuzu/hotkeys.ui index 050fe064e..050fe064e 100644 --- a/src/citra_qt/hotkeys.ui +++ b/src/yuzu/hotkeys.ui diff --git a/src/citra_qt/main.cpp b/src/yuzu/main.cpp index 943aee30d..943aee30d 100644 --- a/src/citra_qt/main.cpp +++ b/src/yuzu/main.cpp diff --git a/src/citra_qt/main.h b/src/yuzu/main.h index d59a6d67d..d59a6d67d 100644 --- a/src/citra_qt/main.h +++ b/src/yuzu/main.h diff --git a/src/citra_qt/main.ui b/src/yuzu/main.ui index b13d578f5..b13d578f5 100644 --- a/src/citra_qt/main.ui +++ b/src/yuzu/main.ui diff --git a/src/citra_qt/ui_settings.cpp b/src/yuzu/ui_settings.cpp index 120b34990..120b34990 100644 --- a/src/citra_qt/ui_settings.cpp +++ b/src/yuzu/ui_settings.cpp diff --git a/src/citra_qt/ui_settings.h b/src/yuzu/ui_settings.h index d85c92765..d85c92765 100644 --- a/src/citra_qt/ui_settings.h +++ b/src/yuzu/ui_settings.h diff --git a/src/citra_qt/util/spinbox.cpp b/src/yuzu/util/spinbox.cpp index 212709007..212709007 100644 --- a/src/citra_qt/util/spinbox.cpp +++ b/src/yuzu/util/spinbox.cpp diff --git a/src/citra_qt/util/spinbox.h b/src/yuzu/util/spinbox.h index 2fa1db3a4..2fa1db3a4 100644 --- a/src/citra_qt/util/spinbox.h +++ b/src/yuzu/util/spinbox.h diff --git a/src/citra_qt/util/util.cpp b/src/yuzu/util/util.cpp index 02be92bbd..02be92bbd 100644 --- a/src/citra_qt/util/util.cpp +++ b/src/yuzu/util/util.cpp diff --git a/src/citra_qt/util/util.h b/src/yuzu/util/util.h index ab443ef9b..ab443ef9b 100644 --- a/src/citra_qt/util/util.h +++ b/src/yuzu/util/util.h diff --git a/src/citra/CMakeLists.txt b/src/yuzu_cmd/CMakeLists.txt index ed92a6ae2..c6c527eb6 100644 --- a/src/citra/CMakeLists.txt +++ b/src/yuzu_cmd/CMakeLists.txt @@ -15,21 +15,21 @@ set(HEADERS create_directory_groups(${SRCS} ${HEADERS}) -add_executable(citra ${SRCS} ${HEADERS}) -target_link_libraries(citra PRIVATE common core input_common network) -target_link_libraries(citra PRIVATE inih glad) +add_executable(yuzu-cmd ${SRCS} ${HEADERS}) +target_link_libraries(yuzu-cmd PRIVATE common core input_common) +target_link_libraries(yuzu-cmd PRIVATE inih glad) if (MSVC) - target_link_libraries(citra PRIVATE getopt) + target_link_libraries(yuzu-cmd PRIVATE getopt) endif() -target_link_libraries(citra PRIVATE ${PLATFORM_LIBRARIES} SDL2 Threads::Threads) +target_link_libraries(yuzu-cmd PRIVATE ${PLATFORM_LIBRARIES} SDL2 Threads::Threads) if(UNIX AND NOT APPLE) - install(TARGETS citra RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") + install(TARGETS yuzu-cmd RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") endif() if (MSVC) include(CopyCitraSDLDeps) include(CopyYuzuUnicornDeps) - copy_citra_SDL_deps(citra) - copy_yuzu_unicorn_deps(citra) + copy_citra_SDL_deps(yuzu-cmd) + copy_yuzu_unicorn_deps(yuzu-cmd) endif() diff --git a/src/citra/citra.cpp b/src/yuzu_cmd/citra.cpp index e524c5535..e524c5535 100644 --- a/src/citra/citra.cpp +++ b/src/yuzu_cmd/citra.cpp diff --git a/src/citra/citra.rc b/src/yuzu_cmd/citra.rc index c490ef302..c490ef302 100644 --- a/src/citra/citra.rc +++ b/src/yuzu_cmd/citra.rc diff --git a/src/citra/config.cpp b/src/yuzu_cmd/config.cpp index 94d1a9f1c..94d1a9f1c 100644 --- a/src/citra/config.cpp +++ b/src/yuzu_cmd/config.cpp diff --git a/src/citra/config.h b/src/yuzu_cmd/config.h index abc90f642..abc90f642 100644 --- a/src/citra/config.h +++ b/src/yuzu_cmd/config.h diff --git a/src/citra/default_ini.h b/src/yuzu_cmd/default_ini.h index b7b8abe1e..b7b8abe1e 100644 --- a/src/citra/default_ini.h +++ b/src/yuzu_cmd/default_ini.h diff --git a/src/citra/emu_window/emu_window_sdl2.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp index e65b04e4b..e65b04e4b 100644 --- a/src/citra/emu_window/emu_window_sdl2.cpp +++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp diff --git a/src/citra/emu_window/emu_window_sdl2.h b/src/yuzu_cmd/emu_window/emu_window_sdl2.h index 3664d2fbe..3664d2fbe 100644 --- a/src/citra/emu_window/emu_window_sdl2.h +++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.h diff --git a/src/citra/resource.h b/src/yuzu_cmd/resource.h index df8e459e4..df8e459e4 100644 --- a/src/citra/resource.h +++ b/src/yuzu_cmd/resource.h |