OpenALAudioOut.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. {
  66. Name = "Audio.PollerThread"
  67. };
  68. _audioPollerThread.Start();
  69. }
  70. private void AudioPollerWork()
  71. {
  72. do
  73. {
  74. foreach (OpenALAudioTrack track in _tracks.Values)
  75. {
  76. lock (track)
  77. {
  78. track.CallReleaseCallbackIfNeeded();
  79. }
  80. }
  81. // If it's not slept it will waste cycles.
  82. Thread.Sleep(10);
  83. }
  84. while (_keepPolling);
  85. foreach (OpenALAudioTrack track in _tracks.Values)
  86. {
  87. track.Dispose();
  88. }
  89. _tracks.Clear();
  90. _context.Dispose();
  91. }
  92. /// <summary>
  93. /// Creates a new audio track with the specified parameters
  94. /// </summary>
  95. /// <param name="sampleRate">The requested sample rate</param>
  96. /// <param name="channels">The requested channels</param>
  97. /// <param name="callback">A <see cref="ReleaseCallback" /> that represents the delegate to invoke when a buffer has been released by the audio track</param>
  98. public int OpenTrack(int sampleRate, int channels, ReleaseCallback callback)
  99. {
  100. OpenALAudioTrack track = new OpenALAudioTrack(sampleRate, GetALFormat(channels), callback);
  101. for (int id = 0; id < MaxTracks; id++)
  102. {
  103. if (_tracks.TryAdd(id, track))
  104. {
  105. return id;
  106. }
  107. }
  108. return -1;
  109. }
  110. private ALFormat GetALFormat(int channels)
  111. {
  112. switch (channels)
  113. {
  114. case 1: return ALFormat.Mono16;
  115. case 2: return ALFormat.Stereo16;
  116. case 6: return ALFormat.Multi51Chn16Ext;
  117. }
  118. throw new ArgumentOutOfRangeException(nameof(channels));
  119. }
  120. /// <summary>
  121. /// Stops playback and closes the track specified by <paramref name="trackId"/>
  122. /// </summary>
  123. /// <param name="trackId">The ID of the track to close</param>
  124. public void CloseTrack(int trackId)
  125. {
  126. if (_tracks.TryRemove(trackId, out OpenALAudioTrack track))
  127. {
  128. lock (track)
  129. {
  130. track.Dispose();
  131. }
  132. }
  133. }
  134. /// <summary>
  135. /// Returns a value indicating whether the specified buffer is currently reserved by the specified track
  136. /// </summary>
  137. /// <param name="trackId">The track to check</param>
  138. /// <param name="bufferTag">The buffer tag to check</param>
  139. public bool ContainsBuffer(int trackId, long bufferTag)
  140. {
  141. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  142. {
  143. lock (track)
  144. {
  145. return track.ContainsBuffer(bufferTag);
  146. }
  147. }
  148. return false;
  149. }
  150. /// <summary>
  151. /// Gets a list of buffer tags the specified track is no longer reserving
  152. /// </summary>
  153. /// <param name="trackId">The track to retrieve buffer tags from</param>
  154. /// <param name="maxCount">The maximum amount of buffer tags to retrieve</param>
  155. /// <returns>Buffers released by the specified track</returns>
  156. public long[] GetReleasedBuffers(int trackId, int maxCount)
  157. {
  158. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  159. {
  160. lock (track)
  161. {
  162. return track.GetReleasedBuffers(maxCount);
  163. }
  164. }
  165. return null;
  166. }
  167. /// <summary>
  168. /// Appends an audio buffer to the specified track
  169. /// </summary>
  170. /// <typeparam name="T">The sample type of the buffer</typeparam>
  171. /// <param name="trackId">The track to append the buffer to</param>
  172. /// <param name="bufferTag">The internal tag of the buffer</param>
  173. /// <param name="buffer">The buffer to append to the track</param>
  174. public void AppendBuffer<T>(int trackId, long bufferTag, T[] buffer) where T : struct
  175. {
  176. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  177. {
  178. lock (track)
  179. {
  180. int bufferId = track.AppendBuffer(bufferTag);
  181. int size = buffer.Length * Marshal.SizeOf<T>();
  182. AL.BufferData(bufferId, track.Format, buffer, size, track.SampleRate);
  183. AL.SourceQueueBuffer(track.SourceId, bufferId);
  184. StartPlaybackIfNeeded(track);
  185. }
  186. }
  187. }
  188. /// <summary>
  189. /// Starts playback
  190. /// </summary>
  191. /// <param name="trackId">The ID of the track to start playback on</param>
  192. public void Start(int trackId)
  193. {
  194. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  195. {
  196. lock (track)
  197. {
  198. track.State = PlaybackState.Playing;
  199. StartPlaybackIfNeeded(track);
  200. }
  201. }
  202. }
  203. private void StartPlaybackIfNeeded(OpenALAudioTrack track)
  204. {
  205. AL.GetSource(track.SourceId, ALGetSourcei.SourceState, out int stateInt);
  206. ALSourceState State = (ALSourceState)stateInt;
  207. if (State != ALSourceState.Playing && track.State == PlaybackState.Playing)
  208. {
  209. if (_volumeChanged)
  210. {
  211. AL.Source(track.SourceId, ALSourcef.Gain, _volume);
  212. _volumeChanged = false;
  213. }
  214. AL.SourcePlay(track.SourceId);
  215. }
  216. }
  217. /// <summary>
  218. /// Stops playback
  219. /// </summary>
  220. /// <param name="trackId">The ID of the track to stop playback on</param>
  221. public void Stop(int trackId)
  222. {
  223. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  224. {
  225. lock (track)
  226. {
  227. track.State = PlaybackState.Stopped;
  228. AL.SourceStop(track.SourceId);
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// Get playback volume
  234. /// </summary>
  235. public float GetVolume() => _volume;
  236. /// <summary>
  237. /// Set playback volume
  238. /// </summary>
  239. /// <param name="volume">The volume of the playback</param>
  240. public void SetVolume(float volume)
  241. {
  242. if (!_volumeChanged)
  243. {
  244. _volume = volume;
  245. _volumeChanged = true;
  246. }
  247. }
  248. /// <summary>
  249. /// Gets the current playback state of the specified track
  250. /// </summary>
  251. /// <param name="trackId">The track to retrieve the playback state for</param>
  252. public PlaybackState GetState(int trackId)
  253. {
  254. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  255. {
  256. return track.State;
  257. }
  258. return PlaybackState.Stopped;
  259. }
  260. public void Dispose()
  261. {
  262. Dispose(true);
  263. }
  264. protected virtual void Dispose(bool disposing)
  265. {
  266. if (disposing)
  267. {
  268. _keepPolling = false;
  269. }
  270. }
  271. }
  272. }