AudioDeviceSession.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. // Copyright (c) 2019-2021 Ryujinx
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Lesser General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU Lesser General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU Lesser General Public License
  14. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  15. //
  16. using Ryujinx.Audio.Integration;
  17. using Ryujinx.Common;
  18. using System;
  19. using System.Diagnostics;
  20. namespace Ryujinx.Audio.Common
  21. {
  22. /// <summary>
  23. /// An audio device session.
  24. /// </summary>
  25. class AudioDeviceSession : IDisposable
  26. {
  27. /// <summary>
  28. /// The volume of the <see cref="AudioDeviceSession"/>.
  29. /// </summary>
  30. private float _volume;
  31. /// <summary>
  32. /// The state of the <see cref="AudioDeviceSession"/>.
  33. /// </summary>
  34. private AudioDeviceState _state;
  35. /// <summary>
  36. /// Array of all buffers currently used or released.
  37. /// </summary>
  38. private AudioBuffer[] _buffers;
  39. /// <summary>
  40. /// The server index inside <see cref="_buffers"/> (appended but not queued to device driver).
  41. /// </summary>
  42. private uint _serverBufferIndex;
  43. /// <summary>
  44. /// The hardware index inside <see cref="_buffers"/> (queued to device driver).
  45. /// </summary>
  46. private uint _hardwareBufferIndex;
  47. /// <summary>
  48. /// The released index inside <see cref="_buffers"/> (released by the device driver).
  49. /// </summary>
  50. private uint _releasedBufferIndex;
  51. /// <summary>
  52. /// The count of buffer appended (server side).
  53. /// </summary>
  54. private uint _bufferAppendedCount;
  55. /// <summary>
  56. /// The count of buffer registered (driver side).
  57. /// </summary>
  58. private uint _bufferRegisteredCount;
  59. /// <summary>
  60. /// The count of buffer released (released by the driver side).
  61. /// </summary>
  62. private uint _bufferReleasedCount;
  63. /// <summary>
  64. /// The released buffer event.
  65. /// </summary>
  66. private IWritableEvent _bufferEvent;
  67. /// <summary>
  68. /// The session on the device driver.
  69. /// </summary>
  70. private IHardwareDeviceSession _hardwareDeviceSession;
  71. /// <summary>
  72. /// Max number of buffers that can be registered to the device driver at a time.
  73. /// </summary>
  74. private uint _bufferRegisteredLimit;
  75. /// <summary>
  76. /// Create a new <see cref="AudioDeviceSession"/>.
  77. /// </summary>
  78. /// <param name="deviceSession">The device driver session associated</param>
  79. /// <param name="bufferEvent">The release buffer event</param>
  80. /// <param name="bufferRegisteredLimit">The max number of buffers that can be registered to the device driver at a time</param>
  81. public AudioDeviceSession(IHardwareDeviceSession deviceSession, IWritableEvent bufferEvent, uint bufferRegisteredLimit = 4)
  82. {
  83. _bufferEvent = bufferEvent;
  84. _hardwareDeviceSession = deviceSession;
  85. _bufferRegisteredLimit = bufferRegisteredLimit;
  86. _buffers = new AudioBuffer[Constants.AudioDeviceBufferCountMax];
  87. _serverBufferIndex = 0;
  88. _hardwareBufferIndex = 0;
  89. _releasedBufferIndex = 0;
  90. _bufferAppendedCount = 0;
  91. _bufferRegisteredCount = 0;
  92. _bufferReleasedCount = 0;
  93. _volume = deviceSession.GetVolume();
  94. _state = AudioDeviceState.Stopped;
  95. }
  96. /// <summary>
  97. /// Get the released buffer event.
  98. /// </summary>
  99. /// <returns>The released buffer event</returns>
  100. public IWritableEvent GetBufferEvent()
  101. {
  102. return _bufferEvent;
  103. }
  104. /// <summary>
  105. /// Get the state of the session.
  106. /// </summary>
  107. /// <returns>The state of the session</returns>
  108. public AudioDeviceState GetState()
  109. {
  110. Debug.Assert(_state == AudioDeviceState.Started || _state == AudioDeviceState.Stopped);
  111. return _state;
  112. }
  113. /// <summary>
  114. /// Get the total buffer count (server + driver + released).
  115. /// </summary>
  116. /// <returns>Return the total buffer count</returns>
  117. private uint GetTotalBufferCount()
  118. {
  119. uint bufferCount = _bufferAppendedCount + _bufferRegisteredCount + _bufferReleasedCount;
  120. Debug.Assert(bufferCount <= Constants.AudioDeviceBufferCountMax);
  121. return bufferCount;
  122. }
  123. /// <summary>
  124. /// Register a new <see cref="AudioBuffer"/> on the server side.
  125. /// </summary>
  126. /// <param name="buffer">The <see cref="AudioBuffer"/> to register</param>
  127. /// <returns>True if the operation succeeded</returns>
  128. private bool RegisterBuffer(AudioBuffer buffer)
  129. {
  130. if (GetTotalBufferCount() == Constants.AudioDeviceBufferCountMax)
  131. {
  132. return false;
  133. }
  134. _buffers[_serverBufferIndex] = buffer;
  135. _serverBufferIndex = (_serverBufferIndex + 1) % Constants.AudioDeviceBufferCountMax;
  136. _bufferAppendedCount++;
  137. return true;
  138. }
  139. /// <summary>
  140. /// Flush server buffers to hardware.
  141. /// </summary>
  142. private void FlushToHardware()
  143. {
  144. uint bufferToFlushCount = Math.Min(Math.Min(_bufferAppendedCount, 4), _bufferRegisteredLimit - _bufferRegisteredCount);
  145. AudioBuffer[] buffersToFlush = new AudioBuffer[bufferToFlushCount];
  146. uint hardwareBufferIndex = _hardwareBufferIndex;
  147. for (int i = 0; i < buffersToFlush.Length; i++)
  148. {
  149. buffersToFlush[i] = _buffers[_hardwareBufferIndex];
  150. _bufferAppendedCount--;
  151. _bufferRegisteredCount++;
  152. hardwareBufferIndex = (hardwareBufferIndex + 1) % Constants.AudioDeviceBufferCountMax;
  153. }
  154. _hardwareBufferIndex = hardwareBufferIndex;
  155. for (int i = 0; i < buffersToFlush.Length; i++)
  156. {
  157. _hardwareDeviceSession.QueueBuffer(buffersToFlush[i]);
  158. }
  159. }
  160. /// <summary>
  161. /// Get the current index of the <see cref="AudioBuffer"/> playing on the driver side.
  162. /// </summary>
  163. /// <param name="playingIndex">The output index of the <see cref="AudioBuffer"/> playing on the driver side</param>
  164. /// <returns>True if any buffer is playing</returns>
  165. private bool TryGetPlayingBufferIndex(out uint playingIndex)
  166. {
  167. if (_bufferRegisteredCount > 0)
  168. {
  169. playingIndex = (_hardwareBufferIndex - _bufferRegisteredCount) % Constants.AudioDeviceBufferCountMax;
  170. return true;
  171. }
  172. playingIndex = 0;
  173. return false;
  174. }
  175. /// <summary>
  176. /// Try to pop the <see cref="AudioBuffer"/> playing on the driver side.
  177. /// </summary>
  178. /// <param name="buffer">The output <see cref="AudioBuffer"/> playing on the driver side</param>
  179. /// <returns>True if any buffer is playing</returns>
  180. private bool TryPopPlayingBuffer(out AudioBuffer buffer)
  181. {
  182. if (_bufferRegisteredCount > 0)
  183. {
  184. uint bufferIndex = (_hardwareBufferIndex - _bufferRegisteredCount) % Constants.AudioDeviceBufferCountMax;
  185. buffer = _buffers[bufferIndex];
  186. _buffers[bufferIndex] = null;
  187. _bufferRegisteredCount--;
  188. return true;
  189. }
  190. buffer = null;
  191. return false;
  192. }
  193. /// <summary>
  194. /// Try to pop a <see cref="AudioBuffer"/> released by the driver side.
  195. /// </summary>
  196. /// <param name="buffer">The output <see cref="AudioBuffer"/> released by the driver side</param>
  197. /// <returns>True if any buffer has been released</returns>
  198. public bool TryPopReleasedBuffer(out AudioBuffer buffer)
  199. {
  200. if (_bufferReleasedCount > 0)
  201. {
  202. uint bufferIndex = (_releasedBufferIndex - _bufferReleasedCount) % Constants.AudioDeviceBufferCountMax;
  203. buffer = _buffers[bufferIndex];
  204. _buffers[bufferIndex] = null;
  205. _bufferReleasedCount--;
  206. return true;
  207. }
  208. buffer = null;
  209. return false;
  210. }
  211. /// <summary>
  212. /// Release a <see cref="AudioBuffer"/>.
  213. /// </summary>
  214. /// <param name="buffer">The <see cref="AudioBuffer"/> to release</param>
  215. private void ReleaseBuffer(AudioBuffer buffer)
  216. {
  217. buffer.PlayedTimestamp = (ulong)PerformanceCounter.ElapsedNanoseconds;
  218. _bufferRegisteredCount--;
  219. _bufferReleasedCount++;
  220. _releasedBufferIndex = (_releasedBufferIndex + 1) % Constants.AudioDeviceBufferCountMax;
  221. }
  222. /// <summary>
  223. /// Update the released buffers.
  224. /// </summary>
  225. /// <param name="updateForStop">True if the session is currently stopping</param>
  226. private void UpdateReleaseBuffers(bool updateForStop = false)
  227. {
  228. bool wasAnyBuffersReleased = false;
  229. while (TryGetPlayingBufferIndex(out uint playingIndex))
  230. {
  231. if (!updateForStop && !_hardwareDeviceSession.WasBufferFullyConsumed(_buffers[playingIndex]))
  232. {
  233. break;
  234. }
  235. if (updateForStop)
  236. {
  237. _hardwareDeviceSession.UnregisterBuffer(_buffers[playingIndex]);
  238. }
  239. ReleaseBuffer(_buffers[playingIndex]);
  240. wasAnyBuffersReleased = true;
  241. }
  242. if (wasAnyBuffersReleased)
  243. {
  244. _bufferEvent.Signal();
  245. }
  246. }
  247. /// <summary>
  248. /// Append a new <see cref="AudioBuffer"/>.
  249. /// </summary>
  250. /// <param name="buffer">The <see cref="AudioBuffer"/> to append</param>
  251. /// <returns>True if the buffer was appended</returns>
  252. public bool AppendBuffer(AudioBuffer buffer)
  253. {
  254. if (_hardwareDeviceSession.RegisterBuffer(buffer))
  255. {
  256. if (RegisterBuffer(buffer))
  257. {
  258. FlushToHardware();
  259. return true;
  260. }
  261. _hardwareDeviceSession.UnregisterBuffer(buffer);
  262. }
  263. return false;
  264. }
  265. public bool AppendUacBuffer(AudioBuffer buffer, uint handle)
  266. {
  267. // NOTE: On hardware, there is another RegisterBuffer method taking an handle.
  268. // This variant of the call always return false (stubbed?) as a result this logic will never succeed.
  269. return false;
  270. }
  271. /// <summary>
  272. /// Start the audio session.
  273. /// </summary>
  274. /// <returns>A <see cref="ResultCode"/> reporting an error or a success</returns>
  275. public ResultCode Start()
  276. {
  277. if (_state == AudioDeviceState.Started)
  278. {
  279. return ResultCode.OperationFailed;
  280. }
  281. _hardwareDeviceSession.Start();
  282. _state = AudioDeviceState.Started;
  283. FlushToHardware();
  284. _hardwareDeviceSession.SetVolume(_volume);
  285. return ResultCode.Success;
  286. }
  287. /// <summary>
  288. /// Stop the audio session.
  289. /// </summary>
  290. /// <returns>A <see cref="ResultCode"/> reporting an error or a success</returns>
  291. public ResultCode Stop()
  292. {
  293. if (_state == AudioDeviceState.Started)
  294. {
  295. _hardwareDeviceSession.Stop();
  296. UpdateReleaseBuffers(true);
  297. _state = AudioDeviceState.Stopped;
  298. }
  299. return ResultCode.Success;
  300. }
  301. /// <summary>
  302. /// Get the volume of the session.
  303. /// </summary>
  304. /// <returns>The volume of the session</returns>
  305. public float GetVolume()
  306. {
  307. return _hardwareDeviceSession.GetVolume();
  308. }
  309. /// <summary>
  310. /// Set the volume of the session.
  311. /// </summary>
  312. /// <param name="volume">The new volume to set</param>
  313. public void SetVolume(float volume)
  314. {
  315. _volume = volume;
  316. if (_state == AudioDeviceState.Started)
  317. {
  318. _hardwareDeviceSession.SetVolume(volume);
  319. }
  320. }
  321. /// <summary>
  322. /// Get the count of buffer currently in use (server + driver side).
  323. /// </summary>
  324. /// <returns>The count of buffer currently in use</returns>
  325. public uint GetBufferCount()
  326. {
  327. return _bufferAppendedCount + _bufferRegisteredCount;
  328. }
  329. /// <summary>
  330. /// Check if a buffer is present.
  331. /// </summary>
  332. /// <param name="bufferTag">The unique tag of the buffer</param>
  333. /// <returns>Return true if a buffer is present</returns>
  334. public bool ContainsBuffer(ulong bufferTag)
  335. {
  336. uint bufferIndex = (_releasedBufferIndex - _bufferReleasedCount) % Constants.AudioDeviceBufferCountMax;
  337. for (int i = 0; i < GetTotalBufferCount(); i++)
  338. {
  339. if (_buffers[bufferIndex].BufferTag == bufferTag)
  340. {
  341. return true;
  342. }
  343. bufferIndex = (bufferIndex + 1) % Constants.AudioDeviceBufferCountMax;
  344. }
  345. return false;
  346. }
  347. /// <summary>
  348. /// Get the count of sample played in this session.
  349. /// </summary>
  350. /// <returns>The count of sample played in this session</returns>
  351. public ulong GetPlayedSampleCount()
  352. {
  353. if (_state == AudioDeviceState.Stopped)
  354. {
  355. return 0;
  356. }
  357. else
  358. {
  359. return _hardwareDeviceSession.GetPlayedSampleCount();
  360. }
  361. }
  362. /// <summary>
  363. /// Flush all buffers to the initial state.
  364. /// </summary>
  365. /// <returns>True if any buffer was flushed</returns>
  366. public bool FlushBuffers()
  367. {
  368. if (_state == AudioDeviceState.Stopped)
  369. {
  370. return false;
  371. }
  372. uint bufferCount = GetBufferCount();
  373. while (TryPopReleasedBuffer(out AudioBuffer buffer))
  374. {
  375. _hardwareDeviceSession.UnregisterBuffer(buffer);
  376. }
  377. while (TryPopPlayingBuffer(out AudioBuffer buffer))
  378. {
  379. _hardwareDeviceSession.UnregisterBuffer(buffer);
  380. }
  381. if (_bufferRegisteredCount == 0 || (_bufferReleasedCount + _bufferAppendedCount) > Constants.AudioDeviceBufferCountMax)
  382. {
  383. return false;
  384. }
  385. _bufferReleasedCount += _bufferAppendedCount;
  386. _releasedBufferIndex = (_releasedBufferIndex + _bufferAppendedCount) % Constants.AudioDeviceBufferCountMax;
  387. _bufferAppendedCount = 0;
  388. _hardwareBufferIndex = _serverBufferIndex;
  389. if (bufferCount > 0)
  390. {
  391. _bufferEvent.Signal();
  392. }
  393. return true;
  394. }
  395. /// <summary>
  396. /// Update the session.
  397. /// </summary>
  398. public void Update()
  399. {
  400. if (_state == AudioDeviceState.Started)
  401. {
  402. UpdateReleaseBuffers();
  403. FlushToHardware();
  404. }
  405. }
  406. public void Dispose()
  407. {
  408. Dispose(true);
  409. }
  410. protected virtual void Dispose(bool disposing)
  411. {
  412. if (disposing)
  413. {
  414. // Tell the hardware session that we are ending.
  415. _hardwareDeviceSession.PrepareToClose();
  416. // Unregister all buffers
  417. while (TryPopReleasedBuffer(out AudioBuffer buffer))
  418. {
  419. _hardwareDeviceSession.UnregisterBuffer(buffer);
  420. }
  421. while (TryPopPlayingBuffer(out AudioBuffer buffer))
  422. {
  423. _hardwareDeviceSession.UnregisterBuffer(buffer);
  424. }
  425. // Finally dispose hardware session.
  426. _hardwareDeviceSession.Dispose();
  427. _bufferEvent.Signal();
  428. }
  429. }
  430. }
  431. }