OpenALAudioOut.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. public bool SupportsChannelCount(int channels)
  93. {
  94. // NOTE: OpenAL doesn't give us a way to know if the 5.1 setup is supported by hardware or actually emulated.
  95. // TODO: find a way to determine hardware support.
  96. return channels == 1 || channels == 2;
  97. }
  98. /// <summary>
  99. /// Creates a new audio track with the specified parameters
  100. /// </summary>
  101. /// <param name="sampleRate">The requested sample rate</param>
  102. /// <param name="hardwareChannels">The requested hardware channels</param>
  103. /// <param name="virtualChannels">The requested virtual channels</param>
  104. /// <param name="callback">A <see cref="ReleaseCallback" /> that represents the delegate to invoke when a buffer has been released by the audio track</param>
  105. /// <returns>The created track's Track ID</returns>
  106. public int OpenHardwareTrack(int sampleRate, int hardwareChannels, int virtualChannels, ReleaseCallback callback)
  107. {
  108. OpenALAudioTrack track = new OpenALAudioTrack(sampleRate, GetALFormat(hardwareChannels), hardwareChannels, virtualChannels, callback);
  109. for (int id = 0; id < MaxTracks; id++)
  110. {
  111. if (_tracks.TryAdd(id, track))
  112. {
  113. return id;
  114. }
  115. }
  116. return -1;
  117. }
  118. private ALFormat GetALFormat(int channels)
  119. {
  120. switch (channels)
  121. {
  122. case 1: return ALFormat.Mono16;
  123. case 2: return ALFormat.Stereo16;
  124. case 6: return ALFormat.Multi51Chn16Ext;
  125. }
  126. throw new ArgumentOutOfRangeException(nameof(channels));
  127. }
  128. /// <summary>
  129. /// Stops playback and closes the track specified by <paramref name="trackId"/>
  130. /// </summary>
  131. /// <param name="trackId">The ID of the track to close</param>
  132. public void CloseTrack(int trackId)
  133. {
  134. if (_tracks.TryRemove(trackId, out OpenALAudioTrack track))
  135. {
  136. lock (track)
  137. {
  138. track.Dispose();
  139. }
  140. }
  141. }
  142. /// <summary>
  143. /// Returns a value indicating whether the specified buffer is currently reserved by the specified track
  144. /// </summary>
  145. /// <param name="trackId">The track to check</param>
  146. /// <param name="bufferTag">The buffer tag to check</param>
  147. public bool ContainsBuffer(int trackId, long bufferTag)
  148. {
  149. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  150. {
  151. lock (track)
  152. {
  153. return track.ContainsBuffer(bufferTag);
  154. }
  155. }
  156. return false;
  157. }
  158. /// <summary>
  159. /// Gets a list of buffer tags the specified track is no longer reserving
  160. /// </summary>
  161. /// <param name="trackId">The track to retrieve buffer tags from</param>
  162. /// <param name="maxCount">The maximum amount of buffer tags to retrieve</param>
  163. /// <returns>Buffers released by the specified track</returns>
  164. public long[] GetReleasedBuffers(int trackId, int maxCount)
  165. {
  166. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  167. {
  168. lock (track)
  169. {
  170. return track.GetReleasedBuffers(maxCount);
  171. }
  172. }
  173. return null;
  174. }
  175. /// <summary>
  176. /// Appends an audio buffer to the specified track
  177. /// </summary>
  178. /// <typeparam name="T">The sample type of the buffer</typeparam>
  179. /// <param name="trackId">The track to append the buffer to</param>
  180. /// <param name="bufferTag">The internal tag of the buffer</param>
  181. /// <param name="buffer">The buffer to append to the track</param>
  182. public void AppendBuffer<T>(int trackId, long bufferTag, T[] buffer) where T : struct
  183. {
  184. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  185. {
  186. lock (track)
  187. {
  188. int bufferId = track.AppendBuffer(bufferTag);
  189. // Do we need to downmix?
  190. if (track.HardwareChannels != track.VirtualChannels)
  191. {
  192. short[] downmixedBuffer;
  193. ReadOnlySpan<short> bufferPCM16 = MemoryMarshal.Cast<T, short>(buffer);
  194. if (track.VirtualChannels == 6)
  195. {
  196. downmixedBuffer = Downmixing.DownMixSurroundToStereo(bufferPCM16);
  197. if (track.HardwareChannels == 1)
  198. {
  199. downmixedBuffer = Downmixing.DownMixStereoToMono(downmixedBuffer);
  200. }
  201. }
  202. else if (track.VirtualChannels == 2)
  203. {
  204. downmixedBuffer = Downmixing.DownMixStereoToMono(bufferPCM16);
  205. }
  206. else
  207. {
  208. throw new NotImplementedException($"Downmixing from {track.VirtualChannels} to {track.HardwareChannels} not implemented!");
  209. }
  210. AL.BufferData(bufferId, track.Format, downmixedBuffer, downmixedBuffer.Length * sizeof(ushort), track.SampleRate);
  211. }
  212. else
  213. {
  214. AL.BufferData(bufferId, track.Format, buffer, buffer.Length * sizeof(ushort), track.SampleRate);
  215. }
  216. AL.SourceQueueBuffer(track.SourceId, bufferId);
  217. StartPlaybackIfNeeded(track);
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// Starts playback
  223. /// </summary>
  224. /// <param name="trackId">The ID of the track to start playback on</param>
  225. public void Start(int trackId)
  226. {
  227. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  228. {
  229. lock (track)
  230. {
  231. track.State = PlaybackState.Playing;
  232. StartPlaybackIfNeeded(track);
  233. }
  234. }
  235. }
  236. private void StartPlaybackIfNeeded(OpenALAudioTrack track)
  237. {
  238. AL.GetSource(track.SourceId, ALGetSourcei.SourceState, out int stateInt);
  239. ALSourceState State = (ALSourceState)stateInt;
  240. if (State != ALSourceState.Playing && track.State == PlaybackState.Playing)
  241. {
  242. if (_volumeChanged)
  243. {
  244. AL.Source(track.SourceId, ALSourcef.Gain, _volume);
  245. _volumeChanged = false;
  246. }
  247. AL.SourcePlay(track.SourceId);
  248. }
  249. }
  250. /// <summary>
  251. /// Stops playback
  252. /// </summary>
  253. /// <param name="trackId">The ID of the track to stop playback on</param>
  254. public void Stop(int trackId)
  255. {
  256. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  257. {
  258. lock (track)
  259. {
  260. track.State = PlaybackState.Stopped;
  261. AL.SourceStop(track.SourceId);
  262. }
  263. }
  264. }
  265. /// <summary>
  266. /// Get playback volume
  267. /// </summary>
  268. public float GetVolume() => _volume;
  269. /// <summary>
  270. /// Set playback volume
  271. /// </summary>
  272. /// <param name="volume">The volume of the playback</param>
  273. public void SetVolume(float volume)
  274. {
  275. if (!_volumeChanged)
  276. {
  277. _volume = volume;
  278. _volumeChanged = true;
  279. }
  280. }
  281. /// <summary>
  282. /// Gets the current playback state of the specified track
  283. /// </summary>
  284. /// <param name="trackId">The track to retrieve the playback state for</param>
  285. public PlaybackState GetState(int trackId)
  286. {
  287. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  288. {
  289. return track.State;
  290. }
  291. return PlaybackState.Stopped;
  292. }
  293. public void Dispose()
  294. {
  295. Dispose(true);
  296. }
  297. protected virtual void Dispose(bool disposing)
  298. {
  299. if (disposing)
  300. {
  301. _keepPolling = false;
  302. }
  303. }
  304. }
  305. }