AudioProcessor.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 readonly 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. // NOTE: We default to stereo as this will get downmixed to mono by the compat layer if it's not compatible.
  48. return 2;
  49. }
  50. public void Start(IHardwareDeviceDriver deviceDriver)
  51. {
  52. OutputDevices = new IHardwareDevice[Constants.AudioRendererSessionCountMax];
  53. uint channelCount = GetHardwareChannelCount(deviceDriver);
  54. for (int i = 0; i < OutputDevices.Length; i++)
  55. {
  56. // TODO: Don't hardcode sample rate.
  57. OutputDevices[i] = new HardwareDeviceImpl(deviceDriver, channelCount, Constants.TargetSampleRate);
  58. }
  59. _mailbox = new Mailbox<MailboxMessage>();
  60. _sessionCommandList = new RendererSession[Constants.AudioRendererSessionCountMax];
  61. _event.Reset();
  62. _lastTime = PerformanceCounter.ElapsedNanoseconds;
  63. _pauseEvent = deviceDriver.GetPauseEvent();
  64. StartThread();
  65. _mailbox.SendMessage(MailboxMessage.Start);
  66. if (_mailbox.ReceiveResponse() != MailboxMessage.Start)
  67. {
  68. throw new InvalidOperationException("Audio Processor Start response was invalid!");
  69. }
  70. }
  71. public void Stop()
  72. {
  73. _mailbox.SendMessage(MailboxMessage.Stop);
  74. if (_mailbox.ReceiveResponse() != MailboxMessage.Stop)
  75. {
  76. throw new InvalidOperationException("Audio Processor Stop response was invalid!");
  77. }
  78. foreach (IHardwareDevice device in OutputDevices)
  79. {
  80. device.Dispose();
  81. }
  82. }
  83. public void Send(int sessionId, CommandList commands, int renderingLimit, ulong appletResourceId)
  84. {
  85. _sessionCommandList[sessionId] = new RendererSession
  86. {
  87. CommandList = commands,
  88. RenderingLimit = renderingLimit,
  89. AppletResourceId = appletResourceId,
  90. };
  91. }
  92. public bool HasRemainingCommands(int sessionId)
  93. {
  94. return _sessionCommandList[sessionId] != null;
  95. }
  96. public void Signal()
  97. {
  98. _mailbox.SendMessage(MailboxMessage.RenderStart);
  99. }
  100. public void Wait()
  101. {
  102. if (_mailbox.ReceiveResponse() != MailboxMessage.RenderEnd)
  103. {
  104. throw new InvalidOperationException("Audio Processor Wait response was invalid!");
  105. }
  106. long increment = Constants.AudioProcessorMaxUpdateTimeTarget;
  107. long timeNow = PerformanceCounter.ElapsedNanoseconds;
  108. if (timeNow > _playbackEnds)
  109. {
  110. // Playback has restarted.
  111. _playbackEnds = timeNow;
  112. }
  113. _playbackEnds += increment;
  114. // The number of frames we are behind where the timer says we should be.
  115. long framesBehind = (timeNow - _lastTime) / increment;
  116. // The number of frames yet to play on the backend.
  117. long bufferedFrames = (_playbackEnds - timeNow) / increment + framesBehind;
  118. // If we've entered a situation where a lot of buffers will be queued on the backend,
  119. // Skip some audio frames so that playback can catch up.
  120. if (bufferedFrames > MaxBufferedFrames)
  121. {
  122. // Skip a few frames so that we're not too far behind. (the target number of frames)
  123. _lastTime += increment * (bufferedFrames - TargetBufferedFrames);
  124. }
  125. while (timeNow < _lastTime + increment)
  126. {
  127. _event.WaitOne(1);
  128. timeNow = PerformanceCounter.ElapsedNanoseconds;
  129. }
  130. _lastTime += increment;
  131. }
  132. private void StartThread()
  133. {
  134. _workerThread = new Thread(Work)
  135. {
  136. Name = "AudioProcessor.Worker",
  137. };
  138. _workerThread.Start();
  139. }
  140. private void Work()
  141. {
  142. if (_mailbox.ReceiveMessage() != MailboxMessage.Start)
  143. {
  144. throw new InvalidOperationException("Audio Processor Start message was invalid!");
  145. }
  146. _mailbox.SendResponse(MailboxMessage.Start);
  147. _mailbox.SendResponse(MailboxMessage.RenderEnd);
  148. Logger.Info?.Print(LogClass.AudioRenderer, "Starting audio processor");
  149. while (true)
  150. {
  151. _pauseEvent?.WaitOne();
  152. MailboxMessage message = _mailbox.ReceiveMessage();
  153. if (message == MailboxMessage.Stop)
  154. {
  155. break;
  156. }
  157. if (message == MailboxMessage.RenderStart)
  158. {
  159. long startTicks = PerformanceCounter.ElapsedNanoseconds;
  160. for (int i = 0; i < _sessionCommandList.Length; i++)
  161. {
  162. if (_sessionCommandList[i] != null)
  163. {
  164. _sessionCommandList[i].CommandList.Process(OutputDevices[i]);
  165. _sessionCommandList[i].CommandList.Dispose();
  166. _sessionCommandList[i] = null;
  167. }
  168. }
  169. long endTicks = PerformanceCounter.ElapsedNanoseconds;
  170. long elapsedTime = endTicks - startTicks;
  171. if (Constants.AudioProcessorMaxUpdateTime < elapsedTime)
  172. {
  173. Logger.Debug?.Print(LogClass.AudioRenderer, $"DSP too slow (exceeded by {elapsedTime - Constants.AudioProcessorMaxUpdateTime}ns)");
  174. }
  175. _mailbox.SendResponse(MailboxMessage.RenderEnd);
  176. }
  177. }
  178. Logger.Info?.Print(LogClass.AudioRenderer, "Stopping audio processor");
  179. _mailbox.SendResponse(MailboxMessage.Stop);
  180. }
  181. public void Dispose()
  182. {
  183. GC.SuppressFinalize(this);
  184. Dispose(true);
  185. }
  186. protected virtual void Dispose(bool disposing)
  187. {
  188. if (disposing)
  189. {
  190. _event.Dispose();
  191. _mailbox?.Dispose();
  192. }
  193. }
  194. }
  195. }