OpenALAudioOut.cs 9.4 KB

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