sink_stream.cpp 12 KB

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