AudioProcessor.cs 8.5 KB

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