summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt9
-rw-r--r--src/audio_core/CMakeLists.txt44
-rw-r--r--src/audio_core/audio_core.cpp61
-rw-r--r--src/audio_core/audio_core.h31
-rw-r--r--src/audio_core/codec.cpp127
-rw-r--r--src/audio_core/codec.h51
-rw-r--r--src/audio_core/hle/common.h34
-rw-r--r--src/audio_core/hle/dsp.cpp172
-rw-r--r--src/audio_core/hle/dsp.h595
-rw-r--r--src/audio_core/hle/filter.cpp117
-rw-r--r--src/audio_core/hle/filter.h117
-rw-r--r--src/audio_core/hle/mixers.cpp210
-rw-r--r--src/audio_core/hle/mixers.h61
-rw-r--r--src/audio_core/hle/pipe.cpp177
-rw-r--r--src/audio_core/hle/pipe.h63
-rw-r--r--src/audio_core/hle/source.cpp349
-rw-r--r--src/audio_core/hle/source.h149
-rw-r--r--src/audio_core/interpolate.cpp76
-rw-r--r--src/audio_core/interpolate.h49
-rw-r--r--src/audio_core/null_sink.h34
-rw-r--r--src/audio_core/sdl2_sink.cpp147
-rw-r--r--src/audio_core/sdl2_sink.h34
-rw-r--r--src/audio_core/sink.h45
-rw-r--r--src/audio_core/sink_details.cpp42
-rw-r--r--src/audio_core/sink_details.h29
-rw-r--r--src/audio_core/time_stretch.cpp143
-rw-r--r--src/audio_core/time_stretch.h60
-rw-r--r--src/network/CMakeLists.txt18
-rw-r--r--src/network/network.cpp50
-rw-r--r--src/network/network.h25
-rw-r--r--src/network/packet.cpp263
-rw-r--r--src/network/packet.h166
-rw-r--r--src/network/room.cpp497
-rw-r--r--src/network/room.h101
-rw-r--r--src/network/room_member.cpp490
-rw-r--r--src/network/room_member.h182
-rw-r--r--src/web_service/CMakeLists.txt16
-rw-r--r--src/web_service/telemetry_json.cpp86
-rw-r--r--src/web_service/telemetry_json.h59
-rw-r--r--src/web_service/verify_login.cpp28
-rw-r--r--src/web_service/verify_login.h24
-rw-r--r--src/web_service/web_backend.cpp140
-rw-r--r--src/web_service/web_backend.h39
-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(.)
4add_subdirectory(common) 4add_subdirectory(common)
5add_subdirectory(core) 5add_subdirectory(core)
6add_subdirectory(video_core) 6add_subdirectory(video_core)
7add_subdirectory(audio_core)
8add_subdirectory(network)
9add_subdirectory(input_common) 7add_subdirectory(input_common)
10add_subdirectory(tests) 8add_subdirectory(tests)
11if (ENABLE_SDL2) 9if (ENABLE_SDL2)
12 add_subdirectory(citra) 10 add_subdirectory(yuzu_cmd)
13endif() 11endif()
14if (ENABLE_QT) 12if (ENABLE_QT)
15 add_subdirectory(citra_qt) 13 add_subdirectory(yuzu)
16endif()
17if (ENABLE_WEB_SERVICE)
18 add_subdirectory(web_service)
19endif() 14endif()
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 @@
1set(SRCS
2 audio_core.cpp
3 codec.cpp
4 hle/dsp.cpp
5 hle/filter.cpp
6 hle/mixers.cpp
7 hle/pipe.cpp
8 hle/source.cpp
9 interpolate.cpp
10 sink_details.cpp
11 time_stretch.cpp
12 )
13
14set(HEADERS
15 audio_core.h
16 codec.h
17 hle/common.h
18 hle/dsp.h
19 hle/filter.h
20 hle/mixers.h
21 hle/pipe.h
22 hle/source.h
23 interpolate.h
24 null_sink.h
25 sink.h
26 sink_details.h
27 time_stretch.h
28 )
29
30if(SDL2_FOUND)
31 set(SRCS ${SRCS} sdl2_sink.cpp)
32 set(HEADERS ${HEADERS} sdl2_sink.h)
33endif()
34
35create_directory_groups(${SRCS} ${HEADERS})
36
37add_library(audio_core STATIC ${SRCS} ${HEADERS})
38target_link_libraries(audio_core PUBLIC common core)
39target_link_libraries(audio_core PRIVATE SoundTouch)
40
41if(SDL2_FOUND)
42 target_link_libraries(audio_core PRIVATE SDL2)
43 target_compile_definitions(audio_core PRIVATE HAVE_SDL2)
44endif()
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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <array>
6#include <memory>
7#include <string>
8#include "audio_core/audio_core.h"
9#include "audio_core/hle/dsp.h"
10#include "audio_core/hle/pipe.h"
11#include "audio_core/null_sink.h"
12#include "audio_core/sink.h"
13#include "audio_core/sink_details.h"
14#include "common/common_types.h"
15#include "core/core_timing.h"
16#include "core/hle/service/dsp_dsp.h"
17
18namespace AudioCore {
19
20// Audio Ticks occur about every 5 miliseconds.
21static CoreTiming::EventType* tick_event; ///< CoreTiming event
22static constexpr u64 audio_frame_ticks = 1310252ull; ///< Units: ARM11 cycles
23
24static void AudioTickCallback(u64 /*userdata*/, int cycles_late) {
25 if (DSP::HLE::Tick()) {
26 // TODO(merry): Signal all the other interrupts as appropriate.
27 Service::DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Audio);
28 // HACK(merry): Added to prevent regressions. Will remove soon.
29 Service::DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Binary);
30 }
31
32 // Reschedule recurrent event
33 CoreTiming::ScheduleEvent(audio_frame_ticks - cycles_late, tick_event);
34}
35
36void Init() {
37 DSP::HLE::Init();
38
39 tick_event = CoreTiming::RegisterEvent("AudioCore::tick_event", AudioTickCallback);
40 CoreTiming::ScheduleEvent(audio_frame_ticks, tick_event);
41}
42
43std::array<u8, Memory::DSP_RAM_SIZE>& GetDspMemory() {
44 return DSP::HLE::g_dsp_memory.raw_memory;
45}
46
47void SelectSink(std::string sink_id) {
48 const SinkDetails& sink_details = GetSinkDetails(sink_id);
49 DSP::HLE::SetSink(sink_details.factory());
50}
51
52void EnableStretching(bool enable) {
53 DSP::HLE::EnableStretching(enable);
54}
55
56void Shutdown() {
57 CoreTiming::UnscheduleEvent(tick_event, 0);
58 DSP::HLE::Shutdown();
59}
60
61} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <string>
9#include "common/common_types.h"
10#include "core/memory.h"
11
12namespace AudioCore {
13
14constexpr int native_sample_rate = 32728; ///< 32kHz
15
16/// Initialise Audio Core
17void Init();
18
19/// Returns a reference to the array backing DSP memory
20std::array<u8, Memory::DSP_RAM_SIZE>& GetDspMemory();
21
22/// Select the sink to use based on sink id.
23void SelectSink(std::string sink_id);
24
25/// Enable/Disable stretching.
26void EnableStretching(bool enable);
27
28/// Shutdown Audio Core
29void Shutdown();
30
31} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <array>
6#include <cstddef>
7#include <cstring>
8#include <vector>
9#include "audio_core/codec.h"
10#include "common/assert.h"
11#include "common/common_types.h"
12#include "common/math_util.h"
13
14namespace Codec {
15
16StereoBuffer16 DecodeADPCM(const u8* const data, const size_t sample_count,
17 const std::array<s16, 16>& adpcm_coeff, ADPCMState& state) {
18 // GC-ADPCM with scale factor and variable coefficients.
19 // Frames are 8 bytes long containing 14 samples each.
20 // Samples are 4 bits (one nibble) long.
21
22 constexpr size_t FRAME_LEN = 8;
23 constexpr size_t SAMPLES_PER_FRAME = 14;
24 constexpr std::array<int, 16> SIGNED_NIBBLES = {
25 {0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1}};
26
27 const size_t ret_size =
28 sample_count % 2 == 0 ? sample_count : sample_count + 1; // Ensure multiple of two.
29 StereoBuffer16 ret(ret_size);
30
31 int yn1 = state.yn1, yn2 = state.yn2;
32
33 const size_t NUM_FRAMES =
34 (sample_count + (SAMPLES_PER_FRAME - 1)) / SAMPLES_PER_FRAME; // Round up.
35 for (size_t framei = 0; framei < NUM_FRAMES; framei++) {
36 const int frame_header = data[framei * FRAME_LEN];
37 const int scale = 1 << (frame_header & 0xF);
38 const int idx = (frame_header >> 4) & 0x7;
39
40 // Coefficients are fixed point with 11 bits fractional part.
41 const int coef1 = adpcm_coeff[idx * 2 + 0];
42 const int coef2 = adpcm_coeff[idx * 2 + 1];
43
44 // Decodes an audio sample. One nibble produces one sample.
45 const auto decode_sample = [&](const int nibble) -> s16 {
46 const int xn = nibble * scale;
47 // We first transform everything into 11 bit fixed point, perform the second order
48 // digital filter, then transform back.
49 // 0x400 == 0.5 in 11 bit fixed point.
50 // Filter: y[n] = x[n] + 0.5 + c1 * y[n-1] + c2 * y[n-2]
51 int val = ((xn << 11) + 0x400 + coef1 * yn1 + coef2 * yn2) >> 11;
52 // Clamp to output range.
53 val = MathUtil::Clamp(val, -32768, 32767);
54 // Advance output feedback.
55 yn2 = yn1;
56 yn1 = val;
57 return (s16)val;
58 };
59
60 size_t outputi = framei * SAMPLES_PER_FRAME;
61 size_t datai = framei * FRAME_LEN + 1;
62 for (size_t i = 0; i < SAMPLES_PER_FRAME && outputi < sample_count; i += 2) {
63 const s16 sample1 = decode_sample(SIGNED_NIBBLES[data[datai] >> 4]);
64 ret[outputi].fill(sample1);
65 outputi++;
66
67 const s16 sample2 = decode_sample(SIGNED_NIBBLES[data[datai] & 0xF]);
68 ret[outputi].fill(sample2);
69 outputi++;
70
71 datai++;
72 }
73 }
74
75 state.yn1 = yn1;
76 state.yn2 = yn2;
77
78 return ret;
79}
80
81static s16 SignExtendS8(u8 x) {
82 // The data is actually signed PCM8.
83 // We sign extend this to signed PCM16.
84 return static_cast<s16>(static_cast<s8>(x));
85}
86
87StereoBuffer16 DecodePCM8(const unsigned num_channels, const u8* const data,
88 const size_t sample_count) {
89 ASSERT(num_channels == 1 || num_channels == 2);
90
91 StereoBuffer16 ret(sample_count);
92
93 if (num_channels == 1) {
94 for (size_t i = 0; i < sample_count; i++) {
95 ret[i].fill(SignExtendS8(data[i]));
96 }
97 } else {
98 for (size_t i = 0; i < sample_count; i++) {
99 ret[i][0] = SignExtendS8(data[i * 2 + 0]);
100 ret[i][1] = SignExtendS8(data[i * 2 + 1]);
101 }
102 }
103
104 return ret;
105}
106
107StereoBuffer16 DecodePCM16(const unsigned num_channels, const u8* const data,
108 const size_t sample_count) {
109 ASSERT(num_channels == 1 || num_channels == 2);
110
111 StereoBuffer16 ret(sample_count);
112
113 if (num_channels == 1) {
114 for (size_t i = 0; i < sample_count; i++) {
115 s16 sample;
116 std::memcpy(&sample, data + i * sizeof(s16), sizeof(s16));
117 ret[i].fill(sample);
118 }
119 } else {
120 for (size_t i = 0; i < sample_count; ++i) {
121 std::memcpy(&ret[i], data + i * sizeof(s16) * 2, 2 * sizeof(s16));
122 }
123 }
124
125 return ret;
126}
127};
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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <deque>
9#include "common/common_types.h"
10
11namespace Codec {
12
13/// A variable length buffer of signed PCM16 stereo samples.
14using StereoBuffer16 = std::deque<std::array<s16, 2>>;
15
16/// See: Codec::DecodeADPCM
17struct ADPCMState {
18 // Two historical samples from previous processed buffer,
19 // required for ADPCM decoding
20 s16 yn1; ///< y[n-1]
21 s16 yn2; ///< y[n-2]
22};
23
24/**
25 * @param data Pointer to buffer that contains ADPCM data to decode
26 * @param sample_count Length of buffer in terms of number of samples
27 * @param adpcm_coeff ADPCM coefficients
28 * @param state ADPCM state, this is updated with new state
29 * @return Decoded stereo signed PCM16 data, sample_count in length
30 */
31StereoBuffer16 DecodeADPCM(const u8* const data, const size_t sample_count,
32 const std::array<s16, 16>& adpcm_coeff, ADPCMState& state);
33
34/**
35 * @param num_channels Number of channels
36 * @param data Pointer to buffer that contains PCM8 data to decode
37 * @param sample_count Length of buffer in terms of number of samples
38 * @return Decoded stereo signed PCM16 data, sample_count in length
39 */
40StereoBuffer16 DecodePCM8(const unsigned num_channels, const u8* const data,
41 const size_t sample_count);
42
43/**
44 * @param num_channels Number of channels
45 * @param data Pointer to buffer that contains PCM16 data to decode
46 * @param sample_count Length of buffer in terms of number of samples
47 * @return Decoded stereo signed PCM16 data, sample_count in length
48 */
49StereoBuffer16 DecodePCM16(const unsigned num_channels, const u8* const data,
50 const size_t sample_count);
51};
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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <algorithm>
8#include <array>
9#include "common/common_types.h"
10
11namespace DSP {
12namespace HLE {
13
14constexpr int num_sources = 24;
15constexpr int samples_per_frame = 160; ///< Samples per audio frame at native sample rate
16
17/// The final output to the speakers is stereo. Preprocessing output in Source is also stereo.
18using StereoFrame16 = std::array<std::array<s16, 2>, samples_per_frame>;
19
20/// The DSP is quadraphonic internally.
21using QuadFrame32 = std::array<std::array<s32, 4>, samples_per_frame>;
22
23/**
24 * This performs the filter operation defined by FilterT::ProcessSample on the frame in-place.
25 * FilterT::ProcessSample is called sequentially on the samples.
26 */
27template <typename FrameT, typename FilterT>
28void FilterFrame(FrameT& frame, FilterT& filter) {
29 std::transform(frame.begin(), frame.end(), frame.begin(),
30 [&filter](const auto& sample) { return filter.ProcessSample(sample); });
31}
32
33} // namespace HLE
34} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <array>
6#include <memory>
7#include "audio_core/hle/dsp.h"
8#include "audio_core/hle/mixers.h"
9#include "audio_core/hle/pipe.h"
10#include "audio_core/hle/source.h"
11#include "audio_core/sink.h"
12#include "audio_core/time_stretch.h"
13
14namespace DSP {
15namespace HLE {
16
17// Region management
18
19DspMemory g_dsp_memory;
20
21static size_t CurrentRegionIndex() {
22 // The region with the higher frame counter is chosen unless there is wraparound.
23 // This function only returns a 0 or 1.
24 u16 frame_counter_0 = g_dsp_memory.region_0.frame_counter;
25 u16 frame_counter_1 = g_dsp_memory.region_1.frame_counter;
26
27 if (frame_counter_0 == 0xFFFFu && frame_counter_1 != 0xFFFEu) {
28 // Wraparound has occurred.
29 return 1;
30 }
31
32 if (frame_counter_1 == 0xFFFFu && frame_counter_0 != 0xFFFEu) {
33 // Wraparound has occurred.
34 return 0;
35 }
36
37 return (frame_counter_0 > frame_counter_1) ? 0 : 1;
38}
39
40static SharedMemory& ReadRegion() {
41 return CurrentRegionIndex() == 0 ? g_dsp_memory.region_0 : g_dsp_memory.region_1;
42}
43
44static SharedMemory& WriteRegion() {
45 return CurrentRegionIndex() != 0 ? g_dsp_memory.region_0 : g_dsp_memory.region_1;
46}
47
48// Audio processing and mixing
49
50static std::array<Source, num_sources> sources = {
51 Source(0), Source(1), Source(2), Source(3), Source(4), Source(5), Source(6), Source(7),
52 Source(8), Source(9), Source(10), Source(11), Source(12), Source(13), Source(14), Source(15),
53 Source(16), Source(17), Source(18), Source(19), Source(20), Source(21), Source(22), Source(23),
54};
55static Mixers mixers;
56
57static StereoFrame16 GenerateCurrentFrame() {
58 SharedMemory& read = ReadRegion();
59 SharedMemory& write = WriteRegion();
60
61 std::array<QuadFrame32, 3> intermediate_mixes = {};
62
63 // Generate intermediate mixes
64 for (size_t i = 0; i < num_sources; i++) {
65 write.source_statuses.status[i] =
66 sources[i].Tick(read.source_configurations.config[i], read.adpcm_coefficients.coeff[i]);
67 for (size_t mix = 0; mix < 3; mix++) {
68 sources[i].MixInto(intermediate_mixes[mix], mix);
69 }
70 }
71
72 // Generate final mix
73 write.dsp_status = mixers.Tick(read.dsp_configuration, read.intermediate_mix_samples,
74 write.intermediate_mix_samples, intermediate_mixes);
75
76 StereoFrame16 output_frame = mixers.GetOutput();
77
78 // Write current output frame to the shared memory region
79 for (size_t samplei = 0; samplei < output_frame.size(); samplei++) {
80 for (size_t channeli = 0; channeli < output_frame[0].size(); channeli++) {
81 write.final_samples.pcm16[samplei][channeli] = s16_le(output_frame[samplei][channeli]);
82 }
83 }
84
85 return output_frame;
86}
87
88// Audio output
89
90static bool perform_time_stretching = true;
91static std::unique_ptr<AudioCore::Sink> sink;
92static AudioCore::TimeStretcher time_stretcher;
93
94static void FlushResidualStretcherAudio() {
95 time_stretcher.Flush();
96 while (true) {
97 std::vector<s16> residual_audio = time_stretcher.Process(sink->SamplesInQueue());
98 if (residual_audio.empty())
99 break;
100 sink->EnqueueSamples(residual_audio.data(), residual_audio.size() / 2);
101 }
102}
103
104static void OutputCurrentFrame(const StereoFrame16& frame) {
105 if (perform_time_stretching) {
106 time_stretcher.AddSamples(&frame[0][0], frame.size());
107 std::vector<s16> stretched_samples = time_stretcher.Process(sink->SamplesInQueue());
108 sink->EnqueueSamples(stretched_samples.data(), stretched_samples.size() / 2);
109 } else {
110 constexpr size_t maximum_sample_latency = 2048; // about 64 miliseconds
111 if (sink->SamplesInQueue() > maximum_sample_latency) {
112 // This can occur if we're running too fast and samples are starting to back up.
113 // Just drop the samples.
114 return;
115 }
116
117 sink->EnqueueSamples(&frame[0][0], frame.size());
118 }
119}
120
121void EnableStretching(bool enable) {
122 if (perform_time_stretching == enable)
123 return;
124
125 if (!enable) {
126 FlushResidualStretcherAudio();
127 }
128 perform_time_stretching = enable;
129}
130
131// Public Interface
132
133void Init() {
134 DSP::HLE::ResetPipes();
135
136 for (auto& source : sources) {
137 source.Reset();
138 }
139
140 mixers.Reset();
141
142 time_stretcher.Reset();
143 if (sink) {
144 time_stretcher.SetOutputSampleRate(sink->GetNativeSampleRate());
145 }
146}
147
148void Shutdown() {
149 if (perform_time_stretching) {
150 FlushResidualStretcherAudio();
151 }
152}
153
154bool Tick() {
155 StereoFrame16 current_frame = {};
156
157 // TODO: Check dsp::DSP semaphore (which indicates emulated application has finished writing to
158 // shared memory region)
159 current_frame = GenerateCurrentFrame();
160
161 OutputCurrentFrame(current_frame);
162
163 return true;
164}
165
166void SetSink(std::unique_ptr<AudioCore::Sink> sink_) {
167 sink = std::move(sink_);
168 time_stretcher.SetOutputSampleRate(sink->GetNativeSampleRate());
169}
170
171} // namespace HLE
172} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <cstddef>
9#include <memory>
10#include <type_traits>
11#include "audio_core/hle/common.h"
12#include "common/bit_field.h"
13#include "common/common_funcs.h"
14#include "common/common_types.h"
15#include "common/swap.h"
16
17namespace AudioCore {
18class Sink;
19}
20
21namespace DSP {
22namespace HLE {
23
24// The application-accessible region of DSP memory consists of two parts. Both are marked as IO and
25// have Read/Write permissions.
26//
27// First Region: 0x1FF50000 (Size: 0x8000)
28// Second Region: 0x1FF70000 (Size: 0x8000)
29//
30// The DSP reads from each region alternately based on the frame counter for each region much like a
31// double-buffer. The frame counter is located as the very last u16 of each region and is
32// incremented each audio tick.
33
34constexpr u32 region0_offset = 0x50000;
35constexpr u32 region1_offset = 0x70000;
36
37/**
38 * The DSP is native 16-bit. The DSP also appears to be big-endian. When reading 32-bit numbers from
39 * its memory regions, the higher and lower 16-bit halves are swapped compared to the little-endian
40 * layout of the ARM11. Hence from the ARM11's point of view the memory space appears to be
41 * middle-endian.
42 *
43 * Unusually this does not appear to be an issue for floating point numbers. The DSP makes the more
44 * sensible choice of keeping that little-endian. There are also some exceptions such as the
45 * IntermediateMixSamples structure, which is little-endian.
46 *
47 * This struct implements the conversion to and from this middle-endianness.
48 */
49struct u32_dsp {
50 u32_dsp() = default;
51 operator u32() const {
52 return Convert(storage);
53 }
54 void operator=(u32 new_value) {
55 storage = Convert(new_value);
56 }
57
58private:
59 static constexpr u32 Convert(u32 value) {
60 return (value << 16) | (value >> 16);
61 }
62 u32_le storage;
63};
64#if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER)
65static_assert(std::is_trivially_copyable<u32_dsp>::value, "u32_dsp isn't trivially copyable");
66#endif
67
68// There are 15 structures in each memory region. A table of them in the order they appear in memory
69// is presented below:
70//
71// # First Region DSP Address Purpose Control
72// 5 0x8400 DSP Status DSP
73// 9 0x8410 DSP Debug Info DSP
74// 6 0x8540 Final Mix Samples DSP
75// 2 0x8680 Source Status [24] DSP
76// 8 0x8710 Compressor Table Application
77// 4 0x9430 DSP Configuration Application
78// 7 0x9492 Intermediate Mix Samples DSP + App
79// 1 0x9E92 Source Configuration [24] Application
80// 3 0xA792 Source ADPCM Coefficients [24] Application
81// 10 0xA912 Surround Sound Related
82// 11 0xAA12 Surround Sound Related
83// 12 0xAAD2 Surround Sound Related
84// 13 0xAC52 Surround Sound Related
85// 14 0xAC5C Surround Sound Related
86// 0 0xBFFF Frame Counter Application
87//
88// #: This refers to the order in which they appear in the DspPipe::Audio DSP pipe.
89// See also: DSP::HLE::PipeRead.
90//
91// Note that the above addresses do vary slightly between audio firmwares observed; the addresses
92// are not fixed in stone. The addresses above are only an examplar; they're what this
93// implementation does and provides to applications.
94//
95// Application requests the DSP service to convert DSP addresses into ARM11 virtual addresses using
96// the ConvertProcessAddressFromDspDram service call. Applications seem to derive the addresses for
97// the second region via:
98// second_region_dsp_addr = first_region_dsp_addr | 0x10000
99//
100// Applications maintain most of its own audio state, the memory region is used mainly for
101// communication and not storage of state.
102//
103// In the documentation below, filter and effect transfer functions are specified in the z domain.
104// (If you are more familiar with the Laplace transform, z = exp(sT). The z domain is the digital
105// frequency domain, just like how the s domain is the analog frequency domain.)
106
107#define INSERT_PADDING_DSPWORDS(num_words) INSERT_PADDING_BYTES(2 * (num_words))
108
109// GCC versions < 5.0 do not implement std::is_trivially_copyable.
110// Excluding MSVC because it has weird behaviour for std::is_trivially_copyable.
111#if (__GNUC__ >= 5) || defined(__clang__)
112#define ASSERT_DSP_STRUCT(name, size) \
113 static_assert(std::is_standard_layout<name>::value, \
114 "DSP structure " #name " doesn't use standard layout"); \
115 static_assert(std::is_trivially_copyable<name>::value, \
116 "DSP structure " #name " isn't trivially copyable"); \
117 static_assert(sizeof(name) == (size), "Unexpected struct size for DSP structure " #name)
118#else
119#define ASSERT_DSP_STRUCT(name, size) \
120 static_assert(std::is_standard_layout<name>::value, \
121 "DSP structure " #name " doesn't use standard layout"); \
122 static_assert(sizeof(name) == (size), "Unexpected struct size for DSP structure " #name)
123#endif
124
125struct SourceConfiguration {
126 struct Configuration {
127 /// These dirty flags are set by the application when it updates the fields in this struct.
128 /// The DSP clears these each audio frame.
129 union {
130 u32_le dirty_raw;
131
132 BitField<0, 1, u32_le> format_dirty;
133 BitField<1, 1, u32_le> mono_or_stereo_dirty;
134 BitField<2, 1, u32_le> adpcm_coefficients_dirty;
135 /// Tends to be set when a looped buffer is queued.
136 BitField<3, 1, u32_le> partial_embedded_buffer_dirty;
137 BitField<4, 1, u32_le> partial_reset_flag;
138
139 BitField<16, 1, u32_le> enable_dirty;
140 BitField<17, 1, u32_le> interpolation_dirty;
141 BitField<18, 1, u32_le> rate_multiplier_dirty;
142 BitField<19, 1, u32_le> buffer_queue_dirty;
143 BitField<20, 1, u32_le> loop_related_dirty;
144 /// Tends to also be set when embedded buffer is updated.
145 BitField<21, 1, u32_le> play_position_dirty;
146 BitField<22, 1, u32_le> filters_enabled_dirty;
147 BitField<23, 1, u32_le> simple_filter_dirty;
148 BitField<24, 1, u32_le> biquad_filter_dirty;
149 BitField<25, 1, u32_le> gain_0_dirty;
150 BitField<26, 1, u32_le> gain_1_dirty;
151 BitField<27, 1, u32_le> gain_2_dirty;
152 BitField<28, 1, u32_le> sync_dirty;
153 BitField<29, 1, u32_le> reset_flag;
154 BitField<30, 1, u32_le> embedded_buffer_dirty;
155 };
156
157 // Gain control
158
159 /**
160 * Gain is between 0.0-1.0. This determines how much will this source appear on each of the
161 * 12 channels that feed into the intermediate mixers. Each of the three intermediate mixers
162 * is fed two left and two right channels.
163 */
164 float_le gain[3][4];
165
166 // Interpolation
167
168 /// Multiplier for sample rate. Resampling occurs with the selected interpolation method.
169 float_le rate_multiplier;
170
171 enum class InterpolationMode : u8 {
172 Polyphase = 0,
173 Linear = 1,
174 None = 2,
175 };
176
177 InterpolationMode interpolation_mode;
178 INSERT_PADDING_BYTES(1); ///< Interpolation related
179
180 // Filters
181
182 /**
183 * This is the simplest normalized first-order digital recursive filter.
184 * The transfer function of this filter is:
185 * H(z) = b0 / (1 - a1 z^-1)
186 * Note the feedbackward coefficient is negated.
187 * Values are signed fixed point with 15 fractional bits.
188 */
189 struct SimpleFilter {
190 s16_le b0;
191 s16_le a1;
192 };
193
194 /**
195 * This is a normalised biquad filter (second-order).
196 * The transfer function of this filter is:
197 * H(z) = (b0 + b1 z^-1 + b2 z^-2) / (1 - a1 z^-1 - a2 z^-2)
198 * Nintendo chose to negate the feedbackward coefficients. This differs from standard
199 * notation as in: https://ccrma.stanford.edu/~jos/filters/Direct_Form_I.html
200 * Values are signed fixed point with 14 fractional bits.
201 */
202 struct BiquadFilter {
203 s16_le a2;
204 s16_le a1;
205 s16_le b2;
206 s16_le b1;
207 s16_le b0;
208 };
209
210 union {
211 u16_le filters_enabled;
212 BitField<0, 1, u16_le> simple_filter_enabled;
213 BitField<1, 1, u16_le> biquad_filter_enabled;
214 };
215
216 SimpleFilter simple_filter;
217 BiquadFilter biquad_filter;
218
219 // Buffer Queue
220
221 /// A buffer of audio data from the application, along with metadata about it.
222 struct Buffer {
223 /// Physical memory address of the start of the buffer
224 u32_dsp physical_address;
225
226 /// This is length in terms of samples.
227 /// Note that in different buffer formats a sample takes up different number of bytes.
228 u32_dsp length;
229
230 /// ADPCM Predictor (4 bits) and Scale (4 bits)
231 union {
232 u16_le adpcm_ps;
233 BitField<0, 4, u16_le> adpcm_scale;
234 BitField<4, 4, u16_le> adpcm_predictor;
235 };
236
237 /// ADPCM Historical Samples (y[n-1] and y[n-2])
238 u16_le adpcm_yn[2];
239
240 /// This is non-zero when the ADPCM values above are to be updated.
241 u8 adpcm_dirty;
242
243 /// Is a looping buffer.
244 u8 is_looping;
245
246 /// This value is shown in SourceStatus::previous_buffer_id when this buffer has
247 /// finished. This allows the emulated application to tell what buffer is currently
248 /// playing.
249 u16_le buffer_id;
250
251 INSERT_PADDING_DSPWORDS(1);
252 };
253
254 u16_le buffers_dirty; ///< Bitmap indicating which buffers are dirty (bit i -> buffers[i])
255 Buffer buffers[4]; ///< Queued Buffers
256
257 // Playback controls
258
259 u32_dsp loop_related;
260 u8 enable;
261 INSERT_PADDING_BYTES(1);
262 u16_le sync; ///< Application-side sync (See also: SourceStatus::sync)
263 u32_dsp play_position; ///< Position. (Units: number of samples)
264 INSERT_PADDING_DSPWORDS(2);
265
266 // Embedded Buffer
267 // This buffer is often the first buffer to be used when initiating audio playback,
268 // after which the buffer queue is used.
269
270 u32_dsp physical_address;
271
272 /// This is length in terms of samples.
273 /// Note a sample takes up different number of bytes in different buffer formats.
274 u32_dsp length;
275
276 enum class MonoOrStereo : u16_le {
277 Mono = 1,
278 Stereo = 2,
279 };
280
281 enum class Format : u16_le {
282 PCM8 = 0,
283 PCM16 = 1,
284 ADPCM = 2,
285 };
286
287 union {
288 u16_le flags1_raw;
289 BitField<0, 2, MonoOrStereo> mono_or_stereo;
290 BitField<2, 2, Format> format;
291 BitField<5, 1, u16_le> fade_in;
292 };
293
294 /// ADPCM Predictor (4 bit) and Scale (4 bit)
295 union {
296 u16_le adpcm_ps;
297 BitField<0, 4, u16_le> adpcm_scale;
298 BitField<4, 4, u16_le> adpcm_predictor;
299 };
300
301 /// ADPCM Historical Samples (y[n-1] and y[n-2])
302 u16_le adpcm_yn[2];
303
304 union {
305 u16_le flags2_raw;
306 BitField<0, 1, u16_le> adpcm_dirty; ///< Has the ADPCM info above been changed?
307 BitField<1, 1, u16_le> is_looping; ///< Is this a looping buffer?
308 };
309
310 /// Buffer id of embedded buffer (used as a buffer id in SourceStatus to reference this
311 /// buffer).
312 u16_le buffer_id;
313 };
314
315 Configuration config[num_sources];
316};
317ASSERT_DSP_STRUCT(SourceConfiguration::Configuration, 192);
318ASSERT_DSP_STRUCT(SourceConfiguration::Configuration::Buffer, 20);
319
320struct SourceStatus {
321 struct Status {
322 u8 is_enabled; ///< Is this channel enabled? (Doesn't have to be playing anything.)
323 u8 current_buffer_id_dirty; ///< Non-zero when current_buffer_id changes
324 u16_le sync; ///< Is set by the DSP to the value of SourceConfiguration::sync
325 u32_dsp buffer_position; ///< Number of samples into the current buffer
326 u16_le current_buffer_id; ///< Updated when a buffer finishes playing
327 INSERT_PADDING_DSPWORDS(1);
328 };
329
330 Status status[num_sources];
331};
332ASSERT_DSP_STRUCT(SourceStatus::Status, 12);
333
334struct DspConfiguration {
335 /// These dirty flags are set by the application when it updates the fields in this struct.
336 /// The DSP clears these each audio frame.
337 union {
338 u32_le dirty_raw;
339
340 BitField<8, 1, u32_le> mixer1_enabled_dirty;
341 BitField<9, 1, u32_le> mixer2_enabled_dirty;
342 BitField<10, 1, u32_le> delay_effect_0_dirty;
343 BitField<11, 1, u32_le> delay_effect_1_dirty;
344 BitField<12, 1, u32_le> reverb_effect_0_dirty;
345 BitField<13, 1, u32_le> reverb_effect_1_dirty;
346
347 BitField<16, 1, u32_le> volume_0_dirty;
348
349 BitField<24, 1, u32_le> volume_1_dirty;
350 BitField<25, 1, u32_le> volume_2_dirty;
351 BitField<26, 1, u32_le> output_format_dirty;
352 BitField<27, 1, u32_le> limiter_enabled_dirty;
353 BitField<28, 1, u32_le> headphones_connected_dirty;
354 };
355
356 /// The DSP has three intermediate audio mixers. This controls the volume level (0.0-1.0) for
357 /// each at the final mixer.
358 float_le volume[3];
359
360 INSERT_PADDING_DSPWORDS(3);
361
362 enum class OutputFormat : u16_le {
363 Mono = 0,
364 Stereo = 1,
365 Surround = 2,
366 };
367
368 OutputFormat output_format;
369
370 u16_le limiter_enabled; ///< Not sure of the exact gain equation for the limiter.
371 u16_le headphones_connected; ///< Application updates the DSP on headphone status.
372 INSERT_PADDING_DSPWORDS(4); ///< TODO: Surround sound related
373 INSERT_PADDING_DSPWORDS(2); ///< TODO: Intermediate mixer 1/2 related
374 u16_le mixer1_enabled;
375 u16_le mixer2_enabled;
376
377 /**
378 * This is delay with feedback.
379 * Transfer function:
380 * H(z) = a z^-N / (1 - b z^-1 + a g z^-N)
381 * where
382 * N = frame_count * samples_per_frame
383 * g, a and b are fixed point with 7 fractional bits
384 */
385 struct DelayEffect {
386 /// These dirty flags are set by the application when it updates the fields in this struct.
387 /// The DSP clears these each audio frame.
388 union {
389 u16_le dirty_raw;
390 BitField<0, 1, u16_le> enable_dirty;
391 BitField<1, 1, u16_le> work_buffer_address_dirty;
392 BitField<2, 1, u16_le> other_dirty; ///< Set when anything else has been changed
393 };
394
395 u16_le enable;
396 INSERT_PADDING_DSPWORDS(1);
397 u16_le outputs;
398 /// The application allocates a block of memory for the DSP to use as a work buffer.
399 u32_dsp work_buffer_address;
400 /// Frames to delay by
401 u16_le frame_count;
402
403 // Coefficients
404 s16_le g; ///< Fixed point with 7 fractional bits
405 s16_le a; ///< Fixed point with 7 fractional bits
406 s16_le b; ///< Fixed point with 7 fractional bits
407 };
408
409 DelayEffect delay_effect[2];
410
411 struct ReverbEffect {
412 INSERT_PADDING_DSPWORDS(26); ///< TODO
413 };
414
415 ReverbEffect reverb_effect[2];
416
417 INSERT_PADDING_DSPWORDS(4);
418};
419ASSERT_DSP_STRUCT(DspConfiguration, 196);
420ASSERT_DSP_STRUCT(DspConfiguration::DelayEffect, 20);
421ASSERT_DSP_STRUCT(DspConfiguration::ReverbEffect, 52);
422
423struct AdpcmCoefficients {
424 /// Coefficients are signed fixed point with 11 fractional bits.
425 /// Each source has 16 coefficients associated with it.
426 s16_le coeff[num_sources][16];
427};
428ASSERT_DSP_STRUCT(AdpcmCoefficients, 768);
429
430struct DspStatus {
431 u16_le unknown;
432 u16_le dropped_frames;
433 INSERT_PADDING_DSPWORDS(0xE);
434};
435ASSERT_DSP_STRUCT(DspStatus, 32);
436
437/// Final mixed output in PCM16 stereo format, what you hear out of the speakers.
438/// When the application writes to this region it has no effect.
439struct FinalMixSamples {
440 s16_le pcm16[samples_per_frame][2];
441};
442ASSERT_DSP_STRUCT(FinalMixSamples, 640);
443
444/// DSP writes output of intermediate mixers 1 and 2 here.
445/// Writes to this region by the application edits the output of the intermediate mixers.
446/// This seems to be intended to allow the application to do custom effects on the ARM11.
447/// Values that exceed s16 range will be clipped by the DSP after further processing.
448struct IntermediateMixSamples {
449 struct Samples {
450 s32_le pcm32[4][samples_per_frame]; ///< Little-endian as opposed to DSP middle-endian.
451 };
452
453 Samples mix1;
454 Samples mix2;
455};
456ASSERT_DSP_STRUCT(IntermediateMixSamples, 5120);
457
458/// Compressor table
459struct Compressor {
460 INSERT_PADDING_DSPWORDS(0xD20); ///< TODO
461};
462
463/// There is no easy way to implement this in a HLE implementation.
464struct DspDebug {
465 INSERT_PADDING_DSPWORDS(0x130);
466};
467ASSERT_DSP_STRUCT(DspDebug, 0x260);
468
469struct SharedMemory {
470 /// Padding
471 INSERT_PADDING_DSPWORDS(0x400);
472
473 DspStatus dsp_status;
474
475 DspDebug dsp_debug;
476
477 FinalMixSamples final_samples;
478
479 SourceStatus source_statuses;
480
481 Compressor compressor;
482
483 DspConfiguration dsp_configuration;
484
485 IntermediateMixSamples intermediate_mix_samples;
486
487 SourceConfiguration source_configurations;
488
489 AdpcmCoefficients adpcm_coefficients;
490
491 struct {
492 INSERT_PADDING_DSPWORDS(0x100);
493 } unknown10;
494
495 struct {
496 INSERT_PADDING_DSPWORDS(0xC0);
497 } unknown11;
498
499 struct {
500 INSERT_PADDING_DSPWORDS(0x180);
501 } unknown12;
502
503 struct {
504 INSERT_PADDING_DSPWORDS(0xA);
505 } unknown13;
506
507 struct {
508 INSERT_PADDING_DSPWORDS(0x13A3);
509 } unknown14;
510
511 u16_le frame_counter;
512};
513ASSERT_DSP_STRUCT(SharedMemory, 0x8000);
514
515union DspMemory {
516 std::array<u8, 0x80000> raw_memory;
517 struct {
518 u8 unused_0[0x50000];
519 SharedMemory region_0;
520 u8 unused_1[0x18000];
521 SharedMemory region_1;
522 u8 unused_2[0x8000];
523 };
524};
525static_assert(offsetof(DspMemory, region_0) == region0_offset,
526 "DSP region 0 is at the wrong offset");
527static_assert(offsetof(DspMemory, region_1) == region1_offset,
528 "DSP region 1 is at the wrong offset");
529
530extern DspMemory g_dsp_memory;
531
532// Structures must have an offset that is a multiple of two.
533static_assert(offsetof(SharedMemory, frame_counter) % 2 == 0,
534 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
535static_assert(offsetof(SharedMemory, source_configurations) % 2 == 0,
536 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
537static_assert(offsetof(SharedMemory, source_statuses) % 2 == 0,
538 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
539static_assert(offsetof(SharedMemory, adpcm_coefficients) % 2 == 0,
540 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
541static_assert(offsetof(SharedMemory, dsp_configuration) % 2 == 0,
542 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
543static_assert(offsetof(SharedMemory, dsp_status) % 2 == 0,
544 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
545static_assert(offsetof(SharedMemory, final_samples) % 2 == 0,
546 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
547static_assert(offsetof(SharedMemory, intermediate_mix_samples) % 2 == 0,
548 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
549static_assert(offsetof(SharedMemory, compressor) % 2 == 0,
550 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
551static_assert(offsetof(SharedMemory, dsp_debug) % 2 == 0,
552 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
553static_assert(offsetof(SharedMemory, unknown10) % 2 == 0,
554 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
555static_assert(offsetof(SharedMemory, unknown11) % 2 == 0,
556 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
557static_assert(offsetof(SharedMemory, unknown12) % 2 == 0,
558 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
559static_assert(offsetof(SharedMemory, unknown13) % 2 == 0,
560 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
561static_assert(offsetof(SharedMemory, unknown14) % 2 == 0,
562 "Structures in DSP::HLE::SharedMemory must be 2-byte aligned");
563
564#undef INSERT_PADDING_DSPWORDS
565#undef ASSERT_DSP_STRUCT
566
567/// Initialize DSP hardware
568void Init();
569
570/// Shutdown DSP hardware
571void Shutdown();
572
573/**
574 * Perform processing and updates state of current shared memory buffer.
575 * This function is called every audio tick before triggering the audio interrupt.
576 * @return Whether an audio interrupt should be triggered this frame.
577 */
578bool Tick();
579
580/**
581 * Set the output sink. This must be called before calling Tick().
582 * @param sink The sink to which audio will be output to.
583 */
584void SetSink(std::unique_ptr<AudioCore::Sink> sink);
585
586/**
587 * Enables/Disables audio-stretching.
588 * Audio stretching is an enhancement that stretches audio to match emulation
589 * speed to prevent stuttering at the cost of some audio latency.
590 * @param enable true to enable, false to disable.
591 */
592void EnableStretching(bool enable);
593
594} // namespace HLE
595} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <array>
6#include <cstddef>
7#include "audio_core/hle/common.h"
8#include "audio_core/hle/dsp.h"
9#include "audio_core/hle/filter.h"
10#include "common/common_types.h"
11#include "common/math_util.h"
12
13namespace DSP {
14namespace HLE {
15
16void SourceFilters::Reset() {
17 Enable(false, false);
18}
19
20void SourceFilters::Enable(bool simple, bool biquad) {
21 simple_filter_enabled = simple;
22 biquad_filter_enabled = biquad;
23
24 if (!simple)
25 simple_filter.Reset();
26 if (!biquad)
27 biquad_filter.Reset();
28}
29
30void SourceFilters::Configure(SourceConfiguration::Configuration::SimpleFilter config) {
31 simple_filter.Configure(config);
32}
33
34void SourceFilters::Configure(SourceConfiguration::Configuration::BiquadFilter config) {
35 biquad_filter.Configure(config);
36}
37
38void SourceFilters::ProcessFrame(StereoFrame16& frame) {
39 if (!simple_filter_enabled && !biquad_filter_enabled)
40 return;
41
42 if (simple_filter_enabled) {
43 FilterFrame(frame, simple_filter);
44 }
45
46 if (biquad_filter_enabled) {
47 FilterFrame(frame, biquad_filter);
48 }
49}
50
51// SimpleFilter
52
53void SourceFilters::SimpleFilter::Reset() {
54 y1.fill(0);
55 // Configure as passthrough.
56 a1 = 0;
57 b0 = 1 << 15;
58}
59
60void SourceFilters::SimpleFilter::Configure(
61 SourceConfiguration::Configuration::SimpleFilter config) {
62
63 a1 = config.a1;
64 b0 = config.b0;
65}
66
67std::array<s16, 2> SourceFilters::SimpleFilter::ProcessSample(const std::array<s16, 2>& x0) {
68 std::array<s16, 2> y0;
69 for (size_t i = 0; i < 2; i++) {
70 const s32 tmp = (b0 * x0[i] + a1 * y1[i]) >> 15;
71 y0[i] = MathUtil::Clamp(tmp, -32768, 32767);
72 }
73
74 y1 = y0;
75
76 return y0;
77}
78
79// BiquadFilter
80
81void SourceFilters::BiquadFilter::Reset() {
82 x1.fill(0);
83 x2.fill(0);
84 y1.fill(0);
85 y2.fill(0);
86 // Configure as passthrough.
87 a1 = a2 = b1 = b2 = 0;
88 b0 = 1 << 14;
89}
90
91void SourceFilters::BiquadFilter::Configure(
92 SourceConfiguration::Configuration::BiquadFilter config) {
93
94 a1 = config.a1;
95 a2 = config.a2;
96 b0 = config.b0;
97 b1 = config.b1;
98 b2 = config.b2;
99}
100
101std::array<s16, 2> SourceFilters::BiquadFilter::ProcessSample(const std::array<s16, 2>& x0) {
102 std::array<s16, 2> y0;
103 for (size_t i = 0; i < 2; i++) {
104 const s32 tmp = (b0 * x0[i] + b1 * x1[i] + b2 * x2[i] + a1 * y1[i] + a2 * y2[i]) >> 14;
105 y0[i] = MathUtil::Clamp(tmp, -32768, 32767);
106 }
107
108 x2 = x1;
109 x1 = x0;
110 y2 = y1;
111 y1 = y0;
112
113 return y0;
114}
115
116} // namespace HLE
117} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include "audio_core/hle/common.h"
9#include "audio_core/hle/dsp.h"
10#include "common/common_types.h"
11
12namespace DSP {
13namespace HLE {
14
15/// Preprocessing filters. There is an independent set of filters for each Source.
16class SourceFilters final {
17public:
18 SourceFilters() {
19 Reset();
20 }
21
22 /// Reset internal state.
23 void Reset();
24
25 /**
26 * Enable/Disable filters
27 * See also: SourceConfiguration::Configuration::simple_filter_enabled,
28 * SourceConfiguration::Configuration::biquad_filter_enabled.
29 * @param simple If true, enables the simple filter. If false, disables it.
30 * @param biquad If true, enables the biquad filter. If false, disables it.
31 */
32 void Enable(bool simple, bool biquad);
33
34 /**
35 * Configure simple filter.
36 * @param config Configuration from DSP shared memory.
37 */
38 void Configure(SourceConfiguration::Configuration::SimpleFilter config);
39
40 /**
41 * Configure biquad filter.
42 * @param config Configuration from DSP shared memory.
43 */
44 void Configure(SourceConfiguration::Configuration::BiquadFilter config);
45
46 /**
47 * Processes a frame in-place.
48 * @param frame Audio samples to process. Modified in-place.
49 */
50 void ProcessFrame(StereoFrame16& frame);
51
52private:
53 bool simple_filter_enabled;
54 bool biquad_filter_enabled;
55
56 struct SimpleFilter {
57 SimpleFilter() {
58 Reset();
59 }
60
61 /// Resets internal state.
62 void Reset();
63
64 /**
65 * Configures this filter with application settings.
66 * @param config Configuration from DSP shared memory.
67 */
68 void Configure(SourceConfiguration::Configuration::SimpleFilter config);
69
70 /**
71 * Processes a single stereo PCM16 sample.
72 * @param x0 Input sample
73 * @return Output sample
74 */
75 std::array<s16, 2> ProcessSample(const std::array<s16, 2>& x0);
76
77 private:
78 // Configuration
79 s32 a1, b0;
80 // Internal state
81 std::array<s16, 2> y1;
82 } simple_filter;
83
84 struct BiquadFilter {
85 BiquadFilter() {
86 Reset();
87 }
88
89 /// Resets internal state.
90 void Reset();
91
92 /**
93 * Configures this filter with application settings.
94 * @param config Configuration from DSP shared memory.
95 */
96 void Configure(SourceConfiguration::Configuration::BiquadFilter config);
97
98 /**
99 * Processes a single stereo PCM16 sample.
100 * @param x0 Input sample
101 * @return Output sample
102 */
103 std::array<s16, 2> ProcessSample(const std::array<s16, 2>& x0);
104
105 private:
106 // Configuration
107 s32 a1, a2, b0, b1, b2;
108 // Internal state
109 std::array<s16, 2> x1;
110 std::array<s16, 2> x2;
111 std::array<s16, 2> y1;
112 std::array<s16, 2> y2;
113 } biquad_filter;
114};
115
116} // namespace HLE
117} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <cstddef>
6
7#include "audio_core/hle/common.h"
8#include "audio_core/hle/dsp.h"
9#include "audio_core/hle/mixers.h"
10#include "common/assert.h"
11#include "common/logging/log.h"
12#include "common/math_util.h"
13
14namespace DSP {
15namespace HLE {
16
17void Mixers::Reset() {
18 current_frame.fill({});
19 state = {};
20}
21
22DspStatus Mixers::Tick(DspConfiguration& config, const IntermediateMixSamples& read_samples,
23 IntermediateMixSamples& write_samples,
24 const std::array<QuadFrame32, 3>& input) {
25 ParseConfig(config);
26
27 AuxReturn(read_samples);
28 AuxSend(write_samples, input);
29
30 MixCurrentFrame();
31
32 return GetCurrentStatus();
33}
34
35void Mixers::ParseConfig(DspConfiguration& config) {
36 if (!config.dirty_raw) {
37 return;
38 }
39
40 if (config.mixer1_enabled_dirty) {
41 config.mixer1_enabled_dirty.Assign(0);
42 state.mixer1_enabled = config.mixer1_enabled != 0;
43 LOG_TRACE(Audio_DSP, "mixers mixer1_enabled = %hu", config.mixer1_enabled);
44 }
45
46 if (config.mixer2_enabled_dirty) {
47 config.mixer2_enabled_dirty.Assign(0);
48 state.mixer2_enabled = config.mixer2_enabled != 0;
49 LOG_TRACE(Audio_DSP, "mixers mixer2_enabled = %hu", config.mixer2_enabled);
50 }
51
52 if (config.volume_0_dirty) {
53 config.volume_0_dirty.Assign(0);
54 state.intermediate_mixer_volume[0] = config.volume[0];
55 LOG_TRACE(Audio_DSP, "mixers volume[0] = %f", config.volume[0]);
56 }
57
58 if (config.volume_1_dirty) {
59 config.volume_1_dirty.Assign(0);
60 state.intermediate_mixer_volume[1] = config.volume[1];
61 LOG_TRACE(Audio_DSP, "mixers volume[1] = %f", config.volume[1]);
62 }
63
64 if (config.volume_2_dirty) {
65 config.volume_2_dirty.Assign(0);
66 state.intermediate_mixer_volume[2] = config.volume[2];
67 LOG_TRACE(Audio_DSP, "mixers volume[2] = %f", config.volume[2]);
68 }
69
70 if (config.output_format_dirty) {
71 config.output_format_dirty.Assign(0);
72 state.output_format = config.output_format;
73 LOG_TRACE(Audio_DSP, "mixers output_format = %zu",
74 static_cast<size_t>(config.output_format));
75 }
76
77 if (config.headphones_connected_dirty) {
78 config.headphones_connected_dirty.Assign(0);
79 // Do nothing. (Note: Whether headphones are connected does affect coefficients used for
80 // surround sound.)
81 LOG_TRACE(Audio_DSP, "mixers headphones_connected=%hu", config.headphones_connected);
82 }
83
84 if (config.dirty_raw) {
85 LOG_DEBUG(Audio_DSP, "mixers remaining_dirty=%x", config.dirty_raw);
86 }
87
88 config.dirty_raw = 0;
89}
90
91static s16 ClampToS16(s32 value) {
92 return static_cast<s16>(MathUtil::Clamp(value, -32768, 32767));
93}
94
95static std::array<s16, 2> AddAndClampToS16(const std::array<s16, 2>& a,
96 const std::array<s16, 2>& b) {
97 return {ClampToS16(static_cast<s32>(a[0]) + static_cast<s32>(b[0])),
98 ClampToS16(static_cast<s32>(a[1]) + static_cast<s32>(b[1]))};
99}
100
101void Mixers::DownmixAndMixIntoCurrentFrame(float gain, const QuadFrame32& samples) {
102 // TODO(merry): Limiter. (Currently we're performing final mixing assuming a disabled limiter.)
103
104 switch (state.output_format) {
105 case OutputFormat::Mono:
106 std::transform(
107 current_frame.begin(), current_frame.end(), samples.begin(), current_frame.begin(),
108 [gain](const std::array<s16, 2>& accumulator,
109 const std::array<s32, 4>& sample) -> std::array<s16, 2> {
110 // Downmix to mono
111 s16 mono = ClampToS16(static_cast<s32>(
112 (gain * sample[0] + gain * sample[1] + gain * sample[2] + gain * sample[3]) /
113 2));
114 // Mix into current frame
115 return AddAndClampToS16(accumulator, {mono, mono});
116 });
117 return;
118
119 case OutputFormat::Surround:
120 // TODO(merry): Implement surround sound.
121 // fallthrough
122
123 case OutputFormat::Stereo:
124 std::transform(
125 current_frame.begin(), current_frame.end(), samples.begin(), current_frame.begin(),
126 [gain](const std::array<s16, 2>& accumulator,
127 const std::array<s32, 4>& sample) -> std::array<s16, 2> {
128 // Downmix to stereo
129 s16 left = ClampToS16(static_cast<s32>(gain * sample[0] + gain * sample[2]));
130 s16 right = ClampToS16(static_cast<s32>(gain * sample[1] + gain * sample[3]));
131 // Mix into current frame
132 return AddAndClampToS16(accumulator, {left, right});
133 });
134 return;
135 }
136
137 UNREACHABLE_MSG("Invalid output_format %zu", static_cast<size_t>(state.output_format));
138}
139
140void Mixers::AuxReturn(const IntermediateMixSamples& read_samples) {
141 // NOTE: read_samples.mix{1,2}.pcm32 annoyingly have their dimensions in reverse order to
142 // QuadFrame32.
143
144 if (state.mixer1_enabled) {
145 for (size_t sample = 0; sample < samples_per_frame; sample++) {
146 for (size_t channel = 0; channel < 4; channel++) {
147 state.intermediate_mix_buffer[1][sample][channel] =
148 read_samples.mix1.pcm32[channel][sample];
149 }
150 }
151 }
152
153 if (state.mixer2_enabled) {
154 for (size_t sample = 0; sample < samples_per_frame; sample++) {
155 for (size_t channel = 0; channel < 4; channel++) {
156 state.intermediate_mix_buffer[2][sample][channel] =
157 read_samples.mix2.pcm32[channel][sample];
158 }
159 }
160 }
161}
162
163void Mixers::AuxSend(IntermediateMixSamples& write_samples,
164 const std::array<QuadFrame32, 3>& input) {
165 // NOTE: read_samples.mix{1,2}.pcm32 annoyingly have their dimensions in reverse order to
166 // QuadFrame32.
167
168 state.intermediate_mix_buffer[0] = input[0];
169
170 if (state.mixer1_enabled) {
171 for (size_t sample = 0; sample < samples_per_frame; sample++) {
172 for (size_t channel = 0; channel < 4; channel++) {
173 write_samples.mix1.pcm32[channel][sample] = input[1][sample][channel];
174 }
175 }
176 } else {
177 state.intermediate_mix_buffer[1] = input[1];
178 }
179
180 if (state.mixer2_enabled) {
181 for (size_t sample = 0; sample < samples_per_frame; sample++) {
182 for (size_t channel = 0; channel < 4; channel++) {
183 write_samples.mix2.pcm32[channel][sample] = input[2][sample][channel];
184 }
185 }
186 } else {
187 state.intermediate_mix_buffer[2] = input[2];
188 }
189}
190
191void Mixers::MixCurrentFrame() {
192 current_frame.fill({});
193
194 for (size_t mix = 0; mix < 3; mix++) {
195 DownmixAndMixIntoCurrentFrame(state.intermediate_mixer_volume[mix],
196 state.intermediate_mix_buffer[mix]);
197 }
198
199 // TODO(merry): Compressor. (We currently assume a disabled compressor.)
200}
201
202DspStatus Mixers::GetCurrentStatus() const {
203 DspStatus status;
204 status.unknown = 0;
205 status.dropped_frames = 0;
206 return status;
207}
208
209} // namespace HLE
210} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include "audio_core/hle/common.h"
9#include "audio_core/hle/dsp.h"
10
11namespace DSP {
12namespace HLE {
13
14class Mixers final {
15public:
16 Mixers() {
17 Reset();
18 }
19
20 void Reset();
21
22 DspStatus Tick(DspConfiguration& config, const IntermediateMixSamples& read_samples,
23 IntermediateMixSamples& write_samples, const std::array<QuadFrame32, 3>& input);
24
25 StereoFrame16 GetOutput() const {
26 return current_frame;
27 }
28
29private:
30 StereoFrame16 current_frame = {};
31
32 using OutputFormat = DspConfiguration::OutputFormat;
33
34 struct {
35 std::array<float, 3> intermediate_mixer_volume = {};
36
37 bool mixer1_enabled = false;
38 bool mixer2_enabled = false;
39 std::array<QuadFrame32, 3> intermediate_mix_buffer = {};
40
41 OutputFormat output_format = OutputFormat::Stereo;
42
43 } state;
44
45 /// INTERNAL: Update our internal state based on the current config.
46 void ParseConfig(DspConfiguration& config);
47 /// INTERNAL: Read samples from shared memory that have been modified by the ARM11.
48 void AuxReturn(const IntermediateMixSamples& read_samples);
49 /// INTERNAL: Write samples to shared memory for the ARM11 to modify.
50 void AuxSend(IntermediateMixSamples& write_samples, const std::array<QuadFrame32, 3>& input);
51 /// INTERNAL: Mix current_frame.
52 void MixCurrentFrame();
53 /// INTERNAL: Downmix from quadraphonic to stereo based on status.output_format and accumulate
54 /// into current_frame.
55 void DownmixAndMixIntoCurrentFrame(float gain, const QuadFrame32& samples);
56 /// INTERNAL: Generate DspStatus based on internal state.
57 DspStatus GetCurrentStatus() const;
58};
59
60} // namespace HLE
61} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <array>
6#include <vector>
7#include "audio_core/hle/dsp.h"
8#include "audio_core/hle/pipe.h"
9#include "common/assert.h"
10#include "common/common_types.h"
11#include "common/logging/log.h"
12#include "core/hle/service/dsp_dsp.h"
13
14namespace DSP {
15namespace HLE {
16
17static DspState dsp_state = DspState::Off;
18
19static std::array<std::vector<u8>, NUM_DSP_PIPE> pipe_data;
20
21void ResetPipes() {
22 for (auto& data : pipe_data) {
23 data.clear();
24 }
25 dsp_state = DspState::Off;
26}
27
28std::vector<u8> PipeRead(DspPipe pipe_number, u32 length) {
29 const size_t pipe_index = static_cast<size_t>(pipe_number);
30
31 if (pipe_index >= NUM_DSP_PIPE) {
32 LOG_ERROR(Audio_DSP, "pipe_number = %zu invalid", pipe_index);
33 return {};
34 }
35
36 if (length > UINT16_MAX) { // Can only read at most UINT16_MAX from the pipe
37 LOG_ERROR(Audio_DSP, "length of %u greater than max of %u", length, UINT16_MAX);
38 return {};
39 }
40
41 std::vector<u8>& data = pipe_data[pipe_index];
42
43 if (length > data.size()) {
44 LOG_WARNING(
45 Audio_DSP,
46 "pipe_number = %zu is out of data, application requested read of %u but %zu remain",
47 pipe_index, length, data.size());
48 length = static_cast<u32>(data.size());
49 }
50
51 if (length == 0)
52 return {};
53
54 std::vector<u8> ret(data.begin(), data.begin() + length);
55 data.erase(data.begin(), data.begin() + length);
56 return ret;
57}
58
59size_t GetPipeReadableSize(DspPipe pipe_number) {
60 const size_t pipe_index = static_cast<size_t>(pipe_number);
61
62 if (pipe_index >= NUM_DSP_PIPE) {
63 LOG_ERROR(Audio_DSP, "pipe_number = %zu invalid", pipe_index);
64 return 0;
65 }
66
67 return pipe_data[pipe_index].size();
68}
69
70static void WriteU16(DspPipe pipe_number, u16 value) {
71 const size_t pipe_index = static_cast<size_t>(pipe_number);
72
73 std::vector<u8>& data = pipe_data.at(pipe_index);
74 // Little endian
75 data.emplace_back(value & 0xFF);
76 data.emplace_back(value >> 8);
77}
78
79static void AudioPipeWriteStructAddresses() {
80 // These struct addresses are DSP dram addresses.
81 // See also: DSP_DSP::ConvertProcessAddressFromDspDram
82 static const std::array<u16, 15> struct_addresses = {
83 0x8000 + offsetof(SharedMemory, frame_counter) / 2,
84 0x8000 + offsetof(SharedMemory, source_configurations) / 2,
85 0x8000 + offsetof(SharedMemory, source_statuses) / 2,
86 0x8000 + offsetof(SharedMemory, adpcm_coefficients) / 2,
87 0x8000 + offsetof(SharedMemory, dsp_configuration) / 2,
88 0x8000 + offsetof(SharedMemory, dsp_status) / 2,
89 0x8000 + offsetof(SharedMemory, final_samples) / 2,
90 0x8000 + offsetof(SharedMemory, intermediate_mix_samples) / 2,
91 0x8000 + offsetof(SharedMemory, compressor) / 2,
92 0x8000 + offsetof(SharedMemory, dsp_debug) / 2,
93 0x8000 + offsetof(SharedMemory, unknown10) / 2,
94 0x8000 + offsetof(SharedMemory, unknown11) / 2,
95 0x8000 + offsetof(SharedMemory, unknown12) / 2,
96 0x8000 + offsetof(SharedMemory, unknown13) / 2,
97 0x8000 + offsetof(SharedMemory, unknown14) / 2,
98 };
99
100 // Begin with a u16 denoting the number of structs.
101 WriteU16(DspPipe::Audio, static_cast<u16>(struct_addresses.size()));
102 // Then write the struct addresses.
103 for (u16 addr : struct_addresses) {
104 WriteU16(DspPipe::Audio, addr);
105 }
106 // Signal that we have data on this pipe.
107 Service::DSP_DSP::SignalPipeInterrupt(DspPipe::Audio);
108}
109
110void PipeWrite(DspPipe pipe_number, const std::vector<u8>& buffer) {
111 switch (pipe_number) {
112 case DspPipe::Audio: {
113 if (buffer.size() != 4) {
114 LOG_ERROR(Audio_DSP, "DspPipe::Audio: Unexpected buffer length %zu was written",
115 buffer.size());
116 return;
117 }
118
119 enum class StateChange {
120 Initialize = 0,
121 Shutdown = 1,
122 Wakeup = 2,
123 Sleep = 3,
124 };
125
126 // The difference between Initialize and Wakeup is that Input state is maintained
127 // when sleeping but isn't when turning it off and on again. (TODO: Implement this.)
128 // Waking up from sleep garbles some of the structs in the memory region. (TODO:
129 // Implement this.) Applications store away the state of these structs before
130 // sleeping and reset it back after wakeup on behalf of the DSP.
131
132 switch (static_cast<StateChange>(buffer[0])) {
133 case StateChange::Initialize:
134 LOG_INFO(Audio_DSP, "Application has requested initialization of DSP hardware");
135 ResetPipes();
136 AudioPipeWriteStructAddresses();
137 dsp_state = DspState::On;
138 break;
139 case StateChange::Shutdown:
140 LOG_INFO(Audio_DSP, "Application has requested shutdown of DSP hardware");
141 dsp_state = DspState::Off;
142 break;
143 case StateChange::Wakeup:
144 LOG_INFO(Audio_DSP, "Application has requested wakeup of DSP hardware");
145 ResetPipes();
146 AudioPipeWriteStructAddresses();
147 dsp_state = DspState::On;
148 break;
149 case StateChange::Sleep:
150 LOG_INFO(Audio_DSP, "Application has requested sleep of DSP hardware");
151 UNIMPLEMENTED();
152 dsp_state = DspState::Sleeping;
153 break;
154 default:
155 LOG_ERROR(Audio_DSP,
156 "Application has requested unknown state transition of DSP hardware %hhu",
157 buffer[0]);
158 dsp_state = DspState::Off;
159 break;
160 }
161
162 return;
163 }
164 default:
165 LOG_CRITICAL(Audio_DSP, "pipe_number = %zu unimplemented",
166 static_cast<size_t>(pipe_number));
167 UNIMPLEMENTED();
168 return;
169 }
170}
171
172DspState GetDspState() {
173 return dsp_state;
174}
175
176} // namespace HLE
177} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <cstddef>
8#include <vector>
9#include "common/common_types.h"
10
11namespace DSP {
12namespace HLE {
13
14/// Reset the pipes by setting pipe positions back to the beginning.
15void ResetPipes();
16
17enum class DspPipe {
18 Debug = 0,
19 Dma = 1,
20 Audio = 2,
21 Binary = 3,
22};
23constexpr size_t NUM_DSP_PIPE = 8;
24
25/**
26 * Reads `length` bytes from the DSP pipe identified with `pipe_number`.
27 * @note Can read up to the maximum value of a u16 in bytes (65,535).
28 * @note IF an error is encoutered with either an invalid `pipe_number` or `length` value, an empty
29 * vector will be returned.
30 * @note IF `length` is set to 0, an empty vector will be returned.
31 * @note IF `length` is greater than the amount of data available, this function will only read the
32 * available amount.
33 * @param pipe_number a `DspPipe`
34 * @param length the number of bytes to read. The max is 65,535 (max of u16).
35 * @returns a vector of bytes from the specified pipe. On error, will be empty.
36 */
37std::vector<u8> PipeRead(DspPipe pipe_number, u32 length);
38
39/**
40 * How much data is left in pipe
41 * @param pipe_number The Pipe ID
42 * @return The amount of data remaning in the pipe. This is the maximum length PipeRead will return.
43 */
44size_t GetPipeReadableSize(DspPipe pipe_number);
45
46/**
47 * Write to a DSP pipe.
48 * @param pipe_number The Pipe ID
49 * @param buffer The data to write to the pipe.
50 */
51void PipeWrite(DspPipe pipe_number, const std::vector<u8>& buffer);
52
53enum class DspState {
54 Off,
55 On,
56 Sleeping,
57};
58
59/// Get the state of the DSP
60DspState GetDspState();
61
62} // namespace HLE
63} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <array>
7#include "audio_core/codec.h"
8#include "audio_core/hle/common.h"
9#include "audio_core/hle/source.h"
10#include "audio_core/interpolate.h"
11#include "common/assert.h"
12#include "common/logging/log.h"
13#include "core/memory.h"
14
15namespace DSP {
16namespace HLE {
17
18SourceStatus::Status Source::Tick(SourceConfiguration::Configuration& config,
19 const s16_le (&adpcm_coeffs)[16]) {
20 ParseConfig(config, adpcm_coeffs);
21
22 if (state.enabled) {
23 GenerateFrame();
24 }
25
26 return GetCurrentStatus();
27}
28
29void Source::MixInto(QuadFrame32& dest, size_t intermediate_mix_id) const {
30 if (!state.enabled)
31 return;
32
33 const std::array<float, 4>& gains = state.gain.at(intermediate_mix_id);
34 for (size_t samplei = 0; samplei < samples_per_frame; samplei++) {
35 // Conversion from stereo (current_frame) to quadraphonic (dest) occurs here.
36 dest[samplei][0] += static_cast<s32>(gains[0] * current_frame[samplei][0]);
37 dest[samplei][1] += static_cast<s32>(gains[1] * current_frame[samplei][1]);
38 dest[samplei][2] += static_cast<s32>(gains[2] * current_frame[samplei][0]);
39 dest[samplei][3] += static_cast<s32>(gains[3] * current_frame[samplei][1]);
40 }
41}
42
43void Source::Reset() {
44 current_frame.fill({});
45 state = {};
46}
47
48void Source::ParseConfig(SourceConfiguration::Configuration& config,
49 const s16_le (&adpcm_coeffs)[16]) {
50 if (!config.dirty_raw) {
51 return;
52 }
53
54 if (config.reset_flag) {
55 config.reset_flag.Assign(0);
56 Reset();
57 LOG_TRACE(Audio_DSP, "source_id=%zu reset", source_id);
58 }
59
60 if (config.partial_reset_flag) {
61 config.partial_reset_flag.Assign(0);
62 state.input_queue = std::priority_queue<Buffer, std::vector<Buffer>, BufferOrder>{};
63 LOG_TRACE(Audio_DSP, "source_id=%zu partial_reset", source_id);
64 }
65
66 if (config.enable_dirty) {
67 config.enable_dirty.Assign(0);
68 state.enabled = config.enable != 0;
69 LOG_TRACE(Audio_DSP, "source_id=%zu enable=%d", source_id, state.enabled);
70 }
71
72 if (config.sync_dirty) {
73 config.sync_dirty.Assign(0);
74 state.sync = config.sync;
75 LOG_TRACE(Audio_DSP, "source_id=%zu sync=%u", source_id, state.sync);
76 }
77
78 if (config.rate_multiplier_dirty) {
79 config.rate_multiplier_dirty.Assign(0);
80 state.rate_multiplier = config.rate_multiplier;
81 LOG_TRACE(Audio_DSP, "source_id=%zu rate=%f", source_id, state.rate_multiplier);
82
83 if (state.rate_multiplier <= 0) {
84 LOG_ERROR(Audio_DSP, "Was given an invalid rate multiplier: source_id=%zu rate=%f",
85 source_id, state.rate_multiplier);
86 state.rate_multiplier = 1.0f;
87 // Note: Actual firmware starts producing garbage if this occurs.
88 }
89 }
90
91 if (config.adpcm_coefficients_dirty) {
92 config.adpcm_coefficients_dirty.Assign(0);
93 std::transform(adpcm_coeffs, adpcm_coeffs + state.adpcm_coeffs.size(),
94 state.adpcm_coeffs.begin(),
95 [](const auto& coeff) { return static_cast<s16>(coeff); });
96 LOG_TRACE(Audio_DSP, "source_id=%zu adpcm update", source_id);
97 }
98
99 if (config.gain_0_dirty) {
100 config.gain_0_dirty.Assign(0);
101 std::transform(config.gain[0], config.gain[0] + state.gain[0].size(), state.gain[0].begin(),
102 [](const auto& coeff) { return static_cast<float>(coeff); });
103 LOG_TRACE(Audio_DSP, "source_id=%zu gain 0 update", source_id);
104 }
105
106 if (config.gain_1_dirty) {
107 config.gain_1_dirty.Assign(0);
108 std::transform(config.gain[1], config.gain[1] + state.gain[1].size(), state.gain[1].begin(),
109 [](const auto& coeff) { return static_cast<float>(coeff); });
110 LOG_TRACE(Audio_DSP, "source_id=%zu gain 1 update", source_id);
111 }
112
113 if (config.gain_2_dirty) {
114 config.gain_2_dirty.Assign(0);
115 std::transform(config.gain[2], config.gain[2] + state.gain[2].size(), state.gain[2].begin(),
116 [](const auto& coeff) { return static_cast<float>(coeff); });
117 LOG_TRACE(Audio_DSP, "source_id=%zu gain 2 update", source_id);
118 }
119
120 if (config.filters_enabled_dirty) {
121 config.filters_enabled_dirty.Assign(0);
122 state.filters.Enable(config.simple_filter_enabled.ToBool(),
123 config.biquad_filter_enabled.ToBool());
124 LOG_TRACE(Audio_DSP, "source_id=%zu enable_simple=%hu enable_biquad=%hu", source_id,
125 config.simple_filter_enabled.Value(), config.biquad_filter_enabled.Value());
126 }
127
128 if (config.simple_filter_dirty) {
129 config.simple_filter_dirty.Assign(0);
130 state.filters.Configure(config.simple_filter);
131 LOG_TRACE(Audio_DSP, "source_id=%zu simple filter update", source_id);
132 }
133
134 if (config.biquad_filter_dirty) {
135 config.biquad_filter_dirty.Assign(0);
136 state.filters.Configure(config.biquad_filter);
137 LOG_TRACE(Audio_DSP, "source_id=%zu biquad filter update", source_id);
138 }
139
140 if (config.interpolation_dirty) {
141 config.interpolation_dirty.Assign(0);
142 state.interpolation_mode = config.interpolation_mode;
143 LOG_TRACE(Audio_DSP, "source_id=%zu interpolation_mode=%zu", source_id,
144 static_cast<size_t>(state.interpolation_mode));
145 }
146
147 if (config.format_dirty || config.embedded_buffer_dirty) {
148 config.format_dirty.Assign(0);
149 state.format = config.format;
150 LOG_TRACE(Audio_DSP, "source_id=%zu format=%zu", source_id,
151 static_cast<size_t>(state.format));
152 }
153
154 if (config.mono_or_stereo_dirty || config.embedded_buffer_dirty) {
155 config.mono_or_stereo_dirty.Assign(0);
156 state.mono_or_stereo = config.mono_or_stereo;
157 LOG_TRACE(Audio_DSP, "source_id=%zu mono_or_stereo=%zu", source_id,
158 static_cast<size_t>(state.mono_or_stereo));
159 }
160
161 u32_dsp play_position = {};
162 if (config.play_position_dirty && config.play_position != 0) {
163 config.play_position_dirty.Assign(0);
164 play_position = config.play_position;
165 // play_position applies only to the embedded buffer, and defaults to 0 w/o a dirty bit
166 // This will be the starting sample for the first time the buffer is played.
167 }
168
169 if (config.embedded_buffer_dirty) {
170 config.embedded_buffer_dirty.Assign(0);
171 state.input_queue.emplace(Buffer{
172 config.physical_address,
173 config.length,
174 static_cast<u8>(config.adpcm_ps),
175 {config.adpcm_yn[0], config.adpcm_yn[1]},
176 config.adpcm_dirty.ToBool(),
177 config.is_looping.ToBool(),
178 config.buffer_id,
179 state.mono_or_stereo,
180 state.format,
181 false,
182 play_position,
183 false,
184 });
185 LOG_TRACE(Audio_DSP, "enqueuing embedded addr=0x%08x len=%u id=%hu start=%u",
186 config.physical_address, config.length, config.buffer_id,
187 static_cast<u32>(config.play_position));
188 }
189
190 if (config.loop_related_dirty && config.loop_related != 0) {
191 config.loop_related_dirty.Assign(0);
192 LOG_WARNING(Audio_DSP, "Unhandled complex loop with loop_related=0x%08x",
193 static_cast<u32>(config.loop_related));
194 }
195
196 if (config.buffer_queue_dirty) {
197 config.buffer_queue_dirty.Assign(0);
198 for (size_t i = 0; i < 4; i++) {
199 if (config.buffers_dirty & (1 << i)) {
200 const auto& b = config.buffers[i];
201 state.input_queue.emplace(Buffer{
202 b.physical_address,
203 b.length,
204 static_cast<u8>(b.adpcm_ps),
205 {b.adpcm_yn[0], b.adpcm_yn[1]},
206 b.adpcm_dirty != 0,
207 b.is_looping != 0,
208 b.buffer_id,
209 state.mono_or_stereo,
210 state.format,
211 true,
212 {}, // 0 in u32_dsp
213 false,
214 });
215 LOG_TRACE(Audio_DSP, "enqueuing queued %zu addr=0x%08x len=%u id=%hu", i,
216 b.physical_address, b.length, b.buffer_id);
217 }
218 }
219 config.buffers_dirty = 0;
220 }
221
222 if (config.dirty_raw) {
223 LOG_DEBUG(Audio_DSP, "source_id=%zu remaining_dirty=%x", source_id, config.dirty_raw);
224 }
225
226 config.dirty_raw = 0;
227}
228
229void Source::GenerateFrame() {
230 current_frame.fill({});
231
232 if (state.current_buffer.empty() && !DequeueBuffer()) {
233 state.enabled = false;
234 state.buffer_update = true;
235 state.current_buffer_id = 0;
236 return;
237 }
238
239 size_t frame_position = 0;
240
241 state.current_sample_number = state.next_sample_number;
242 while (frame_position < current_frame.size()) {
243 if (state.current_buffer.empty() && !DequeueBuffer()) {
244 break;
245 }
246
247 switch (state.interpolation_mode) {
248 case InterpolationMode::None:
249 AudioInterp::None(state.interp_state, state.current_buffer, state.rate_multiplier,
250 current_frame, frame_position);
251 break;
252 case InterpolationMode::Linear:
253 AudioInterp::Linear(state.interp_state, state.current_buffer, state.rate_multiplier,
254 current_frame, frame_position);
255 break;
256 case InterpolationMode::Polyphase:
257 // TODO(merry): Implement polyphase interpolation
258 LOG_DEBUG(Audio_DSP, "Polyphase interpolation unimplemented; falling back to linear");
259 AudioInterp::Linear(state.interp_state, state.current_buffer, state.rate_multiplier,
260 current_frame, frame_position);
261 break;
262 default:
263 UNIMPLEMENTED();
264 break;
265 }
266 }
267 state.next_sample_number += static_cast<u32>(frame_position);
268
269 state.filters.ProcessFrame(current_frame);
270}
271
272bool Source::DequeueBuffer() {
273 ASSERT_MSG(state.current_buffer.empty(),
274 "Shouldn't dequeue; we still have data in current_buffer");
275
276 if (state.input_queue.empty())
277 return false;
278
279 Buffer buf = state.input_queue.top();
280
281 // if we're in a loop, the current sound keeps playing afterwards, so leave the queue alone
282 if (!buf.is_looping) {
283 state.input_queue.pop();
284 }
285
286 if (buf.adpcm_dirty) {
287 state.adpcm_state.yn1 = buf.adpcm_yn[0];
288 state.adpcm_state.yn2 = buf.adpcm_yn[1];
289 }
290
291 const u8* const memory = Memory::GetPhysicalPointer(buf.physical_address);
292 if (memory) {
293 const unsigned num_channels = buf.mono_or_stereo == MonoOrStereo::Stereo ? 2 : 1;
294 switch (buf.format) {
295 case Format::PCM8:
296 state.current_buffer = Codec::DecodePCM8(num_channels, memory, buf.length);
297 break;
298 case Format::PCM16:
299 state.current_buffer = Codec::DecodePCM16(num_channels, memory, buf.length);
300 break;
301 case Format::ADPCM:
302 DEBUG_ASSERT(num_channels == 1);
303 state.current_buffer =
304 Codec::DecodeADPCM(memory, buf.length, state.adpcm_coeffs, state.adpcm_state);
305 break;
306 default:
307 UNIMPLEMENTED();
308 break;
309 }
310 } else {
311 LOG_WARNING(Audio_DSP,
312 "source_id=%zu buffer_id=%hu length=%u: Invalid physical address 0x%08X",
313 source_id, buf.buffer_id, buf.length, buf.physical_address);
314 state.current_buffer.clear();
315 return true;
316 }
317
318 // the first playthrough starts at play_position, loops start at the beginning of the buffer
319 state.current_sample_number = (!buf.has_played) ? buf.play_position : 0;
320 state.next_sample_number = state.current_sample_number;
321 state.current_buffer_id = buf.buffer_id;
322 state.buffer_update = buf.from_queue && !buf.has_played;
323
324 buf.has_played = true;
325
326 LOG_TRACE(Audio_DSP, "source_id=%zu buffer_id=%hu from_queue=%s current_buffer.size()=%zu",
327 source_id, buf.buffer_id, buf.from_queue ? "true" : "false",
328 state.current_buffer.size());
329 return true;
330}
331
332SourceStatus::Status Source::GetCurrentStatus() {
333 SourceStatus::Status ret;
334
335 // Applications depend on the correct emulation of
336 // current_buffer_id_dirty and current_buffer_id to synchronise
337 // audio with video.
338 ret.is_enabled = state.enabled;
339 ret.current_buffer_id_dirty = state.buffer_update ? 1 : 0;
340 state.buffer_update = false;
341 ret.current_buffer_id = state.current_buffer_id;
342 ret.buffer_position = state.current_sample_number;
343 ret.sync = state.sync;
344
345 return ret;
346}
347
348} // namespace HLE
349} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <queue>
9#include <vector>
10#include "audio_core/codec.h"
11#include "audio_core/hle/common.h"
12#include "audio_core/hle/dsp.h"
13#include "audio_core/hle/filter.h"
14#include "audio_core/interpolate.h"
15#include "common/common_types.h"
16
17namespace DSP {
18namespace HLE {
19
20/**
21 * This module performs:
22 * - Buffer management
23 * - Decoding of buffers
24 * - Buffer resampling and interpolation
25 * - Per-source filtering (SimpleFilter, BiquadFilter)
26 * - Per-source gain
27 * - Other per-source processing
28 */
29class Source final {
30public:
31 explicit Source(size_t source_id_) : source_id(source_id_) {
32 Reset();
33 }
34
35 /// Resets internal state.
36 void Reset();
37
38 /**
39 * This is called once every audio frame. This performs per-source processing every frame.
40 * @param config The new configuration we've got for this Source from the application.
41 * @param adpcm_coeffs ADPCM coefficients to use if config tells us to use them (may contain
42 * invalid values otherwise).
43 * @return The current status of this Source. This is given back to the emulated application via
44 * SharedMemory.
45 */
46 SourceStatus::Status Tick(SourceConfiguration::Configuration& config,
47 const s16_le (&adpcm_coeffs)[16]);
48
49 /**
50 * Mix this source's output into dest, using the gains for the `intermediate_mix_id`-th
51 * intermediate mixer.
52 * @param dest The QuadFrame32 to mix into.
53 * @param intermediate_mix_id The id of the intermediate mix whose gains we are using.
54 */
55 void MixInto(QuadFrame32& dest, size_t intermediate_mix_id) const;
56
57private:
58 const size_t source_id;
59 StereoFrame16 current_frame;
60
61 using Format = SourceConfiguration::Configuration::Format;
62 using InterpolationMode = SourceConfiguration::Configuration::InterpolationMode;
63 using MonoOrStereo = SourceConfiguration::Configuration::MonoOrStereo;
64
65 /// Internal representation of a buffer for our buffer queue
66 struct Buffer {
67 PAddr physical_address;
68 u32 length;
69 u8 adpcm_ps;
70 std::array<u16, 2> adpcm_yn;
71 bool adpcm_dirty;
72 bool is_looping;
73 u16 buffer_id;
74
75 MonoOrStereo mono_or_stereo;
76 Format format;
77
78 bool from_queue;
79 u32_dsp play_position; // = 0;
80 bool has_played; // = false;
81 };
82
83 struct BufferOrder {
84 bool operator()(const Buffer& a, const Buffer& b) const {
85 // Lower buffer_id comes first.
86 return a.buffer_id > b.buffer_id;
87 }
88 };
89
90 struct {
91
92 // State variables
93
94 bool enabled = false;
95 u16 sync = 0;
96
97 // Mixing
98
99 std::array<std::array<float, 4>, 3> gain = {};
100
101 // Buffer queue
102
103 std::priority_queue<Buffer, std::vector<Buffer>, BufferOrder> input_queue;
104 MonoOrStereo mono_or_stereo = MonoOrStereo::Mono;
105 Format format = Format::ADPCM;
106
107 // Current buffer
108
109 u32 current_sample_number = 0;
110 u32 next_sample_number = 0;
111 AudioInterp::StereoBuffer16 current_buffer;
112
113 // buffer_id state
114
115 bool buffer_update = false;
116 u32 current_buffer_id = 0;
117
118 // Decoding state
119
120 std::array<s16, 16> adpcm_coeffs = {};
121 Codec::ADPCMState adpcm_state = {};
122
123 // Resampling state
124
125 float rate_multiplier = 1.0;
126 InterpolationMode interpolation_mode = InterpolationMode::Polyphase;
127 AudioInterp::State interp_state = {};
128
129 // Filter state
130
131 SourceFilters filters;
132
133 } state;
134
135 // Internal functions
136
137 /// INTERNAL: Update our internal state based on the current config.
138 void ParseConfig(SourceConfiguration::Configuration& config, const s16_le (&adpcm_coeffs)[16]);
139 /// INTERNAL: Generate the current audio output for this frame based on our internal state.
140 void GenerateFrame();
141 /// INTERNAL: Dequeues a buffer and does preprocessing on it (decoding, resampling). Puts it
142 /// into current_buffer.
143 bool DequeueBuffer();
144 /// INTERNAL: Generates a SourceStatus::Status based on our internal state.
145 SourceStatus::Status GetCurrentStatus();
146};
147
148} // namespace HLE
149} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "audio_core/interpolate.h"
6#include "common/assert.h"
7#include "common/math_util.h"
8
9namespace AudioInterp {
10
11// Calculations are done in fixed point with 24 fractional bits.
12// (This is not verified. This was chosen for minimal error.)
13constexpr u64 scale_factor = 1 << 24;
14constexpr u64 scale_mask = scale_factor - 1;
15
16/// Here we step over the input in steps of rate, until we consume all of the input.
17/// Three adjacent samples are passed to fn each step.
18template <typename Function>
19static void StepOverSamples(State& state, StereoBuffer16& input, float rate,
20 DSP::HLE::StereoFrame16& output, size_t& outputi, Function fn) {
21 ASSERT(rate > 0);
22
23 if (input.empty())
24 return;
25
26 input.insert(input.begin(), {state.xn2, state.xn1});
27
28 const u64 step_size = static_cast<u64>(rate * scale_factor);
29 u64 fposition = state.fposition;
30 size_t inputi = 0;
31
32 while (outputi < output.size()) {
33 inputi = static_cast<size_t>(fposition / scale_factor);
34
35 if (inputi + 2 >= input.size()) {
36 inputi = input.size() - 2;
37 break;
38 }
39
40 u64 fraction = fposition & scale_mask;
41 output[outputi++] = fn(fraction, input[inputi], input[inputi + 1], input[inputi + 2]);
42
43 fposition += step_size;
44 }
45
46 state.xn2 = input[inputi];
47 state.xn1 = input[inputi + 1];
48 state.fposition = fposition - inputi * scale_factor;
49
50 input.erase(input.begin(), std::next(input.begin(), inputi + 2));
51}
52
53void None(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output,
54 size_t& outputi) {
55 StepOverSamples(
56 state, input, rate, output, outputi,
57 [](u64 fraction, const auto& x0, const auto& x1, const auto& x2) { return x0; });
58}
59
60void Linear(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output,
61 size_t& outputi) {
62 // Note on accuracy: Some values that this produces are +/- 1 from the actual firmware.
63 StepOverSamples(state, input, rate, output, outputi,
64 [](u64 fraction, const auto& x0, const auto& x1, const auto& x2) {
65 // This is a saturated subtraction. (Verified by black-box fuzzing.)
66 s64 delta0 = MathUtil::Clamp<s64>(x1[0] - x0[0], -32768, 32767);
67 s64 delta1 = MathUtil::Clamp<s64>(x1[1] - x0[1], -32768, 32767);
68
69 return std::array<s16, 2>{
70 static_cast<s16>(x0[0] + fraction * delta0 / scale_factor),
71 static_cast<s16>(x0[1] + fraction * delta1 / scale_factor),
72 };
73 });
74}
75
76} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <deque>
9#include "audio_core/hle/common.h"
10#include "common/common_types.h"
11
12namespace AudioInterp {
13
14/// A variable length buffer of signed PCM16 stereo samples.
15using StereoBuffer16 = std::deque<std::array<s16, 2>>;
16
17struct State {
18 /// Two historical samples.
19 std::array<s16, 2> xn1 = {}; ///< x[n-1]
20 std::array<s16, 2> xn2 = {}; ///< x[n-2]
21 /// Current fractional position.
22 u64 fposition = 0;
23};
24
25/**
26 * No interpolation. This is equivalent to a zero-order hold. There is a two-sample predelay.
27 * @param state Interpolation state.
28 * @param input Input buffer.
29 * @param rate Stretch factor. Must be a positive non-zero value.
30 * rate > 1.0 performs decimation and rate < 1.0 performs upsampling.
31 * @param output The resampled audio buffer.
32 * @param outputi The index of output to start writing to.
33 */
34void None(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output,
35 size_t& outputi);
36
37/**
38 * Linear interpolation. This is equivalent to a first-order hold. There is a two-sample predelay.
39 * @param state Interpolation state.
40 * @param input Input buffer.
41 * @param rate Stretch factor. Must be a positive non-zero value.
42 * rate > 1.0 performs decimation and rate < 1.0 performs upsampling.
43 * @param output The resampled audio buffer.
44 * @param outputi The index of output to start writing to.
45 */
46void Linear(State& state, StereoBuffer16& input, float rate, DSP::HLE::StereoFrame16& output,
47 size_t& outputi);
48
49} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <cstddef>
8#include "audio_core/audio_core.h"
9#include "audio_core/sink.h"
10
11namespace AudioCore {
12
13class NullSink final : public Sink {
14public:
15 ~NullSink() override = default;
16
17 unsigned int GetNativeSampleRate() const override {
18 return native_sample_rate;
19 }
20
21 void EnqueueSamples(const s16*, size_t) override {}
22
23 size_t SamplesInQueue() const override {
24 return 0;
25 }
26
27 void SetDevice(int device_id) override {}
28
29 std::vector<std::string> GetDeviceList() const override {
30 return {};
31 }
32};
33
34} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <list>
6#include <numeric>
7#include <SDL.h>
8#include "audio_core/audio_core.h"
9#include "audio_core/sdl2_sink.h"
10#include "common/assert.h"
11#include "common/logging/log.h"
12#include "core/settings.h"
13
14namespace AudioCore {
15
16struct SDL2Sink::Impl {
17 unsigned int sample_rate = 0;
18
19 SDL_AudioDeviceID audio_device_id = 0;
20
21 std::list<std::vector<s16>> queue;
22
23 static void Callback(void* impl_, u8* buffer, int buffer_size_in_bytes);
24};
25
26SDL2Sink::SDL2Sink() : impl(std::make_unique<Impl>()) {
27 if (SDL_Init(SDL_INIT_AUDIO) < 0) {
28 LOG_CRITICAL(Audio_Sink, "SDL_Init(SDL_INIT_AUDIO) failed with: %s", SDL_GetError());
29 impl->audio_device_id = 0;
30 return;
31 }
32
33 SDL_AudioSpec desired_audiospec;
34 SDL_zero(desired_audiospec);
35 desired_audiospec.format = AUDIO_S16;
36 desired_audiospec.channels = 2;
37 desired_audiospec.freq = native_sample_rate;
38 desired_audiospec.samples = 512;
39 desired_audiospec.userdata = impl.get();
40 desired_audiospec.callback = &Impl::Callback;
41
42 SDL_AudioSpec obtained_audiospec;
43 SDL_zero(obtained_audiospec);
44
45 int device_count = SDL_GetNumAudioDevices(0);
46 device_list.clear();
47 for (int i = 0; i < device_count; ++i) {
48 device_list.push_back(SDL_GetAudioDeviceName(i, 0));
49 }
50
51 const char* device = nullptr;
52
53 if (device_count >= 1 && Settings::values.audio_device_id != "auto" &&
54 !Settings::values.audio_device_id.empty()) {
55 device = Settings::values.audio_device_id.c_str();
56 }
57
58 impl->audio_device_id = SDL_OpenAudioDevice(device, false, &desired_audiospec,
59 &obtained_audiospec, SDL_AUDIO_ALLOW_ANY_CHANGE);
60 if (impl->audio_device_id <= 0) {
61 LOG_CRITICAL(Audio_Sink, "SDL_OpenAudioDevice failed with code %d for device \"%s\"",
62 impl->audio_device_id, Settings::values.audio_device_id.c_str());
63 return;
64 }
65
66 impl->sample_rate = obtained_audiospec.freq;
67
68 // SDL2 audio devices start out paused, unpause it:
69 SDL_PauseAudioDevice(impl->audio_device_id, 0);
70}
71
72SDL2Sink::~SDL2Sink() {
73 if (impl->audio_device_id <= 0)
74 return;
75
76 SDL_CloseAudioDevice(impl->audio_device_id);
77}
78
79unsigned int SDL2Sink::GetNativeSampleRate() const {
80 if (impl->audio_device_id <= 0)
81 return native_sample_rate;
82
83 return impl->sample_rate;
84}
85
86std::vector<std::string> SDL2Sink::GetDeviceList() const {
87 return device_list;
88}
89
90void SDL2Sink::EnqueueSamples(const s16* samples, size_t sample_count) {
91 if (impl->audio_device_id <= 0)
92 return;
93
94 SDL_LockAudioDevice(impl->audio_device_id);
95 impl->queue.emplace_back(samples, samples + sample_count * 2);
96 SDL_UnlockAudioDevice(impl->audio_device_id);
97}
98
99size_t SDL2Sink::SamplesInQueue() const {
100 if (impl->audio_device_id <= 0)
101 return 0;
102
103 SDL_LockAudioDevice(impl->audio_device_id);
104
105 size_t total_size = std::accumulate(impl->queue.begin(), impl->queue.end(),
106 static_cast<size_t>(0), [](size_t sum, const auto& buffer) {
107 // Division by two because each stereo sample is made of
108 // two s16.
109 return sum + buffer.size() / 2;
110 });
111
112 SDL_UnlockAudioDevice(impl->audio_device_id);
113
114 return total_size;
115}
116
117void SDL2Sink::SetDevice(int device_id) {
118 this->device_id = device_id;
119}
120
121void SDL2Sink::Impl::Callback(void* impl_, u8* buffer, int buffer_size_in_bytes) {
122 Impl* impl = reinterpret_cast<Impl*>(impl_);
123
124 size_t remaining_size = static_cast<size_t>(buffer_size_in_bytes) /
125 sizeof(s16); // Keep track of size in 16-bit increments.
126
127 while (remaining_size > 0 && !impl->queue.empty()) {
128 if (impl->queue.front().size() <= remaining_size) {
129 memcpy(buffer, impl->queue.front().data(), impl->queue.front().size() * sizeof(s16));
130 buffer += impl->queue.front().size() * sizeof(s16);
131 remaining_size -= impl->queue.front().size();
132 impl->queue.pop_front();
133 } else {
134 memcpy(buffer, impl->queue.front().data(), remaining_size * sizeof(s16));
135 buffer += remaining_size * sizeof(s16);
136 impl->queue.front().erase(impl->queue.front().begin(),
137 impl->queue.front().begin() + remaining_size);
138 remaining_size = 0;
139 }
140 }
141
142 if (remaining_size > 0) {
143 memset(buffer, 0, remaining_size * sizeof(s16));
144 }
145}
146
147} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <cstddef>
8#include <memory>
9#include "audio_core/sink.h"
10
11namespace AudioCore {
12
13class SDL2Sink final : public Sink {
14public:
15 SDL2Sink();
16 ~SDL2Sink() override;
17
18 unsigned int GetNativeSampleRate() const override;
19
20 void EnqueueSamples(const s16* samples, size_t sample_count) override;
21
22 size_t SamplesInQueue() const override;
23
24 std::vector<std::string> GetDeviceList() const override;
25 void SetDevice(int device_id) override;
26
27private:
28 struct Impl;
29 std::unique_ptr<Impl> impl;
30 int device_id;
31 std::vector<std::string> device_list;
32};
33
34} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <vector>
8#include "common/common_types.h"
9
10namespace AudioCore {
11
12/**
13 * This class is an interface for an audio sink. An audio sink accepts samples in stereo signed
14 * PCM16 format to be output. Sinks *do not* handle resampling and expect the correct sample rate.
15 * They are dumb outputs.
16 */
17class Sink {
18public:
19 virtual ~Sink() = default;
20
21 /// The native rate of this sink. The sink expects to be fed samples that respect this. (Units:
22 /// samples/sec)
23 virtual unsigned int GetNativeSampleRate() const = 0;
24
25 /**
26 * Feed stereo samples to sink.
27 * @param samples Samples in interleaved stereo PCM16 format.
28 * @param sample_count Number of samples.
29 */
30 virtual void EnqueueSamples(const s16* samples, size_t sample_count) = 0;
31
32 /// Samples enqueued that have not been played yet.
33 virtual std::size_t SamplesInQueue() const = 0;
34
35 /**
36 * Sets the desired output device.
37 * @param device_id ID of the desired device.
38 */
39 virtual void SetDevice(int device_id) = 0;
40
41 /// Returns the list of available devices.
42 virtual std::vector<std::string> GetDeviceList() const = 0;
43};
44
45} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <memory>
7#include <vector>
8#include "audio_core/null_sink.h"
9#include "audio_core/sink_details.h"
10#ifdef HAVE_SDL2
11#include "audio_core/sdl2_sink.h"
12#endif
13#include "common/logging/log.h"
14
15namespace AudioCore {
16
17// g_sink_details is ordered in terms of desirability, with the best choice at the top.
18const std::vector<SinkDetails> g_sink_details = {
19#ifdef HAVE_SDL2
20 {"sdl2", []() { return std::make_unique<SDL2Sink>(); }},
21#endif
22 {"null", []() { return std::make_unique<NullSink>(); }},
23};
24
25const SinkDetails& GetSinkDetails(std::string sink_id) {
26 auto iter =
27 std::find_if(g_sink_details.begin(), g_sink_details.end(),
28 [sink_id](const auto& sink_detail) { return sink_detail.id == sink_id; });
29
30 if (sink_id == "auto" || iter == g_sink_details.end()) {
31 if (sink_id != "auto") {
32 LOG_ERROR(Audio, "AudioCore::SelectSink given invalid sink_id %s", sink_id.c_str());
33 }
34 // Auto-select.
35 // g_sink_details is ordered in terms of desirability, with the best choice at the front.
36 iter = g_sink_details.begin();
37 }
38
39 return *iter;
40}
41
42} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <memory>
9#include <vector>
10
11namespace AudioCore {
12
13class Sink;
14
15struct SinkDetails {
16 SinkDetails(const char* id_, std::function<std::unique_ptr<Sink>()> factory_)
17 : id(id_), factory(factory_) {}
18
19 /// Name for this sink.
20 const char* id;
21 /// A method to call to construct an instance of this type of sink.
22 std::function<std::unique_ptr<Sink>()> factory;
23};
24
25extern const std::vector<SinkDetails> g_sink_details;
26
27const SinkDetails& GetSinkDetails(std::string sink_id);
28
29} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <chrono>
6#include <cmath>
7#include <vector>
8#include <SoundTouch.h>
9#include "audio_core/audio_core.h"
10#include "audio_core/time_stretch.h"
11#include "common/common_types.h"
12#include "common/logging/log.h"
13#include "common/math_util.h"
14
15using steady_clock = std::chrono::steady_clock;
16
17namespace AudioCore {
18
19constexpr double MIN_RATIO = 0.1;
20constexpr double MAX_RATIO = 100.0;
21
22static double ClampRatio(double ratio) {
23 return MathUtil::Clamp(ratio, MIN_RATIO, MAX_RATIO);
24}
25
26constexpr double MIN_DELAY_TIME = 0.05; // Units: seconds
27constexpr double MAX_DELAY_TIME = 0.25; // Units: seconds
28constexpr size_t DROP_FRAMES_SAMPLE_DELAY = 16000; // Units: samples
29
30constexpr double SMOOTHING_FACTOR = 0.007;
31
32struct TimeStretcher::Impl {
33 soundtouch::SoundTouch soundtouch;
34
35 steady_clock::time_point frame_timer = steady_clock::now();
36 size_t samples_queued = 0;
37
38 double smoothed_ratio = 1.0;
39
40 double sample_rate = static_cast<double>(native_sample_rate);
41};
42
43std::vector<s16> TimeStretcher::Process(size_t samples_in_queue) {
44 // This is a very simple algorithm without any fancy control theory. It works and is stable.
45
46 double ratio = CalculateCurrentRatio();
47 ratio = CorrectForUnderAndOverflow(ratio, samples_in_queue);
48 impl->smoothed_ratio =
49 (1.0 - SMOOTHING_FACTOR) * impl->smoothed_ratio + SMOOTHING_FACTOR * ratio;
50 impl->smoothed_ratio = ClampRatio(impl->smoothed_ratio);
51
52 // SoundTouch's tempo definition the inverse of our ratio definition.
53 impl->soundtouch.setTempo(1.0 / impl->smoothed_ratio);
54
55 std::vector<s16> samples = GetSamples();
56 if (samples_in_queue >= DROP_FRAMES_SAMPLE_DELAY) {
57 samples.clear();
58 LOG_TRACE(Audio, "Dropping frames!");
59 }
60 return samples;
61}
62
63TimeStretcher::TimeStretcher() : impl(std::make_unique<Impl>()) {
64 impl->soundtouch.setPitch(1.0);
65 impl->soundtouch.setChannels(2);
66 impl->soundtouch.setSampleRate(native_sample_rate);
67 Reset();
68}
69
70TimeStretcher::~TimeStretcher() {
71 impl->soundtouch.clear();
72}
73
74void TimeStretcher::SetOutputSampleRate(unsigned int sample_rate) {
75 impl->sample_rate = static_cast<double>(sample_rate);
76 impl->soundtouch.setRate(static_cast<double>(native_sample_rate) / impl->sample_rate);
77}
78
79void TimeStretcher::AddSamples(const s16* buffer, size_t num_samples) {
80 impl->soundtouch.putSamples(buffer, static_cast<uint>(num_samples));
81 impl->samples_queued += num_samples;
82}
83
84void TimeStretcher::Flush() {
85 impl->soundtouch.flush();
86}
87
88void TimeStretcher::Reset() {
89 impl->soundtouch.setTempo(1.0);
90 impl->soundtouch.clear();
91 impl->smoothed_ratio = 1.0;
92 impl->frame_timer = steady_clock::now();
93 impl->samples_queued = 0;
94 SetOutputSampleRate(native_sample_rate);
95}
96
97double TimeStretcher::CalculateCurrentRatio() {
98 const steady_clock::time_point now = steady_clock::now();
99 const std::chrono::duration<double> duration = now - impl->frame_timer;
100
101 const double expected_time =
102 static_cast<double>(impl->samples_queued) / static_cast<double>(native_sample_rate);
103 const double actual_time = duration.count();
104
105 double ratio;
106 if (expected_time != 0) {
107 ratio = ClampRatio(actual_time / expected_time);
108 } else {
109 ratio = impl->smoothed_ratio;
110 }
111
112 impl->frame_timer = now;
113 impl->samples_queued = 0;
114
115 return ratio;
116}
117
118double TimeStretcher::CorrectForUnderAndOverflow(double ratio, size_t sample_delay) const {
119 const size_t min_sample_delay = static_cast<size_t>(MIN_DELAY_TIME * impl->sample_rate);
120 const size_t max_sample_delay = static_cast<size_t>(MAX_DELAY_TIME * impl->sample_rate);
121
122 if (sample_delay < min_sample_delay) {
123 // Make the ratio bigger.
124 ratio = ratio > 1.0 ? ratio * ratio : sqrt(ratio);
125 } else if (sample_delay > max_sample_delay) {
126 // Make the ratio smaller.
127 ratio = ratio > 1.0 ? sqrt(ratio) : ratio * ratio;
128 }
129
130 return ClampRatio(ratio);
131}
132
133std::vector<s16> TimeStretcher::GetSamples() {
134 uint available = impl->soundtouch.numSamples();
135
136 std::vector<s16> output(static_cast<size_t>(available) * 2);
137
138 impl->soundtouch.receiveSamples(output.data(), available);
139
140 return output;
141}
142
143} // 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 @@
1// Copyright 2016 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <cstddef>
8#include <memory>
9#include <vector>
10#include "common/common_types.h"
11
12namespace AudioCore {
13
14class TimeStretcher final {
15public:
16 TimeStretcher();
17 ~TimeStretcher();
18
19 /**
20 * Set sample rate for the samples that Process returns.
21 * @param sample_rate The sample rate.
22 */
23 void SetOutputSampleRate(unsigned int sample_rate);
24
25 /**
26 * Add samples to be processed.
27 * @param sample_buffer Buffer of samples in interleaved stereo PCM16 format.
28 * @param num_samples Number of samples.
29 */
30 void AddSamples(const s16* sample_buffer, size_t num_samples);
31
32 /// Flush audio remaining in internal buffers.
33 void Flush();
34
35 /// Resets internal state and clears buffers.
36 void Reset();
37
38 /**
39 * Does audio stretching and produces the time-stretched samples.
40 * Timer calculations use sample_delay to determine how much of a margin we have.
41 * @param sample_delay How many samples are buffered downstream of this module and haven't been
42 * played yet.
43 * @return Samples to play in interleaved stereo PCM16 format.
44 */
45 std::vector<s16> Process(size_t sample_delay);
46
47private:
48 struct Impl;
49 std::unique_ptr<Impl> impl;
50
51 /// INTERNAL: ratio = wallclock time / emulated time
52 double CalculateCurrentRatio();
53 /// INTERNAL: If we have too many or too few samples downstream, nudge ratio in the appropriate
54 /// direction.
55 double CorrectForUnderAndOverflow(double ratio, size_t sample_delay) const;
56 /// INTERNAL: Gets the time-stretched samples from SoundTouch.
57 std::vector<s16> GetSamples();
58};
59
60} // 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 @@
1set(SRCS
2 network.cpp
3 packet.cpp
4 room.cpp
5 room_member.cpp
6 )
7
8set(HEADERS
9 network.h
10 packet.h
11 room.h
12 room_member.h
13 )
14
15create_directory_groups(${SRCS} ${HEADERS})
16
17add_library(network STATIC ${SRCS} ${HEADERS})
18target_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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/assert.h"
6#include "common/logging/log.h"
7#include "enet/enet.h"
8#include "network/network.h"
9
10namespace Network {
11
12static std::shared_ptr<RoomMember> g_room_member; ///< RoomMember (Client) for network games
13static std::shared_ptr<Room> g_room; ///< Room (Server) for network games
14// TODO(B3N30): Put these globals into a networking class
15
16bool Init() {
17 if (enet_initialize() != 0) {
18 LOG_ERROR(Network, "Error initalizing ENet");
19 return false;
20 }
21 g_room = std::make_shared<Room>();
22 g_room_member = std::make_shared<RoomMember>();
23 LOG_DEBUG(Network, "initialized OK");
24 return true;
25}
26
27std::weak_ptr<Room> GetRoom() {
28 return g_room;
29}
30
31std::weak_ptr<RoomMember> GetRoomMember() {
32 return g_room_member;
33}
34
35void Shutdown() {
36 if (g_room_member) {
37 if (g_room_member->IsConnected())
38 g_room_member->Leave();
39 g_room_member.reset();
40 }
41 if (g_room) {
42 if (g_room->GetState() == Room::State::Open)
43 g_room->Destroy();
44 g_room.reset();
45 }
46 enet_deinitialize();
47 LOG_DEBUG(Network, "shutdown OK");
48}
49
50} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <memory>
8#include "network/room.h"
9#include "network/room_member.h"
10
11namespace Network {
12
13/// Initializes and registers the network device, the room, and the room member.
14bool Init();
15
16/// Returns a pointer to the room handle
17std::weak_ptr<Room> GetRoom();
18
19/// Returns a pointer to the room member handle
20std::weak_ptr<RoomMember> GetRoomMember();
21
22/// Unregisters the network device, the room, and the room member and shut them down.
23void Shutdown();
24
25} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#ifdef _WIN32
6#include <winsock2.h>
7#else
8#include <arpa/inet.h>
9#endif
10#include <cstring>
11#include <string>
12#include "network/packet.h"
13
14namespace Network {
15
16#ifndef htonll
17u64 htonll(u64 x) {
18 return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32));
19}
20#endif
21
22#ifndef ntohll
23u64 ntohll(u64 x) {
24 return ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x)&0xFFFFFFFF) << 32) | ntohl((x) >> 32));
25}
26#endif
27
28void Packet::Append(const void* in_data, std::size_t size_in_bytes) {
29 if (in_data && (size_in_bytes > 0)) {
30 std::size_t start = data.size();
31 data.resize(start + size_in_bytes);
32 std::memcpy(&data[start], in_data, size_in_bytes);
33 }
34}
35
36void Packet::Read(void* out_data, std::size_t size_in_bytes) {
37 if (out_data && CheckSize(size_in_bytes)) {
38 std::memcpy(out_data, &data[read_pos], size_in_bytes);
39 read_pos += size_in_bytes;
40 }
41}
42
43void Packet::Clear() {
44 data.clear();
45 read_pos = 0;
46 is_valid = true;
47}
48
49const void* Packet::GetData() const {
50 return !data.empty() ? &data[0] : nullptr;
51}
52
53void Packet::IgnoreBytes(u32 length) {
54 read_pos += length;
55}
56
57std::size_t Packet::GetDataSize() const {
58 return data.size();
59}
60
61bool Packet::EndOfPacket() const {
62 return read_pos >= data.size();
63}
64
65Packet::operator bool() const {
66 return is_valid ? &Packet::CheckSize : nullptr;
67}
68
69Packet& Packet::operator>>(bool& out_data) {
70 u8 value;
71 if (*this >> value) {
72 out_data = (value != 0);
73 }
74 return *this;
75}
76
77Packet& Packet::operator>>(s8& out_data) {
78 Read(&out_data, sizeof(out_data));
79 return *this;
80}
81
82Packet& Packet::operator>>(u8& out_data) {
83 Read(&out_data, sizeof(out_data));
84 return *this;
85}
86
87Packet& Packet::operator>>(s16& out_data) {
88 s16 value;
89 Read(&value, sizeof(value));
90 out_data = ntohs(value);
91 return *this;
92}
93
94Packet& Packet::operator>>(u16& out_data) {
95 u16 value;
96 Read(&value, sizeof(value));
97 out_data = ntohs(value);
98 return *this;
99}
100
101Packet& Packet::operator>>(s32& out_data) {
102 s32 value;
103 Read(&value, sizeof(value));
104 out_data = ntohl(value);
105 return *this;
106}
107
108Packet& Packet::operator>>(u32& out_data) {
109 u32 value;
110 Read(&value, sizeof(value));
111 out_data = ntohl(value);
112 return *this;
113}
114
115Packet& Packet::operator>>(s64& out_data) {
116 s64 value;
117 Read(&value, sizeof(value));
118 out_data = ntohll(value);
119 return *this;
120}
121
122Packet& Packet::operator>>(u64& out_data) {
123 u64 value;
124 Read(&value, sizeof(value));
125 out_data = ntohll(value);
126 return *this;
127}
128
129Packet& Packet::operator>>(float& out_data) {
130 Read(&out_data, sizeof(out_data));
131 return *this;
132}
133
134Packet& Packet::operator>>(double& out_data) {
135 Read(&out_data, sizeof(out_data));
136 return *this;
137}
138
139Packet& Packet::operator>>(char* out_data) {
140 // First extract string length
141 u32 length = 0;
142 *this >> length;
143
144 if ((length > 0) && CheckSize(length)) {
145 // Then extract characters
146 std::memcpy(out_data, &data[read_pos], length);
147 out_data[length] = '\0';
148
149 // Update reading position
150 read_pos += length;
151 }
152
153 return *this;
154}
155
156Packet& Packet::operator>>(std::string& out_data) {
157 // First extract string length
158 u32 length = 0;
159 *this >> length;
160
161 out_data.clear();
162 if ((length > 0) && CheckSize(length)) {
163 // Then extract characters
164 out_data.assign(&data[read_pos], length);
165
166 // Update reading position
167 read_pos += length;
168 }
169
170 return *this;
171}
172
173Packet& Packet::operator<<(bool in_data) {
174 *this << static_cast<u8>(in_data);
175 return *this;
176}
177
178Packet& Packet::operator<<(s8 in_data) {
179 Append(&in_data, sizeof(in_data));
180 return *this;
181}
182
183Packet& Packet::operator<<(u8 in_data) {
184 Append(&in_data, sizeof(in_data));
185 return *this;
186}
187
188Packet& Packet::operator<<(s16 in_data) {
189 s16 toWrite = htons(in_data);
190 Append(&toWrite, sizeof(toWrite));
191 return *this;
192}
193
194Packet& Packet::operator<<(u16 in_data) {
195 u16 toWrite = htons(in_data);
196 Append(&toWrite, sizeof(toWrite));
197 return *this;
198}
199
200Packet& Packet::operator<<(s32 in_data) {
201 s32 toWrite = htonl(in_data);
202 Append(&toWrite, sizeof(toWrite));
203 return *this;
204}
205
206Packet& Packet::operator<<(u32 in_data) {
207 u32 toWrite = htonl(in_data);
208 Append(&toWrite, sizeof(toWrite));
209 return *this;
210}
211
212Packet& Packet::operator<<(s64 in_data) {
213 s64 toWrite = htonll(in_data);
214 Append(&toWrite, sizeof(toWrite));
215 return *this;
216}
217
218Packet& Packet::operator<<(u64 in_data) {
219 u64 toWrite = htonll(in_data);
220 Append(&toWrite, sizeof(toWrite));
221 return *this;
222}
223
224Packet& Packet::operator<<(float in_data) {
225 Append(&in_data, sizeof(in_data));
226 return *this;
227}
228
229Packet& Packet::operator<<(double in_data) {
230 Append(&in_data, sizeof(in_data));
231 return *this;
232}
233
234Packet& Packet::operator<<(const char* in_data) {
235 // First insert string length
236 u32 length = static_cast<u32>(std::strlen(in_data));
237 *this << length;
238
239 // Then insert characters
240 Append(in_data, length * sizeof(char));
241
242 return *this;
243}
244
245Packet& Packet::operator<<(const std::string& in_data) {
246 // First insert string length
247 u32 length = static_cast<u32>(in_data.size());
248 *this << length;
249
250 // Then insert characters
251 if (length > 0)
252 Append(in_data.c_str(), length * sizeof(std::string::value_type));
253
254 return *this;
255}
256
257bool Packet::CheckSize(std::size_t size) {
258 is_valid = is_valid && (read_pos + size <= data.size());
259
260 return is_valid;
261}
262
263} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <vector>
9#include "common/common_types.h"
10
11namespace Network {
12
13/// A class that serializes data for network transfer. It also handles endianess
14class Packet {
15public:
16 Packet() = default;
17 ~Packet() = default;
18
19 /**
20 * Append data to the end of the packet
21 * @param data Pointer to the sequence of bytes to append
22 * @param size_in_bytes Number of bytes to append
23 */
24 void Append(const void* data, std::size_t size_in_bytes);
25
26 /**
27 * Reads data from the current read position of the packet
28 * @param out_data Pointer where the data should get written to
29 * @param size_in_bytes Number of bytes to read
30 */
31 void Read(void* out_data, std::size_t size_in_bytes);
32
33 /**
34 * Clear the packet
35 * After calling Clear, the packet is empty.
36 */
37 void Clear();
38
39 /**
40 * Ignores bytes while reading
41 * @param length THe number of bytes to ignore
42 */
43 void IgnoreBytes(u32 length);
44
45 /**
46 * Get a pointer to the data contained in the packet
47 * @return Pointer to the data
48 */
49 const void* GetData() const;
50
51 /**
52 * This function returns the number of bytes pointed to by
53 * what getData returns.
54 * @return Data size, in bytes
55 */
56 std::size_t GetDataSize() const;
57
58 /**
59 * This function is useful to know if there is some data
60 * left to be read, without actually reading it.
61 * @return True if all data was read, false otherwise
62 */
63 bool EndOfPacket() const;
64
65 explicit operator bool() const;
66
67 /// Overloads of operator >> to read data from the packet
68 Packet& operator>>(bool& out_data);
69 Packet& operator>>(s8& out_data);
70 Packet& operator>>(u8& out_data);
71 Packet& operator>>(s16& out_data);
72 Packet& operator>>(u16& out_data);
73 Packet& operator>>(s32& out_data);
74 Packet& operator>>(u32& out_data);
75 Packet& operator>>(s64& out_data);
76 Packet& operator>>(u64& out_data);
77 Packet& operator>>(float& out_data);
78 Packet& operator>>(double& out_data);
79 Packet& operator>>(char* out_data);
80 Packet& operator>>(std::string& out_data);
81 template <typename T>
82 Packet& operator>>(std::vector<T>& out_data);
83 template <typename T, std::size_t S>
84 Packet& operator>>(std::array<T, S>& out_data);
85
86 /// Overloads of operator << to write data into the packet
87 Packet& operator<<(bool in_data);
88 Packet& operator<<(s8 in_data);
89 Packet& operator<<(u8 in_data);
90 Packet& operator<<(s16 in_data);
91 Packet& operator<<(u16 in_data);
92 Packet& operator<<(s32 in_data);
93 Packet& operator<<(u32 in_data);
94 Packet& operator<<(s64 in_data);
95 Packet& operator<<(u64 in_data);
96 Packet& operator<<(float in_data);
97 Packet& operator<<(double in_data);
98 Packet& operator<<(const char* in_data);
99 Packet& operator<<(const std::string& in_data);
100 template <typename T>
101 Packet& operator<<(const std::vector<T>& in_data);
102 template <typename T, std::size_t S>
103 Packet& operator<<(const std::array<T, S>& data);
104
105private:
106 /**
107 * Check if the packet can extract a given number of bytes
108 * This function updates accordingly the state of the packet.
109 * @param size Size to check
110 * @return True if size bytes can be read from the packet
111 */
112 bool CheckSize(std::size_t size);
113
114 // Member data
115 std::vector<char> data; ///< Data stored in the packet
116 std::size_t read_pos = 0; ///< Current reading position in the packet
117 bool is_valid = true; ///< Reading state of the packet
118};
119
120template <typename T>
121Packet& Packet::operator>>(std::vector<T>& out_data) {
122 // First extract the size
123 u32 size = 0;
124 *this >> size;
125 out_data.resize(size);
126
127 // Then extract the data
128 for (std::size_t i = 0; i < out_data.size(); ++i) {
129 T character = 0;
130 *this >> character;
131 out_data[i] = character;
132 }
133 return *this;
134}
135
136template <typename T, std::size_t S>
137Packet& Packet::operator>>(std::array<T, S>& out_data) {
138 for (std::size_t i = 0; i < out_data.size(); ++i) {
139 T character = 0;
140 *this >> character;
141 out_data[i] = character;
142 }
143 return *this;
144}
145
146template <typename T>
147Packet& Packet::operator<<(const std::vector<T>& in_data) {
148 // First insert the size
149 *this << static_cast<u32>(in_data.size());
150
151 // Then insert the data
152 for (std::size_t i = 0; i < in_data.size(); ++i) {
153 *this << in_data[i];
154 }
155 return *this;
156}
157
158template <typename T, std::size_t S>
159Packet& Packet::operator<<(const std::array<T, S>& in_data) {
160 for (std::size_t i = 0; i < in_data.size(); ++i) {
161 *this << in_data[i];
162 }
163 return *this;
164}
165
166} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <algorithm>
6#include <atomic>
7#include <mutex>
8#include <random>
9#include <thread>
10#include "enet/enet.h"
11#include "network/packet.h"
12#include "network/room.h"
13
14namespace Network {
15
16/// Maximum number of concurrent connections allowed to this room.
17static constexpr u32 MaxConcurrentConnections = 10;
18
19class Room::RoomImpl {
20public:
21 // This MAC address is used to generate a 'Nintendo' like Mac address.
22 const MacAddress NintendoOUI;
23 std::mt19937 random_gen; ///< Random number generator. Used for GenerateMacAddress
24
25 ENetHost* server = nullptr; ///< Network interface.
26
27 std::atomic<State> state{State::Closed}; ///< Current state of the room.
28 RoomInformation room_information; ///< Information about this room.
29
30 struct Member {
31 std::string nickname; ///< The nickname of the member.
32 GameInfo game_info; ///< The current game of the member
33 MacAddress mac_address; ///< The assigned mac address of the member.
34 ENetPeer* peer; ///< The remote peer.
35 };
36 using MemberList = std::vector<Member>;
37 MemberList members; ///< Information about the members of this room
38 mutable std::mutex member_mutex; ///< Mutex for locking the members list
39 /// This should be a std::shared_mutex as soon as C++17 is supported
40
41 RoomImpl()
42 : random_gen(std::random_device()()), NintendoOUI{0x00, 0x1F, 0x32, 0x00, 0x00, 0x00} {}
43
44 /// Thread that receives and dispatches network packets
45 std::unique_ptr<std::thread> room_thread;
46
47 /// Thread function that will receive and dispatch messages until the room is destroyed.
48 void ServerLoop();
49 void StartLoop();
50
51 /**
52 * Parses and answers a room join request from a client.
53 * Validates the uniqueness of the username and assigns the MAC address
54 * that the client will use for the remainder of the connection.
55 */
56 void HandleJoinRequest(const ENetEvent* event);
57
58 /**
59 * Returns whether the nickname is valid, ie. isn't already taken by someone else in the room.
60 */
61 bool IsValidNickname(const std::string& nickname) const;
62
63 /**
64 * Returns whether the MAC address is valid, ie. isn't already taken by someone else in the
65 * room.
66 */
67 bool IsValidMacAddress(const MacAddress& address) const;
68
69 /**
70 * Sends a ID_ROOM_NAME_COLLISION message telling the client that the name is invalid.
71 */
72 void SendNameCollision(ENetPeer* client);
73
74 /**
75 * Sends a ID_ROOM_MAC_COLLISION message telling the client that the MAC is invalid.
76 */
77 void SendMacCollision(ENetPeer* client);
78
79 /**
80 * Sends a ID_ROOM_VERSION_MISMATCH message telling the client that the version is invalid.
81 */
82 void SendVersionMismatch(ENetPeer* client);
83
84 /**
85 * Notifies the member that its connection attempt was successful,
86 * and it is now part of the room.
87 */
88 void SendJoinSuccess(ENetPeer* client, MacAddress mac_address);
89
90 /**
91 * Notifies the members that the room is closed,
92 */
93 void SendCloseMessage();
94
95 /**
96 * Sends the information about the room, along with the list of members
97 * to every connected client in the room.
98 * The packet has the structure:
99 * <MessageID>ID_ROOM_INFORMATION
100 * <String> room_name
101 * <u32> member_slots: The max number of clients allowed in this room
102 * <u32> num_members: the number of currently joined clients
103 * This is followed by the following three values for each member:
104 * <String> nickname of that member
105 * <MacAddress> mac_address of that member
106 * <String> game_name of that member
107 */
108 void BroadcastRoomInformation();
109
110 /**
111 * Generates a free MAC address to assign to a new client.
112 * The first 3 bytes are the NintendoOUI 0x00, 0x1F, 0x32
113 */
114 MacAddress GenerateMacAddress();
115
116 /**
117 * Broadcasts this packet to all members except the sender.
118 * @param event The ENet event containing the data
119 */
120 void HandleWifiPacket(const ENetEvent* event);
121
122 /**
123 * Extracts a chat entry from a received ENet packet and adds it to the chat queue.
124 * @param event The ENet event that was received.
125 */
126 void HandleChatPacket(const ENetEvent* event);
127
128 /**
129 * Extracts the game name from a received ENet packet and broadcasts it.
130 * @param event The ENet event that was received.
131 */
132 void HandleGameNamePacket(const ENetEvent* event);
133
134 /**
135 * Removes the client from the members list if it was in it and announces the change
136 * to all other clients.
137 */
138 void HandleClientDisconnection(ENetPeer* client);
139};
140
141// RoomImpl
142void Room::RoomImpl::ServerLoop() {
143 while (state != State::Closed) {
144 ENetEvent event;
145 if (enet_host_service(server, &event, 100) > 0) {
146 switch (event.type) {
147 case ENET_EVENT_TYPE_RECEIVE:
148 switch (event.packet->data[0]) {
149 case IdJoinRequest:
150 HandleJoinRequest(&event);
151 break;
152 case IdSetGameInfo:
153 HandleGameNamePacket(&event);
154 break;
155 case IdWifiPacket:
156 HandleWifiPacket(&event);
157 break;
158 case IdChatMessage:
159 HandleChatPacket(&event);
160 break;
161 }
162 enet_packet_destroy(event.packet);
163 break;
164 case ENET_EVENT_TYPE_DISCONNECT:
165 HandleClientDisconnection(event.peer);
166 break;
167 }
168 }
169 }
170 // Close the connection to all members:
171 SendCloseMessage();
172}
173
174void Room::RoomImpl::StartLoop() {
175 room_thread = std::make_unique<std::thread>(&Room::RoomImpl::ServerLoop, this);
176}
177
178void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) {
179 Packet packet;
180 packet.Append(event->packet->data, event->packet->dataLength);
181 packet.IgnoreBytes(sizeof(u8)); // Igonore the message type
182 std::string nickname;
183 packet >> nickname;
184
185 MacAddress preferred_mac;
186 packet >> preferred_mac;
187
188 u32 client_version;
189 packet >> client_version;
190
191 if (!IsValidNickname(nickname)) {
192 SendNameCollision(event->peer);
193 return;
194 }
195
196 if (preferred_mac != NoPreferredMac) {
197 // Verify if the preferred mac is available
198 if (!IsValidMacAddress(preferred_mac)) {
199 SendMacCollision(event->peer);
200 return;
201 }
202 } else {
203 // Assign a MAC address of this client automatically
204 preferred_mac = GenerateMacAddress();
205 }
206
207 if (client_version != network_version) {
208 SendVersionMismatch(event->peer);
209 return;
210 }
211
212 // At this point the client is ready to be added to the room.
213 Member member{};
214 member.mac_address = preferred_mac;
215 member.nickname = nickname;
216 member.peer = event->peer;
217
218 {
219 std::lock_guard<std::mutex> lock(member_mutex);
220 members.push_back(std::move(member));
221 }
222
223 // Notify everyone that the room information has changed.
224 BroadcastRoomInformation();
225 SendJoinSuccess(event->peer, preferred_mac);
226}
227
228bool Room::RoomImpl::IsValidNickname(const std::string& nickname) const {
229 // A nickname is valid if it is not already taken by anybody else in the room.
230 // TODO(B3N30): Check for empty names, spaces, etc.
231 std::lock_guard<std::mutex> lock(member_mutex);
232 return std::all_of(members.begin(), members.end(),
233 [&nickname](const auto& member) { return member.nickname != nickname; });
234}
235
236bool Room::RoomImpl::IsValidMacAddress(const MacAddress& address) const {
237 // A MAC address is valid if it is not already taken by anybody else in the room.
238 std::lock_guard<std::mutex> lock(member_mutex);
239 return std::all_of(members.begin(), members.end(),
240 [&address](const auto& member) { return member.mac_address != address; });
241}
242
243void Room::RoomImpl::SendNameCollision(ENetPeer* client) {
244 Packet packet;
245 packet << static_cast<u8>(IdNameCollision);
246
247 ENetPacket* enet_packet =
248 enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
249 enet_peer_send(client, 0, enet_packet);
250 enet_host_flush(server);
251}
252
253void Room::RoomImpl::SendMacCollision(ENetPeer* client) {
254 Packet packet;
255 packet << static_cast<u8>(IdMacCollision);
256
257 ENetPacket* enet_packet =
258 enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
259 enet_peer_send(client, 0, enet_packet);
260 enet_host_flush(server);
261}
262
263void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) {
264 Packet packet;
265 packet << static_cast<u8>(IdVersionMismatch);
266 packet << network_version;
267
268 ENetPacket* enet_packet =
269 enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
270 enet_peer_send(client, 0, enet_packet);
271 enet_host_flush(server);
272}
273
274void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) {
275 Packet packet;
276 packet << static_cast<u8>(IdJoinSuccess);
277 packet << mac_address;
278 ENetPacket* enet_packet =
279 enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
280 enet_peer_send(client, 0, enet_packet);
281 enet_host_flush(server);
282}
283
284void Room::RoomImpl::SendCloseMessage() {
285 Packet packet;
286 packet << static_cast<u8>(IdCloseRoom);
287 ENetPacket* enet_packet =
288 enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
289 std::lock_guard<std::mutex> lock(member_mutex);
290 for (auto& member : members) {
291 enet_peer_send(member.peer, 0, enet_packet);
292 }
293 enet_host_flush(server);
294 for (auto& member : members) {
295 enet_peer_disconnect(member.peer, 0);
296 }
297}
298
299void Room::RoomImpl::BroadcastRoomInformation() {
300 Packet packet;
301 packet << static_cast<u8>(IdRoomInformation);
302 packet << room_information.name;
303 packet << room_information.member_slots;
304
305 packet << static_cast<u32>(members.size());
306 {
307 std::lock_guard<std::mutex> lock(member_mutex);
308 for (const auto& member : members) {
309 packet << member.nickname;
310 packet << member.mac_address;
311 packet << member.game_info.name;
312 packet << member.game_info.id;
313 }
314 }
315
316 ENetPacket* enet_packet =
317 enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE);
318 enet_host_broadcast(server, 0, enet_packet);
319 enet_host_flush(server);
320}
321
322MacAddress Room::RoomImpl::GenerateMacAddress() {
323 MacAddress result_mac =
324 NintendoOUI; // The first three bytes of each MAC address will be the NintendoOUI
325 std::uniform_int_distribution<> dis(0x00, 0xFF); // Random byte between 0 and 0xFF
326 do {
327 for (size_t i = 3; i < result_mac.size(); ++i) {
328 result_mac[i] = dis(random_gen);
329 }
330 } while (!IsValidMacAddress(result_mac));
331 return result_mac;
332}
333
334void Room::RoomImpl::HandleWifiPacket(const ENetEvent* event) {
335 Packet in_packet;
336 in_packet.Append(event->packet->data, event->packet->dataLength);
337 in_packet.IgnoreBytes(sizeof(u8)); // Message type
338 in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Type
339 in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Channel
340 in_packet.IgnoreBytes(sizeof(MacAddress)); // WifiPacket Transmitter Address
341 MacAddress destination_address;
342 in_packet >> destination_address;
343
344 Packet out_packet;
345 out_packet.Append(event->packet->data, event->packet->dataLength);
346 ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(),
347 ENET_PACKET_FLAG_RELIABLE);
348
349 if (destination_address == BroadcastMac) { // Send the data to everyone except the sender
350 std::lock_guard<std::mutex> lock(member_mutex);
351 for (const auto& member : members) {
352 if (member.peer != event->peer)
353 enet_peer_send(member.peer, 0, enet_packet);
354 }
355 } else { // Send the data only to the destination client
356 std::lock_guard<std::mutex> lock(member_mutex);
357 auto member = std::find_if(members.begin(), members.end(),
358 [destination_address](const Member& member) -> bool {
359 return member.mac_address == destination_address;
360 });
361 if (member != members.end()) {
362 enet_peer_send(member->peer, 0, enet_packet);
363 }
364 }
365 enet_host_flush(server);
366}
367
368void Room::RoomImpl::HandleChatPacket(const ENetEvent* event) {
369 Packet in_packet;
370 in_packet.Append(event->packet->data, event->packet->dataLength);
371
372 in_packet.IgnoreBytes(sizeof(u8)); // Igonore the message type
373 std::string message;
374 in_packet >> message;
375 auto CompareNetworkAddress = [event](const Member member) -> bool {
376 return member.peer == event->peer;
377 };
378
379 std::lock_guard<std::mutex> lock(member_mutex);
380 const auto sending_member = std::find_if(members.begin(), members.end(), CompareNetworkAddress);
381 if (sending_member == members.end()) {
382 return; // Received a chat message from a unknown sender
383 }
384
385 Packet out_packet;
386 out_packet << static_cast<u8>(IdChatMessage);
387 out_packet << sending_member->nickname;
388 out_packet << message;
389
390 ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(),
391 ENET_PACKET_FLAG_RELIABLE);
392 for (const auto& member : members) {
393 if (member.peer != event->peer)
394 enet_peer_send(member.peer, 0, enet_packet);
395 }
396 enet_host_flush(server);
397}
398
399void Room::RoomImpl::HandleGameNamePacket(const ENetEvent* event) {
400 Packet in_packet;
401 in_packet.Append(event->packet->data, event->packet->dataLength);
402
403 in_packet.IgnoreBytes(sizeof(u8)); // Igonore the message type
404 GameInfo game_info;
405 in_packet >> game_info.name;
406 in_packet >> game_info.id;
407
408 {
409 std::lock_guard<std::mutex> lock(member_mutex);
410 auto member =
411 std::find_if(members.begin(), members.end(), [event](const Member& member) -> bool {
412 return member.peer == event->peer;
413 });
414 if (member != members.end()) {
415 member->game_info = game_info;
416 }
417 }
418 BroadcastRoomInformation();
419}
420
421void Room::RoomImpl::HandleClientDisconnection(ENetPeer* client) {
422 // Remove the client from the members list.
423 {
424 std::lock_guard<std::mutex> lock(member_mutex);
425 members.erase(
426 std::remove_if(members.begin(), members.end(),
427 [client](const Member& member) { return member.peer == client; }),
428 members.end());
429 }
430
431 // Announce the change to all clients.
432 enet_peer_disconnect(client, 0);
433 BroadcastRoomInformation();
434}
435
436// Room
437Room::Room() : room_impl{std::make_unique<RoomImpl>()} {}
438
439Room::~Room() = default;
440
441void Room::Create(const std::string& name, const std::string& server_address, u16 server_port) {
442 ENetAddress address;
443 address.host = ENET_HOST_ANY;
444 if (!server_address.empty()) {
445 enet_address_set_host(&address, server_address.c_str());
446 }
447 address.port = server_port;
448
449 room_impl->server = enet_host_create(&address, MaxConcurrentConnections, NumChannels, 0, 0);
450 // TODO(B3N30): Allow specifying the maximum number of concurrent connections.
451 room_impl->state = State::Open;
452
453 room_impl->room_information.name = name;
454 room_impl->room_information.member_slots = MaxConcurrentConnections;
455 room_impl->StartLoop();
456}
457
458Room::State Room::GetState() const {
459 return room_impl->state;
460}
461
462const RoomInformation& Room::GetRoomInformation() const {
463 return room_impl->room_information;
464}
465
466std::vector<Room::Member> Room::GetRoomMemberList() const {
467 std::vector<Room::Member> member_list;
468 std::lock_guard<std::mutex> lock(room_impl->member_mutex);
469 for (const auto& member_impl : room_impl->members) {
470 Member member;
471 member.nickname = member_impl.nickname;
472 member.mac_address = member_impl.mac_address;
473 member.game_info = member_impl.game_info;
474 member_list.push_back(member);
475 }
476 return member_list;
477};
478
479void Room::Destroy() {
480 room_impl->state = State::Closed;
481 room_impl->room_thread->join();
482 room_impl->room_thread.reset();
483
484 if (room_impl->server) {
485 enet_host_destroy(room_impl->server);
486 }
487 room_impl->room_information = {};
488 room_impl->server = nullptr;
489 {
490 std::lock_guard<std::mutex> lock(room_impl->member_mutex);
491 room_impl->members.clear();
492 }
493 room_impl->room_information.member_slots = 0;
494 room_impl->room_information.name.clear();
495}
496
497} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <memory>
9#include <string>
10#include <vector>
11#include "common/common_types.h"
12
13namespace Network {
14
15constexpr u32 network_version = 1; ///< The version of this Room and RoomMember
16
17constexpr u16 DefaultRoomPort = 1234;
18constexpr size_t NumChannels = 1; // Number of channels used for the connection
19
20struct RoomInformation {
21 std::string name; ///< Name of the server
22 u32 member_slots; ///< Maximum number of members in this room
23};
24
25struct GameInfo {
26 std::string name{""};
27 u64 id{0};
28};
29
30using MacAddress = std::array<u8, 6>;
31/// A special MAC address that tells the room we're joining to assign us a MAC address
32/// automatically.
33constexpr MacAddress NoPreferredMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
34
35// 802.11 broadcast MAC address
36constexpr MacAddress BroadcastMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
37
38// The different types of messages that can be sent. The first byte of each packet defines the type
39enum RoomMessageTypes : u8 {
40 IdJoinRequest = 1,
41 IdJoinSuccess,
42 IdRoomInformation,
43 IdSetGameInfo,
44 IdWifiPacket,
45 IdChatMessage,
46 IdNameCollision,
47 IdMacCollision,
48 IdVersionMismatch,
49 IdCloseRoom
50};
51
52/// This is what a server [person creating a server] would use.
53class Room final {
54public:
55 enum class State : u8 {
56 Open, ///< The room is open and ready to accept connections.
57 Closed, ///< The room is not opened and can not accept connections.
58 };
59
60 struct Member {
61 std::string nickname; ///< The nickname of the member.
62 GameInfo game_info; ///< The current game of the member
63 MacAddress mac_address; ///< The assigned mac address of the member.
64 };
65
66 Room();
67 ~Room();
68
69 /**
70 * Gets the current state of the room.
71 */
72 State GetState() const;
73
74 /**
75 * Gets the room information of the room.
76 */
77 const RoomInformation& GetRoomInformation() const;
78
79 /**
80 * Gets a list of the mbmers connected to the room.
81 */
82 std::vector<Member> GetRoomMemberList() const;
83
84 /**
85 * Creates the socket for this room. Will bind to default address if
86 * server is empty string.
87 */
88 void Create(const std::string& name, const std::string& server = "",
89 u16 server_port = DefaultRoomPort);
90
91 /**
92 * Destroys the socket
93 */
94 void Destroy();
95
96private:
97 class RoomImpl;
98 std::unique_ptr<RoomImpl> room_impl;
99};
100
101} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <atomic>
6#include <list>
7#include <mutex>
8#include <set>
9#include <thread>
10#include "common/assert.h"
11#include "enet/enet.h"
12#include "network/packet.h"
13#include "network/room_member.h"
14
15namespace Network {
16
17constexpr u32 ConnectionTimeoutMs = 5000;
18
19class RoomMember::RoomMemberImpl {
20public:
21 ENetHost* client = nullptr; ///< ENet network interface.
22 ENetPeer* server = nullptr; ///< The server peer the client is connected to
23
24 /// Information about the clients connected to the same room as us.
25 MemberList member_information;
26 /// Information about the room we're connected to.
27 RoomInformation room_information;
28
29 /// The current game name, id and version
30 GameInfo current_game_info;
31
32 std::atomic<State> state{State::Idle}; ///< Current state of the RoomMember.
33 void SetState(const State new_state);
34 bool IsConnected() const;
35
36 std::string nickname; ///< The nickname of this member.
37 MacAddress mac_address; ///< The mac_address of this member.
38
39 std::mutex network_mutex; ///< Mutex that controls access to the `client` variable.
40 /// Thread that receives and dispatches network packets
41 std::unique_ptr<std::thread> loop_thread;
42 std::mutex send_list_mutex; ///< Mutex that controls access to the `send_list` variable.
43 std::list<Packet> send_list; ///< A list that stores all packets to send the async
44
45 template <typename T>
46 using CallbackSet = std::set<CallbackHandle<T>>;
47 std::mutex callback_mutex; ///< The mutex used for handling callbacks
48
49 class Callbacks {
50 public:
51 template <typename T>
52 CallbackSet<T>& Get();
53
54 private:
55 CallbackSet<WifiPacket> callback_set_wifi_packet;
56 CallbackSet<ChatEntry> callback_set_chat_messages;
57 CallbackSet<RoomInformation> callback_set_room_information;
58 CallbackSet<State> callback_set_state;
59 };
60 Callbacks callbacks; ///< All CallbackSets to all events
61
62 void MemberLoop();
63
64 void StartLoop();
65
66 /**
67 * Sends data to the room. It will be send on channel 0 with flag RELIABLE
68 * @param packet The data to send
69 */
70 void Send(Packet&& packet);
71
72 /**
73 * Sends a request to the server, asking for permission to join a room with the specified
74 * nickname and preferred mac.
75 * @params nickname The desired nickname.
76 * @params preferred_mac The preferred MAC address to use in the room, the NoPreferredMac tells
77 * the server to assign one for us.
78 */
79 void SendJoinRequest(const std::string& nickname,
80 const MacAddress& preferred_mac = NoPreferredMac);
81
82 /**
83 * Extracts a MAC Address from a received ENet packet.
84 * @param event The ENet event that was received.
85 */
86 void HandleJoinPacket(const ENetEvent* event);
87 /**
88 * Extracts RoomInformation and MemberInformation from a received RakNet packet.
89 * @param event The ENet event that was received.
90 */
91 void HandleRoomInformationPacket(const ENetEvent* event);
92
93 /**
94 * Extracts a WifiPacket from a received ENet packet.
95 * @param event The ENet event that was received.
96 */
97 void HandleWifiPackets(const ENetEvent* event);
98
99 /**
100 * Extracts a chat entry from a received ENet packet and adds it to the chat queue.
101 * @param event The ENet event that was received.
102 */
103 void HandleChatPacket(const ENetEvent* event);
104
105 /**
106 * Disconnects the RoomMember from the Room
107 */
108 void Disconnect();
109
110 template <typename T>
111 void Invoke(const T& data);
112
113 template <typename T>
114 CallbackHandle<T> Bind(std::function<void(const T&)> callback);
115};
116
117// RoomMemberImpl
118void RoomMember::RoomMemberImpl::SetState(const State new_state) {
119 if (state != new_state) {
120 state = new_state;
121 Invoke<State>(state);
122 }
123}
124
125bool RoomMember::RoomMemberImpl::IsConnected() const {
126 return state == State::Joining || state == State::Joined;
127}
128
129void RoomMember::RoomMemberImpl::MemberLoop() {
130 // Receive packets while the connection is open
131 while (IsConnected()) {
132 std::lock_guard<std::mutex> lock(network_mutex);
133 ENetEvent event;
134 if (enet_host_service(client, &event, 100) > 0) {
135 switch (event.type) {
136 case ENET_EVENT_TYPE_RECEIVE:
137 switch (event.packet->data[0]) {
138 case IdWifiPacket:
139 HandleWifiPackets(&event);
140 break;
141 case IdChatMessage:
142 HandleChatPacket(&event);
143 break;
144 case IdRoomInformation:
145 HandleRoomInformationPacket(&event);
146 break;
147 case IdJoinSuccess:
148 // The join request was successful, we are now in the room.
149 // If we joined successfully, there must be at least one client in the room: us.
150 ASSERT_MSG(member_information.size() > 0,
151 "We have not yet received member information.");
152 HandleJoinPacket(&event); // Get the MAC Address for the client
153 SetState(State::Joined);
154 break;
155 case IdNameCollision:
156 SetState(State::NameCollision);
157 break;
158 case IdMacCollision:
159 SetState(State::MacCollision);
160 break;
161 case IdVersionMismatch:
162 SetState(State::WrongVersion);
163 break;
164 case IdCloseRoom:
165 SetState(State::LostConnection);
166 break;
167 }
168 enet_packet_destroy(event.packet);
169 break;
170 case ENET_EVENT_TYPE_DISCONNECT:
171 SetState(State::LostConnection);
172 break;
173 }
174 }
175 {
176 std::lock_guard<std::mutex> lock(send_list_mutex);
177 for (const auto& packet : send_list) {
178 ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetDataSize(),
179 ENET_PACKET_FLAG_RELIABLE);
180 enet_peer_send(server, 0, enetPacket);
181 }
182 enet_host_flush(client);
183 send_list.clear();
184 }
185 }
186 Disconnect();
187};
188
189void RoomMember::RoomMemberImpl::StartLoop() {
190 loop_thread = std::make_unique<std::thread>(&RoomMember::RoomMemberImpl::MemberLoop, this);
191}
192
193void RoomMember::RoomMemberImpl::Send(Packet&& packet) {
194 std::lock_guard<std::mutex> lock(send_list_mutex);
195 send_list.push_back(std::move(packet));
196}
197
198void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname,
199 const MacAddress& preferred_mac) {
200 Packet packet;
201 packet << static_cast<u8>(IdJoinRequest);
202 packet << nickname;
203 packet << preferred_mac;
204 packet << network_version;
205 Send(std::move(packet));
206}
207
208void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* event) {
209 Packet packet;
210 packet.Append(event->packet->data, event->packet->dataLength);
211
212 // Ignore the first byte, which is the message id.
213 packet.IgnoreBytes(sizeof(u8)); // Igonore the message type
214
215 RoomInformation info{};
216 packet >> info.name;
217 packet >> info.member_slots;
218 room_information.name = info.name;
219 room_information.member_slots = info.member_slots;
220
221 u32 num_members;
222 packet >> num_members;
223 member_information.resize(num_members);
224
225 for (auto& member : member_information) {
226 packet >> member.nickname;
227 packet >> member.mac_address;
228 packet >> member.game_info.name;
229 packet >> member.game_info.id;
230 }
231 Invoke(room_information);
232}
233
234void RoomMember::RoomMemberImpl::HandleJoinPacket(const ENetEvent* event) {
235 Packet packet;
236 packet.Append(event->packet->data, event->packet->dataLength);
237
238 // Ignore the first byte, which is the message id.
239 packet.IgnoreBytes(sizeof(u8)); // Igonore the message type
240
241 // Parse the MAC Address from the packet
242 packet >> mac_address;
243 SetState(State::Joined);
244}
245
246void RoomMember::RoomMemberImpl::HandleWifiPackets(const ENetEvent* event) {
247 WifiPacket wifi_packet{};
248 Packet packet;
249 packet.Append(event->packet->data, event->packet->dataLength);
250
251 // Ignore the first byte, which is the message id.
252 packet.IgnoreBytes(sizeof(u8)); // Igonore the message type
253
254 // Parse the WifiPacket from the packet
255 u8 frame_type;
256 packet >> frame_type;
257 WifiPacket::PacketType type = static_cast<WifiPacket::PacketType>(frame_type);
258
259 wifi_packet.type = type;
260 packet >> wifi_packet.channel;
261 packet >> wifi_packet.transmitter_address;
262 packet >> wifi_packet.destination_address;
263
264 u32 data_length;
265 packet >> data_length;
266
267 packet >> wifi_packet.data;
268
269 Invoke<WifiPacket>(wifi_packet);
270}
271
272void RoomMember::RoomMemberImpl::HandleChatPacket(const ENetEvent* event) {
273 Packet packet;
274 packet.Append(event->packet->data, event->packet->dataLength);
275
276 // Ignore the first byte, which is the message id.
277 packet.IgnoreBytes(sizeof(u8));
278
279 ChatEntry chat_entry{};
280 packet >> chat_entry.nickname;
281 packet >> chat_entry.message;
282 Invoke<ChatEntry>(chat_entry);
283}
284
285void RoomMember::RoomMemberImpl::Disconnect() {
286 member_information.clear();
287 room_information.member_slots = 0;
288 room_information.name.clear();
289
290 if (!server)
291 return;
292 enet_peer_disconnect(server, 0);
293
294 ENetEvent event;
295 while (enet_host_service(client, &event, ConnectionTimeoutMs) > 0) {
296 switch (event.type) {
297 case ENET_EVENT_TYPE_RECEIVE:
298 enet_packet_destroy(event.packet); // Ignore all incoming data
299 break;
300 case ENET_EVENT_TYPE_DISCONNECT:
301 server = nullptr;
302 return;
303 }
304 }
305 // didn't disconnect gracefully force disconnect
306 enet_peer_reset(server);
307 server = nullptr;
308}
309
310template <>
311RoomMember::RoomMemberImpl::CallbackSet<WifiPacket>& RoomMember::RoomMemberImpl::Callbacks::Get() {
312 return callback_set_wifi_packet;
313}
314
315template <>
316RoomMember::RoomMemberImpl::CallbackSet<RoomMember::State>&
317RoomMember::RoomMemberImpl::Callbacks::Get() {
318 return callback_set_state;
319}
320
321template <>
322RoomMember::RoomMemberImpl::CallbackSet<RoomInformation>&
323RoomMember::RoomMemberImpl::Callbacks::Get() {
324 return callback_set_room_information;
325}
326
327template <>
328RoomMember::RoomMemberImpl::CallbackSet<ChatEntry>& RoomMember::RoomMemberImpl::Callbacks::Get() {
329 return callback_set_chat_messages;
330}
331
332template <typename T>
333void RoomMember::RoomMemberImpl::Invoke(const T& data) {
334 std::lock_guard<std::mutex> lock(callback_mutex);
335 CallbackSet<T> callback_set = callbacks.Get<T>();
336 for (auto const& callback : callback_set)
337 (*callback)(data);
338}
339
340template <typename T>
341RoomMember::CallbackHandle<T> RoomMember::RoomMemberImpl::Bind(
342 std::function<void(const T&)> callback) {
343 std::lock_guard<std::mutex> lock(callback_mutex);
344 CallbackHandle<T> handle;
345 handle = std::make_shared<std::function<void(const T&)>>(callback);
346 callbacks.Get<T>().insert(handle);
347 return handle;
348}
349
350// RoomMember
351RoomMember::RoomMember() : room_member_impl{std::make_unique<RoomMemberImpl>()} {
352 room_member_impl->client = enet_host_create(nullptr, 1, NumChannels, 0, 0);
353 ASSERT_MSG(room_member_impl->client != nullptr, "Could not create client");
354}
355
356RoomMember::~RoomMember() {
357 ASSERT_MSG(!IsConnected(), "RoomMember is being destroyed while connected");
358 enet_host_destroy(room_member_impl->client);
359}
360
361RoomMember::State RoomMember::GetState() const {
362 return room_member_impl->state;
363}
364
365const RoomMember::MemberList& RoomMember::GetMemberInformation() const {
366 return room_member_impl->member_information;
367}
368
369const std::string& RoomMember::GetNickname() const {
370 return room_member_impl->nickname;
371}
372
373const MacAddress& RoomMember::GetMacAddress() const {
374 ASSERT_MSG(IsConnected(), "Tried to get MAC address while not connected");
375 return room_member_impl->mac_address;
376}
377
378RoomInformation RoomMember::GetRoomInformation() const {
379 return room_member_impl->room_information;
380}
381
382void RoomMember::Join(const std::string& nick, const char* server_addr, u16 server_port,
383 u16 client_port, const MacAddress& preferred_mac) {
384 // If the member is connected, kill the connection first
385 if (room_member_impl->loop_thread && room_member_impl->loop_thread->joinable()) {
386 room_member_impl->SetState(State::Error);
387 room_member_impl->loop_thread->join();
388 room_member_impl->loop_thread.reset();
389 }
390 // If the thread isn't running but the ptr still exists, reset it
391 else if (room_member_impl->loop_thread) {
392 room_member_impl->loop_thread.reset();
393 }
394
395 ENetAddress address{};
396 enet_address_set_host(&address, server_addr);
397 address.port = server_port;
398 room_member_impl->server =
399 enet_host_connect(room_member_impl->client, &address, NumChannels, 0);
400
401 if (!room_member_impl->server) {
402 room_member_impl->SetState(State::Error);
403 return;
404 }
405
406 ENetEvent event{};
407 int net = enet_host_service(room_member_impl->client, &event, ConnectionTimeoutMs);
408 if (net > 0 && event.type == ENET_EVENT_TYPE_CONNECT) {
409 room_member_impl->nickname = nick;
410 room_member_impl->SetState(State::Joining);
411 room_member_impl->StartLoop();
412 room_member_impl->SendJoinRequest(nick, preferred_mac);
413 SendGameInfo(room_member_impl->current_game_info);
414 } else {
415 room_member_impl->SetState(State::CouldNotConnect);
416 }
417}
418
419bool RoomMember::IsConnected() const {
420 return room_member_impl->IsConnected();
421}
422
423void RoomMember::SendWifiPacket(const WifiPacket& wifi_packet) {
424 Packet packet;
425 packet << static_cast<u8>(IdWifiPacket);
426 packet << static_cast<u8>(wifi_packet.type);
427 packet << wifi_packet.channel;
428 packet << wifi_packet.transmitter_address;
429 packet << wifi_packet.destination_address;
430 packet << wifi_packet.data;
431 room_member_impl->Send(std::move(packet));
432}
433
434void RoomMember::SendChatMessage(const std::string& message) {
435 Packet packet;
436 packet << static_cast<u8>(IdChatMessage);
437 packet << message;
438 room_member_impl->Send(std::move(packet));
439}
440
441void RoomMember::SendGameInfo(const GameInfo& game_info) {
442 room_member_impl->current_game_info = game_info;
443 if (!IsConnected())
444 return;
445
446 Packet packet;
447 packet << static_cast<u8>(IdSetGameInfo);
448 packet << game_info.name;
449 packet << game_info.id;
450 room_member_impl->Send(std::move(packet));
451}
452
453RoomMember::CallbackHandle<RoomMember::State> RoomMember::BindOnStateChanged(
454 std::function<void(const RoomMember::State&)> callback) {
455 return room_member_impl->Bind(callback);
456}
457
458RoomMember::CallbackHandle<WifiPacket> RoomMember::BindOnWifiPacketReceived(
459 std::function<void(const WifiPacket&)> callback) {
460 return room_member_impl->Bind(callback);
461}
462
463RoomMember::CallbackHandle<RoomInformation> RoomMember::BindOnRoomInformationChanged(
464 std::function<void(const RoomInformation&)> callback) {
465 return room_member_impl->Bind(callback);
466}
467
468RoomMember::CallbackHandle<ChatEntry> RoomMember::BindOnChatMessageRecieved(
469 std::function<void(const ChatEntry&)> callback) {
470 return room_member_impl->Bind(callback);
471}
472
473template <typename T>
474void RoomMember::Unbind(CallbackHandle<T> handle) {
475 std::lock_guard<std::mutex> lock(room_member_impl->callback_mutex);
476 room_member_impl->callbacks.Get<T>().erase(handle);
477}
478
479void RoomMember::Leave() {
480 room_member_impl->SetState(State::Idle);
481 room_member_impl->loop_thread->join();
482 room_member_impl->loop_thread.reset();
483}
484
485template void RoomMember::Unbind(CallbackHandle<WifiPacket>);
486template void RoomMember::Unbind(CallbackHandle<RoomMember::State>);
487template void RoomMember::Unbind(CallbackHandle<RoomInformation>);
488template void RoomMember::Unbind(CallbackHandle<ChatEntry>);
489
490} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <memory>
9#include <string>
10#include <vector>
11#include "common/common_types.h"
12#include "network/room.h"
13
14namespace Network {
15
16/// Information about the received WiFi packets.
17/// Acts as our own 802.11 header.
18struct WifiPacket {
19 enum class PacketType : u8 { Beacon, Data, Authentication, AssociationResponse };
20 PacketType type; ///< The type of 802.11 frame.
21 std::vector<u8> data; ///< Raw 802.11 frame data, starting at the management frame header
22 /// for management frames.
23 MacAddress transmitter_address; ///< Mac address of the transmitter.
24 MacAddress destination_address; ///< Mac address of the receiver.
25 u8 channel; ///< WiFi channel where this frame was transmitted.
26};
27
28/// Represents a chat message.
29struct ChatEntry {
30 std::string nickname; ///< Nickname of the client who sent this message.
31 std::string message; ///< Body of the message.
32};
33
34/**
35 * This is what a client [person joining a server] would use.
36 * It also has to be used if you host a game yourself (You'd create both, a Room and a
37 * RoomMembership for yourself)
38 */
39class RoomMember final {
40public:
41 enum class State : u8 {
42 Idle, ///< Default state
43 Error, ///< Some error [permissions to network device missing or something]
44 Joining, ///< The client is attempting to join a room.
45 Joined, ///< The client is connected to the room and is ready to send/receive packets.
46 LostConnection, ///< Connection closed
47
48 // Reasons why connection was rejected
49 NameCollision, ///< Somebody is already using this name
50 MacCollision, ///< Somebody is already using that mac-address
51 WrongVersion, ///< The room version is not the same as for this RoomMember
52 CouldNotConnect ///< The room is not responding to a connection attempt
53 };
54
55 struct MemberInformation {
56 std::string nickname; ///< Nickname of the member.
57 GameInfo game_info; ///< Name of the game they're currently playing, or empty if they're
58 /// not playing anything.
59 MacAddress mac_address; ///< MAC address associated with this member.
60 };
61 using MemberList = std::vector<MemberInformation>;
62
63 // The handle for the callback functions
64 template <typename T>
65 using CallbackHandle = std::shared_ptr<std::function<void(const T&)>>;
66
67 /**
68 * Unbinds a callback function from the events.
69 * @param handle The connection handle to disconnect
70 */
71 template <typename T>
72 void Unbind(CallbackHandle<T> handle);
73
74 RoomMember();
75 ~RoomMember();
76
77 /**
78 * Returns the status of our connection to the room.
79 */
80 State GetState() const;
81
82 /**
83 * Returns information about the members in the room we're currently connected to.
84 */
85 const MemberList& GetMemberInformation() const;
86
87 /**
88 * Returns the nickname of the RoomMember.
89 */
90 const std::string& GetNickname() const;
91
92 /**
93 * Returns the MAC address of the RoomMember.
94 */
95 const MacAddress& GetMacAddress() const;
96
97 /**
98 * Returns information about the room we're currently connected to.
99 */
100 RoomInformation GetRoomInformation() const;
101
102 /**
103 * Returns whether we're connected to a server or not.
104 */
105 bool IsConnected() const;
106
107 /**
108 * Attempts to join a room at the specified address and port, using the specified nickname.
109 * This may fail if the username is already taken.
110 */
111 void Join(const std::string& nickname, const char* server_addr = "127.0.0.1",
112 const u16 serverPort = DefaultRoomPort, const u16 clientPort = 0,
113 const MacAddress& preferred_mac = NoPreferredMac);
114
115 /**
116 * Sends a WiFi packet to the room.
117 * @param packet The WiFi packet to send.
118 */
119 void SendWifiPacket(const WifiPacket& packet);
120
121 /**
122 * Sends a chat message to the room.
123 * @param message The contents of the message.
124 */
125 void SendChatMessage(const std::string& message);
126
127 /**
128 * Sends the current game info to the room.
129 * @param game_info The game information.
130 */
131 void SendGameInfo(const GameInfo& game_info);
132
133 /**
134 * Binds a function to an event that will be triggered every time the State of the member
135 * changed. The function wil be called every time the event is triggered. The callback function
136 * must not bind or unbind a function. Doing so will cause a deadlock
137 * @param callback The function to call
138 * @return A handle used for removing the function from the registered list
139 */
140 CallbackHandle<State> BindOnStateChanged(std::function<void(const State&)> callback);
141
142 /**
143 * Binds a function to an event that will be triggered every time a WifiPacket is received.
144 * The function wil be called everytime the event is triggered.
145 * The callback function must not bind or unbind a function. Doing so will cause a deadlock
146 * @param callback The function to call
147 * @return A handle used for removing the function from the registered list
148 */
149 CallbackHandle<WifiPacket> BindOnWifiPacketReceived(
150 std::function<void(const WifiPacket&)> callback);
151
152 /**
153 * Binds a function to an event that will be triggered every time the RoomInformation changes.
154 * The function wil be called every time the event is triggered.
155 * The callback function must not bind or unbind a function. Doing so will cause a deadlock
156 * @param callback The function to call
157 * @return A handle used for removing the function from the registered list
158 */
159 CallbackHandle<RoomInformation> BindOnRoomInformationChanged(
160 std::function<void(const RoomInformation&)> callback);
161
162 /**
163 * Binds a function to an event that will be triggered every time a ChatMessage is received.
164 * The function wil be called every time the event is triggered.
165 * The callback function must not bind or unbind a function. Doing so will cause a deadlock
166 * @param callback The function to call
167 * @return A handle used for removing the function from the registered list
168 */
169 CallbackHandle<ChatEntry> BindOnChatMessageRecieved(
170 std::function<void(const ChatEntry&)> callback);
171
172 /**
173 * Leaves the current room.
174 */
175 void Leave();
176
177private:
178 class RoomMemberImpl;
179 std::unique_ptr<RoomMemberImpl> room_member_impl;
180};
181
182} // 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 @@
1set(SRCS
2 telemetry_json.cpp
3 verify_login.cpp
4 web_backend.cpp
5 )
6
7set(HEADERS
8 telemetry_json.h
9 verify_login.h
10 web_backend.h
11 )
12
13create_directory_groups(${SRCS} ${HEADERS})
14
15add_library(web_service STATIC ${SRCS} ${HEADERS})
16target_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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include "common/assert.h"
6#include "web_service/telemetry_json.h"
7#include "web_service/web_backend.h"
8
9namespace WebService {
10
11template <class T>
12void TelemetryJson::Serialize(Telemetry::FieldType type, const std::string& name, T value) {
13 sections[static_cast<u8>(type)][name] = value;
14}
15
16void TelemetryJson::SerializeSection(Telemetry::FieldType type, const std::string& name) {
17 TopSection()[name] = sections[static_cast<unsigned>(type)];
18}
19
20void TelemetryJson::Visit(const Telemetry::Field<bool>& field) {
21 Serialize(field.GetType(), field.GetName(), field.GetValue());
22}
23
24void TelemetryJson::Visit(const Telemetry::Field<double>& field) {
25 Serialize(field.GetType(), field.GetName(), field.GetValue());
26}
27
28void TelemetryJson::Visit(const Telemetry::Field<float>& field) {
29 Serialize(field.GetType(), field.GetName(), field.GetValue());
30}
31
32void TelemetryJson::Visit(const Telemetry::Field<u8>& field) {
33 Serialize(field.GetType(), field.GetName(), field.GetValue());
34}
35
36void TelemetryJson::Visit(const Telemetry::Field<u16>& field) {
37 Serialize(field.GetType(), field.GetName(), field.GetValue());
38}
39
40void TelemetryJson::Visit(const Telemetry::Field<u32>& field) {
41 Serialize(field.GetType(), field.GetName(), field.GetValue());
42}
43
44void TelemetryJson::Visit(const Telemetry::Field<u64>& field) {
45 Serialize(field.GetType(), field.GetName(), field.GetValue());
46}
47
48void TelemetryJson::Visit(const Telemetry::Field<s8>& field) {
49 Serialize(field.GetType(), field.GetName(), field.GetValue());
50}
51
52void TelemetryJson::Visit(const Telemetry::Field<s16>& field) {
53 Serialize(field.GetType(), field.GetName(), field.GetValue());
54}
55
56void TelemetryJson::Visit(const Telemetry::Field<s32>& field) {
57 Serialize(field.GetType(), field.GetName(), field.GetValue());
58}
59
60void TelemetryJson::Visit(const Telemetry::Field<s64>& field) {
61 Serialize(field.GetType(), field.GetName(), field.GetValue());
62}
63
64void TelemetryJson::Visit(const Telemetry::Field<std::string>& field) {
65 Serialize(field.GetType(), field.GetName(), field.GetValue());
66}
67
68void TelemetryJson::Visit(const Telemetry::Field<const char*>& field) {
69 Serialize(field.GetType(), field.GetName(), std::string(field.GetValue()));
70}
71
72void TelemetryJson::Visit(const Telemetry::Field<std::chrono::microseconds>& field) {
73 Serialize(field.GetType(), field.GetName(), field.GetValue().count());
74}
75
76void TelemetryJson::Complete() {
77 SerializeSection(Telemetry::FieldType::App, "App");
78 SerializeSection(Telemetry::FieldType::Session, "Session");
79 SerializeSection(Telemetry::FieldType::Performance, "Performance");
80 SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback");
81 SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig");
82 SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem");
83 PostJson(endpoint_url, TopSection().dump(), true, username, token);
84}
85
86} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8#include <string>
9#include <json.hpp>
10#include "common/telemetry.h"
11
12namespace WebService {
13
14/**
15 * Implementation of VisitorInterface that serialized telemetry into JSON, and submits it to the
16 * Citra web service
17 */
18class TelemetryJson : public Telemetry::VisitorInterface {
19public:
20 TelemetryJson(const std::string& endpoint_url, const std::string& username,
21 const std::string& token)
22 : endpoint_url(endpoint_url), username(username), token(token) {}
23 ~TelemetryJson() = default;
24
25 void Visit(const Telemetry::Field<bool>& field) override;
26 void Visit(const Telemetry::Field<double>& field) override;
27 void Visit(const Telemetry::Field<float>& field) override;
28 void Visit(const Telemetry::Field<u8>& field) override;
29 void Visit(const Telemetry::Field<u16>& field) override;
30 void Visit(const Telemetry::Field<u32>& field) override;
31 void Visit(const Telemetry::Field<u64>& field) override;
32 void Visit(const Telemetry::Field<s8>& field) override;
33 void Visit(const Telemetry::Field<s16>& field) override;
34 void Visit(const Telemetry::Field<s32>& field) override;
35 void Visit(const Telemetry::Field<s64>& field) override;
36 void Visit(const Telemetry::Field<std::string>& field) override;
37 void Visit(const Telemetry::Field<const char*>& field) override;
38 void Visit(const Telemetry::Field<std::chrono::microseconds>& field) override;
39
40 void Complete() override;
41
42private:
43 nlohmann::json& TopSection() {
44 return sections[static_cast<u8>(Telemetry::FieldType::None)];
45 }
46
47 template <class T>
48 void Serialize(Telemetry::FieldType type, const std::string& name, T value);
49
50 void SerializeSection(Telemetry::FieldType type, const std::string& name);
51
52 nlohmann::json output;
53 std::array<nlohmann::json, 7> sections;
54 std::string endpoint_url;
55 std::string username;
56 std::string token;
57};
58
59} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#include <json.hpp>
6#include "web_service/verify_login.h"
7#include "web_service/web_backend.h"
8
9namespace WebService {
10
11std::future<bool> VerifyLogin(std::string& username, std::string& token,
12 const std::string& endpoint_url, std::function<void()> func) {
13 auto get_func = [func, username](const std::string& reply) -> bool {
14 func();
15 if (reply.empty())
16 return false;
17 nlohmann::json json = nlohmann::json::parse(reply);
18 std::string result;
19 try {
20 result = json["username"];
21 } catch (const nlohmann::detail::out_of_range&) {
22 }
23 return result == username;
24 };
25 return GetJson<bool>(get_func, endpoint_url, false, username, token);
26}
27
28} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <future>
9#include <string>
10
11namespace WebService {
12
13/**
14 * Checks if username and token is valid
15 * @param username Citra username to use for authentication.
16 * @param token Citra token to use for authentication.
17 * @param endpoint_url URL of the services.citra-emu.org endpoint.
18 * @param func A function that gets exectued when the verification is finished
19 * @returns Future with bool indicating whether the verification succeeded
20 */
21std::future<bool> VerifyLogin(std::string& username, std::string& token,
22 const std::string& endpoint_url, std::function<void()> func);
23
24} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#ifdef _WIN32
6#include <winsock.h>
7#endif
8
9#include <cstdlib>
10#include <thread>
11#include <cpr/cpr.h>
12#include "common/logging/log.h"
13#include "web_service/web_backend.h"
14
15namespace WebService {
16
17static constexpr char API_VERSION[]{"1"};
18
19static std::unique_ptr<cpr::Session> g_session;
20
21void Win32WSAStartup() {
22#ifdef _WIN32
23 // On Windows, CPR/libcurl does not properly initialize Winsock. The below code is used to
24 // initialize Winsock globally, which fixes this problem. Without this, only the first CPR
25 // session will properly be created, and subsequent ones will fail.
26 WSADATA wsa_data;
27 const int wsa_result{WSAStartup(MAKEWORD(2, 2), &wsa_data)};
28 if (wsa_result) {
29 LOG_CRITICAL(WebService, "WSAStartup failed: %d", wsa_result);
30 }
31#endif
32}
33
34void PostJson(const std::string& url, const std::string& data, bool allow_anonymous,
35 const std::string& username, const std::string& token) {
36 if (url.empty()) {
37 LOG_ERROR(WebService, "URL is invalid");
38 return;
39 }
40
41 const bool are_credentials_provided{!token.empty() && !username.empty()};
42 if (!allow_anonymous && !are_credentials_provided) {
43 LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
44 return;
45 }
46
47 Win32WSAStartup();
48
49 // Built request header
50 cpr::Header header;
51 if (are_credentials_provided) {
52 // Authenticated request if credentials are provided
53 header = {{"Content-Type", "application/json"},
54 {"x-username", username.c_str()},
55 {"x-token", token.c_str()},
56 {"api-version", API_VERSION}};
57 } else {
58 // Otherwise, anonymous request
59 header = cpr::Header{{"Content-Type", "application/json"}, {"api-version", API_VERSION}};
60 }
61
62 // Post JSON asynchronously
63 static std::future<void> future;
64 future = cpr::PostCallback(
65 [](cpr::Response r) {
66 if (r.error) {
67 LOG_ERROR(WebService, "POST returned cpr error: %u:%s",
68 static_cast<u32>(r.error.code), r.error.message.c_str());
69 return;
70 }
71 if (r.status_code >= 400) {
72 LOG_ERROR(WebService, "POST returned error status code: %u", r.status_code);
73 return;
74 }
75 if (r.header["content-type"].find("application/json") == std::string::npos) {
76 LOG_ERROR(WebService, "POST returned wrong content: %s",
77 r.header["content-type"].c_str());
78 return;
79 }
80 },
81 cpr::Url{url}, cpr::Body{data}, header);
82}
83
84template <typename T>
85std::future<T> GetJson(std::function<T(const std::string&)> func, const std::string& url,
86 bool allow_anonymous, const std::string& username,
87 const std::string& token) {
88 if (url.empty()) {
89 LOG_ERROR(WebService, "URL is invalid");
90 return std::async(std::launch::async, [func{std::move(func)}]() { return func(""); });
91 }
92
93 const bool are_credentials_provided{!token.empty() && !username.empty()};
94 if (!allow_anonymous && !are_credentials_provided) {
95 LOG_ERROR(WebService, "Credentials must be provided for authenticated requests");
96 return std::async(std::launch::async, [func{std::move(func)}]() { return func(""); });
97 }
98
99 Win32WSAStartup();
100
101 // Built request header
102 cpr::Header header;
103 if (are_credentials_provided) {
104 // Authenticated request if credentials are provided
105 header = {{"Content-Type", "application/json"},
106 {"x-username", username.c_str()},
107 {"x-token", token.c_str()},
108 {"api-version", API_VERSION}};
109 } else {
110 // Otherwise, anonymous request
111 header = cpr::Header{{"Content-Type", "application/json"}, {"api-version", API_VERSION}};
112 }
113
114 // Get JSON asynchronously
115 return cpr::GetCallback(
116 [func{std::move(func)}](cpr::Response r) {
117 if (r.error) {
118 LOG_ERROR(WebService, "GET returned cpr error: %u:%s",
119 static_cast<u32>(r.error.code), r.error.message.c_str());
120 return func("");
121 }
122 if (r.status_code >= 400) {
123 LOG_ERROR(WebService, "GET returned error code: %u", r.status_code);
124 return func("");
125 }
126 if (r.header["content-type"].find("application/json") == std::string::npos) {
127 LOG_ERROR(WebService, "GET returned wrong content: %s",
128 r.header["content-type"].c_str());
129 return func("");
130 }
131 return func(r.text);
132 },
133 cpr::Url{url}, header);
134}
135
136template std::future<bool> GetJson(std::function<bool(const std::string&)> func,
137 const std::string& url, bool allow_anonymous,
138 const std::string& username, const std::string& token);
139
140} // 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 @@
1// Copyright 2017 Citra Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <functional>
8#include <future>
9#include <string>
10#include "common/common_types.h"
11
12namespace WebService {
13
14/**
15 * Posts JSON to services.citra-emu.org.
16 * @param url URL of the services.citra-emu.org endpoint to post data to.
17 * @param data String of JSON data to use for the body of the POST request.
18 * @param allow_anonymous If true, allow anonymous unauthenticated requests.
19 * @param username Citra username to use for authentication.
20 * @param token Citra token to use for authentication.
21 */
22void PostJson(const std::string& url, const std::string& data, bool allow_anonymous,
23 const std::string& username = {}, const std::string& token = {});
24
25/**
26 * Gets JSON from services.citra-emu.org.
27 * @param func A function that gets exectued when the json as a string is received
28 * @param url URL of the services.citra-emu.org endpoint to post data to.
29 * @param allow_anonymous If true, allow anonymous unauthenticated requests.
30 * @param username Citra username to use for authentication.
31 * @param token Citra token to use for authentication.
32 * @return future that holds the return value T of the func
33 */
34template <typename T>
35std::future<T> GetJson(std::function<T(const std::string&)> func, const std::string& url,
36 bool allow_anonymous, const std::string& username = {},
37 const std::string& token = {});
38
39} // 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
79 main.ui 79 main.ui
80 ) 80 )
81 81
82file(GLOB_RECURSE ICONS ${CMAKE_SOURCE_DIR}/dist/icons/*) 82# file(GLOB_RECURSE ICONS ${CMAKE_SOURCE_DIR}/dist/icons/*)
83file(GLOB_RECURSE THEMES ${CMAKE_SOURCE_DIR}/dist/qt_themes/*) 83file(GLOB_RECURSE THEMES ${CMAKE_SOURCE_DIR}/dist/qt_themes/*)
84 84
85create_directory_groups(${SRCS} ${HEADERS} ${UIS}) 85create_directory_groups(${SRCS} ${HEADERS} ${UIS})
@@ -93,24 +93,24 @@ endif()
93if (APPLE) 93if (APPLE)
94 set(MACOSX_ICON "../../dist/citra.icns") 94 set(MACOSX_ICON "../../dist/citra.icns")
95 set_source_files_properties(${MACOSX_ICON} PROPERTIES MACOSX_PACKAGE_LOCATION Resources) 95 set_source_files_properties(${MACOSX_ICON} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
96 add_executable(citra-qt MACOSX_BUNDLE ${SRCS} ${HEADERS} ${UI_HDRS} ${ICONS} ${THEMES} ${MACOSX_ICON}) 96 add_executable(yuzu MACOSX_BUNDLE ${SRCS} ${HEADERS} ${UI_HDRS} ${MACOSX_ICON})
97 set_target_properties(citra-qt PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) 97 set_target_properties(yuzu PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist)
98else() 98else()
99 add_executable(citra-qt ${SRCS} ${HEADERS} ${UI_HDRS} ${ICONS} ${THEMES}) 99 add_executable(yuzu ${SRCS} ${HEADERS} ${UI_HDRS})
100endif() 100endif()
101target_link_libraries(citra-qt PRIVATE audio_core common core input_common network video_core) 101target_link_libraries(yuzu PRIVATE common core input_common video_core)
102target_link_libraries(citra-qt PRIVATE Boost::boost glad nihstro-headers Qt5::OpenGL Qt5::Widgets) 102target_link_libraries(yuzu PRIVATE Boost::boost glad Qt5::OpenGL Qt5::Widgets)
103target_link_libraries(citra-qt PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) 103target_link_libraries(yuzu PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads)
104 104
105if(UNIX AND NOT APPLE) 105if(UNIX AND NOT APPLE)
106 install(TARGETS citra-qt RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") 106 install(TARGETS yuzu RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
107endif() 107endif()
108 108
109if (MSVC) 109if (MSVC)
110 include(CopyCitraQt5Deps) 110 include(CopyCitraQt5Deps)
111 include(CopyCitraSDLDeps) 111 include(CopyCitraSDLDeps)
112 include(CopyYuzuUnicornDeps) 112 include(CopyYuzuUnicornDeps)
113 copy_citra_Qt5_deps(citra-qt) 113 copy_citra_Qt5_deps(yuzu)
114 copy_citra_SDL_deps(citra-qt) 114 copy_citra_SDL_deps(yuzu)
115 copy_yuzu_unicorn_deps(citra-qt) 115 copy_yuzu_unicorn_deps(yuzu)
116endif() 116endif()
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
15 15
16create_directory_groups(${SRCS} ${HEADERS}) 16create_directory_groups(${SRCS} ${HEADERS})
17 17
18add_executable(citra ${SRCS} ${HEADERS}) 18add_executable(yuzu-cmd ${SRCS} ${HEADERS})
19target_link_libraries(citra PRIVATE common core input_common network) 19target_link_libraries(yuzu-cmd PRIVATE common core input_common)
20target_link_libraries(citra PRIVATE inih glad) 20target_link_libraries(yuzu-cmd PRIVATE inih glad)
21if (MSVC) 21if (MSVC)
22 target_link_libraries(citra PRIVATE getopt) 22 target_link_libraries(yuzu-cmd PRIVATE getopt)
23endif() 23endif()
24target_link_libraries(citra PRIVATE ${PLATFORM_LIBRARIES} SDL2 Threads::Threads) 24target_link_libraries(yuzu-cmd PRIVATE ${PLATFORM_LIBRARIES} SDL2 Threads::Threads)
25 25
26if(UNIX AND NOT APPLE) 26if(UNIX AND NOT APPLE)
27 install(TARGETS citra RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") 27 install(TARGETS yuzu-cmd RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
28endif() 28endif()
29 29
30if (MSVC) 30if (MSVC)
31 include(CopyCitraSDLDeps) 31 include(CopyCitraSDLDeps)
32 include(CopyYuzuUnicornDeps) 32 include(CopyYuzuUnicornDeps)
33 copy_citra_SDL_deps(citra) 33 copy_citra_SDL_deps(yuzu-cmd)
34 copy_yuzu_unicorn_deps(citra) 34 copy_yuzu_unicorn_deps(yuzu-cmd)
35endif() 35endif()
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