audio_renderer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <limits>
  4. #include <vector>
  5. #include "audio_core/audio_out.h"
  6. #include "audio_core/audio_renderer.h"
  7. #include "audio_core/common.h"
  8. #include "audio_core/info_updater.h"
  9. #include "audio_core/voice_context.h"
  10. #include "common/logging/log.h"
  11. #include "common/settings.h"
  12. #include "core/core_timing.h"
  13. #include "core/memory.h"
  14. namespace {
  15. [[nodiscard]] static constexpr s16 ClampToS16(s32 value) {
  16. return static_cast<s16>(std::clamp(value, s32{std::numeric_limits<s16>::min()},
  17. s32{std::numeric_limits<s16>::max()}));
  18. }
  19. [[nodiscard]] static constexpr s16 Mix2To1(s16 l_channel, s16 r_channel) {
  20. // Mix 50% from left and 50% from right channel
  21. constexpr float l_mix_amount = 50.0f / 100.0f;
  22. constexpr float r_mix_amount = 50.0f / 100.0f;
  23. return ClampToS16(static_cast<s32>((static_cast<float>(l_channel) * l_mix_amount) +
  24. (static_cast<float>(r_channel) * r_mix_amount)));
  25. }
  26. [[maybe_unused, nodiscard]] static constexpr std::tuple<s16, s16> Mix6To2(
  27. s16 fl_channel, s16 fr_channel, s16 fc_channel, [[maybe_unused]] s16 lf_channel, s16 bl_channel,
  28. s16 br_channel) {
  29. // Front channels are mixed 36.94%, Center channels are mixed to be 26.12% & the back channels
  30. // are mixed to be 36.94%
  31. constexpr float front_mix_amount = 36.94f / 100.0f;
  32. constexpr float center_mix_amount = 26.12f / 100.0f;
  33. constexpr float back_mix_amount = 36.94f / 100.0f;
  34. // Mix 50% from left and 50% from right channel
  35. const auto left = front_mix_amount * static_cast<float>(fl_channel) +
  36. center_mix_amount * static_cast<float>(fc_channel) +
  37. back_mix_amount * static_cast<float>(bl_channel);
  38. const auto right = front_mix_amount * static_cast<float>(fr_channel) +
  39. center_mix_amount * static_cast<float>(fc_channel) +
  40. back_mix_amount * static_cast<float>(br_channel);
  41. return {ClampToS16(static_cast<s32>(left)), ClampToS16(static_cast<s32>(right))};
  42. }
  43. [[nodiscard]] static constexpr std::tuple<s16, s16> Mix6To2WithCoefficients(
  44. s16 fl_channel, s16 fr_channel, s16 fc_channel, s16 lf_channel, s16 bl_channel, s16 br_channel,
  45. const std::array<float_le, 4>& coeff) {
  46. const auto left =
  47. static_cast<float>(fl_channel) * coeff[0] + static_cast<float>(fc_channel) * coeff[1] +
  48. static_cast<float>(lf_channel) * coeff[2] + static_cast<float>(bl_channel) * coeff[3];
  49. const auto right =
  50. static_cast<float>(fr_channel) * coeff[0] + static_cast<float>(fc_channel) * coeff[1] +
  51. static_cast<float>(lf_channel) * coeff[2] + static_cast<float>(br_channel) * coeff[3];
  52. return {ClampToS16(static_cast<s32>(left)), ClampToS16(static_cast<s32>(right))};
  53. }
  54. } // namespace
  55. namespace AudioCore {
  56. constexpr s32 NUM_BUFFERS = 2;
  57. AudioRenderer::AudioRenderer(Core::Timing::CoreTiming& core_timing_, Core::Memory::Memory& memory_,
  58. AudioCommon::AudioRendererParameter params,
  59. Stream::ReleaseCallback&& release_callback,
  60. std::size_t instance_number)
  61. : worker_params{params}, memory_pool_info(params.effect_count + params.voice_count * 4),
  62. voice_context(params.voice_count), effect_context(params.effect_count), mix_context(),
  63. sink_context(params.sink_count), splitter_context(),
  64. voices(params.voice_count), memory{memory_},
  65. command_generator(worker_params, voice_context, mix_context, splitter_context, effect_context,
  66. memory),
  67. core_timing{core_timing_} {
  68. behavior_info.SetUserRevision(params.revision);
  69. splitter_context.Initialize(behavior_info, params.splitter_count,
  70. params.num_splitter_send_channels);
  71. mix_context.Initialize(behavior_info, params.submix_count + 1, params.effect_count);
  72. audio_out = std::make_unique<AudioCore::AudioOut>();
  73. stream = audio_out->OpenStream(
  74. core_timing, params.sample_rate, AudioCommon::STREAM_NUM_CHANNELS,
  75. fmt::format("AudioRenderer-Instance{}", instance_number), std::move(release_callback));
  76. process_event = Core::Timing::CreateEvent(
  77. fmt::format("AudioRenderer-Instance{}-Process", instance_number),
  78. [this](std::uintptr_t, std::chrono::nanoseconds) { ReleaseAndQueueBuffers(); });
  79. for (s32 i = 0; i < NUM_BUFFERS; ++i) {
  80. QueueMixedBuffer(i);
  81. }
  82. }
  83. AudioRenderer::~AudioRenderer() = default;
  84. ResultCode AudioRenderer::Start() {
  85. audio_out->StartStream(stream);
  86. ReleaseAndQueueBuffers();
  87. return ResultSuccess;
  88. }
  89. ResultCode AudioRenderer::Stop() {
  90. audio_out->StopStream(stream);
  91. return ResultSuccess;
  92. }
  93. u32 AudioRenderer::GetSampleRate() const {
  94. return worker_params.sample_rate;
  95. }
  96. u32 AudioRenderer::GetSampleCount() const {
  97. return worker_params.sample_count;
  98. }
  99. u32 AudioRenderer::GetMixBufferCount() const {
  100. return worker_params.mix_buffer_count;
  101. }
  102. Stream::State AudioRenderer::GetStreamState() const {
  103. return stream->GetState();
  104. }
  105. ResultCode AudioRenderer::UpdateAudioRenderer(const std::vector<u8>& input_params,
  106. std::vector<u8>& output_params) {
  107. std::scoped_lock lock{mutex};
  108. InfoUpdater info_updater{input_params, output_params, behavior_info};
  109. if (!info_updater.UpdateBehaviorInfo(behavior_info)) {
  110. LOG_ERROR(Audio, "Failed to update behavior info input parameters");
  111. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  112. }
  113. if (!info_updater.UpdateMemoryPools(memory_pool_info)) {
  114. LOG_ERROR(Audio, "Failed to update memory pool parameters");
  115. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  116. }
  117. if (!info_updater.UpdateVoiceChannelResources(voice_context)) {
  118. LOG_ERROR(Audio, "Failed to update voice channel resource parameters");
  119. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  120. }
  121. if (!info_updater.UpdateVoices(voice_context, memory_pool_info, 0)) {
  122. LOG_ERROR(Audio, "Failed to update voice parameters");
  123. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  124. }
  125. // TODO(ogniK): Deal with stopped audio renderer but updates still taking place
  126. if (!info_updater.UpdateEffects(effect_context, true)) {
  127. LOG_ERROR(Audio, "Failed to update effect parameters");
  128. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  129. }
  130. if (behavior_info.IsSplitterSupported()) {
  131. if (!info_updater.UpdateSplitterInfo(splitter_context)) {
  132. LOG_ERROR(Audio, "Failed to update splitter parameters");
  133. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  134. }
  135. }
  136. const auto mix_result = info_updater.UpdateMixes(mix_context, worker_params.mix_buffer_count,
  137. splitter_context, effect_context);
  138. if (mix_result.IsError()) {
  139. LOG_ERROR(Audio, "Failed to update mix parameters");
  140. return mix_result;
  141. }
  142. // TODO(ogniK): Sinks
  143. if (!info_updater.UpdateSinks(sink_context)) {
  144. LOG_ERROR(Audio, "Failed to update sink parameters");
  145. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  146. }
  147. // TODO(ogniK): Performance buffer
  148. if (!info_updater.UpdatePerformanceBuffer()) {
  149. LOG_ERROR(Audio, "Failed to update performance buffer parameters");
  150. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  151. }
  152. if (!info_updater.UpdateErrorInfo(behavior_info)) {
  153. LOG_ERROR(Audio, "Failed to update error info");
  154. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  155. }
  156. if (behavior_info.IsElapsedFrameCountSupported()) {
  157. if (!info_updater.UpdateRendererInfo(elapsed_frame_count)) {
  158. LOG_ERROR(Audio, "Failed to update renderer info");
  159. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  160. }
  161. }
  162. // TODO(ogniK): Statistics
  163. if (!info_updater.WriteOutputHeader()) {
  164. LOG_ERROR(Audio, "Failed to write output header");
  165. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  166. }
  167. // TODO(ogniK): Check when all sections are implemented
  168. if (!info_updater.CheckConsumedSize()) {
  169. LOG_ERROR(Audio, "Audio buffers were not consumed!");
  170. return AudioCommon::Audren::ERR_INVALID_PARAMETERS;
  171. }
  172. return ResultSuccess;
  173. }
  174. void AudioRenderer::QueueMixedBuffer(Buffer::Tag tag) {
  175. command_generator.PreCommand();
  176. // Clear mix buffers before our next operation
  177. command_generator.ClearMixBuffers();
  178. // If the splitter is not in use, sort our mixes
  179. if (!splitter_context.UsingSplitter()) {
  180. mix_context.SortInfo();
  181. }
  182. // Sort our voices
  183. voice_context.SortInfo();
  184. // Handle samples
  185. command_generator.GenerateVoiceCommands();
  186. command_generator.GenerateSubMixCommands();
  187. command_generator.GenerateFinalMixCommands();
  188. command_generator.PostCommand();
  189. // Base sample size
  190. std::size_t BUFFER_SIZE{worker_params.sample_count};
  191. // Samples, making sure to clear
  192. std::vector<s16> buffer(BUFFER_SIZE * stream->GetNumChannels(), 0);
  193. if (sink_context.InUse()) {
  194. const auto stream_channel_count = stream->GetNumChannels();
  195. const auto buffer_offsets = sink_context.OutputBuffers();
  196. const auto channel_count = buffer_offsets.size();
  197. const auto& final_mix = mix_context.GetFinalMixInfo();
  198. const auto& in_params = final_mix.GetInParams();
  199. std::vector<std::span<s32>> mix_buffers(channel_count);
  200. for (std::size_t i = 0; i < channel_count; i++) {
  201. mix_buffers[i] =
  202. command_generator.GetMixBuffer(in_params.buffer_offset + buffer_offsets[i]);
  203. }
  204. for (std::size_t i = 0; i < BUFFER_SIZE; i++) {
  205. if (channel_count == 1) {
  206. const auto sample = ClampToS16(mix_buffers[0][i]);
  207. // Place sample in all channels
  208. for (u32 channel = 0; channel < stream_channel_count; channel++) {
  209. buffer[i * stream_channel_count + channel] = sample;
  210. }
  211. if (stream_channel_count == 6) {
  212. // Output stream has a LF channel, mute it!
  213. buffer[i * stream_channel_count + 3] = 0;
  214. }
  215. } else if (channel_count == 2) {
  216. const auto l_sample = ClampToS16(mix_buffers[0][i]);
  217. const auto r_sample = ClampToS16(mix_buffers[1][i]);
  218. if (stream_channel_count == 1) {
  219. buffer[i * stream_channel_count + 0] = Mix2To1(l_sample, r_sample);
  220. } else if (stream_channel_count == 2) {
  221. buffer[i * stream_channel_count + 0] = l_sample;
  222. buffer[i * stream_channel_count + 1] = r_sample;
  223. } else if (stream_channel_count == 6) {
  224. buffer[i * stream_channel_count + 0] = l_sample;
  225. buffer[i * stream_channel_count + 1] = r_sample;
  226. // Combine both left and right channels to the center channel
  227. buffer[i * stream_channel_count + 2] = Mix2To1(l_sample, r_sample);
  228. buffer[i * stream_channel_count + 4] = l_sample;
  229. buffer[i * stream_channel_count + 5] = r_sample;
  230. }
  231. } else if (channel_count == 6) {
  232. const auto fl_sample = ClampToS16(mix_buffers[0][i]);
  233. const auto fr_sample = ClampToS16(mix_buffers[1][i]);
  234. const auto fc_sample = ClampToS16(mix_buffers[2][i]);
  235. const auto lf_sample = ClampToS16(mix_buffers[3][i]);
  236. const auto bl_sample = ClampToS16(mix_buffers[4][i]);
  237. const auto br_sample = ClampToS16(mix_buffers[5][i]);
  238. if (stream_channel_count == 1) {
  239. // Games seem to ignore the center channel half the time, we use the front left
  240. // and right channel for mixing as that's where majority of the audio goes
  241. buffer[i * stream_channel_count + 0] = Mix2To1(fl_sample, fr_sample);
  242. } else if (stream_channel_count == 2) {
  243. // Mix all channels into 2 channels
  244. const auto [left, right] = Mix6To2WithCoefficients(
  245. fl_sample, fr_sample, fc_sample, lf_sample, bl_sample, br_sample,
  246. sink_context.GetDownmixCoefficients());
  247. buffer[i * stream_channel_count + 0] = left;
  248. buffer[i * stream_channel_count + 1] = right;
  249. } else if (stream_channel_count == 6) {
  250. // Pass through
  251. buffer[i * stream_channel_count + 0] = fl_sample;
  252. buffer[i * stream_channel_count + 1] = fr_sample;
  253. buffer[i * stream_channel_count + 2] = fc_sample;
  254. buffer[i * stream_channel_count + 3] = lf_sample;
  255. buffer[i * stream_channel_count + 4] = bl_sample;
  256. buffer[i * stream_channel_count + 5] = br_sample;
  257. }
  258. }
  259. }
  260. }
  261. audio_out->QueueBuffer(stream, tag, std::move(buffer));
  262. elapsed_frame_count++;
  263. voice_context.UpdateStateByDspShared();
  264. }
  265. void AudioRenderer::ReleaseAndQueueBuffers() {
  266. if (!stream->IsPlaying()) {
  267. return;
  268. }
  269. {
  270. std::scoped_lock lock{mutex};
  271. const auto released_buffers{audio_out->GetTagsAndReleaseBuffers(stream)};
  272. for (const auto& tag : released_buffers) {
  273. QueueMixedBuffer(tag);
  274. }
  275. }
  276. const f32 sample_rate = static_cast<f32>(GetSampleRate());
  277. const f32 sample_count = static_cast<f32>(GetSampleCount());
  278. const f32 consume_rate = sample_rate / (sample_count * (sample_count / 240));
  279. const s32 ms = (1000 / static_cast<s32>(consume_rate)) - 1;
  280. const std::chrono::milliseconds next_event_time(std::max(ms / NUM_BUFFERS, 1));
  281. core_timing.ScheduleEvent(next_event_time, process_event, {});
  282. }
  283. } // namespace AudioCore