SDL2HardwareDeviceSession.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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) : 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 = 1.0f;
  38. }
  39. private void EnsureAudioStreamSetup(AudioBuffer buffer)
  40. {
  41. bool needAudioSetup = _outputStream == 0 || ((uint)GetSampleCount(buffer) % _sampleCount) != 0;
  42. if (needAudioSetup)
  43. {
  44. _sampleCount = Math.Max(Constants.TargetSampleCount, (uint)GetSampleCount(buffer));
  45. uint newOutputStream = SDL2HardwareDeviceDriver.OpenStream(RequestedSampleFormat, RequestedSampleRate, RequestedChannelCount, _sampleCount, _callbackDelegate);
  46. if (newOutputStream == 0)
  47. {
  48. // No stream in place, this is unexpected.
  49. throw new InvalidOperationException($"OpenStream failed with error: \"{SDL_GetError()}\"");
  50. }
  51. else
  52. {
  53. if (_outputStream != 0)
  54. {
  55. SDL_CloseAudioDevice(_outputStream);
  56. }
  57. _outputStream = newOutputStream;
  58. SDL_PauseAudioDevice(_outputStream, _started ? 0 : 1);
  59. Logger.Info?.Print(LogClass.Audio, $"New audio stream setup with a target sample count of {_sampleCount}");
  60. }
  61. }
  62. }
  63. private unsafe void Update(IntPtr userdata, IntPtr stream, int streamLength)
  64. {
  65. Span<byte> streamSpan = new Span<byte>((void*)stream, streamLength);
  66. int maxFrameCount = (int)GetSampleCount(streamLength);
  67. int bufferedFrames = _ringBuffer.Length / _bytesPerFrame;
  68. int frameCount = Math.Min(bufferedFrames, maxFrameCount);
  69. if (frameCount == 0)
  70. {
  71. // SDL2 left the responsability to the user to clear the buffer.
  72. streamSpan.Fill(0);
  73. return;
  74. }
  75. byte[] samples = new byte[frameCount * _bytesPerFrame];
  76. _ringBuffer.Read(samples, 0, samples.Length);
  77. samples.AsSpan().CopyTo(streamSpan);
  78. streamSpan.Slice(samples.Length).Fill(0);
  79. // Apply volume to written data
  80. SDL_MixAudioFormat(stream, stream, _nativeSampleFormat, (uint)samples.Length, (int)(_volume * SDL_MIX_MAXVOLUME));
  81. ulong sampleCount = GetSampleCount(samples.Length);
  82. ulong availaibleSampleCount = sampleCount;
  83. bool needUpdate = false;
  84. while (availaibleSampleCount > 0 && _queuedBuffers.TryPeek(out SDL2AudioBuffer driverBuffer))
  85. {
  86. ulong sampleStillNeeded = driverBuffer.SampleCount - Interlocked.Read(ref driverBuffer.SamplePlayed);
  87. ulong playedAudioBufferSampleCount = Math.Min(sampleStillNeeded, availaibleSampleCount);
  88. ulong currentSamplePlayed = Interlocked.Add(ref driverBuffer.SamplePlayed, playedAudioBufferSampleCount);
  89. availaibleSampleCount -= playedAudioBufferSampleCount;
  90. if (currentSamplePlayed == driverBuffer.SampleCount)
  91. {
  92. _queuedBuffers.TryDequeue(out _);
  93. needUpdate = true;
  94. }
  95. Interlocked.Add(ref _playedSampleCount, playedAudioBufferSampleCount);
  96. }
  97. // Notify the output if needed.
  98. if (needUpdate)
  99. {
  100. _updateRequiredEvent.Set();
  101. }
  102. }
  103. public override ulong GetPlayedSampleCount()
  104. {
  105. return Interlocked.Read(ref _playedSampleCount);
  106. }
  107. public override float GetVolume()
  108. {
  109. return _volume;
  110. }
  111. public override void PrepareToClose() { }
  112. public override void QueueBuffer(AudioBuffer buffer)
  113. {
  114. EnsureAudioStreamSetup(buffer);
  115. SDL2AudioBuffer driverBuffer = new SDL2AudioBuffer(buffer.DataPointer, GetSampleCount(buffer));
  116. _ringBuffer.Write(buffer.Data, 0, buffer.Data.Length);
  117. _queuedBuffers.Enqueue(driverBuffer);
  118. }
  119. public override void SetVolume(float volume)
  120. {
  121. _volume = volume;
  122. }
  123. public override void Start()
  124. {
  125. if (!_started)
  126. {
  127. if (_outputStream != 0)
  128. {
  129. SDL_PauseAudioDevice(_outputStream, 0);
  130. }
  131. _started = true;
  132. }
  133. }
  134. public override void Stop()
  135. {
  136. if (_started)
  137. {
  138. if (_outputStream != 0)
  139. {
  140. SDL_PauseAudioDevice(_outputStream, 1);
  141. }
  142. _started = false;
  143. }
  144. }
  145. public override void UnregisterBuffer(AudioBuffer buffer) { }
  146. public override bool WasBufferFullyConsumed(AudioBuffer buffer)
  147. {
  148. if (!_queuedBuffers.TryPeek(out SDL2AudioBuffer driverBuffer))
  149. {
  150. return true;
  151. }
  152. return driverBuffer.DriverIdentifier != buffer.DataPointer;
  153. }
  154. protected virtual void Dispose(bool disposing)
  155. {
  156. if (disposing && _driver.Unregister(this))
  157. {
  158. PrepareToClose();
  159. Stop();
  160. if (_outputStream != 0)
  161. {
  162. SDL_CloseAudioDevice(_outputStream);
  163. }
  164. }
  165. }
  166. public override void Dispose()
  167. {
  168. Dispose(true);
  169. }
  170. }
  171. }