OpenALAudioOut.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. /// True if OpenAL is supported on the device
  36. /// </summary>
  37. public static bool IsSupported
  38. {
  39. get
  40. {
  41. try
  42. {
  43. return AudioContext.AvailableDevices.Count > 0;
  44. }
  45. catch
  46. {
  47. return false;
  48. }
  49. }
  50. }
  51. public OpenALAudioOut()
  52. {
  53. _context = new AudioContext();
  54. _tracks = new ConcurrentDictionary<int, OpenALAudioTrack>();
  55. _keepPolling = true;
  56. _audioPollerThread = new Thread(AudioPollerWork)
  57. {
  58. Name = "Audio.PollerThread"
  59. };
  60. _audioPollerThread.Start();
  61. }
  62. private void AudioPollerWork()
  63. {
  64. do
  65. {
  66. foreach (OpenALAudioTrack track in _tracks.Values)
  67. {
  68. lock (track)
  69. {
  70. track.CallReleaseCallbackIfNeeded();
  71. }
  72. }
  73. // If it's not slept it will waste cycles.
  74. Thread.Sleep(10);
  75. }
  76. while (_keepPolling);
  77. foreach (OpenALAudioTrack track in _tracks.Values)
  78. {
  79. track.Dispose();
  80. }
  81. _tracks.Clear();
  82. _context.Dispose();
  83. }
  84. public bool SupportsChannelCount(int channels)
  85. {
  86. // NOTE: OpenAL doesn't give us a way to know if the 5.1 setup is supported by hardware or actually emulated.
  87. // TODO: find a way to determine hardware support.
  88. return channels == 1 || channels == 2;
  89. }
  90. /// <summary>
  91. /// Creates a new audio track with the specified parameters
  92. /// </summary>
  93. /// <param name="sampleRate">The requested sample rate</param>
  94. /// <param name="hardwareChannels">The requested hardware channels</param>
  95. /// <param name="virtualChannels">The requested virtual 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. /// <returns>The created track's Track ID</returns>
  98. public int OpenHardwareTrack(int sampleRate, int hardwareChannels, int virtualChannels, ReleaseCallback callback)
  99. {
  100. OpenALAudioTrack track = new OpenALAudioTrack(sampleRate, GetALFormat(hardwareChannels), hardwareChannels, virtualChannels, 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. // Do we need to downmix?
  182. if (track.HardwareChannels != track.VirtualChannels)
  183. {
  184. short[] downmixedBuffer;
  185. ReadOnlySpan<short> bufferPCM16 = MemoryMarshal.Cast<T, short>(buffer);
  186. if (track.VirtualChannels == 6)
  187. {
  188. downmixedBuffer = Downmixing.DownMixSurroundToStereo(bufferPCM16);
  189. if (track.HardwareChannels == 1)
  190. {
  191. downmixedBuffer = Downmixing.DownMixStereoToMono(downmixedBuffer);
  192. }
  193. }
  194. else if (track.VirtualChannels == 2)
  195. {
  196. downmixedBuffer = Downmixing.DownMixStereoToMono(bufferPCM16);
  197. }
  198. else
  199. {
  200. throw new NotImplementedException($"Downmixing from {track.VirtualChannels} to {track.HardwareChannels} not implemented!");
  201. }
  202. AL.BufferData(bufferId, track.Format, downmixedBuffer, downmixedBuffer.Length * sizeof(ushort), track.SampleRate);
  203. }
  204. else
  205. {
  206. AL.BufferData(bufferId, track.Format, buffer, buffer.Length * sizeof(ushort), track.SampleRate);
  207. }
  208. AL.SourceQueueBuffer(track.SourceId, bufferId);
  209. StartPlaybackIfNeeded(track);
  210. track.PlayedSampleCount += (ulong)buffer.Length;
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// Starts playback
  216. /// </summary>
  217. /// <param name="trackId">The ID of the track to start playback on</param>
  218. public void Start(int trackId)
  219. {
  220. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  221. {
  222. lock (track)
  223. {
  224. track.State = PlaybackState.Playing;
  225. StartPlaybackIfNeeded(track);
  226. }
  227. }
  228. }
  229. private void StartPlaybackIfNeeded(OpenALAudioTrack track)
  230. {
  231. AL.GetSource(track.SourceId, ALGetSourcei.SourceState, out int stateInt);
  232. ALSourceState State = (ALSourceState)stateInt;
  233. if (State != ALSourceState.Playing && track.State == PlaybackState.Playing)
  234. {
  235. AL.SourcePlay(track.SourceId);
  236. }
  237. }
  238. /// <summary>
  239. /// Stops playback
  240. /// </summary>
  241. /// <param name="trackId">The ID of the track to stop playback on</param>
  242. public void Stop(int trackId)
  243. {
  244. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  245. {
  246. lock (track)
  247. {
  248. track.State = PlaybackState.Stopped;
  249. AL.SourceStop(track.SourceId);
  250. }
  251. }
  252. }
  253. /// <summary>
  254. /// Get track buffer count
  255. /// </summary>
  256. /// <param name="trackId">The ID of the track to get buffer count</param>
  257. public uint GetBufferCount(int trackId)
  258. {
  259. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  260. {
  261. lock (track)
  262. {
  263. return track.BufferCount;
  264. }
  265. }
  266. return 0;
  267. }
  268. /// <summary>
  269. /// Get track played sample count
  270. /// </summary>
  271. /// <param name="trackId">The ID of the track to get played sample count</param>
  272. public ulong GetPlayedSampleCount(int trackId)
  273. {
  274. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  275. {
  276. lock (track)
  277. {
  278. return track.PlayedSampleCount;
  279. }
  280. }
  281. return 0;
  282. }
  283. /// <summary>
  284. /// Flush all track buffers
  285. /// </summary>
  286. /// <param name="trackId">The ID of the track to flush</param>
  287. public bool FlushBuffers(int trackId)
  288. {
  289. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  290. {
  291. lock (track)
  292. {
  293. track.FlushBuffers();
  294. }
  295. }
  296. return false;
  297. }
  298. /// <summary>
  299. /// Set track volume
  300. /// </summary>
  301. /// <param name="trackId">The ID of the track to set volume</param>
  302. /// <param name="volume">The volume of the track</param>
  303. public void SetVolume(int trackId, float volume)
  304. {
  305. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  306. {
  307. lock (track)
  308. {
  309. track.SetVolume(volume);
  310. }
  311. }
  312. }
  313. /// <summary>
  314. /// Get track volume
  315. /// </summary>
  316. /// <param name="trackId">The ID of the track to get volume</param>
  317. public float GetVolume(int trackId)
  318. {
  319. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  320. {
  321. lock (track)
  322. {
  323. return track.Volume;
  324. }
  325. }
  326. return 1.0f;
  327. }
  328. /// <summary>
  329. /// Gets the current playback state of the specified track
  330. /// </summary>
  331. /// <param name="trackId">The track to retrieve the playback state for</param>
  332. public PlaybackState GetState(int trackId)
  333. {
  334. if (_tracks.TryGetValue(trackId, out OpenALAudioTrack track))
  335. {
  336. return track.State;
  337. }
  338. return PlaybackState.Stopped;
  339. }
  340. public void Dispose()
  341. {
  342. Dispose(true);
  343. }
  344. protected virtual void Dispose(bool disposing)
  345. {
  346. if (disposing)
  347. {
  348. _keepPolling = false;
  349. }
  350. }
  351. }
  352. }