sink_stream.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <atomic>
  5. #include <memory>
  6. #include <span>
  7. #include <vector>
  8. #include "audio_core/audio_core.h"
  9. #include "audio_core/common/common.h"
  10. #include "audio_core/sink/sink_stream.h"
  11. #include "common/common_types.h"
  12. #include "common/fixed_point.h"
  13. #include "common/settings.h"
  14. #include "core/core.h"
  15. #include "core/core_timing.h"
  16. #include "core/core_timing_util.h"
  17. namespace AudioCore::Sink {
  18. void SinkStream::AppendBuffer(SinkBuffer& buffer, std::vector<s16>& samples) {
  19. if (type == StreamType::In) {
  20. queue.enqueue(buffer);
  21. queued_buffers++;
  22. return;
  23. }
  24. constexpr s32 min{std::numeric_limits<s16>::min()};
  25. constexpr s32 max{std::numeric_limits<s16>::max()};
  26. auto yuzu_volume{Settings::Volume()};
  27. if (yuzu_volume > 1.0f) {
  28. yuzu_volume = 0.6f + 20 * std::log10(yuzu_volume);
  29. }
  30. auto volume{system_volume * device_volume * yuzu_volume};
  31. if (system_channels == 6 && device_channels == 2) {
  32. // We're given 6 channels, but our device only outputs 2, so downmix.
  33. static constexpr std::array<f32, 4> down_mix_coeff{1.0f, 0.707f, 0.251f, 0.707f};
  34. for (u32 read_index = 0, write_index = 0; read_index < samples.size();
  35. read_index += system_channels, write_index += device_channels) {
  36. const auto left_sample{
  37. ((Common::FixedPoint<49, 15>(
  38. samples[read_index + static_cast<u32>(Channels::FrontLeft)]) *
  39. down_mix_coeff[0] +
  40. samples[read_index + static_cast<u32>(Channels::Center)] * down_mix_coeff[1] +
  41. samples[read_index + static_cast<u32>(Channels::LFE)] * down_mix_coeff[2] +
  42. samples[read_index + static_cast<u32>(Channels::BackLeft)] * down_mix_coeff[3]) *
  43. volume)
  44. .to_int()};
  45. const auto right_sample{
  46. ((Common::FixedPoint<49, 15>(
  47. samples[read_index + static_cast<u32>(Channels::FrontRight)]) *
  48. down_mix_coeff[0] +
  49. samples[read_index + static_cast<u32>(Channels::Center)] * down_mix_coeff[1] +
  50. samples[read_index + static_cast<u32>(Channels::LFE)] * down_mix_coeff[2] +
  51. samples[read_index + static_cast<u32>(Channels::BackRight)] * down_mix_coeff[3]) *
  52. volume)
  53. .to_int()};
  54. samples[write_index + static_cast<u32>(Channels::FrontLeft)] =
  55. static_cast<s16>(std::clamp(left_sample, min, max));
  56. samples[write_index + static_cast<u32>(Channels::FrontRight)] =
  57. static_cast<s16>(std::clamp(right_sample, min, max));
  58. }
  59. samples.resize(samples.size() / system_channels * device_channels);
  60. } else if (system_channels == 2 && device_channels == 6) {
  61. // We need moar samples! Not all games will provide 6 channel audio.
  62. // TODO: Implement some upmixing here. Currently just passthrough, with other
  63. // channels left as silence.
  64. std::vector<s16> new_samples(samples.size() / system_channels * device_channels, 0);
  65. for (u32 read_index = 0, write_index = 0; read_index < samples.size();
  66. read_index += system_channels, write_index += device_channels) {
  67. const auto left_sample{static_cast<s16>(std::clamp(
  68. static_cast<s32>(
  69. static_cast<f32>(samples[read_index + static_cast<u32>(Channels::FrontLeft)]) *
  70. volume),
  71. min, max))};
  72. new_samples[write_index + static_cast<u32>(Channels::FrontLeft)] = left_sample;
  73. const auto right_sample{static_cast<s16>(std::clamp(
  74. static_cast<s32>(
  75. static_cast<f32>(samples[read_index + static_cast<u32>(Channels::FrontRight)]) *
  76. volume),
  77. min, max))};
  78. new_samples[write_index + static_cast<u32>(Channels::FrontRight)] = right_sample;
  79. }
  80. samples = std::move(new_samples);
  81. } else if (volume != 1.0f) {
  82. for (u32 i = 0; i < samples.size(); i++) {
  83. samples[i] = static_cast<s16>(
  84. std::clamp(static_cast<s32>(static_cast<f32>(samples[i]) * volume), min, max));
  85. }
  86. }
  87. samples_buffer.Push(samples);
  88. queue.enqueue(buffer);
  89. queued_buffers++;
  90. }
  91. std::vector<s16> SinkStream::ReleaseBuffer(u64 num_samples) {
  92. constexpr s32 min = std::numeric_limits<s16>::min();
  93. constexpr s32 max = std::numeric_limits<s16>::max();
  94. auto samples{samples_buffer.Pop(num_samples)};
  95. // TODO: Up-mix to 6 channels if the game expects it.
  96. // For audio input this is unlikely to ever be the case though.
  97. // Incoming mic volume seems to always be very quiet, so multiply by an additional 8 here.
  98. // TODO: Play with this and find something that works better.
  99. auto volume{system_volume * device_volume * 8};
  100. for (u32 i = 0; i < samples.size(); i++) {
  101. samples[i] = static_cast<s16>(
  102. std::clamp(static_cast<s32>(static_cast<f32>(samples[i]) * volume), min, max));
  103. }
  104. if (samples.size() < num_samples) {
  105. samples.resize(num_samples, 0);
  106. }
  107. return samples;
  108. }
  109. void SinkStream::ClearQueue() {
  110. samples_buffer.Pop();
  111. while (queue.pop()) {
  112. }
  113. queued_buffers = 0;
  114. playing_buffer = {};
  115. playing_buffer.consumed = true;
  116. }
  117. void SinkStream::ProcessAudioIn(std::span<const s16> input_buffer, std::size_t num_frames) {
  118. const std::size_t num_channels = GetDeviceChannels();
  119. const std::size_t frame_size = num_channels;
  120. const std::size_t frame_size_bytes = frame_size * sizeof(s16);
  121. size_t frames_written{0};
  122. // If we're paused or going to shut down, we don't want to consume buffers as coretiming is
  123. // paused and we'll desync, so just return.
  124. if (system.IsPaused() || system.IsShuttingDown()) {
  125. return;
  126. }
  127. while (frames_written < num_frames) {
  128. // If the playing buffer has been consumed or has no frames, we need a new one
  129. if (playing_buffer.consumed || playing_buffer.frames == 0) {
  130. if (!queue.try_dequeue(playing_buffer)) {
  131. // If no buffer was available we've underrun, just push the samples and
  132. // continue.
  133. samples_buffer.Push(&input_buffer[frames_written * frame_size],
  134. (num_frames - frames_written) * frame_size);
  135. frames_written = num_frames;
  136. continue;
  137. }
  138. // Successfully dequeued a new buffer.
  139. queued_buffers--;
  140. }
  141. // Get the minimum frames available between the currently playing buffer, and the
  142. // amount we have left to fill
  143. size_t frames_available{std::min<u64>(playing_buffer.frames - playing_buffer.frames_played,
  144. num_frames - frames_written)};
  145. samples_buffer.Push(&input_buffer[frames_written * frame_size],
  146. frames_available * frame_size);
  147. frames_written += frames_available;
  148. playing_buffer.frames_played += frames_available;
  149. // If that's all the frames in the current buffer, add its samples and mark it as
  150. // consumed
  151. if (playing_buffer.frames_played >= playing_buffer.frames) {
  152. playing_buffer.consumed = true;
  153. }
  154. }
  155. std::memcpy(&last_frame[0], &input_buffer[(frames_written - 1) * frame_size], frame_size_bytes);
  156. }
  157. void SinkStream::ProcessAudioOutAndRender(std::span<s16> output_buffer, std::size_t num_frames) {
  158. const std::size_t num_channels = GetDeviceChannels();
  159. const std::size_t frame_size = num_channels;
  160. const std::size_t frame_size_bytes = frame_size * sizeof(s16);
  161. size_t frames_written{0};
  162. size_t actual_frames_written{0};
  163. // If we're paused or going to shut down, we don't want to consume buffers as coretiming is
  164. // paused and we'll desync, so just play silence.
  165. if (system.IsPaused() || system.IsShuttingDown()) {
  166. if (system.IsShuttingDown()) {
  167. release_cv.notify_one();
  168. }
  169. static constexpr std::array<s16, 6> silence{};
  170. for (size_t i = frames_written; i < num_frames; i++) {
  171. std::memcpy(&output_buffer[i * frame_size], &silence[0], frame_size_bytes);
  172. }
  173. return;
  174. }
  175. while (frames_written < num_frames) {
  176. // If the playing buffer has been consumed or has no frames, we need a new one
  177. if (playing_buffer.consumed || playing_buffer.frames == 0) {
  178. if (!queue.try_dequeue(playing_buffer)) {
  179. // If no buffer was available we've underrun, fill the remaining buffer with
  180. // the last written frame and continue.
  181. for (size_t i = frames_written; i < num_frames; i++) {
  182. std::memcpy(&output_buffer[i * frame_size], &last_frame[0], frame_size_bytes);
  183. }
  184. frames_written = num_frames;
  185. continue;
  186. }
  187. // Successfully dequeued a new buffer.
  188. queued_buffers--;
  189. { std::unique_lock lk{release_mutex}; }
  190. release_cv.notify_one();
  191. }
  192. // Get the minimum frames available between the currently playing buffer, and the
  193. // amount we have left to fill
  194. size_t frames_available{std::min<u64>(playing_buffer.frames - playing_buffer.frames_played,
  195. num_frames - frames_written)};
  196. samples_buffer.Pop(&output_buffer[frames_written * frame_size],
  197. frames_available * frame_size);
  198. frames_written += frames_available;
  199. actual_frames_written += frames_available;
  200. playing_buffer.frames_played += frames_available;
  201. // If that's all the frames in the current buffer, add its samples and mark it as
  202. // consumed
  203. if (playing_buffer.frames_played >= playing_buffer.frames) {
  204. playing_buffer.consumed = true;
  205. }
  206. }
  207. std::memcpy(&last_frame[0], &output_buffer[(frames_written - 1) * frame_size],
  208. frame_size_bytes);
  209. {
  210. std::scoped_lock lk{sample_count_lock};
  211. last_sample_count_update_time = system.CoreTiming().GetGlobalTimeNs();
  212. min_played_sample_count = max_played_sample_count;
  213. max_played_sample_count += actual_frames_written;
  214. }
  215. }
  216. u64 SinkStream::GetExpectedPlayedSampleCount() {
  217. std::scoped_lock lk{sample_count_lock};
  218. auto cur_time{system.CoreTiming().GetGlobalTimeNs()};
  219. auto time_delta{cur_time - last_sample_count_update_time};
  220. auto exp_played_sample_count{min_played_sample_count +
  221. (TargetSampleRate * time_delta) / std::chrono::seconds{1}};
  222. // Add 15ms of latency in sample reporting to allow for some leeway in scheduler timings
  223. return std::min<u64>(exp_played_sample_count, max_played_sample_count) + TargetSampleCount * 3;
  224. }
  225. void SinkStream::WaitFreeSpace(std::stop_token stop_token) {
  226. std::unique_lock lk{release_mutex};
  227. release_cv.wait_for(lk, std::chrono::milliseconds(5),
  228. [this]() { return queued_buffers < max_queue_size; });
  229. if (queued_buffers > max_queue_size + 3) {
  230. Common::CondvarWait(release_cv, lk, stop_token,
  231. [this] { return queued_buffers < max_queue_size; });
  232. }
  233. }
  234. } // namespace AudioCore::Sink