AudioProcessor.cs 8.1 KB

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