audio_renderer.cpp 14 KB

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