diff --git a/src/audio_core/CMakeLists.txt b/src/audio_core/CMakeLists.txt index 28af21c5d..f5cf72c63 100644 --- a/src/audio_core/CMakeLists.txt +++ b/src/audio_core/CMakeLists.txt @@ -2,6 +2,8 @@ add_library(audio_core STATIC EXCLUDE_FROM_ALL audio_types.h codec.cpp codec.h + csnd.cpp + csnd.h dsp_interface.cpp dsp_interface.h hle/aac_decoder.cpp diff --git a/src/audio_core/csnd.cpp b/src/audio_core/csnd.cpp new file mode 100644 index 000000000..bd4ebf0bd --- /dev/null +++ b/src/audio_core/csnd.cpp @@ -0,0 +1,354 @@ +// Copyright 2026 Citra Emulator Project / Azahar Emulator Project +// Licensed under GPLv3 or any later version +// Refer to the LICENSE.txt file included. + +#include +#include +#include "audio_core/csnd.h" +#include "common/archives.h" +#include "core/memory.h" + +namespace AudioCore { + +namespace { + +/// The channel timers tick at 67027964 Hz (the ARM11 base clock / 4) and the output runs at +/// 67027964 / 2048 Hz (the native sample rate), so one output sample is 2048 timer ticks. +constexpr u32 TimerTicksPerOutputSample = 2048; +/// Shortest period the hardware supports, faster timer values hang it. +constexpr u32 MinTimerPeriod = 0x42; + +constexpr u16 MaxVolume = 0x8000; + +constexpr std::array ImaStepTable{ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, + 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, + 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, + 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, + 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, + 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, + 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, +}; +constexpr std::array ImaIndexTable{-1, -1, -1, -1, 2, 4, 6, 8}; + +u16 ClampVolume(u16 volume) { + return std::min(volume, MaxVolume); +} + +} // namespace + +Csnd::Csnd(Memory::MemorySystem& memory_) : memory(memory_) {} + +Csnd::~Csnd() = default; + +CsndCnt Csnd::GetCnt(u32 channel) const { + return channels[channel].cnt; +} + +void Csnd::SetCnt(u32 channel, CsndCnt value) { + Channel& ch = channels[channel]; + const bool was_enabled = True(ch.cnt & CsndCnt::Enable); + ch.cnt = value; + if (!was_enabled && True(value & CsndCnt::Enable)) { + StartChannel(channel); + } else if (was_enabled && False(value & CsndCnt::Enable)) { + StopChannel(ch); + ch.holding = false; + } + if (False(value & CsndCnt::Hold)) { + ch.holding = false; + } +} + +void Csnd::SetTimer(u32 channel, u16 value) { + channels[channel].timer = value; +} + +void Csnd::SetVolume(u32 channel, u16 left, u16 right) { + channels[channel].volume_left = ClampVolume(left); + channels[channel].volume_right = ClampVolume(right); +} + +void Csnd::SetCaptureVolume(u32 channel, u16 left, u16 right) { + channels[channel].capture_volume_left = ClampVolume(left); + channels[channel].capture_volume_right = ClampVolume(right); +} + +void Csnd::SetStartAddress(u32 channel, u32 address) { + channels[channel].start_address = address; +} + +void Csnd::SetSize(u32 channel, u32 size) { + channels[channel].size = size & 0x7FFFFFF; +} + +void Csnd::SetLoopAddress(u32 channel, u32 address) { + channels[channel].loop_address = address; +} + +u32 Csnd::GetAdpcmState(u32 channel) const { + const Channel& ch = channels[channel]; + if (True(ch.cnt & CsndCnt::Enable)) { + return static_cast(ch.adpcm_predictor) | (static_cast(ch.adpcm_index) << 16); + } + return ch.adpcm_state; +} + +void Csnd::SetAdpcmState(u32 channel, u32 value) { + channels[channel].adpcm_state = value; +} + +u32 Csnd::GetLoopAdpcmState(u32 channel) const { + return channels[channel].loop_adpcm_state; +} + +void Csnd::SetLoopAdpcmState(u32 channel, u32 value) { + channels[channel].loop_adpcm_state = value; +} + +CsndCaptureCnt Csnd::GetCaptureCnt(u32 unit) const { + return capture_units[unit].cnt; +} + +void Csnd::SetCaptureCnt(u32 unit, CsndCaptureCnt value) { + capture_units[unit].cnt = value; +} + +void Csnd::SetCaptureTimer(u32 unit, u16 value) { + capture_units[unit].timer = value; +} + +void Csnd::SetCaptureAddress(u32 unit, u32 address, u32 size) { + capture_units[unit].address = address; + capture_units[unit].size = size; +} + +void Csnd::SetMasterVolume(u16 value) { + master_volume = ClampVolume(value); +} + +u32 Csnd::GetChannelMaskRegister() const { + return channel_mask_register; +} + +void Csnd::SetChannelMaskRegister(u32 value) { + channel_mask_register = value; +} + +void Csnd::SetCaptureMaskRegister(u8 value) { + capture_mask_register = value; +} + +bool Csnd::IsAnyChannelBusy() const { + return std::any_of(channels.begin(), channels.end(), + [](const Channel& ch) { return True(ch.cnt & CsndCnt::Enable); }); +} + +void Csnd::StartChannel(u32 index) { + Channel& ch = channels[index]; + ch.block_address = ch.start_address; + ch.block_size = ch.size; + ch.position = 0; + ch.high_nibble = false; + ch.holding = false; + ch.counter = 0; + ch.previous_sample = 0; + ch.current_sample = 0; + ch.adpcm_predictor = static_cast(ch.adpcm_state & 0xFFFF); + ch.adpcm_index = std::min((ch.adpcm_state >> 16) & 0x7F, 88); +} + +void Csnd::StopChannel(Channel& ch) { + // Keep the decoder state consistent after the channel stops. + ch.adpcm_state = + static_cast(ch.adpcm_predictor) | (static_cast(ch.adpcm_index) << 16); + ch.cnt &= ~CsndCnt::Enable; +} + +bool Csnd::ReachedBlockEnd(const Channel& ch) const { + if (GetFormat(ch.cnt) == Format::PsgNoise || GetLoopMode(ch.cnt) == LoopMode::Manual) { + return false; + } + return ch.position >= ch.block_size; +} + +void Csnd::Step(Channel& ch) { + if (ReachedBlockEnd(ch)) { + const LoopMode loop_mode = GetLoopMode(ch.cnt); + if (loop_mode == LoopMode::OneShot) { + StopChannel(ch); + ch.holding = True(ch.cnt & CsndCnt::Hold); + return; + } + ch.block_address = ch.loop_address; + if (loop_mode == LoopMode::Normal) { + ch.block_size = ch.size; + } + ch.position = 0; + ch.high_nibble = false; + if (ch.loop_adpcm_state & LoopAdpcmReload) { + ch.adpcm_predictor = static_cast(ch.loop_adpcm_state & 0xFFFF); + ch.adpcm_index = std::min((ch.loop_adpcm_state >> 16) & 0x7F, 88); + } + if (ch.block_size == 0) { + // An empty looped block would never advance. + StopChannel(ch); + return; + } + } + + ch.previous_sample = ch.current_sample; + ch.current_sample = FetchSample(ch); +} + +s16 Csnd::FetchSample(Channel& ch) { + const u32 address = ch.block_address + ch.position; + switch (GetFormat(ch.cnt)) { + case Format::Pcm8: { + const u8* data = memory.GetPhysicalPointer(address); + ch.position++; + return data ? static_cast(static_cast(*data) * 256) : 0; + } + case Format::Pcm16: { + // At physical memory boundaries, the high byte may end outside of the + // memory region, sacrifice that single OOB read edge case for speed. + const u8* low = memory.GetPhysicalPointer(address); + const u8* high = low + 1; + ch.position += 2; + if (!low) { + return 0; + } + return static_cast(*low | (*high << 8)); + } + case Format::ImaAdpcm: { + const u8* data = memory.GetPhysicalPointer(address); + const u8 byte = data ? *data : 0; + const u8 nibble = ch.high_nibble ? (byte >> 4) : (byte & 0xF); + if (ch.high_nibble) { + ch.position++; + } + ch.high_nibble = !ch.high_nibble; + + const s32 step = ImaStepTable[ch.adpcm_index]; + s32 diff = step >> 3; + if (nibble & 1) { + diff += step >> 2; + } + if (nibble & 2) { + diff += step >> 1; + } + if (nibble & 4) { + diff += step; + } + s32 predictor = ch.adpcm_predictor; + if (nibble & 8) { + predictor = std::max(predictor - diff, -0x7FFF); + } else { + predictor = std::min(predictor + diff, 0x7FFF); + } + ch.adpcm_predictor = static_cast(predictor); + ch.adpcm_index = + static_cast(std::clamp(ch.adpcm_index + ImaIndexTable[nibble & 7], 0, 88)); + return ch.adpcm_predictor; + } + case Format::PsgNoise: + // TODO(PabloMK7): PSG square waves (channels 8-13) and noise (channels 14-15). + return 0; + } + return 0; +} + +s16 Csnd::Interpolated(const Channel& ch) const { + if (False(ch.cnt & CsndCnt::LinearInterpolation)) { + return ch.current_sample; + } + const u32 period = std::max(0x10000 - ch.timer, MinTimerPeriod); + const s32 delta = ch.current_sample - ch.previous_sample; + return static_cast(ch.previous_sample + + delta * static_cast(ch.counter) / static_cast(period)); +} + +void Csnd::Render(std::span> out) { + for (auto& frame : out) { + s32 left = 0; + s32 right = 0; + for (u32 i = 0; i < NumChannels; i++) { + Channel& ch = channels[i]; + if (False(ch.cnt & CsndCnt::Enable)) { + if (ch.holding) { + left += ch.current_sample * ch.volume_left >> 15; + right += ch.current_sample * ch.volume_right >> 15; + } + continue; + } + if (True(ch.cnt & CsndCnt::Run)) { + const u32 period = std::max(0x10000 - ch.timer, MinTimerPeriod); + ch.counter += TimerTicksPerOutputSample; + while (ch.counter >= period && True(ch.cnt & CsndCnt::Enable)) { + ch.counter -= period; + Step(ch); + } + if (False(ch.cnt & CsndCnt::Enable)) { + if (ch.holding) { + left += ch.current_sample * ch.volume_left >> 15; + right += ch.current_sample * ch.volume_right >> 15; + } + continue; + } + } + const s32 sample = Interpolated(ch); + left += sample * ch.volume_left >> 15; + right += sample * ch.volume_right >> 15; + } + + const s64 mixed_left = static_cast(left) * master_volume >> 15; + const s64 mixed_right = static_cast(right) * master_volume >> 15; + frame[0] = static_cast(std::clamp(mixed_left, -0x8000, 0x7FFF)); + frame[1] = static_cast(std::clamp(mixed_right, -0x8000, 0x7FFF)); + } +} + +template +void Csnd::Channel::serialize(Archive& ar, const unsigned int) { + ar & cnt; + ar & timer; + ar & volume_left; + ar & volume_right; + ar & capture_volume_left; + ar & capture_volume_right; + ar & start_address; + ar & size; + ar & loop_address; + ar & adpcm_state; + ar & loop_adpcm_state; + ar & block_address; + ar & block_size; + ar & position; + ar & high_nibble; + ar & holding; + ar & counter; + ar & previous_sample; + ar & current_sample; + ar & adpcm_predictor; + ar & adpcm_index; +} + +template +void Csnd::CaptureUnit::serialize(Archive& ar, const unsigned int) { + ar & cnt; + ar & timer; + ar & address; + ar & size; +} + +template +void Csnd::serialize(Archive& ar, const unsigned int) { + ar & channels; + ar & capture_units; + ar & master_volume; + ar & channel_mask_register; + ar & capture_mask_register; +} +SERIALIZE_IMPL(Csnd) + +} // namespace AudioCore diff --git a/src/audio_core/csnd.h b/src/audio_core/csnd.h new file mode 100644 index 000000000..ae9e5c7c4 --- /dev/null +++ b/src/audio_core/csnd.h @@ -0,0 +1,201 @@ +// Copyright 2026 Citra Emulator Project / Azahar Emulator Project +// Licensed under GPLv3 or any later version +// Refer to the LICENSE.txt file included. + +#pragma once + +#include +#include +#include +#include "common/common_funcs.h" +#include "common/common_types.h" + +namespace Memory { +class MemorySystem; +} + +namespace AudioCore { + +/// Bits of a CSND channel CNT register. +enum class CsndCnt : u16 { + None = 0, + + LinearInterpolation = 1 << 6, // Linear interpolation on each two samples (0=Disable, 1=Enable) + Hold = 1 << 7, // (0=Normal, 1=Hold last sample after one-shot sound) + Run = 1 << 14, // Run DMA (0=Pause the channel, 1=Run the channel) + Enable = 1 << 15, // Start/Stop control (0=Stop, 1=Start/Busy) +}; +DECLARE_ENUM_FLAG_OPERATORS(CsndCnt) + +/// Bits of a CSND capture unit CNT register. +enum class CsndCaptureCnt : u16 { + None = 0, + + OneShot = 1 << 0, + Pcm8 = 1 << 1, + Unknown2 = 1 << 2, + Enable = 1 << 15, +}; +DECLARE_ENUM_FLAG_OPERATORS(CsndCaptureCnt) + +/** + * Register level model of the CSND sound hardware (0x10103000). It has 32 channels that play + * PCM8, PCM16 or IMA-ADPCM samples from physical memory (or a PSG square wave / noise, not + * emulated yet), and outputs the stereo mix at the I2S rate, the same rate as the DSP. + * On hardware the mix goes to the codec chip on its own I2S line, where it is mixed with the DSP + * output. + * + * Render() produces samples and advances the channels, the caller decides + * when. Writes to the registers take effect from the next rendered sample. + */ +class Csnd { +public: + static constexpr u32 NumChannels = 32; + static constexpr u32 NumCaptureUnits = 2; + + static constexpr u32 CntLoopModeShift = 10; + static constexpr u32 CntLoopModeMask = 0x3 << CntLoopModeShift; + + static constexpr u32 CntFormatShift = 12; + static constexpr u32 CntFormatMask = 0x3 << CntFormatShift; + + /// Reloads the IMA-ADPCM state at the loop address. + static constexpr u32 LoopAdpcmReload = 1u << 31; + + enum class Format : u32 { + Pcm8 = 0, + Pcm16 = 1, + ImaAdpcm = 2, + PsgNoise = 3, ///< Not emulated yet + }; + + enum class LoopMode : u32 { + Manual = 0, ///< Plays ignoring the size + Normal = 1, ///< At the end, restarts from the loop address, reloading the size + OneShot = 2, ///< Stops at the end + NormalNoReload = 3, ///< Like Normal, but latches the size at start + }; + + explicit Csnd(Memory::MemorySystem& memory); + ~Csnd(); + + /// Get CNT bits of a format. + static constexpr CsndCnt CntFormat(Format format) { + return static_cast(static_cast(format) << CntFormatShift); + } + /// Get CNT bits of a loop mode. + static constexpr CsndCnt CntLoopMode(LoopMode loop_mode) { + return static_cast(static_cast(loop_mode) << CntLoopModeShift); + } + + /// Get format from CNT bits. + static constexpr Format GetFormat(CsndCnt cnt) { + return static_cast((static_cast(cnt) & CntFormatMask) >> CntFormatShift); + } + // Get loop mode from CNT bits. + static constexpr LoopMode GetLoopMode(CsndCnt cnt) { + return static_cast((static_cast(cnt) & CntLoopModeMask) >> CntLoopModeShift); + } + + CsndCnt GetCnt(u32 channel) const; + void SetCnt(u32 channel, CsndCnt value); + + void SetTimer(u32 channel, u16 value); + void SetVolume(u32 channel, u16 left, u16 right); + void SetCaptureVolume(u32 channel, u16 left, u16 right); + void SetStartAddress(u32 channel, u32 address); + void SetSize(u32 channel, u32 size); + void SetLoopAddress(u32 channel, u32 address); + + /// IMA-ADPCM state register. PCM16 value in bits 0-15, table index in bits 16-22. + /// While the channel plays it reads back the decoder's current state. + u32 GetAdpcmState(u32 channel) const; + void SetAdpcmState(u32 channel, u32 value); + + /// Loop IMA-ADPCM state register. Bit 31 reloads it at the loop address. + u32 GetLoopAdpcmState(u32 channel) const; + void SetLoopAdpcmState(u32 channel, u32 value); + + // Capture registers. Stored only as capture is not emulated. + CsndCaptureCnt GetCaptureCnt(u32 unit) const; + void SetCaptureCnt(u32 unit, CsndCaptureCnt value); + void SetCaptureTimer(u32 unit, u16 value); + void SetCaptureAddress(u32 unit, u32 address, u32 size); + + // Global registers. + void SetMasterVolume(u16 value); + u32 GetChannelMaskRegister() const; + void SetChannelMaskRegister(u32 value); + void SetCaptureMaskRegister(u8 value); + + /// True when at least one channel is enabled. + bool IsAnyChannelBusy() const; + + /// Renders samples into out, advancing every channel. + void Render(std::span> out); + +private: + struct Channel { + // Registers + CsndCnt cnt = CsndCnt::None; + u16 timer = 0; + u16 volume_left = 0; + u16 volume_right = 0; + u16 capture_volume_left = 0; + u16 capture_volume_right = 0; + u32 start_address = 0; + u32 size = 0; + u32 loop_address = 0; + u32 adpcm_state = 0; + u32 loop_adpcm_state = 0; + + // Playback state + u32 block_address = 0; ///< Start of the block being played + u32 block_size = 0; ///< Size latched for the block being played + u32 position = 0; ///< Byte offset in the block + bool high_nibble = false; + bool holding = false; ///< Ended a one-shot block with Hold set, outputs its last sample + u32 counter = 0; ///< Timer, in units of 1/2048 output samples + s16 previous_sample = 0; + s16 current_sample = 0; + s16 adpcm_predictor = 0; + u8 adpcm_index = 0; + + template + void serialize(Archive& ar, const unsigned int); + friend class boost::serialization::access; + }; + + struct CaptureUnit { + CsndCaptureCnt cnt = CsndCaptureCnt::None; + u16 timer = 0; + u32 address = 0; + u32 size = 0; + + template + void serialize(Archive& ar, const unsigned int); + friend class boost::serialization::access; + }; + + void StartChannel(u32 index); + void StopChannel(Channel& channel); + void Step(Channel& channel); + + s16 FetchSample(Channel& channel); + s16 Interpolated(const Channel& channel) const; + bool ReachedBlockEnd(const Channel& channel) const; + + Memory::MemorySystem& memory; + + std::array channels{}; + std::array capture_units{}; + u16 master_volume = 0x8000; + u32 channel_mask_register = 0; + u8 capture_mask_register = 0; + + template + void serialize(Archive& ar, const unsigned int); + friend class boost::serialization::access; +}; + +} // namespace AudioCore diff --git a/src/audio_core/dsp_interface.cpp b/src/audio_core/dsp_interface.cpp index a4edb3778..fd9d29fca 100644 --- a/src/audio_core/dsp_interface.cpp +++ b/src/audio_core/dsp_interface.cpp @@ -1,8 +1,10 @@ // Copyright 2017-2026 Citra Emulator Project / Azahar Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the misc/licenses/gplv2.txt file included. +// Licensed under GPLv3 or any later version +// Refer to the LICENSE.txt file included. +#include #include +#include #include "audio_core/dsp_interface.h" #include "audio_core/sink.h" #include "audio_core/sink_details.h" @@ -13,6 +15,14 @@ namespace AudioCore { +namespace { +/// Amount of CSND frames to wait until they are outputted on their own +/// because DSP is not producing any output. +constexpr u32 CsndFramesBeforeDspIdle = 2; +/// Max amount of CSND pending samples. +constexpr std::size_t MaxCsndPendingSamples = samples_per_frame * 4; +} // namespace + DspInterface::DspInterface(Core::System& system_) : system(system_) {} DspInterface::~DspInterface() = default; @@ -37,36 +47,74 @@ void DspInterface::EnableStretching(bool enable) { } void DspInterface::OutputFrame(StereoFrame16 frame) { - if (!sink) { - return; - } - - if (sink->ImmediateSubmission()) { - sink->PushSamples(frame.data(), frame.size()); - } else { - fifo.Push(frame.data(), frame.size()); - } - - auto video_dumper = system.GetVideoDumper(); - if (video_dumper && video_dumper->IsDumping()) { - video_dumper->AddAudioFrame(std::move(frame)); - } + std::scoped_lock lock{csnd_mutex}; + MixCsnd(frame); + PushSamples(frame); } void DspInterface::OutputSample(std::array sample) { + std::scoped_lock lock{csnd_mutex}; + MixCsnd({&sample, 1}); + PushSamples({&sample, 1}); +} + +void DspInterface::OutputCsndFrame(const StereoFrame16& frame) { + std::scoped_lock lock{csnd_mutex}; + + if (dsp_samples_since_csnd_frame == 0) { + csnd_frames_without_dsp++; + } else { + csnd_frames_without_dsp = 0; + } + dsp_samples_since_csnd_frame = 0; + + csnd_pending.insert(csnd_pending.end(), frame.begin(), frame.end()); + + if (csnd_frames_without_dsp >= CsndFramesBeforeDspIdle) { + // The DSP is not running, CSND is the only output. + const std::vector> samples(csnd_pending.begin(), csnd_pending.end()); + csnd_pending.clear(); + PushSamples(samples); + return; + } + + // The two clocks may drift a little, don't let CSND fall too far behind the DSP output. + while (csnd_pending.size() > MaxCsndPendingSamples) { + csnd_pending.pop_front(); + } +} + +void DspInterface::MixCsnd(std::span> samples) { + // TODO(PabloMK7): Implement SIMD mixing here if possible. + dsp_samples_since_csnd_frame += samples.size(); + for (auto& sample : samples) { + if (csnd_pending.empty()) { + break; + } + const auto& csnd = csnd_pending.front(); + for (std::size_t i = 0; i < 2; i++) { + sample[i] = static_cast(std::clamp(sample[i] + csnd[i], -0x8000, 0x7FFF)); + } + csnd_pending.pop_front(); + } +} + +void DspInterface::PushSamples(std::span> samples) { if (!sink) { return; } if (sink->ImmediateSubmission()) { - sink->PushSamples(&sample, 1); + sink->PushSamples(samples.data(), samples.size()); } else { - fifo.Push(&sample, 1); + fifo.Push(samples.data(), samples.size()); } auto video_dumper = system.GetVideoDumper(); if (video_dumper && video_dumper->IsDumping()) { - video_dumper->AddAudioSample(std::move(sample)); + for (const auto& sample : samples) { + video_dumper->AddAudioSample(sample); + } } } diff --git a/src/audio_core/dsp_interface.h b/src/audio_core/dsp_interface.h index 5a33fcbcd..a84cdc43c 100644 --- a/src/audio_core/dsp_interface.h +++ b/src/audio_core/dsp_interface.h @@ -1,10 +1,11 @@ -// Copyright 2017-2025 Citra Emulator Project / Azahar Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the misc/licenses/gplv2.txt file included. +// Copyright 2017-2026 Citra Emulator Project / Azahar Emulator Project +// Licensed under GPLv3 or any later version +// Refer to the LICENSE.txt file included. #pragma once #include +#include #include #include #include "audio_core/audio_types.h" @@ -103,6 +104,13 @@ public: /// Enable/Disable audio stretching. void EnableStretching(bool enable); + /** + * Adds one frame of CSND output. On hardware CSND and the DSP reach the codec chip on separate + * I2S lines and the codec mixes them, here the frame is mixed to the DSP output. + * Must be called once per audio frame period. + */ + void OutputCsndFrame(const StereoFrame16& frame); + protected: void OutputFrame(StereoFrame16 frame); void OutputSample(std::array sample); @@ -110,6 +118,8 @@ protected: private: void FlushResidualStretcherAudio(); void OutputCallback(s16* buffer, std::size_t num_frames); + void MixCsnd(std::span> samples); + void PushSamples(std::span> samples); Core::System& system; @@ -121,6 +131,11 @@ private: TimeStretcher time_stretcher; std::unique_ptr sink; + std::mutex csnd_mutex; + StereoBuffer16 csnd_pending; + std::size_t dsp_samples_since_csnd_frame = 0; + u32 csnd_frames_without_dsp = 0; + template void serialize(Archive& ar, const unsigned int) {} friend class boost::serialization::access; diff --git a/src/core/hle/service/csnd/csnd_snd.cpp b/src/core/hle/service/csnd/csnd_snd.cpp index 440f189e6..e7b1f99b3 100644 --- a/src/core/hle/service/csnd/csnd_snd.cpp +++ b/src/core/hle/service/csnd/csnd_snd.cpp @@ -1,398 +1,647 @@ -// Copyright 2014 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the misc/licenses/gplv2.txt file included. +// Copyright 2014-2026 Citra Emulator Project / Azahar Emulator Project +// Licensed under GPLv3 or any later version +// Refer to the LICENSE.txt file included. +#include +#include +#include +#include "audio_core/dsp_interface.h" #include "common/alignment.h" #include "common/archives.h" +#include "common/bit_field.h" +#include "common/settings.h" #include "core/core.h" +#include "core/core_timing.h" #include "core/hle/ipc_helpers.h" -#include "core/hle/kernel/resource_limit.h" +#include "core/hle/kernel/process.h" #include "core/hle/result.h" #include "core/hle/service/csnd/csnd_snd.h" SERVICE_CONSTRUCT_IMPL(Service::CSND::CSND_SND) SERIALIZE_EXPORT_IMPL(Service::CSND::CSND_SND) +SERIALIZE_EXPORT_IMPL(Service::CSND::ClientData) namespace Service::CSND { +namespace { + +using Hw = AudioCore::Csnd; +using AudioCore::CsndCaptureCnt; +using AudioCore::CsndCnt; + +constexpr Result ResultInvalidState(ErrorDescription::InvalidResultValue, ErrorModule::CSND, + ErrorSummary::InvalidState, + ErrorLevel::Status); // 0xC8A0B7FF +constexpr Result ResultAlreadyInitialized(59, ErrorModule::OS, ErrorSummary::InvalidState, + ErrorLevel::Usage); // 0xE0A0183B +constexpr Result ResultInvalidAddress(ErrorDescription::InvalidPointer, ErrorModule::Common, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E3FFF6 + +/// Channels that AcquireSoundChannels gives to clients, 0-7 are used for direct sound. +constexpr u32 ClientChannelMask = 0xFFFFFF00; + +constexpr u16 CommandListEnd = 0xFFFF; + +/// Volume fades, CSND moves volumes in 40 steps, 4 steps (200 us apart) +/// per tick of a 1.666 ms timer. +constexpr s32 FadeSteps = 40; +constexpr u32 FadeStepsPerTick = 4; +constexpr u64 FadeTickUs = 1666; +constexpr u64 FadeStepUs = 200; +constexpr s32 MaxVolume = 0x8000; + +/// ARM11 cycles per audio frame, same as for the DSP (see audio_core/hle/hle.cpp). +constexpr s64 AudioFrameTicks = AudioCore::samples_per_frame * 4096 * 2; + enum class CommandId : u16 { - Start = 0x000, - Pause = 0x001, + SetPlayStateRaw = 0x000, + SetPlayState = 0x001, SetEncoding = 0x002, - SetSecondBlock = 0x003, + SetLoopBlock = 0x003, SetLoopMode = 0x004, - // unknown = 0x005, + SetHold = 0x005, SetLinearInterpolation = 0x006, SetPsgDuty = 0x007, - SetSampleRate = 0x008, + SetTimer = 0x008, SetVolume = 0x009, - SetFirstBlock = 0x00A, - SetFirstBlockAdpcmState = 0x00B, - SetSecondBlockAdpcmState = 0x00C, - SetSecondBlockAdpcmReload = 0x00D, + SetBlock = 0x00A, + SetAdpcmState = 0x00B, + SetLoopAdpcmState = 0x00C, + SetLoopAdpcmReload = 0x00D, ConfigureChannel = 0x00E, ConfigurePsg = 0x00F, - ConfigurePsgNoise = 0x010, - // 0x10x commands are audio capture related - // unknown = 0x200 + ConfigureNoise = 0x010, + SetCaptureEnable = 0x100, + SetCaptureOneShot = 0x101, + SetCaptureFormat = 0x102, + SetCaptureBit2 = 0x103, + SetCaptureTimer = 0x104, + SetCaptureBuffer = 0x105, + ConfigureCapture = 0x106, + ApplyMasks = 0x200, UpdateState = 0x300, }; +/// Channel state entry written by UpdateState, one per acquired channel. +struct ChannelState { + u8 active; + INSERT_PADDING_BYTES(3); + s16_le adpcm_predictor; + u8 adpcm_index; + INSERT_PADDING_BYTES(1); + u32_le zero; +}; +static_assert(sizeof(ChannelState) == 0xC, "ChannelState structure size is wrong"); + +constexpr u32 CaptureStateSize = 8; + +/// First parameter of command 0xE (ConfigureChannel). +union ConfigureChannelFlags { + u32 raw; + BitField<0, 5, u32> channel; + BitField<6, 1, u32> linear_interpolation; + BitField<10, 2, Hw::LoopMode> loop_mode; + BitField<12, 2, Hw::Format> format; + BitField<14, 1, u32> play; + BitField<16, 16, u32> timer; +}; + +} // namespace + struct Type0Command { u16_le next_command_offset; enum_le command_id; u8 finished; INSERT_PADDING_BYTES(3); - union { - struct { - u32_le channel; - u32_le value; - INSERT_PADDING_BYTES(0x10); - } start; - - struct { - u32_le channel; - u32_le value; - INSERT_PADDING_BYTES(0x10); - } pause; - - struct { - u32_le channel; - Encoding value; - INSERT_PADDING_BYTES(0x13); - } set_encoding; - - struct { - u32_le channel; - LoopMode value; - INSERT_PADDING_BYTES(0x13); - } set_loop_mode; - - struct { - u32_le channel; - u32_le value; - INSERT_PADDING_BYTES(0x10); - } set_linear_interpolation; - - struct { - u32_le channel; - u8 value; - INSERT_PADDING_BYTES(0x13); - } set_psg_duty; - - struct { - u32_le channel; - u32_le value; - INSERT_PADDING_BYTES(0x10); - } set_sample_rate; - - struct { - u32_le channel; - u16_le left_channel_volume; - u16_le right_channel_volume; - u16_le left_capture_volume; - u16_le right_capture_volume; - INSERT_PADDING_BYTES(0xC); - } set_volume; - - struct { - u32_le channel; - u32_le address; - u32_le size; - INSERT_PADDING_BYTES(0xC); - } set_block; // for either first block or second block - - struct { - u32_le channel; - s16_le predictor; - u8 step_index; - INSERT_PADDING_BYTES(0x11); - } set_adpcm_state; // for either first block or second block - - struct { - u32_le channel; - u8 value; - INSERT_PADDING_BYTES(0x13); - } set_second_block_adpcm_reload; - - struct { - union { - BitField<0, 6, u32> channel; - BitField<6, 1, u32> linear_interpolation; - - BitField<10, 2, u32> loop_mode; - BitField<12, 2, u32> encoding; - BitField<14, 1, u32> enable_playback; - - BitField<16, 16, u32> sample_rate; - }; - - u16_le left_channel_volume; - u16_le right_channel_volume; - u16_le left_capture_volume; - u16_le right_capture_volume; - u32_le block1_address; - u32_le block2_address; - u32_le size; - } configure_channel; - - struct { - union { - BitField<0, 6, u32> channel; - BitField<14, 1, u32> enable_playback; - BitField<16, 16, u32> sample_rate; - }; - u16_le left_channel_volume; - u16_le right_channel_volume; - u16_le left_capture_volume; - u16_le right_capture_volume; - u32_le duty; - INSERT_PADDING_BYTES(0x8); - } configure_psg; - - struct { - union { - BitField<0, 6, u32> channel; - BitField<14, 1, u32> enable_playback; - }; - u16_le left_channel_volume; - u16_le right_channel_volume; - u16_le left_capture_volume; - u16_le right_capture_volume; - INSERT_PADDING_BYTES(0xC); - } configure_psg_noise; - }; + std::array params; }; static_assert(sizeof(Type0Command) == 0x20, "Type0Command structure size is wrong"); -struct MasterState { - u32_le unknown_channel_flag; - u32_le unknown; -}; -static_assert(sizeof(MasterState) == 0x8, "MasterState structure size is wrong"); +template +void ClientData::serialize(Archive& ar, const unsigned int) { + ar& boost::serialization::base_object(*this); + ar & mutex; + ar & shared_memory; + ar & master_state_offset; + ar & channel_state_offset; + ar & capture_state_offset; + ar & direct_sound_offset; + ar & channel_mask; + ar & capture_mask; +} +SERIALIZE_IMPL(ClientData) -struct ChannelState { - u8 active; - INSERT_PADDING_BYTES(0x3); - s16_le adpcm_predictor; - u8 adpcm_step_index; - INSERT_PADDING_BYTES(0x1); +/// Writes to the client's shared memory, if it fits. +template +static void WriteShared(ClientData& client, u32 offset, const T& data) { + if (!client.shared_memory || offset > client.shared_memory->GetSize() || + client.shared_memory->GetSize() - offset < sizeof(T)) { + LOG_ERROR(Service_CSND, "out of bounds write size=0x{:X} offset=0x{:X}", sizeof(T), offset); + return; + } + std::memcpy(client.shared_memory->GetPointer(offset), &data, sizeof(T)); +} - // 3dbrew says this is the current physical address. However the assembly of CSND module - // from 11.3 system shows this is simply assigned as 0, which is also documented on ctrulib. - u32_le zero; -}; -static_assert(sizeof(ChannelState) == 0xC, "ChannelState structure size is wrong"); +void CSND_SND::UpdateHardware() { + if (!is_ticking) { + return; + } + const s64 elapsed = system.CoreTiming().GetTicks() - frame_start_ticks; + const u32 elapsed_scaled = static_cast(std::clamp( + elapsed * AudioCore::samples_per_frame / frame_length_ticks, 0, frame.size())); + if (elapsed_scaled > frame_samples) { + csnd_hw.Render(std::span(frame).subspan(frame_samples, elapsed_scaled - frame_samples)); + frame_samples = elapsed_scaled; + } +} -struct CaptureState { - u8 active; - INSERT_PADDING_BYTES(0x3); - u32_le zero; -}; -static_assert(sizeof(CaptureState) == 0x8, "CaptureState structure size is wrong"); +void CSND_SND::AudioTickCallback(s64 cycles_late) { + if (frame_samples < frame.size()) { + csnd_hw.Render(std::span(frame).subspan(frame_samples)); + } + + system.DSP().OutputCsndFrame(frame); + frame_samples = 0; + + if (initialized_clients == 0 && !csnd_hw.IsAnyChannelBusy()) { + is_ticking = false; + return; + } + + // Keep in sync with the DSP audio frames (see DspHle::Impl::AudioTickCallback). + const double time_scale = Settings::values.enable_realtime_audio + ? std::max(0.01, system.GetStableFrameTimeScale()) + : 1.0; + frame_length_ticks = std::max(static_cast(AudioFrameTicks / time_scale), 1); + frame_start_ticks = system.CoreTiming().GetTicks() - cycles_late; + system.CoreTiming().ScheduleEvent(frame_length_ticks - cycles_late, audio_tick_event); +} + +void CSND_SND::StartTicking() { + if (is_ticking) { + return; + } + is_ticking = true; + frame_samples = 0; + frame_length_ticks = AudioFrameTicks; + frame_start_ticks = system.CoreTiming().GetTicks(); + system.CoreTiming().ScheduleEvent(frame_length_ticks, audio_tick_event); +} + +bool CSND_SND::IsRunning(u32 channel) { + constexpr CsndCnt running = CsndCnt::Enable | CsndCnt::Run; + return (csnd_hw.GetCnt(channel) & running) == running; +} + +void CSND_SND::WriteCurrentVolume(u32 channel) { + const auto& volume = volumes[channel]; + csnd_hw.SetVolume(channel, static_cast(volume.current[0]), + static_cast(volume.current[1])); +} + +void CSND_SND::SetRequestedVolume(u32 channel, u16 left, u16 right, bool start_fade) { + volumes[channel].requested = {left, right}; + SetTargetVolume(channel, left, right, start_fade); +} + +void CSND_SND::SetTargetVolume(u32 channel, u16 left, u16 right, bool start_fade) { + auto& volume = volumes[channel]; + const std::array target{left, right}; + for (std::size_t side = 0; side < 2; side++) { + volume.step[side] = (target[side] - volume.current[side]) / FadeSteps; + volume.target[side] = target[side]; + if (volume.step[side] == 0) { + volume.current[side] = target[side]; + } + } + fading.set(channel); + if (start_fade) { + StartFade(); + } +} + +void CSND_SND::StartFade() { + if (fade_scheduled) { + return; + } + fade_scheduled = true; + // The module's timer has no initial delay, the first tick runs immediately. + system.CoreTiming().ScheduleEvent(0, fade_event, 0); +} + +void CSND_SND::FadeCallback(std::uintptr_t step, s64 cycles_late) { + const ChannelSet work = (fading | stop_pending | pause_pending) & started; + if (work.none()) { + fade_scheduled = false; + return; + } + + UpdateHardware(); + + const ChannelSet fading_now = fading & started; + for (u32 channel = 0; channel < Hw::NumChannels; channel++) { + if (!fading_now[channel]) { + continue; + } + auto& volume = volumes[channel]; + for (std::size_t side = 0; side < 2; side++) { + if (volume.current[side] != volume.target[side]) { + volume.current[side] = + std::clamp(volume.current[side] + volume.step[side], 0, MaxVolume); + } + } + } + + if (step == FadeStepsPerTick - 1) { + // Finish the fades that reached their target. + for (u32 channel = 0; channel < Hw::NumChannels; channel++) { + if (!work[channel]) { + continue; + } + auto& volume = volumes[channel]; + bool reached = true; + for (std::size_t side = 0; side < 2; side++) { + const bool done = volume.step[side] > 0 + ? volume.current[side] >= volume.target[side] + : volume.current[side] <= volume.target[side]; + if (done) { + volume.current[side] = volume.target[side]; + } else { + reached = false; + } + } + if (!reached) { + continue; + } + fading.reset(channel); + if (stop_pending[channel]) { + StopChannel(channel); + stop_pending.reset(channel); + started.reset(channel); + } + if (pause_pending[channel]) { + csnd_hw.SetCnt(channel, csnd_hw.GetCnt(channel) & ~CsndCnt::Run); + pause_pending.reset(channel); + started.reset(channel); + } + } + } + + for (u32 channel = 0; channel < Hw::NumChannels; channel++) { + if (fading_now[channel]) { + WriteCurrentVolume(channel); + } + } + + if (((fading | stop_pending | pause_pending) & started).none()) { + fade_scheduled = false; + return; + } + if (step + 1 < FadeStepsPerTick) { + system.CoreTiming().ScheduleEvent(usToCycles(FadeStepUs) - cycles_late, fade_event, + step + 1); + } else { + const u64 rest = FadeTickUs - FadeStepUs * (FadeStepsPerTick - 1); + system.CoreTiming().ScheduleEvent(usToCycles(rest) - cycles_late, fade_event, 0); + } +} + +void CSND_SND::StopChannel(u32 channel) { + // Real hardware stops the channel by starting a non-looping short silent sound. + // We do not need that and can just clear the channel. + csnd_hw.SetCnt(channel, + csnd_hw.GetCnt(channel) & ~(CsndCnt::Enable | CsndCnt::Run | + CsndCnt::LinearInterpolation | CsndCnt::Hold)); +} + +void CSND_SND::SetPlayStateRaw(u32 channel, bool play) { + if (play) { + csnd_hw.SetCnt(channel, csnd_hw.GetCnt(channel) | CsndCnt::Enable); + } else if (IsRunning(channel)) { + stop_pending.set(channel); + SetTargetVolume(channel, 0, 0, true); + } else { + StopChannel(channel); + volumes[channel].current = {}; + started.reset(channel); + } +} + +void CSND_SND::SetPlayState(u32 channel, bool play) { + auto& volume = volumes[channel]; + if (play) { + started.set(channel); + volume.current = {volume.requested[0], volume.requested[1]}; + WriteCurrentVolume(channel); + csnd_hw.SetCnt(channel, csnd_hw.GetCnt(channel) | CsndCnt::Enable | CsndCnt::Run); + } else if (IsRunning(channel)) { + pause_pending.set(channel); + SetTargetVolume(channel, 0, 0, true); + } else { + csnd_hw.SetCnt(channel, csnd_hw.GetCnt(channel) & ~CsndCnt::Run); + volume.current = {}; + started.reset(channel); + } +} + +void CSND_SND::UpdateState(ClientData& client) { + const u32 mask_register = csnd_hw.GetChannelMaskRegister(); + WriteShared(client, client.master_state_offset, + std::array{mask_register & client.channel_mask, + mask_register & client.capture_mask}); + + u32 index = 0; + for (u32 channel = 0; channel < Hw::NumChannels; channel++) { + if (!(client.channel_mask & (1u << channel))) { + continue; + } + const u32 adpcm = csnd_hw.GetAdpcmState(channel); + const u32 offset = client.channel_state_offset + index * sizeof(ChannelState); + WriteShared(client, offset, static_cast(IsRunning(channel))); + WriteShared(client, offset + offsetof(ChannelState, adpcm_predictor), + s16_le{static_cast(adpcm & 0xFFFF)}); + WriteShared(client, offset + offsetof(ChannelState, adpcm_index), + static_cast((adpcm >> 16) & 0x7F)); + WriteShared(client, offset + offsetof(ChannelState, zero), u32_le{0}); + index++; + } + + for (u32 unit = 0; unit < Hw::NumCaptureUnits; unit++) { + if (!(client.capture_mask & (1u << unit))) { + continue; + } + // Capture is not emulated: a capture unit never runs. + const u32 offset = client.capture_state_offset + unit * CaptureStateSize; + WriteShared(client, offset, u8{0}); + WriteShared(client, offset + 4, u32_le{0}); + } +} + +void CSND_SND::ExecuteCommand(ClientData& client, const Type0Command& command) { + const CommandId id = command.command_id; + const auto& params = command.params; + const u32 channel = params[0] & 0x1F; + const u32 value = params[1]; + + if (static_cast(id) < 0x100) { + // Channel commands only reach the channels the client acquired. + if (!(client.channel_mask & (1u << channel))) { + return; + } + } else if (static_cast(id) < 0x200) { + if (channel >= Hw::NumCaptureUnits) { + return; + } + LOG_WARNING(Service_CSND, "capture is not emulated (command 0x{:03X})", + static_cast(id)); + } + + const auto clear_channel_state = [&] { + const u32 index = std::popcount(client.channel_mask & ((1u << channel) - 1)); + WriteShared(client, client.channel_state_offset + index * sizeof(ChannelState) + 8, + u32_le{0}); + }; + const auto clear_capture_state = [&] { + WriteShared(client, client.capture_state_offset + channel * CaptureStateSize + 4, + u32_le{0}); + }; + const auto set_cnt_bits = [&](u32 mask, CsndCnt bits) { + csnd_hw.SetCnt(channel, (csnd_hw.GetCnt(channel) & ~static_cast(mask)) | bits); + }; + const auto set_capture_cnt_bits = [&](CsndCaptureCnt mask, CsndCaptureCnt bits) { + csnd_hw.SetCaptureCnt(channel, (csnd_hw.GetCaptureCnt(channel) & ~mask) | bits); + }; + const bool busy = True(csnd_hw.GetCnt(channel) & CsndCnt::Enable); + + switch (id) { + case CommandId::SetPlayStateRaw: + SetPlayStateRaw(channel, value != 0); + break; + case CommandId::SetPlayState: + SetPlayState(channel, value != 0); + break; + case CommandId::SetEncoding: + // The value is not masked to the field, as in real hardware. + if (!busy) { + set_cnt_bits(AudioCore::Csnd::CntFormatMask, + static_cast((value & 0xFF) << Hw::CntFormatShift)); + } + break; + case CommandId::SetLoopBlock: + csnd_hw.SetLoopAddress(channel, value); + csnd_hw.SetSize(channel, params[2]); + break; + case CommandId::SetLoopMode: + if (!busy) { + set_cnt_bits(AudioCore::Csnd::CntLoopModeMask, + static_cast((value & 0xFF) << Hw::CntLoopModeShift)); + } + break; + case CommandId::SetHold: + set_cnt_bits(static_cast(CsndCnt::Hold), value != 0 ? CsndCnt::Hold : CsndCnt::None); + break; + case CommandId::SetLinearInterpolation: + if (!busy) { + set_cnt_bits(static_cast(CsndCnt::LinearInterpolation), + value != 0 ? CsndCnt::LinearInterpolation : CsndCnt::None); + } + break; + case CommandId::SetTimer: + csnd_hw.SetTimer(channel, static_cast(0x10000 - value)); + break; + case CommandId::SetVolume: + SetRequestedVolume(channel, value & 0xFFFF, value >> 16, true); + csnd_hw.SetCaptureVolume(channel, params[2] & 0xFFFF, params[2] >> 16); + break; + case CommandId::SetBlock: + csnd_hw.SetStartAddress(channel, value); + csnd_hw.SetSize(channel, params[2]); + clear_channel_state(); + break; + case CommandId::SetAdpcmState: + csnd_hw.SetAdpcmState(channel, (value & 0xFFFF) | ((params[2] & 0xFF) << 16)); + csnd_hw.SetLoopAdpcmState(channel, 0); + break; + case CommandId::SetLoopAdpcmState: + csnd_hw.SetLoopAdpcmState(channel, (value & 0xFFFF) | ((params[2] & 0xFF) << 16) | + Hw::LoopAdpcmReload); + break; + case CommandId::SetLoopAdpcmReload: { + const u32 state = csnd_hw.GetLoopAdpcmState(channel) & ~Hw::LoopAdpcmReload; + csnd_hw.SetLoopAdpcmState(channel, state | (value != 0 ? Hw::LoopAdpcmReload : 0)); + break; + } + case CommandId::ConfigureChannel: { + const ConfigureChannelFlags flags{params[0]}; + csnd_hw.SetCnt(channel, CsndCnt::None); + csnd_hw.SetTimer(channel, static_cast(0x10000 - flags.timer)); + csnd_hw.SetVolume(channel, 0, 0); + csnd_hw.SetCaptureVolume(channel, params[2] & 0xFFFF, params[2] >> 16); + csnd_hw.SetLoopAddress(channel, params[4]); + csnd_hw.SetSize(channel, params[5] & 0x7FFFFFF); + csnd_hw.SetStartAddress(channel, params[3]); + if (flags.format != Hw::Format::ImaAdpcm) { + csnd_hw.SetAdpcmState(channel, 0); + csnd_hw.SetLoopAdpcmState(channel, 0); + } + csnd_hw.SetCnt(channel, Hw::CntFormat(flags.format) | Hw::CntLoopMode(flags.loop_mode) | + (flags.linear_interpolation ? CsndCnt::LinearInterpolation + : CsndCnt::None)); + SetRequestedVolume(channel, value & 0xFFFF, value >> 16, false); + SetPlayState(channel, flags.play != 0); + clear_channel_state(); + break; + } + case CommandId::SetPsgDuty: + case CommandId::ConfigurePsg: + case CommandId::ConfigureNoise: + // TODO(PabloMK7): PSG and noise channels. + LOG_WARNING(Service_CSND, "(STUBBED) PSG/noise command 0x{:03X}, channel {}", + static_cast(id), channel); + break; + case CommandId::SetCaptureEnable: + set_capture_cnt_bits(CsndCaptureCnt::Enable, + value != 0 ? CsndCaptureCnt::Enable : CsndCaptureCnt::None); + break; + case CommandId::SetCaptureOneShot: + // The value is not masked to the field, as in real hardware. + set_capture_cnt_bits(CsndCaptureCnt::OneShot, static_cast(value & 0xFF)); + break; + case CommandId::SetCaptureFormat: + set_capture_cnt_bits(CsndCaptureCnt::Pcm8, + static_cast((value & 0xFF) << 1)); + break; + case CommandId::SetCaptureBit2: + set_capture_cnt_bits(CsndCaptureCnt::Unknown2, + value != 0 ? CsndCaptureCnt::Unknown2 : CsndCaptureCnt::None); + break; + case CommandId::SetCaptureTimer: + csnd_hw.SetCaptureTimer(channel, static_cast(0x10000 - value)); + break; + case CommandId::SetCaptureBuffer: + csnd_hw.SetCaptureAddress(channel, value, params[2]); + clear_capture_state(); + break; + case CommandId::ConfigureCapture: + csnd_hw.SetCaptureCnt(channel, CsndCaptureCnt::None); + csnd_hw.SetCaptureTimer(channel, static_cast(0x10000 - (value >> 16))); + csnd_hw.SetCaptureAddress(channel, params[2], params[3]); + csnd_hw.SetCaptureCnt(channel, static_cast(value) & + (CsndCaptureCnt::Enable | CsndCaptureCnt::OneShot | + CsndCaptureCnt::Pcm8 | CsndCaptureCnt::Unknown2)); + clear_capture_state(); + break; + case CommandId::ApplyMasks: + csnd_hw.SetChannelMaskRegister(client.channel_mask); + csnd_hw.SetCaptureMaskRegister(client.capture_mask); + break; + case CommandId::UpdateState: + UpdateState(client); + break; + default: + LOG_DEBUG(Service_CSND, "unknown command 0x{:X}", static_cast(id)); + break; + } +} void CSND_SND::Initialize(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); - const u32 size = Common::AlignUp(rp.Pop(), Memory::CITRA_PAGE_SIZE); - master_state_offset = rp.Pop(); - channel_state_offset = rp.Pop(); - capture_state_offset = rp.Pop(); - type1_command_offset = rp.Pop(); + const u32 size = rp.Pop(); + const u32 master_state_offset = rp.Pop(); + const u32 channel_state_offset = rp.Pop(); + const u32 capture_state_offset = rp.Pop(); + const u32 direct_sound_offset = rp.Pop(); - using Kernel::MemoryPermission; - mutex = system.Kernel().CreateMutex(false, "CSND:mutex"); - shared_memory = system.Kernel() - .CreateSharedMemory(nullptr, size, MemoryPermission::ReadWrite, - MemoryPermission::ReadWrite, 0, - Kernel::MemoryRegion::BASE, "CSND:SharedMemory") - .Unwrap(); + LOG_DEBUG(Service_CSND, + "called, size=0x{:08X} master_state_offset=0x{:08X} " + "channel_state_offset=0x{:08X} capture_state_offset=0x{:08X} " + "direct_sound_offset=0x{:08X}", + size, master_state_offset, channel_state_offset, capture_state_offset, + direct_sound_offset); + + auto* client = GetSessionData(ctx.Session()); + if (client->mutex) { + // Real hardware panics, we are more gentle and return an error instead. + LOG_ERROR(Service_CSND, "session already initialized"); + IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); + rb.Push(ResultAlreadyInitialized); + return; + } + + auto shared_memory = system.Kernel().CreateSharedMemory( + nullptr, Common::AlignUp(std::max(size, 1), Memory::CITRA_PAGE_SIZE), + Kernel::MemoryPermission::ReadWrite, Kernel::MemoryPermission::ReadWrite, 0, + Kernel::MemoryRegion::BASE, "CSND:SharedMemory"); + if (shared_memory.Failed()) { + IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); + rb.Push(shared_memory.Code()); + return; + } + + client->mutex = system.Kernel().CreateMutex(false, "CSND:mutex"); + client->shared_memory = shared_memory.Unwrap(); + std::memset(client->shared_memory->GetPointer(), 0, client->shared_memory->GetSize()); + client->master_state_offset = master_state_offset; + client->channel_state_offset = channel_state_offset; + client->capture_state_offset = capture_state_offset; + client->direct_sound_offset = direct_sound_offset; + initialized_clients++; + StartTicking(); IPC::RequestBuilder rb = rp.MakeBuilder(1, 3); rb.Push(ResultSuccess); - rb.PushCopyObjects(mutex, shared_memory); - - LOG_WARNING(Service_CSND, - "(STUBBED) called, size=0x{:08X} " - "master_state_offset=0x{:08X} channel_state_offset=0x{:08X} " - "capture_state_offset=0x{:08X} type1_command_offset=0x{:08X}", - size, master_state_offset, channel_state_offset, capture_state_offset, - type1_command_offset); + rb.PushCopyObjects(client->mutex, client->shared_memory); } void CSND_SND::Shutdown(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); + LOG_DEBUG(Service_CSND, "called"); - if (mutex) - mutex = nullptr; - if (shared_memory) - shared_memory = nullptr; + // Channels keep playing and stay acquired, as in real hardware. + auto* client = GetSessionData(ctx.Session()); + if (client->mutex) { + initialized_clients--; + } + client->mutex = nullptr; + client->shared_memory = nullptr; IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); rb.Push(ResultSuccess); - - LOG_WARNING(Service_CSND, "(STUBBED) called"); } void CSND_SND::ExecuteCommands(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); - const u32 addr = rp.Pop(); - LOG_DEBUG(Service_CSND, "(STUBBED) called, addr=0x{:08X}", addr); + const u32 first_offset = rp.Pop(); + LOG_TRACE(Service_CSND, "called, offset=0x{:08X}", first_offset); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); - if (!shared_memory) { - rb.Push(Result(ErrorDescription::InvalidResultValue, ErrorModule::CSND, - ErrorSummary::InvalidState, ErrorLevel::Status)); - LOG_ERROR(Service_CSND, "called, shared memory not allocated"); + auto* client = GetSessionData(ctx.Session()); + if (!client->shared_memory) { + LOG_ERROR(Service_CSND, "called before Initialize"); + rb.Push(ResultInvalidState); return; } - u32 offset = addr; - while (offset != 0xFFFF) { + // Real hardware defers this to a worker thread. + UpdateHardware(); + const u64 size = client->shared_memory->GetSize(); + const u64 max_commands = size / sizeof(Type0Command); + u64 executed = 0; + for (u32 offset = first_offset; offset != CommandListEnd;) { + if (offset + sizeof(Type0Command) > size || executed++ >= max_commands) { + LOG_ERROR(Service_CSND, "bad command list (offset 0x{:X})", offset); + break; + } Type0Command command; - u8* ptr = shared_memory->GetPointer(offset); - std::memcpy(&command, ptr, sizeof(Type0Command)); + std::memcpy(&command, client->shared_memory->GetPointer(offset), sizeof(command)); + ExecuteCommand(*client, command); offset = command.next_command_offset; - - switch (command.command_id) { - case CommandId::Start: - // TODO: start/stop the sound - break; - case CommandId::Pause: - // TODO: pause/resume the sound - break; - case CommandId::SetEncoding: - channels[command.set_encoding.channel].encoding = command.set_encoding.value; - break; - case CommandId::SetSecondBlock: - channels[command.set_block.channel].block2_address = command.set_block.address; - channels[command.set_block.channel].block2_size = command.set_block.size; - break; - case CommandId::SetLoopMode: - channels[command.set_loop_mode.channel].loop_mode = command.set_loop_mode.value; - break; - case CommandId::SetLinearInterpolation: - channels[command.set_linear_interpolation.channel].linear_interpolation = - command.set_linear_interpolation.value != 0; - break; - case CommandId::SetPsgDuty: - channels[command.set_psg_duty.channel].psg_duty = command.set_psg_duty.value; - break; - case CommandId::SetSampleRate: - channels[command.set_sample_rate.channel].sample_rate = command.set_sample_rate.value; - break; - case CommandId::SetVolume: - channels[command.set_volume.channel].left_channel_volume = - command.set_volume.left_channel_volume; - channels[command.set_volume.channel].right_channel_volume = - command.set_volume.right_channel_volume; - channels[command.set_volume.channel].left_capture_volume = - command.set_volume.left_capture_volume; - channels[command.set_volume.channel].right_capture_volume = - command.set_volume.right_capture_volume; - break; - case CommandId::SetFirstBlock: - channels[command.set_block.channel].block1_address = command.set_block.address; - channels[command.set_block.channel].block1_size = command.set_block.size; - break; - case CommandId::SetFirstBlockAdpcmState: - channels[command.set_adpcm_state.channel].block1_adpcm_state = { - command.set_adpcm_state.predictor, command.set_adpcm_state.step_index}; - channels[command.set_adpcm_state.channel].block2_adpcm_state = {}; - channels[command.set_adpcm_state.channel].block2_adpcm_reload = false; - break; - case CommandId::SetSecondBlockAdpcmState: - channels[command.set_adpcm_state.channel].block2_adpcm_state = { - command.set_adpcm_state.predictor, command.set_adpcm_state.step_index}; - channels[command.set_adpcm_state.channel].block2_adpcm_reload = true; - break; - case CommandId::SetSecondBlockAdpcmReload: - channels[command.set_second_block_adpcm_reload.channel].block2_adpcm_reload = - command.set_second_block_adpcm_reload.value != 0; - break; - case CommandId::ConfigureChannel: { - auto& configure = command.configure_channel; - auto& channel = channels[configure.channel]; - channel.linear_interpolation = configure.linear_interpolation != 0; - channel.loop_mode = static_cast(configure.loop_mode.Value()); - channel.encoding = static_cast(configure.encoding.Value()); - channel.sample_rate = configure.sample_rate; - channel.left_channel_volume = configure.left_channel_volume; - channel.right_channel_volume = configure.right_channel_volume; - channel.left_capture_volume = configure.left_capture_volume; - channel.right_capture_volume = configure.right_capture_volume; - channel.block1_address = configure.block1_address; - channel.block2_address = configure.block2_address; - channel.block1_size = channel.block2_size = configure.size; - if (configure.enable_playback) { - // TODO: startthe sound - } - break; - } - case CommandId::ConfigurePsg: { - auto& configure = command.configure_psg; - auto& channel = channels[configure.channel]; - channel.encoding = Encoding::Psg; - channel.psg_duty = configure.duty; - channel.sample_rate = configure.sample_rate; - channel.left_channel_volume = configure.left_channel_volume; - channel.right_channel_volume = configure.right_channel_volume; - channel.left_capture_volume = configure.left_capture_volume; - channel.right_capture_volume = configure.right_capture_volume; - if (configure.enable_playback) { - // TODO: startthe sound - } - break; - } - case CommandId::ConfigurePsgNoise: { - auto& configure = command.configure_psg_noise; - auto& channel = channels[configure.channel]; - channel.encoding = Encoding::Psg; - channel.left_channel_volume = configure.left_channel_volume; - channel.right_channel_volume = configure.right_channel_volume; - channel.left_capture_volume = configure.left_capture_volume; - channel.right_capture_volume = configure.right_capture_volume; - if (configure.enable_playback) { - // TODO: startthe sound - } - break; - } - case CommandId::UpdateState: { - MasterState master{0, 0}; - std::memcpy(shared_memory->GetPointer(master_state_offset), &master, sizeof(master)); - - u32 output_index = 0; - for (u32 i = 0; i < ChannelCount; ++i) { - if ((acquired_channel_mask & (1 << i)) == 0) - continue; - ChannelState state; - state.active = false; - state.adpcm_predictor = channels[i].block1_adpcm_state.predictor; - state.adpcm_predictor = channels[i].block1_adpcm_state.step_index; - state.zero = 0; - std::memcpy( - shared_memory->GetPointer(channel_state_offset + sizeof(state) * output_index), - &state, sizeof(state)); - ++output_index; - } - - for (u32 i = 0; i < MaxCaptureUnits; ++i) { - if (!capture_units[i]) - continue; - CaptureState state; - state.active = false; - state.zero = 0; - std::memcpy(shared_memory->GetPointer(capture_state_offset + sizeof(state) * i), - &state, sizeof(state)); - } - - break; - } - default: - LOG_ERROR(Service_CSND, "Unimplemented command ID 0x{:X}", command.command_id); - } } - *shared_memory->GetPointer(addr + offsetof(Type0Command, finished)) = 1; + if (first_offset + sizeof(Type0Command) <= size) { + *client->shared_memory->GetPointer(first_offset + offsetof(Type0Command, finished)) = 1; + } rb.Push(ResultSuccess); } @@ -400,119 +649,138 @@ void CSND_SND::ExecuteCommands(Kernel::HLERequestContext& ctx) { void CSND_SND::AcquireSoundChannels(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); - // This is "almost" hardcoded, as in CSND initializes this with some code during sysmodule - // startup, but it always compute to the same value. - acquired_channel_mask = 0xFFFFFF00; + // There is no real channel allocation per client, all clients get the same channels. + auto* client = GetSessionData(ctx.Session()); + client->channel_mask = ClientChannelMask; IPC::RequestBuilder rb = rp.MakeBuilder(2, 0); rb.Push(ResultSuccess); - rb.Push(acquired_channel_mask); - - LOG_WARNING(Service_CSND, "(STUBBED) called"); + rb.Push(client->channel_mask); } void CSND_SND::ReleaseSoundChannels(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); - acquired_channel_mask = 0; + GetSessionData(ctx.Session())->channel_mask = 0; IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); rb.Push(ResultSuccess); - - LOG_WARNING(Service_CSND, "(STUBBED) called"); } void CSND_SND::AcquireCapUnit(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); + auto* client = GetSessionData(ctx.Session()); IPC::RequestBuilder rb = rp.MakeBuilder(2, 0); - if (capture_units[0] && capture_units[1]) { + const auto free_unit = + std::find(capture_units_in_use.begin(), capture_units_in_use.end(), false); + if (free_unit == capture_units_in_use.end()) { LOG_WARNING(Service_CSND, "No more capture units available"); - rb.Push(Result(ErrorDescription::InvalidResultValue, ErrorModule::CSND, - ErrorSummary::OutOfResource, ErrorLevel::Status)); - rb.Skip(1, false); + rb.Push(ResultInvalidState); + rb.Push(0xFFFFFFFF); return; } + + const u32 unit = static_cast(free_unit - capture_units_in_use.begin()); + *free_unit = true; + client->capture_mask |= 1u << unit; + WriteShared(*client, client->capture_state_offset + unit * CaptureStateSize, u8{0}); + WriteShared(*client, client->capture_state_offset + unit * CaptureStateSize + 4, u32_le{0}); + rb.Push(ResultSuccess); - - if (capture_units[0]) { - capture_units[1] = true; - rb.Push(1); - } else { - capture_units[0] = true; - rb.Push(0); - } - - LOG_WARNING(Service_CSND, "(STUBBED) called"); + rb.Push(unit); } void CSND_SND::ReleaseCapUnit(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); - const u32 index = rp.Pop(); - - capture_units[index] = false; + const u32 unit = rp.Pop(); + auto* client = GetSessionData(ctx.Session()); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); - rb.Push(ResultSuccess); + if (unit >= Hw::NumCaptureUnits || !(client->capture_mask & (1u << unit))) { + LOG_ERROR(Service_CSND, "capture unit {} not acquired", unit); + rb.Push(ResultInvalidState); + return; + } - LOG_WARNING(Service_CSND, "(STUBBED) called, capture_unit_index={}", index); + client->capture_mask &= ~(1u << unit); + capture_units_in_use[unit] = false; + rb.Push(ResultSuccess); +} + +void CSND_SND::CacheOperation(Kernel::HLERequestContext& ctx) { + IPC::RequestParser rp(ctx); + const VAddr address = rp.Pop(); + const u32 size = rp.Pop(); + [[maybe_unused]] const auto process = rp.PopObject(); + + // The CPU cache is not emulated, only the range check is. + const auto in_range = [&](u32 low, u32 high) { + const u32 end = address + size; + return low <= address && address <= high && low <= end && end <= high; + }; + const bool valid = in_range(0x14000000, 0x1C000000) || in_range(0x30000000, 0x40000000); + + IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); + rb.Push(valid ? ResultSuccess : ResultInvalidAddress); + + LOG_TRACE(Service_CSND, "called address=0x{:08X}, size=0x{:08X}", address, size); } void CSND_SND::FlushDataCache(Kernel::HLERequestContext& ctx) { - IPC::RequestParser rp(ctx); - [[maybe_unused]] const VAddr address = rp.Pop(); - [[maybe_unused]] const u32 size = rp.Pop(); - const auto process = rp.PopObject(); - - IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); - rb.Push(ResultSuccess); - - LOG_TRACE(Service_CSND, "(STUBBED) called address=0x{:08X}, size=0x{:08X}, process={}", address, - size, process->process_id); + CacheOperation(ctx); } void CSND_SND::StoreDataCache(Kernel::HLERequestContext& ctx) { - IPC::RequestParser rp(ctx); - [[maybe_unused]] const VAddr address = rp.Pop(); - [[maybe_unused]] const u32 size = rp.Pop(); - const auto process = rp.PopObject(); - - IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); - rb.Push(ResultSuccess); - - LOG_TRACE(Service_CSND, "(STUBBED) called address=0x{:08X}, size=0x{:08X}, process={}", address, - size, process->process_id); + CacheOperation(ctx); } void CSND_SND::InvalidateDataCache(Kernel::HLERequestContext& ctx) { - IPC::RequestParser rp(ctx); - [[maybe_unused]] const VAddr address = rp.Pop(); - [[maybe_unused]] const u32 size = rp.Pop(); - const auto process = rp.PopObject(); - - IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); - rb.Push(ResultSuccess); - - LOG_TRACE(Service_CSND, "(STUBBED) called address=0x{:08X}, size=0x{:08X}, process={}", address, - size, process->process_id); + CacheOperation(ctx); } void CSND_SND::Reset(Kernel::HLERequestContext& ctx) { IPC::RequestParser rp(ctx); + LOG_DEBUG(Service_CSND, "called"); + + // Stops all channels immediately, without fading. + UpdateHardware(); + for (u32 channel = 0; channel < Hw::NumChannels; channel++) { + StopChannel(channel); + volumes[channel].current = {}; + WriteCurrentVolume(channel); + } + started.reset(); + fading.reset(); + stop_pending.reset(); + pause_pending.reset(); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); rb.Push(ResultSuccess); - - LOG_WARNING(Service_CSND, "(STUBBED) called"); } -CSND_SND::CSND_SND(Core::System& system) : ServiceFramework("csnd:SND", 4), system(system) { +void CSND_SND::ClientDisconnected(std::shared_ptr server_session) { + if (auto* client = GetSessionData(server_session)) { + if (client->mutex) { + initialized_clients--; + } + for (u32 unit = 0; unit < Hw::NumCaptureUnits; unit++) { + if (client->capture_mask & (1u << unit)) { + capture_units_in_use[unit] = false; + } + } + } + SessionRequestHandler::ClientDisconnected(server_session); +} + +CSND_SND::CSND_SND(Core::System& system) + : ServiceFramework("csnd:SND", 4), system(system), csnd_hw(system.Memory()) { static const FunctionInfo functions[] = { // clang-format off {0x0001, &CSND_SND::Initialize, "Initialize"}, {0x0002, &CSND_SND::Shutdown, "Shutdown"}, {0x0003, &CSND_SND::ExecuteCommands, "ExecuteCommands"}, - {0x0004, nullptr, "ExecuteType1Commands"}, + {0x0004, nullptr, "PlaySoundDirectly"}, {0x0005, &CSND_SND::AcquireSoundChannels, "AcquireSoundChannels"}, {0x0006, &CSND_SND::ReleaseSoundChannels, "ReleaseSoundChannels"}, {0x0007, &CSND_SND::AcquireCapUnit, "AcquireCapUnit"}, @@ -523,9 +791,41 @@ CSND_SND::CSND_SND(Core::System& system) : ServiceFramework("csnd:SND", 4), syst {0x000C, &CSND_SND::Reset, "Reset"}, // clang-format on }; - RegisterHandlers(functions); -}; + + Core::Timing& timing = system.CoreTiming(); + audio_tick_event = + timing.RegisterEvent("CSND::AudioTickCallback", [this](std::uintptr_t, s64 cycles_late) { + AudioTickCallback(cycles_late); + }); + fade_event = + timing.RegisterEvent("CSND::FadeCallback", [this](std::uintptr_t step, s64 cycles_late) { + FadeCallback(step, cycles_late); + }); +} + +CSND_SND::~CSND_SND() = default; + +template +void CSND_SND::serialize(Archive& ar, const unsigned int) { + DEBUG_SERIALIZATION_POINT; + ar& boost::serialization::base_object(*this); + ar & csnd_hw; + ar & volumes; + ar & started; + ar & fading; + ar & stop_pending; + ar & pause_pending; + ar & fade_scheduled; + ar & capture_units_in_use; + ar & is_ticking; + ar & initialized_clients; + ar & frame; + ar & frame_samples; + ar & frame_start_ticks; + ar & frame_length_ticks; +} +SERIALIZE_IMPL(CSND_SND) void InstallInterfaces(Core::System& system) { auto& service_manager = system.ServiceManager(); diff --git a/src/core/hle/service/csnd/csnd_snd.h b/src/core/hle/service/csnd/csnd_snd.h index 3c566603e..26ca3a879 100644 --- a/src/core/hle/service/csnd/csnd_snd.h +++ b/src/core/hle/service/csnd/csnd_snd.h @@ -1,12 +1,17 @@ -// Copyright 2014-2025 Citra Emulator Project / Azahar Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the misc/licenses/gplv2.txt file included. +// Copyright 2014-2026 Citra Emulator Project / Azahar Emulator Project +// Licensed under GPLv3 or any later version +// Refer to the LICENSE.txt file included. #pragma once +#include +#include #include #include +#include #include +#include "audio_core/audio_types.h" +#include "audio_core/csnd.h" #include "common/archives.h" #include "core/hle/kernel/mutex.h" #include "core/hle/kernel/shared_memory.h" @@ -14,83 +19,36 @@ namespace Core { class System; -} +struct TimingEventType; +} // namespace Core namespace Service::CSND { -enum class Encoding : u8 { - Pcm8 = 0, - Pcm16 = 1, - Adpcm = 2, - Psg = 3, -}; +struct Type0Command; -enum class LoopMode : u8 { - Manual = 0, // Play block 1 endlessly ignoring the size - Normal = 1, // Play block 1 once, then repeat with block 2. Block size is reloaded every time a - // new block is started - OneShot = 2, // Play block 1 once and stop - ConstantSize = 3, // Similar to Normal, but only load block size once at the beginning -}; - -struct AdpcmState { - s16 predictor = 0; - u8 step_index = 0; +/// State the CSND module keeps for each client session. +struct ClientData : public Kernel::SessionRequestHandler::SessionDataBase { + std::shared_ptr mutex; + std::shared_ptr shared_memory; + u32 master_state_offset = 0; + u32 channel_state_offset = 0; + u32 capture_state_offset = 0; + u32 direct_sound_offset = 0; + u32 channel_mask = 0; + u8 capture_mask = 0; private: template - void serialize(Archive& ar, const unsigned int) { - ar & predictor; - ar & step_index; - } + void serialize(Archive& ar, const unsigned int); friend class boost::serialization::access; }; -struct Channel { - PAddr block1_address = 0; - PAddr block2_address = 0; - u32 block1_size = 0; - u32 block2_size = 0; - AdpcmState block1_adpcm_state; - AdpcmState block2_adpcm_state; - bool block2_adpcm_reload = false; - u16 left_channel_volume = 0; - u16 right_channel_volume = 0; - u16 left_capture_volume = 0; - u16 right_capture_volume = 0; - u32 sample_rate = 0; - bool linear_interpolation = false; - LoopMode loop_mode = LoopMode::Manual; - Encoding encoding = Encoding::Pcm8; - u8 psg_duty = 0; - -private: - template - void serialize(Archive& ar, const unsigned int) { - ar & block1_address; - ar & block2_address; - ar & block1_size; - ar & block2_size; - ar & block1_adpcm_state; - ar & block2_adpcm_state; - ar & block2_adpcm_reload; - ar & left_channel_volume; - ar & right_channel_volume; - ar & left_capture_volume; - ar & right_capture_volume; - ar & sample_rate; - ar & linear_interpolation; - ar & loop_mode; - ar & encoding; - ar & psg_duty; - } - friend class boost::serialization::access; -}; - -class CSND_SND final : public ServiceFramework { +class CSND_SND final : public ServiceFramework { public: explicit CSND_SND(Core::System& system); - ~CSND_SND() = default; + ~CSND_SND(); + + void ClientDisconnected(std::shared_ptr server_session) override; private: /** @@ -101,7 +59,7 @@ private: * 2 : offset to master state located in the shared-memory, region size=8 * 3 : offset to channel state located in the shared-memory, region size=12*num_channels * 4 : offset to capture state located in the shared-memory, region size=8*num_captures - * 5 : offset to type 1 commands (?) located in the shared-memory. + * 5 : offset to the direct sound structure located in the shared-memory. * Outputs: * 1 : Result of function, 0 on success, otherwise error code * 2 : Handle-list header @@ -129,17 +87,6 @@ private: */ void ExecuteCommands(Kernel::HLERequestContext& ctx); - /** - * CSND_SND::ExecuteType1Commands service function - * Inputs: - * 0 : Header Code[0x00040080] - * 1 : unknown - * 2 : unknown - * Outputs: - * 1 : Result of function, 0 on success, otherwise error code - */ - void ExecuteType1Commands(Kernel::HLERequestContext& ctx); - /** * CSND_SND::AcquireSoundChannels service function * Inputs: @@ -238,38 +185,69 @@ private: */ void Reset(Kernel::HLERequestContext& ctx); + void CacheOperation(Kernel::HLERequestContext& ctx); + + void ExecuteCommand(ClientData& client, const Type0Command& command); + void UpdateState(ClientData& client); + + /// Renders the pending samples up to the current emulated time, so that the registers read and + /// written respresent the proper values at that time. + void UpdateHardware(); + + bool IsRunning(u32 channel); + void SetPlayStateRaw(u32 channel, bool play); + void SetPlayState(u32 channel, bool play); + void StopChannel(u32 channel); + void SetRequestedVolume(u32 channel, u16 left, u16 right, bool start_fade); + void SetTargetVolume(u32 channel, u16 left, u16 right, bool start_fade); + void WriteCurrentVolume(u32 channel); + void StartFade(); + void FadeCallback(std::uintptr_t step, s64 cycles_late); + void StartTicking(); + void AudioTickCallback(s64 cycles_late); + Core::System& system; - std::shared_ptr mutex = nullptr; - std::shared_ptr shared_memory = nullptr; + AudioCore::Csnd csnd_hw; - static constexpr u32 MaxCaptureUnits = 2; - std::array capture_units = {false, false}; + struct ChannelVolume { + std::array requested{}; + std::array target{}; + std::array current{}; + std::array step{}; - static constexpr u32 ChannelCount = 32; - std::array channels; + private: + template + void serialize(Archive& ar, const unsigned int) { + ar & requested; + ar & target; + ar & current; + ar & step; + } + friend class boost::serialization::access; + }; + std::array volumes{}; + using ChannelSet = std::bitset; + ChannelSet started; ///< Channels started through command 1 + ChannelSet fading; ///< Channels fading towards their target + ChannelSet stop_pending; ///< Channels to stop once faded out + ChannelSet pause_pending; ///< Channels to pause once faded out + bool fade_scheduled = false; - u32 master_state_offset = 0; - u32 channel_state_offset = 0; - u32 capture_state_offset = 0; - u32 type1_command_offset = 0; + std::array capture_units_in_use{}; - u32 acquired_channel_mask = 0; + bool is_ticking = false; + u32 initialized_clients = 0; + AudioCore::StereoFrame16 frame{}; + u32 frame_samples = 0; + s64 frame_start_ticks = 0; + s64 frame_length_ticks = 0; + + Core::TimingEventType* audio_tick_event = nullptr; + Core::TimingEventType* fade_event = nullptr; template - void serialize(Archive& ar, const unsigned int) { - DEBUG_SERIALIZATION_POINT; - ar& boost::serialization::base_object(*this); - ar & mutex; - ar & shared_memory; - ar & capture_units; - ar & channels; - ar & master_state_offset; - ar & channel_state_offset; - ar & capture_state_offset; - ar & type1_command_offset; - ar & acquired_channel_mask; - } + void serialize(Archive& ar, const unsigned int); friend class boost::serialization::access; }; @@ -279,4 +257,5 @@ void InstallInterfaces(Core::System& system); } // namespace Service::CSND BOOST_CLASS_EXPORT_KEY(Service::CSND::CSND_SND) +BOOST_CLASS_EXPORT_KEY(Service::CSND::ClientData) SERVICE_CONSTRUCT(Service::CSND::CSND_SND)