AudioOutputManager.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. //
  2. // Copyright (c) 2019-2021 Ryujinx
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. //
  17. using Ryujinx.Audio.Common;
  18. using Ryujinx.Audio.Integration;
  19. using Ryujinx.Common.Logging;
  20. using Ryujinx.Memory;
  21. using System;
  22. using System.Diagnostics;
  23. using System.Linq;
  24. using System.Threading;
  25. namespace Ryujinx.Audio.Output
  26. {
  27. /// <summary>
  28. /// The audio output manager.
  29. /// </summary>
  30. public class AudioOutputManager : IDisposable
  31. {
  32. private object _lock = new object();
  33. /// <summary>
  34. /// Lock used for session allocation.
  35. /// </summary>
  36. private object _sessionLock = new object();
  37. /// <summary>
  38. /// The session ids allocation table.
  39. /// </summary>
  40. private int[] _sessionIds;
  41. /// <summary>
  42. /// The device driver.
  43. /// </summary>
  44. private IHardwareDeviceDriver _deviceDriver;
  45. /// <summary>
  46. /// The events linked to each session.
  47. /// </summary>
  48. private IWritableEvent[] _sessionsBufferEvents;
  49. /// <summary>
  50. /// The <see cref="AudioOutputSystem"/> session instances.
  51. /// </summary>
  52. private AudioOutputSystem[] _sessions;
  53. /// <summary>
  54. /// The count of active sessions.
  55. /// </summary>
  56. private int _activeSessionCount;
  57. /// <summary>
  58. /// The dispose state.
  59. /// </summary>
  60. private int _disposeState;
  61. /// <summary>
  62. /// Create a new <see cref="AudioOutputManager"/>.
  63. /// </summary>
  64. public AudioOutputManager()
  65. {
  66. _sessionIds = new int[Constants.AudioOutSessionCountMax];
  67. _sessions = new AudioOutputSystem[Constants.AudioOutSessionCountMax];
  68. _activeSessionCount = 0;
  69. for (int i = 0; i < _sessionIds.Length; i++)
  70. {
  71. _sessionIds[i] = i;
  72. }
  73. }
  74. /// <summary>
  75. /// Initialize the <see cref="AudioOutputManager"/>.
  76. /// </summary>
  77. /// <param name="deviceDriver">The device driver.</param>
  78. /// <param name="sessionRegisterEvents">The events associated to each session.</param>
  79. public void Initialize(IHardwareDeviceDriver deviceDriver, IWritableEvent[] sessionRegisterEvents)
  80. {
  81. _deviceDriver = deviceDriver;
  82. _sessionsBufferEvents = sessionRegisterEvents;
  83. }
  84. /// <summary>
  85. /// Acquire a new session id.
  86. /// </summary>
  87. /// <returns>A new session id.</returns>
  88. private int AcquireSessionId()
  89. {
  90. lock (_sessionLock)
  91. {
  92. int index = _activeSessionCount;
  93. Debug.Assert(index < _sessionIds.Length);
  94. int sessionId = _sessionIds[index];
  95. _sessionIds[index] = -1;
  96. _activeSessionCount++;
  97. Logger.Info?.Print(LogClass.AudioRenderer, $"Registered new output ({sessionId})");
  98. return sessionId;
  99. }
  100. }
  101. /// <summary>
  102. /// Release a given <paramref name="sessionId"/>.
  103. /// </summary>
  104. /// <param name="sessionId">The session id to release.</param>
  105. private void ReleaseSessionId(int sessionId)
  106. {
  107. lock (_sessionLock)
  108. {
  109. Debug.Assert(_activeSessionCount > 0);
  110. int newIndex = --_activeSessionCount;
  111. _sessionIds[newIndex] = sessionId;
  112. }
  113. Logger.Info?.Print(LogClass.AudioRenderer, $"Unregistered output ({sessionId})");
  114. }
  115. /// <summary>
  116. /// Used to update audio output system.
  117. /// </summary>
  118. public void Update()
  119. {
  120. lock (_sessionLock)
  121. {
  122. foreach (AudioOutputSystem output in _sessions)
  123. {
  124. output?.Update();
  125. }
  126. }
  127. }
  128. /// <summary>
  129. /// Register a new <see cref="AudioOutputSystem"/>.
  130. /// </summary>
  131. /// <param name="output">The <see cref="AudioOutputSystem"/> to register.</param>
  132. private void Register(AudioOutputSystem output)
  133. {
  134. lock (_sessionLock)
  135. {
  136. _sessions[output.GetSessionId()] = output;
  137. }
  138. }
  139. /// <summary>
  140. /// Unregister a new <see cref="AudioOutputSystem"/>.
  141. /// </summary>
  142. /// <param name="output">The <see cref="AudioOutputSystem"/> to unregister.</param>
  143. internal void Unregister(AudioOutputSystem output)
  144. {
  145. lock (_sessionLock)
  146. {
  147. int sessionId = output.GetSessionId();
  148. _sessions[output.GetSessionId()] = null;
  149. ReleaseSessionId(sessionId);
  150. }
  151. }
  152. /// <summary>
  153. /// Get the list of all audio outputs name.
  154. /// </summary>
  155. /// <returns>The list of all audio outputs name</returns>
  156. public string[] ListAudioOuts()
  157. {
  158. return new string[] { Constants.DefaultDeviceOutputName };
  159. }
  160. /// <summary>
  161. /// Open a new <see cref="AudioOutputSystem"/>.
  162. /// </summary>
  163. /// <param name="outputDeviceName">The output device name selected by the <see cref="AudioOutputSystem"/></param>
  164. /// <param name="outputConfiguration">The output audio configuration selected by the <see cref="AudioOutputSystem"/></param>
  165. /// <param name="obj">The new <see cref="AudioOutputSystem"/></param>
  166. /// <param name="memoryManager">The memory manager that will be used for all guest memory operations</param>
  167. /// <param name="inputDeviceName">The input device name wanted by the user</param>
  168. /// <param name="sampleFormat">The sample format to use</param>
  169. /// <param name="parameter">The user configuration</param>
  170. /// <param name="appletResourceUserId">The applet resource user id of the application</param>
  171. /// <param name="processHandle">The process handle of the application</param>
  172. /// <returns>A <see cref="ResultCode"/> reporting an error or a success</returns>
  173. public ResultCode OpenAudioOut(out string outputDeviceName,
  174. out AudioOutputConfiguration outputConfiguration,
  175. out AudioOutputSystem obj,
  176. IVirtualMemoryManager memoryManager,
  177. string inputDeviceName,
  178. SampleFormat sampleFormat,
  179. ref AudioInputConfiguration parameter,
  180. ulong appletResourceUserId,
  181. uint processHandle,
  182. float volume)
  183. {
  184. int sessionId = AcquireSessionId();
  185. _sessionsBufferEvents[sessionId].Clear();
  186. IHardwareDeviceSession deviceSession = _deviceDriver.OpenDeviceSession(IHardwareDeviceDriver.Direction.Output, memoryManager, sampleFormat, parameter.SampleRate, parameter.ChannelCount, volume);
  187. AudioOutputSystem audioOut = new AudioOutputSystem(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]);
  188. ResultCode result = audioOut.Initialize(inputDeviceName, sampleFormat, ref parameter, sessionId);
  189. if (result == ResultCode.Success)
  190. {
  191. outputDeviceName = audioOut.DeviceName;
  192. outputConfiguration = new AudioOutputConfiguration
  193. {
  194. ChannelCount = audioOut.ChannelCount,
  195. SampleFormat = audioOut.SampleFormat,
  196. SampleRate = audioOut.SampleRate,
  197. AudioOutState = audioOut.GetState(),
  198. };
  199. obj = audioOut;
  200. Register(audioOut);
  201. }
  202. else
  203. {
  204. ReleaseSessionId(sessionId);
  205. obj = null;
  206. outputDeviceName = null;
  207. outputConfiguration = default;
  208. }
  209. return result;
  210. }
  211. /// <summary>
  212. /// Sets the volume for all output devices.
  213. /// </summary>
  214. /// <param name="volume">The volume to set.</param>
  215. public void SetVolume(float volume)
  216. {
  217. if (_sessions != null)
  218. {
  219. foreach (AudioOutputSystem session in _sessions)
  220. {
  221. session?.SetVolume(volume);
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Gets the volume for all output devices.
  227. /// </summary>
  228. /// <returns>A float indicating the volume level.</returns>
  229. public float GetVolume()
  230. {
  231. if (_sessions != null)
  232. {
  233. foreach (AudioOutputSystem session in _sessions)
  234. {
  235. if (session != null)
  236. {
  237. return session.GetVolume();
  238. }
  239. }
  240. }
  241. return 0.0f;
  242. }
  243. public void Dispose()
  244. {
  245. if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0)
  246. {
  247. Dispose(true);
  248. }
  249. }
  250. protected virtual void Dispose(bool disposing)
  251. {
  252. if (disposing)
  253. {
  254. // Clone the sessions array to dispose them outside the lock.
  255. AudioOutputSystem[] sessions;
  256. lock (_sessionLock)
  257. {
  258. sessions = _sessions.ToArray();
  259. }
  260. foreach (AudioOutputSystem output in sessions)
  261. {
  262. output?.Dispose();
  263. }
  264. }
  265. }
  266. }
  267. }