AudioProcessor.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. //
  2. // Copyright (c) 2019-2021 Ryujinx
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. //
  17. using Ryujinx.Audio.Integration;
  18. using Ryujinx.Audio.Renderer.Dsp.Command;
  19. using Ryujinx.Audio.Renderer.Utils;
  20. using Ryujinx.Common;
  21. using Ryujinx.Common.Logging;
  22. using System;
  23. using System.Threading;
  24. namespace Ryujinx.Audio.Renderer.Dsp
  25. {
  26. public class AudioProcessor : IDisposable
  27. {
  28. private const int MaxBufferedFrames = 5;
  29. private const int TargetBufferedFrames = 3;
  30. private enum MailboxMessage : uint
  31. {
  32. Start,
  33. Stop,
  34. RenderStart,
  35. RenderEnd
  36. }
  37. private class RendererSession
  38. {
  39. public CommandList CommandList;
  40. public int RenderingLimit;
  41. public ulong AppletResourceId;
  42. }
  43. private Mailbox<MailboxMessage> _mailbox;
  44. private RendererSession[] _sessionCommandList;
  45. private Thread _workerThread;
  46. public IHardwareDevice[] OutputDevices { get; private set; }
  47. private long _lastTime;
  48. private long _playbackEnds;
  49. private ManualResetEvent _event;
  50. private ManualResetEvent _pauseEvent;
  51. public AudioProcessor()
  52. {
  53. _event = new ManualResetEvent(false);
  54. }
  55. private static uint GetHardwareChannelCount(IHardwareDeviceDriver deviceDriver)
  56. {
  57. // Get the real device driver (In case the compat layer is on top of it).
  58. deviceDriver = deviceDriver.GetRealDeviceDriver();
  59. if (deviceDriver.SupportsChannelCount(6))
  60. {
  61. return 6;
  62. }
  63. else
  64. {
  65. // NOTE: We default to stereo as this will get downmixed to mono by the compat layer if it's not compatible.
  66. return 2;
  67. }
  68. }
  69. public void Start(IHardwareDeviceDriver deviceDriver, float volume)
  70. {
  71. OutputDevices = new IHardwareDevice[Constants.AudioRendererSessionCountMax];
  72. // TODO: Before enabling this, we need up-mixing from stereo to 5.1.
  73. // uint channelCount = GetHardwareChannelCount(deviceDriver);
  74. uint channelCount = 2;
  75. for (int i = 0; i < OutputDevices.Length; i++)
  76. {
  77. // TODO: Don't hardcode sample rate.
  78. OutputDevices[i] = new HardwareDeviceImpl(deviceDriver, channelCount, Constants.TargetSampleRate, volume);
  79. }
  80. _mailbox = new Mailbox<MailboxMessage>();
  81. _sessionCommandList = new RendererSession[Constants.AudioRendererSessionCountMax];
  82. _event.Reset();
  83. _lastTime = PerformanceCounter.ElapsedNanoseconds;
  84. _pauseEvent = deviceDriver.GetPauseEvent();
  85. StartThread();
  86. _mailbox.SendMessage(MailboxMessage.Start);
  87. if (_mailbox.ReceiveResponse() != MailboxMessage.Start)
  88. {
  89. throw new InvalidOperationException("Audio Processor Start response was invalid!");
  90. }
  91. }
  92. public void Stop()
  93. {
  94. _mailbox.SendMessage(MailboxMessage.Stop);
  95. if (_mailbox.ReceiveResponse() != MailboxMessage.Stop)
  96. {
  97. throw new InvalidOperationException("Audio Processor Stop response was invalid!");
  98. }
  99. foreach (IHardwareDevice device in OutputDevices)
  100. {
  101. device.Dispose();
  102. }
  103. }
  104. public void Send(int sessionId, CommandList commands, int renderingLimit, ulong appletResourceId)
  105. {
  106. _sessionCommandList[sessionId] = new RendererSession
  107. {
  108. CommandList = commands,
  109. RenderingLimit = renderingLimit,
  110. AppletResourceId = appletResourceId
  111. };
  112. }
  113. public void Signal()
  114. {
  115. _mailbox.SendMessage(MailboxMessage.RenderStart);
  116. }
  117. public void Wait()
  118. {
  119. if (_mailbox.ReceiveResponse() != MailboxMessage.RenderEnd)
  120. {
  121. throw new InvalidOperationException("Audio Processor Wait response was invalid!");
  122. }
  123. long increment = Constants.AudioProcessorMaxUpdateTimeTarget;
  124. long timeNow = PerformanceCounter.ElapsedNanoseconds;
  125. if (timeNow > _playbackEnds)
  126. {
  127. // Playback has restarted.
  128. _playbackEnds = timeNow;
  129. }
  130. _playbackEnds += increment;
  131. // The number of frames we are behind where the timer says we should be.
  132. long framesBehind = (timeNow - _lastTime) / increment;
  133. // The number of frames yet to play on the backend.
  134. long bufferedFrames = (_playbackEnds - timeNow) / increment + framesBehind;
  135. // If we've entered a situation where a lot of buffers will be queued on the backend,
  136. // Skip some audio frames so that playback can catch up.
  137. if (bufferedFrames > MaxBufferedFrames)
  138. {
  139. // Skip a few frames so that we're not too far behind. (the target number of frames)
  140. _lastTime += increment * (bufferedFrames - TargetBufferedFrames);
  141. }
  142. while (timeNow < _lastTime + increment)
  143. {
  144. _event.WaitOne(1);
  145. timeNow = PerformanceCounter.ElapsedNanoseconds;
  146. }
  147. _lastTime += increment;
  148. }
  149. private void StartThread()
  150. {
  151. _workerThread = new Thread(Work)
  152. {
  153. Name = "AudioProcessor.Worker"
  154. };
  155. _workerThread.Start();
  156. }
  157. private void Work()
  158. {
  159. if (_mailbox.ReceiveMessage() != MailboxMessage.Start)
  160. {
  161. throw new InvalidOperationException("Audio Processor Start message was invalid!");
  162. }
  163. _mailbox.SendResponse(MailboxMessage.Start);
  164. _mailbox.SendResponse(MailboxMessage.RenderEnd);
  165. Logger.Info?.Print(LogClass.AudioRenderer, "Starting audio processor");
  166. while (true)
  167. {
  168. _pauseEvent?.WaitOne();
  169. MailboxMessage message = _mailbox.ReceiveMessage();
  170. if (message == MailboxMessage.Stop)
  171. {
  172. break;
  173. }
  174. if (message == MailboxMessage.RenderStart)
  175. {
  176. long startTicks = PerformanceCounter.ElapsedNanoseconds;
  177. for (int i = 0; i < _sessionCommandList.Length; i++)
  178. {
  179. if (_sessionCommandList[i] != null)
  180. {
  181. _sessionCommandList[i].CommandList.Process(OutputDevices[i]);
  182. _sessionCommandList[i].CommandList.Dispose();
  183. _sessionCommandList[i] = null;
  184. }
  185. }
  186. long endTicks = PerformanceCounter.ElapsedNanoseconds;
  187. long elapsedTime = endTicks - startTicks;
  188. if (Constants.AudioProcessorMaxUpdateTime < elapsedTime)
  189. {
  190. Logger.Debug?.Print(LogClass.AudioRenderer, $"DSP too slow (exceeded by {elapsedTime - Constants.AudioProcessorMaxUpdateTime}ns)");
  191. }
  192. _mailbox.SendResponse(MailboxMessage.RenderEnd);
  193. }
  194. }
  195. Logger.Info?.Print(LogClass.AudioRenderer, "Stopping audio processor");
  196. _mailbox.SendResponse(MailboxMessage.Stop);
  197. }
  198. public float GetVolume()
  199. {
  200. if (OutputDevices != null)
  201. {
  202. foreach (IHardwareDevice outputDevice in OutputDevices)
  203. {
  204. if (outputDevice != null)
  205. {
  206. return outputDevice.GetVolume();
  207. }
  208. }
  209. }
  210. return 0f;
  211. }
  212. public void SetVolume(float volume)
  213. {
  214. if (OutputDevices != null)
  215. {
  216. foreach (IHardwareDevice outputDevice in OutputDevices)
  217. {
  218. outputDevice?.SetVolume(volume);
  219. }
  220. }
  221. }
  222. public void Dispose()
  223. {
  224. Dispose(true);
  225. }
  226. protected virtual void Dispose(bool disposing)
  227. {
  228. if (disposing)
  229. {
  230. _event.Dispose();
  231. }
  232. }
  233. }
  234. }