OpenALAudioOut.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. using OpenTK.Audio;
  2. using OpenTK.Audio.OpenAL;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. namespace Ryujinx.Audio
  8. {
  9. /// <summary>
  10. /// An audio renderer that uses OpenAL as the audio backend
  11. /// </summary>
  12. public class OpenALAudioOut : IAalOutput, IDisposable
  13. {
  14. /// <summary>
  15. /// The maximum amount of tracks we can issue simultaneously
  16. /// </summary>
  17. private const int MaxTracks = 256;
  18. /// <summary>
  19. /// The <see cref="OpenTK.Audio"/> audio context
  20. /// </summary>
  21. private AudioContext _context;
  22. /// <summary>
  23. /// An object pool containing <see cref="OpenALAudioTrack"/> objects
  24. /// </summary>
  25. private ConcurrentDictionary<int, OpenALAudioTrack> _tracks;
  26. /// <summary>
  27. /// True if the thread need to keep polling
  28. /// </summary>
  29. private bool _keepPolling;
  30. /// <summary>
  31. /// The poller thread audio context
  32. /// </summary>
  33. private Thread _audioPollerThread;
  34. /// <summary>
  35. /// The volume of audio renderer
  36. /// </summary>
  37. private float _volume = 1.0f;
  38. /// <summary>
  39. /// True if the volume of audio renderer have changed
  40. /// </summary>
  41. private bool _volumeChanged;
  42. /// <summary>
  43. /// True if OpenAL is supported on the device
  44. /// </summary>
  45. public static bool IsSupported
  46. {
  47. get
  48. {
  49. try
  50. {
  51. return AudioContext.AvailableDevices.Count > 0;
  52. }
  53. catch
  54. {
  55. return false;
  56. }
  57. }
  58. }
  59. public OpenALAudioOut()
  60. {
  61. _context = new AudioContext();
  62. _tracks = new ConcurrentDictionary<int, OpenALAudioTrack>();
  63. _keepPolling = true;
  64. _audioPollerThread = new Thread(AudioPollerWork);
  65. _audioPollerThread.Start();
  66. }
  67. private void AudioPollerWork()
  68. {
  69. do
  70. {
  71. foreach (OpenALAudioTrack track in _tracks.Values)
  72. {
  73. lock (track)
  74. {
  75. track.CallReleaseCallbackIfNeeded();
  76. }
  77. }
  78. // If it's not slept it will waste cycles.
  79. Thread.Sleep(10);
  80. }
  81. while (_keepPolling);
  82. foreach (OpenALAudioTrack track in _tracks.Values)
  83. {
  84. track.Dispose();
  85. }
  86. _tracks.Clear();
  87. }
  88. /// <summary>
  89. /// Creates a new audio track with the specified parameters
  90. /// </summary>
  91. /// <param name="sampleRate">The requested sample rate</param>
  92. /// <param name="channels">The requested channels</param>
  93. /// <param name="callback">A <see cref="ReleaseCallback" /> that represents the delegate to invoke when a buffer has been released by the audio track</param>
  94. public int OpenTrack(int sampleRate, int channels, ReleaseCallback callback)
  95. {
  96. OpenALAudioTrack track = new OpenALAudioTrack(sampleRate, GetALFormat(channels), callback);
  97. for (int id = 0; id < MaxTracks; id++)
  98. {
  99. if (_tracks.TryAdd(id, track))
  100. {
  101. return id;
  102. }
  103. }
  104. return -1;
  105. }
  106. private ALFormat GetALFormat(int channels)
  107. {
  108. switch (channels)
  109. {
  110. case 1: return ALFormat.Mono16;
  111. case 2: return ALFormat.Stereo16;
  112. case 6: return ALFormat.Multi51Chn16Ext;
  113. }
  114. throw new ArgumentOutOfRangeException(nameof(channels));
  115. }
  116. /// <summary>
  117. /// Stops playback and closes the track specified by <paramref name="trackId"/>
  118. /// </summary>
  119. /// <param name="trackId">The ID of the track to close</param>
  120. public void CloseTrack(int trackId)
  121. {
  122. if (_tracks.TryRemove(trackId, out OpenALAudioTrack track))
  123. {
  124. lock (track)
  125. {
  126. track.Dispose();
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// Returns a value indicating whether the specified buffer is currently reserved by the specified track
  132. /// </summary>
  133. /// <param name="trackId">The track to check</param>
  134. /// <param name="bufferTag">The buffer tag to check</param>
  135. public bool ContainsBuffer(int trackId, long bufferTag)
  136. {
  137. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  138. {
  139. lock (track)
  140. {
  141. return track.ContainsBuffer(bufferTag);
  142. }
  143. }
  144. return false;
  145. }
  146. /// <summary>
  147. /// Gets a list of buffer tags the specified track is no longer reserving
  148. /// </summary>
  149. /// <param name="trackId">The track to retrieve buffer tags from</param>
  150. /// <param name="maxCount">The maximum amount of buffer tags to retrieve</param>
  151. /// <returns>Buffers released by the specified track</returns>
  152. public long[] GetReleasedBuffers(int trackId, int maxCount)
  153. {
  154. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  155. {
  156. lock (track)
  157. {
  158. return track.GetReleasedBuffers(maxCount);
  159. }
  160. }
  161. return null;
  162. }
  163. /// <summary>
  164. /// Appends an audio buffer to the specified track
  165. /// </summary>
  166. /// <typeparam name="T">The sample type of the buffer</typeparam>
  167. /// <param name="trackId">The track to append the buffer to</param>
  168. /// <param name="bufferTag">The internal tag of the buffer</param>
  169. /// <param name="buffer">The buffer to append to the track</param>
  170. public void AppendBuffer<T>(int trackId, long bufferTag, T[] buffer) where T : struct
  171. {
  172. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  173. {
  174. lock (track)
  175. {
  176. int bufferId = track.AppendBuffer(bufferTag);
  177. int size = buffer.Length * Marshal.SizeOf<T>();
  178. AL.BufferData(bufferId, track.Format, buffer, size, track.SampleRate);
  179. AL.SourceQueueBuffer(track.SourceId, bufferId);
  180. StartPlaybackIfNeeded(track);
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Starts playback
  186. /// </summary>
  187. /// <param name="trackId">The ID of the track to start playback on</param>
  188. public void Start(int trackId)
  189. {
  190. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  191. {
  192. lock (track)
  193. {
  194. track.State = PlaybackState.Playing;
  195. StartPlaybackIfNeeded(track);
  196. }
  197. }
  198. }
  199. private void StartPlaybackIfNeeded(OpenALAudioTrack track)
  200. {
  201. AL.GetSource(track.SourceId, ALGetSourcei.SourceState, out int stateInt);
  202. ALSourceState State = (ALSourceState)stateInt;
  203. if (State != ALSourceState.Playing && track.State == PlaybackState.Playing)
  204. {
  205. if (_volumeChanged)
  206. {
  207. AL.Source(track.SourceId, ALSourcef.Gain, _volume);
  208. _volumeChanged = false;
  209. }
  210. AL.SourcePlay(track.SourceId);
  211. }
  212. }
  213. /// <summary>
  214. /// Stops playback
  215. /// </summary>
  216. /// <param name="trackId">The ID of the track to stop playback on</param>
  217. public void Stop(int trackId)
  218. {
  219. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  220. {
  221. lock (track)
  222. {
  223. track.State = PlaybackState.Stopped;
  224. AL.SourceStop(track.SourceId);
  225. }
  226. }
  227. }
  228. /// <summary>
  229. /// Get playback volume
  230. /// </summary>
  231. public float GetVolume() => _volume;
  232. /// <summary>
  233. /// Set playback volume
  234. /// </summary>
  235. /// <param name="volume">The volume of the playback</param>
  236. public void SetVolume(float volume)
  237. {
  238. if (!_volumeChanged)
  239. {
  240. _volume = volume;
  241. _volumeChanged = true;
  242. }
  243. }
  244. /// <summary>
  245. /// Gets the current playback state of the specified track
  246. /// </summary>
  247. /// <param name="trackId">The track to retrieve the playback state for</param>
  248. public PlaybackState GetState(int trackId)
  249. {
  250. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  251. {
  252. return track.State;
  253. }
  254. return PlaybackState.Stopped;
  255. }
  256. public void Dispose()
  257. {
  258. Dispose(true);
  259. }
  260. protected virtual void Dispose(bool disposing)
  261. {
  262. if (disposing)
  263. {
  264. _keepPolling = false;
  265. }
  266. }
  267. }
  268. }