SDL2HardwareDeviceSession.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. using Ryujinx.Audio.Backends.Common;
  2. using Ryujinx.Audio.Common;
  3. using Ryujinx.Common.Logging;
  4. using Ryujinx.Memory;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Runtime.InteropServices;
  8. using System.Threading;
  9. using static SDL2.SDL;
  10. namespace Ryujinx.Audio.Backends.SDL2
  11. {
  12. class SDL2HardwareDeviceSession : HardwareDeviceSessionOutputBase
  13. {
  14. private SDL2HardwareDeviceDriver _driver;
  15. private ConcurrentQueue<SDL2AudioBuffer> _queuedBuffers;
  16. private DynamicRingBuffer _ringBuffer;
  17. private ulong _playedSampleCount;
  18. private ManualResetEvent _updateRequiredEvent;
  19. private uint _outputStream;
  20. private SDL_AudioCallback _callbackDelegate;
  21. private int _bytesPerFrame;
  22. private uint _sampleCount;
  23. private bool _started;
  24. private float _volume;
  25. private ushort _nativeSampleFormat;
  26. public SDL2HardwareDeviceSession(SDL2HardwareDeviceDriver driver, IVirtualMemoryManager memoryManager, SampleFormat requestedSampleFormat, uint requestedSampleRate, uint requestedChannelCount, float requestedVolume) : base(memoryManager, requestedSampleFormat, requestedSampleRate, requestedChannelCount)
  27. {
  28. _driver = driver;
  29. _updateRequiredEvent = _driver.GetUpdateRequiredEvent();
  30. _queuedBuffers = new ConcurrentQueue<SDL2AudioBuffer>();
  31. _ringBuffer = new DynamicRingBuffer();
  32. _callbackDelegate = Update;
  33. _bytesPerFrame = BackendHelper.GetSampleSize(RequestedSampleFormat) * (int)RequestedChannelCount;
  34. _nativeSampleFormat = SDL2HardwareDeviceDriver.GetSDL2Format(RequestedSampleFormat);
  35. _sampleCount = uint.MaxValue;
  36. _started = false;
  37. _volume = requestedVolume;
  38. }
  39. private void EnsureAudioStreamSetup(AudioBuffer buffer)
  40. {
  41. uint bufferSampleCount = (uint)GetSampleCount(buffer);
  42. bool needAudioSetup = _outputStream == 0 ||
  43. (bufferSampleCount >= Constants.TargetSampleCount && bufferSampleCount < _sampleCount);
  44. if (needAudioSetup)
  45. {
  46. _sampleCount = Math.Max(Constants.TargetSampleCount, bufferSampleCount);
  47. uint newOutputStream = SDL2HardwareDeviceDriver.OpenStream(RequestedSampleFormat, RequestedSampleRate, RequestedChannelCount, _sampleCount, _callbackDelegate);
  48. if (newOutputStream == 0)
  49. {
  50. // No stream in place, this is unexpected.
  51. throw new InvalidOperationException($"OpenStream failed with error: \"{SDL_GetError()}\"");
  52. }
  53. else
  54. {
  55. if (_outputStream != 0)
  56. {
  57. SDL_CloseAudioDevice(_outputStream);
  58. }
  59. _outputStream = newOutputStream;
  60. SDL_PauseAudioDevice(_outputStream, _started ? 0 : 1);
  61. Logger.Info?.Print(LogClass.Audio, $"New audio stream setup with a target sample count of {_sampleCount}");
  62. }
  63. }
  64. }
  65. private unsafe void Update(IntPtr userdata, IntPtr stream, int streamLength)
  66. {
  67. Span<byte> streamSpan = new Span<byte>((void*)stream, streamLength);
  68. int maxFrameCount = (int)GetSampleCount(streamLength);
  69. int bufferedFrames = _ringBuffer.Length / _bytesPerFrame;
  70. int frameCount = Math.Min(bufferedFrames, maxFrameCount);
  71. if (frameCount == 0)
  72. {
  73. // SDL2 left the responsibility to the user to clear the buffer.
  74. streamSpan.Fill(0);
  75. return;
  76. }
  77. byte[] samples = new byte[frameCount * _bytesPerFrame];
  78. _ringBuffer.Read(samples, 0, samples.Length);
  79. fixed (byte* p = samples)
  80. {
  81. IntPtr pStreamSrc = (IntPtr)p;
  82. // Zero the dest buffer
  83. streamSpan.Fill(0);
  84. // Apply volume to written data
  85. SDL_MixAudioFormat(stream, pStreamSrc, _nativeSampleFormat, (uint)samples.Length, (int)(_volume * SDL_MIX_MAXVOLUME));
  86. }
  87. ulong sampleCount = GetSampleCount(samples.Length);
  88. ulong availaibleSampleCount = sampleCount;
  89. bool needUpdate = false;
  90. while (availaibleSampleCount > 0 && _queuedBuffers.TryPeek(out SDL2AudioBuffer driverBuffer))
  91. {
  92. ulong sampleStillNeeded = driverBuffer.SampleCount - Interlocked.Read(ref driverBuffer.SamplePlayed);
  93. ulong playedAudioBufferSampleCount = Math.Min(sampleStillNeeded, availaibleSampleCount);
  94. ulong currentSamplePlayed = Interlocked.Add(ref driverBuffer.SamplePlayed, playedAudioBufferSampleCount);
  95. availaibleSampleCount -= playedAudioBufferSampleCount;
  96. if (currentSamplePlayed == driverBuffer.SampleCount)
  97. {
  98. _queuedBuffers.TryDequeue(out _);
  99. needUpdate = true;
  100. }
  101. Interlocked.Add(ref _playedSampleCount, playedAudioBufferSampleCount);
  102. }
  103. // Notify the output if needed.
  104. if (needUpdate)
  105. {
  106. _updateRequiredEvent.Set();
  107. }
  108. }
  109. public override ulong GetPlayedSampleCount()
  110. {
  111. return Interlocked.Read(ref _playedSampleCount);
  112. }
  113. public override float GetVolume()
  114. {
  115. return _volume;
  116. }
  117. public override void PrepareToClose() { }
  118. public override void QueueBuffer(AudioBuffer buffer)
  119. {
  120. EnsureAudioStreamSetup(buffer);
  121. SDL2AudioBuffer driverBuffer = new SDL2AudioBuffer(buffer.DataPointer, GetSampleCount(buffer));
  122. _ringBuffer.Write(buffer.Data, 0, buffer.Data.Length);
  123. _queuedBuffers.Enqueue(driverBuffer);
  124. }
  125. public override void SetVolume(float volume)
  126. {
  127. _volume = volume;
  128. }
  129. public override void Start()
  130. {
  131. if (!_started)
  132. {
  133. if (_outputStream != 0)
  134. {
  135. SDL_PauseAudioDevice(_outputStream, 0);
  136. }
  137. _started = true;
  138. }
  139. }
  140. public override void Stop()
  141. {
  142. if (_started)
  143. {
  144. if (_outputStream != 0)
  145. {
  146. SDL_PauseAudioDevice(_outputStream, 1);
  147. }
  148. _started = false;
  149. }
  150. }
  151. public override void UnregisterBuffer(AudioBuffer buffer) { }
  152. public override bool WasBufferFullyConsumed(AudioBuffer buffer)
  153. {
  154. if (!_queuedBuffers.TryPeek(out SDL2AudioBuffer driverBuffer))
  155. {
  156. return true;
  157. }
  158. return driverBuffer.DriverIdentifier != buffer.DataPointer;
  159. }
  160. protected virtual void Dispose(bool disposing)
  161. {
  162. if (disposing && _driver.Unregister(this))
  163. {
  164. PrepareToClose();
  165. Stop();
  166. if (_outputStream != 0)
  167. {
  168. SDL_CloseAudioDevice(_outputStream);
  169. }
  170. }
  171. }
  172. public override void Dispose()
  173. {
  174. Dispose(true);
  175. }
  176. }
  177. }