sink_stream.cpp 11 KB

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