audio_renderer.cpp 15 KB

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