VoiceState.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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.Renderer.Common;
  18. using Ryujinx.Audio.Renderer.Parameter;
  19. using Ryujinx.Audio.Renderer.Server.MemoryPool;
  20. using Ryujinx.Common.Memory;
  21. using Ryujinx.Common.Utilities;
  22. using System;
  23. using System.Diagnostics;
  24. using System.Runtime.InteropServices;
  25. using static Ryujinx.Audio.Renderer.Common.BehaviourParameter;
  26. using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter;
  27. namespace Ryujinx.Audio.Renderer.Server.Voice
  28. {
  29. [StructLayout(LayoutKind.Sequential, Pack = Alignment)]
  30. public struct VoiceState
  31. {
  32. public const int Alignment = 0x10;
  33. /// <summary>
  34. /// Set to true if the voice is used.
  35. /// </summary>
  36. [MarshalAs(UnmanagedType.I1)]
  37. public bool InUse;
  38. /// <summary>
  39. /// Set to true if the voice is new.
  40. /// </summary>
  41. [MarshalAs(UnmanagedType.I1)]
  42. public bool IsNew;
  43. [MarshalAs(UnmanagedType.I1)]
  44. public bool WasPlaying;
  45. /// <summary>
  46. /// The <see cref="SampleFormat"/> of the voice.
  47. /// </summary>
  48. public SampleFormat SampleFormat;
  49. /// <summary>
  50. /// The sample rate of the voice.
  51. /// </summary>
  52. public uint SampleRate;
  53. /// <summary>
  54. /// The total channel count used.
  55. /// </summary>
  56. public uint ChannelsCount;
  57. /// <summary>
  58. /// Id of the voice.
  59. /// </summary>
  60. public int Id;
  61. /// <summary>
  62. /// Node id of the voice.
  63. /// </summary>
  64. public int NodeId;
  65. /// <summary>
  66. /// The target mix id of the voice.
  67. /// </summary>
  68. public int MixId;
  69. /// <summary>
  70. /// The current voice <see cref="Types.PlayState"/>.
  71. /// </summary>
  72. public Types.PlayState PlayState;
  73. /// <summary>
  74. /// The previous voice <see cref="Types.PlayState"/>.
  75. /// </summary>
  76. public Types.PlayState PreviousPlayState;
  77. /// <summary>
  78. /// The priority of the voice.
  79. /// </summary>
  80. public uint Priority;
  81. /// <summary>
  82. /// Target sorting position of the voice. (used to sort voice with the same <see cref="Priority"/>)
  83. /// </summary>
  84. public uint SortingOrder;
  85. /// <summary>
  86. /// The pitch used on the voice.
  87. /// </summary>
  88. public float Pitch;
  89. /// <summary>
  90. /// The output volume of the voice.
  91. /// </summary>
  92. public float Volume;
  93. /// <summary>
  94. /// The previous output volume of the voice.
  95. /// </summary>
  96. public float PreviousVolume;
  97. /// <summary>
  98. /// Biquad filters to apply to the output of the voice.
  99. /// </summary>
  100. public Array2<BiquadFilterParameter> BiquadFilters;
  101. /// <summary>
  102. /// Total count of <see cref="WaveBufferInternal"/> of the voice.
  103. /// </summary>
  104. public uint WaveBuffersCount;
  105. /// <summary>
  106. /// Current playing <see cref="WaveBufferInternal"/> of the voice.
  107. /// </summary>
  108. public uint WaveBuffersIndex;
  109. /// <summary>
  110. /// Change the behaviour of the voice.
  111. /// </summary>
  112. /// <remarks>This was added on REV5.</remarks>
  113. public DecodingBehaviour DecodingBehaviour;
  114. /// <summary>
  115. /// User state <see cref="AddressInfo"/> required by the data source.
  116. /// </summary>
  117. /// <remarks>Only used for <see cref="SampleFormat.Adpcm"/> as the GC-ADPCM coefficients.</remarks>
  118. public AddressInfo DataSourceStateAddressInfo;
  119. /// <summary>
  120. /// The wavebuffers of this voice.
  121. /// </summary>
  122. public Array4<WaveBuffer> WaveBuffers;
  123. /// <summary>
  124. /// The channel resource ids associated to the voice.
  125. /// </summary>
  126. public Array6<int> ChannelResourceIds;
  127. /// <summary>
  128. /// The target splitter id of the voice.
  129. /// </summary>
  130. public uint SplitterId;
  131. /// <summary>
  132. /// Change the Sample Rate Conversion (SRC) quality of the voice.
  133. /// </summary>
  134. /// <remarks>This was added on REV8.</remarks>
  135. public SampleRateConversionQuality SrcQuality;
  136. /// <summary>
  137. /// If set to true, the voice was dropped.
  138. /// </summary>
  139. [MarshalAs(UnmanagedType.I1)]
  140. public bool VoiceDropFlag;
  141. /// <summary>
  142. /// Set to true if the data source state work buffer wasn't mapped.
  143. /// </summary>
  144. [MarshalAs(UnmanagedType.I1)]
  145. public bool DataSourceStateUnmapped;
  146. /// <summary>
  147. /// Set to true if any of the <see cref="WaveBuffer.BufferAddressInfo"/> work buffer wasn't mapped.
  148. /// </summary>
  149. [MarshalAs(UnmanagedType.I1)]
  150. public bool BufferInfoUnmapped;
  151. /// <summary>
  152. /// The biquad filter initialization state storage.
  153. /// </summary>
  154. private BiquadFilterNeedInitializationArrayStruct _biquadFilterNeedInitialization;
  155. /// <summary>
  156. /// Flush the amount of wavebuffer specified. This will result in the wavebuffer being skipped and marked played.
  157. /// </summary>
  158. /// <remarks>This was added on REV5.</remarks>
  159. public byte FlushWaveBufferCount;
  160. [StructLayout(LayoutKind.Sequential, Size = RendererConstants.VoiceBiquadFilterCount)]
  161. private struct BiquadFilterNeedInitializationArrayStruct { }
  162. /// <summary>
  163. /// The biquad filter initialization state array.
  164. /// </summary>
  165. public Span<bool> BiquadFilterNeedInitialization => SpanHelpers.AsSpan<BiquadFilterNeedInitializationArrayStruct, bool>(ref _biquadFilterNeedInitialization);
  166. /// <summary>
  167. /// Initialize the <see cref="VoiceState"/>.
  168. /// </summary>
  169. public void Initialize()
  170. {
  171. IsNew = false;
  172. VoiceDropFlag = false;
  173. DataSourceStateUnmapped = false;
  174. BufferInfoUnmapped = false;
  175. FlushWaveBufferCount = 0;
  176. PlayState = Types.PlayState.Stopped;
  177. Priority = RendererConstants.VoiceLowestPriority;
  178. Id = 0;
  179. NodeId = 0;
  180. SampleRate = 0;
  181. SampleFormat = SampleFormat.Invalid;
  182. ChannelsCount = 0;
  183. Pitch = 0.0f;
  184. Volume= 0.0f;
  185. PreviousVolume = 0.0f;
  186. BiquadFilters.ToSpan().Fill(new BiquadFilterParameter());
  187. WaveBuffersCount = 0;
  188. WaveBuffersIndex = 0;
  189. MixId = RendererConstants.UnusedMixId;
  190. SplitterId = RendererConstants.UnusedSplitterId;
  191. DataSourceStateAddressInfo.Setup(0, 0);
  192. InitializeWaveBuffers();
  193. }
  194. /// <summary>
  195. /// Initialize the <see cref="WaveBuffer"/> in this <see cref="VoiceState"/>.
  196. /// </summary>
  197. private void InitializeWaveBuffers()
  198. {
  199. for (int i = 0; i < WaveBuffers.Length; i++)
  200. {
  201. WaveBuffers[i].StartSampleOffset = 0;
  202. WaveBuffers[i].EndSampleOffset = 0;
  203. WaveBuffers[i].ShouldLoop = false;
  204. WaveBuffers[i].IsEndOfStream = false;
  205. WaveBuffers[i].BufferAddressInfo.Setup(0, 0);
  206. WaveBuffers[i].ContextAddressInfo.Setup(0, 0);
  207. WaveBuffers[i].IsSendToAudioProcessor = true;
  208. }
  209. }
  210. /// <summary>
  211. /// Check if the voice needs to be skipped.
  212. /// </summary>
  213. /// <returns>Returns true if the voice needs to be skipped.</returns>
  214. public bool ShouldSkip()
  215. {
  216. return !InUse || WaveBuffersCount == 0 || DataSourceStateUnmapped || BufferInfoUnmapped || VoiceDropFlag;
  217. }
  218. /// <summary>
  219. /// Return true if the mix has any destinations.
  220. /// </summary>
  221. /// <returns>True if the mix has any destinations.</returns>
  222. public bool HasAnyDestination()
  223. {
  224. return MixId != RendererConstants.UnusedMixId || SplitterId != RendererConstants.UnusedSplitterId;
  225. }
  226. /// <summary>
  227. /// Indicate if the server voice information needs to be updated.
  228. /// </summary>
  229. /// <param name="parameter">The user parameter.</param>
  230. /// <returns>Return true, if the server voice information needs to be updated.</returns>
  231. private bool ShouldUpdateParameters(ref VoiceInParameter parameter)
  232. {
  233. if (DataSourceStateAddressInfo.CpuAddress == parameter.DataSourceStateAddress)
  234. {
  235. return DataSourceStateAddressInfo.Size != parameter.DataSourceStateSize;
  236. }
  237. return DataSourceStateAddressInfo.CpuAddress != parameter.DataSourceStateAddress ||
  238. DataSourceStateAddressInfo.Size != parameter.DataSourceStateSize ||
  239. DataSourceStateUnmapped;
  240. }
  241. /// <summary>
  242. /// Update the internal state from a user parameter.
  243. /// </summary>
  244. /// <param name="outErrorInfo">The possible <see cref="ErrorInfo"/> that was generated.</param>
  245. /// <param name="parameter">The user parameter.</param>
  246. /// <param name="poolMapper">The mapper to use.</param>
  247. /// <param name="behaviourContext">The behaviour context.</param>
  248. public void UpdateParameters(out ErrorInfo outErrorInfo, ref VoiceInParameter parameter, ref PoolMapper poolMapper, ref BehaviourContext behaviourContext)
  249. {
  250. InUse = parameter.InUse;
  251. Id = parameter.Id;
  252. NodeId = parameter.NodeId;
  253. UpdatePlayState(parameter.PlayState);
  254. SrcQuality = parameter.SrcQuality;
  255. Priority = parameter.Priority;
  256. SortingOrder = parameter.SortingOrder;
  257. SampleRate = parameter.SampleRate;
  258. SampleFormat = parameter.SampleFormat;
  259. ChannelsCount = parameter.ChannelCount;
  260. Pitch = parameter.Pitch;
  261. Volume = parameter.Volume;
  262. parameter.BiquadFilters.ToSpan().CopyTo(BiquadFilters.ToSpan());
  263. WaveBuffersCount = parameter.WaveBuffersCount;
  264. WaveBuffersIndex = parameter.WaveBuffersIndex;
  265. if (behaviourContext.IsFlushVoiceWaveBuffersSupported())
  266. {
  267. FlushWaveBufferCount += parameter.FlushWaveBufferCount;
  268. }
  269. MixId = parameter.MixId;
  270. if (behaviourContext.IsSplitterSupported())
  271. {
  272. SplitterId = parameter.SplitterId;
  273. }
  274. else
  275. {
  276. SplitterId = RendererConstants.UnusedSplitterId;
  277. }
  278. parameter.ChannelResourceIds.ToSpan().CopyTo(ChannelResourceIds.ToSpan());
  279. DecodingBehaviour behaviour = DecodingBehaviour.Default;
  280. if (behaviourContext.IsDecodingBehaviourFlagSupported())
  281. {
  282. behaviour = parameter.DecodingBehaviourFlags;
  283. }
  284. DecodingBehaviour = behaviour;
  285. if (parameter.ResetVoiceDropFlag)
  286. {
  287. VoiceDropFlag = false;
  288. }
  289. if (ShouldUpdateParameters(ref parameter))
  290. {
  291. DataSourceStateUnmapped = !poolMapper.TryAttachBuffer(out outErrorInfo, ref DataSourceStateAddressInfo, parameter.DataSourceStateAddress, parameter.DataSourceStateSize);
  292. }
  293. else
  294. {
  295. outErrorInfo = new ErrorInfo();
  296. }
  297. }
  298. /// <summary>
  299. /// Update the internal play state from user play state.
  300. /// </summary>
  301. /// <param name="userPlayState">The target user play state.</param>
  302. public void UpdatePlayState(PlayState userPlayState)
  303. {
  304. Types.PlayState oldServerPlayState = PlayState;
  305. PreviousPlayState = oldServerPlayState;
  306. Types.PlayState newServerPlayState;
  307. switch (userPlayState)
  308. {
  309. case Common.PlayState.Start:
  310. newServerPlayState = Types.PlayState.Started;
  311. break;
  312. case Common.PlayState.Stop:
  313. if (oldServerPlayState == Types.PlayState.Stopped)
  314. {
  315. return;
  316. }
  317. newServerPlayState = Types.PlayState.Stopping;
  318. break;
  319. case Common.PlayState.Pause:
  320. newServerPlayState = Types.PlayState.Paused;
  321. break;
  322. default:
  323. throw new NotImplementedException($"Unhandled PlayState.{userPlayState}");
  324. }
  325. PlayState = newServerPlayState;
  326. }
  327. /// <summary>
  328. /// Write the status of the voice to the given user output.
  329. /// </summary>
  330. /// <param name="outStatus">The given user output.</param>
  331. /// <param name="parameter">The user parameter.</param>
  332. /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
  333. public void WriteOutStatus(ref VoiceOutStatus outStatus, ref VoiceInParameter parameter, Memory<VoiceUpdateState>[] voiceUpdateStates)
  334. {
  335. #if DEBUG
  336. // Sanity check in debug mode of the internal state
  337. if (!parameter.IsNew && !IsNew)
  338. {
  339. for (int i = 1; i < ChannelsCount; i++)
  340. {
  341. ref VoiceUpdateState stateA = ref voiceUpdateStates[i - 1].Span[0];
  342. ref VoiceUpdateState stateB = ref voiceUpdateStates[i].Span[0];
  343. Debug.Assert(stateA.WaveBufferConsumed == stateB.WaveBufferConsumed);
  344. Debug.Assert(stateA.PlayedSampleCount == stateB.PlayedSampleCount);
  345. Debug.Assert(stateA.Offset == stateB.Offset);
  346. Debug.Assert(stateA.WaveBufferIndex == stateB.WaveBufferIndex);
  347. Debug.Assert(stateA.Fraction == stateB.Fraction);
  348. Debug.Assert(stateA.IsWaveBufferValid.SequenceEqual(stateB.IsWaveBufferValid));
  349. }
  350. }
  351. #endif
  352. if (parameter.IsNew || IsNew)
  353. {
  354. IsNew = true;
  355. outStatus.VoiceDropFlag = false;
  356. outStatus.PlayedWaveBuffersCount = 0;
  357. outStatus.PlayedSampleCount = 0;
  358. }
  359. else
  360. {
  361. ref VoiceUpdateState state = ref voiceUpdateStates[0].Span[0];
  362. outStatus.VoiceDropFlag = VoiceDropFlag;
  363. outStatus.PlayedWaveBuffersCount = state.WaveBufferConsumed;
  364. outStatus.PlayedSampleCount = state.PlayedSampleCount;
  365. }
  366. }
  367. /// <summary>
  368. /// Update the internal state of all the <see cref="WaveBuffer"/> of the <see cref="VoiceState"/>.
  369. /// </summary>
  370. /// <param name="errorInfos">An array of <see cref="ErrorInfo"/> used to report errors when mapping any of the <see cref="WaveBuffer"/>.</param>
  371. /// <param name="parameter">The user parameter.</param>
  372. /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
  373. /// <param name="mapper">The mapper to use.</param>
  374. /// <param name="behaviourContext">The behaviour context.</param>
  375. public void UpdateWaveBuffers(out ErrorInfo[] errorInfos, ref VoiceInParameter parameter, Memory<VoiceUpdateState>[] voiceUpdateStates, ref PoolMapper mapper, ref BehaviourContext behaviourContext)
  376. {
  377. errorInfos = new ErrorInfo[RendererConstants.VoiceWaveBufferCount * 2];
  378. if (parameter.IsNew)
  379. {
  380. InitializeWaveBuffers();
  381. for (int i = 0; i < parameter.ChannelCount; i++)
  382. {
  383. voiceUpdateStates[i].Span[0].IsWaveBufferValid.Fill(false);
  384. }
  385. }
  386. ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[0].Span[0];
  387. for (int i = 0; i < RendererConstants.VoiceWaveBufferCount; i++)
  388. {
  389. UpdateWaveBuffer(errorInfos.AsSpan().Slice(i * 2, 2), ref WaveBuffers[i], ref parameter.WaveBuffers[i], parameter.SampleFormat, voiceUpdateState.IsWaveBufferValid[i], ref mapper, ref behaviourContext);
  390. }
  391. }
  392. /// <summary>
  393. /// Update the internal state of one of the <see cref="WaveBuffer"/> of the <see cref="VoiceState"/>.
  394. /// </summary>
  395. /// <param name="errorInfos">A <see cref="Span{ErrorInfo}"/> used to report errors when mapping the <see cref="WaveBuffer"/>.</param>
  396. /// <param name="waveBuffer">The <see cref="WaveBuffer"/> to update.</param>
  397. /// <param name="inputWaveBuffer">The <see cref="WaveBufferInternal"/> from the user input.</param>
  398. /// <param name="sampleFormat">The <see cref="SampleFormat"/> from the user input.</param>
  399. /// <param name="isValid">If set to true, the server side wavebuffer is considered valid.</param>
  400. /// <param name="mapper">The mapper to use.</param>
  401. /// <param name="behaviourContext">The behaviour context.</param>
  402. private void UpdateWaveBuffer(Span<ErrorInfo> errorInfos, ref WaveBuffer waveBuffer, ref WaveBufferInternal inputWaveBuffer, SampleFormat sampleFormat, bool isValid, ref PoolMapper mapper, ref BehaviourContext behaviourContext)
  403. {
  404. if (!isValid && waveBuffer.IsSendToAudioProcessor && waveBuffer.BufferAddressInfo.CpuAddress != 0)
  405. {
  406. mapper.ForceUnmap(ref waveBuffer.BufferAddressInfo);
  407. waveBuffer.BufferAddressInfo.Setup(0, 0);
  408. }
  409. if (!inputWaveBuffer.SentToServer || BufferInfoUnmapped)
  410. {
  411. if (inputWaveBuffer.IsSampleOffsetValid(sampleFormat))
  412. {
  413. Debug.Assert(waveBuffer.IsSendToAudioProcessor);
  414. waveBuffer.IsSendToAudioProcessor = false;
  415. waveBuffer.StartSampleOffset = inputWaveBuffer.StartSampleOffset;
  416. waveBuffer.EndSampleOffset = inputWaveBuffer.EndSampleOffset;
  417. waveBuffer.ShouldLoop = inputWaveBuffer.ShouldLoop;
  418. waveBuffer.IsEndOfStream = inputWaveBuffer.IsEndOfStream;
  419. waveBuffer.LoopStartSampleOffset = inputWaveBuffer.LoopFirstSampleOffset;
  420. waveBuffer.LoopEndSampleOffset = inputWaveBuffer.LoopLastSampleOffset;
  421. waveBuffer.LoopCount = inputWaveBuffer.LoopCount;
  422. BufferInfoUnmapped = !mapper.TryAttachBuffer(out ErrorInfo bufferInfoError, ref waveBuffer.BufferAddressInfo, inputWaveBuffer.Address, inputWaveBuffer.Size);
  423. errorInfos[0] = bufferInfoError;
  424. if (sampleFormat == SampleFormat.Adpcm && behaviourContext.IsAdpcmLoopContextBugFixed() && inputWaveBuffer.ContextAddress != 0)
  425. {
  426. bool adpcmLoopContextMapped = mapper.TryAttachBuffer(out ErrorInfo adpcmLoopContextInfoError,
  427. ref waveBuffer.ContextAddressInfo,
  428. inputWaveBuffer.ContextAddress,
  429. inputWaveBuffer.ContextSize);
  430. errorInfos[1] = adpcmLoopContextInfoError;
  431. if (adpcmLoopContextMapped)
  432. {
  433. BufferInfoUnmapped = DataSourceStateUnmapped;
  434. }
  435. else
  436. {
  437. BufferInfoUnmapped = true;
  438. }
  439. }
  440. else
  441. {
  442. waveBuffer.ContextAddressInfo.Setup(0, 0);
  443. }
  444. }
  445. else
  446. {
  447. errorInfos[0].ErrorCode = ResultCode.InvalidAddressInfo;
  448. errorInfos[0].ExtraErrorInfo = inputWaveBuffer.Address;
  449. }
  450. }
  451. }
  452. /// <summary>
  453. /// Reset the resources associated to this <see cref="VoiceState"/>.
  454. /// </summary>
  455. /// <param name="context">The voice context.</param>
  456. private void ResetResources(VoiceContext context)
  457. {
  458. for (int i = 0; i < ChannelsCount; i++)
  459. {
  460. int channelResourceId = ChannelResourceIds[i];
  461. ref VoiceChannelResource voiceChannelResource = ref context.GetChannelResource(channelResourceId);
  462. Debug.Assert(voiceChannelResource.IsUsed);
  463. Memory<VoiceUpdateState> dspSharedState = context.GetUpdateStateForDsp(channelResourceId);
  464. MemoryMarshal.Cast<VoiceUpdateState, byte>(dspSharedState.Span).Fill(0);
  465. voiceChannelResource.UpdateState();
  466. }
  467. }
  468. /// <summary>
  469. /// Flush a certain amount of <see cref="WaveBuffer"/>.
  470. /// </summary>
  471. /// <param name="waveBufferCount">The amount of wavebuffer to flush.</param>
  472. /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
  473. /// <param name="channelCount">The channel count from user input.</param>
  474. private void FlushWaveBuffers(uint waveBufferCount, Memory<VoiceUpdateState>[] voiceUpdateStates, uint channelCount)
  475. {
  476. uint waveBufferIndex = WaveBuffersIndex;
  477. for (int i = 0; i < waveBufferCount; i++)
  478. {
  479. WaveBuffers[(int)waveBufferIndex].IsSendToAudioProcessor = true;
  480. for (int j = 0; j < channelCount; j++)
  481. {
  482. ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[j].Span[0];
  483. voiceUpdateState.WaveBufferIndex = (voiceUpdateState.WaveBufferIndex + 1) % RendererConstants.VoiceWaveBufferCount;
  484. voiceUpdateState.WaveBufferConsumed++;
  485. voiceUpdateState.IsWaveBufferValid[(int)waveBufferIndex] = false;
  486. }
  487. waveBufferIndex = (waveBufferIndex + 1) % RendererConstants.VoiceWaveBufferCount;
  488. }
  489. }
  490. /// <summary>
  491. /// Update the internal parameters for command generation.
  492. /// </summary>
  493. /// <param name="voiceUpdateStates">The voice states associated to the <see cref="VoiceState"/>.</param>
  494. /// <returns>Return true if this voice should be played.</returns>
  495. public bool UpdateParametersForCommandGeneration(Memory<VoiceUpdateState>[] voiceUpdateStates)
  496. {
  497. if (FlushWaveBufferCount != 0)
  498. {
  499. FlushWaveBuffers(FlushWaveBufferCount, voiceUpdateStates, ChannelsCount);
  500. FlushWaveBufferCount = 0;
  501. }
  502. switch (PlayState)
  503. {
  504. case Types.PlayState.Started:
  505. for (int i = 0; i < WaveBuffers.Length; i++)
  506. {
  507. ref WaveBuffer wavebuffer = ref WaveBuffers[i];
  508. if (!wavebuffer.IsSendToAudioProcessor)
  509. {
  510. for (int y = 0; y < ChannelsCount; y++)
  511. {
  512. Debug.Assert(!voiceUpdateStates[y].Span[0].IsWaveBufferValid[i]);
  513. voiceUpdateStates[y].Span[0].IsWaveBufferValid[i] = true;
  514. }
  515. wavebuffer.IsSendToAudioProcessor = true;
  516. }
  517. }
  518. WasPlaying = false;
  519. ref VoiceUpdateState primaryVoiceUpdateState = ref voiceUpdateStates[0].Span[0];
  520. for (int i = 0; i < primaryVoiceUpdateState.IsWaveBufferValid.Length; i++)
  521. {
  522. if (primaryVoiceUpdateState.IsWaveBufferValid[i])
  523. {
  524. return true;
  525. }
  526. }
  527. return false;
  528. case Types.PlayState.Stopping:
  529. for (int i = 0; i < WaveBuffers.Length; i++)
  530. {
  531. ref WaveBuffer wavebuffer = ref WaveBuffers[i];
  532. wavebuffer.IsSendToAudioProcessor = true;
  533. for (int j = 0; j < ChannelsCount; j++)
  534. {
  535. ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[j].Span[0];
  536. if (voiceUpdateState.IsWaveBufferValid[i])
  537. {
  538. voiceUpdateState.WaveBufferIndex = (voiceUpdateState.WaveBufferIndex + 1) % RendererConstants.VoiceWaveBufferCount;
  539. voiceUpdateState.WaveBufferConsumed++;
  540. }
  541. voiceUpdateState.IsWaveBufferValid[i] = false;
  542. }
  543. }
  544. for (int i = 0; i < ChannelsCount; i++)
  545. {
  546. ref VoiceUpdateState voiceUpdateState = ref voiceUpdateStates[i].Span[0];
  547. voiceUpdateState.Offset = 0;
  548. voiceUpdateState.PlayedSampleCount = 0;
  549. voiceUpdateState.Pitch.ToSpan().Fill(0);
  550. voiceUpdateState.Fraction = 0;
  551. voiceUpdateState.LoopContext = new Dsp.State.AdpcmLoopContext();
  552. }
  553. PlayState = Types.PlayState.Stopped;
  554. WasPlaying = PreviousPlayState == Types.PlayState.Started;
  555. return WasPlaying;
  556. case Types.PlayState.Stopped:
  557. case Types.PlayState.Paused:
  558. foreach (ref WaveBuffer wavebuffer in WaveBuffers.ToSpan())
  559. {
  560. wavebuffer.BufferAddressInfo.GetReference(true);
  561. wavebuffer.ContextAddressInfo.GetReference(true);
  562. }
  563. if (SampleFormat == SampleFormat.Adpcm)
  564. {
  565. if (DataSourceStateAddressInfo.CpuAddress != 0)
  566. {
  567. DataSourceStateAddressInfo.GetReference(true);
  568. }
  569. }
  570. WasPlaying = PreviousPlayState == Types.PlayState.Started;
  571. return WasPlaying;
  572. default:
  573. throw new NotImplementedException($"{PlayState}");
  574. }
  575. }
  576. /// <summary>
  577. /// Update the internal state for command generation.
  578. /// </summary>
  579. /// <param name="context">The voice context.</param>
  580. /// <returns>Return true if this voice should be played.</returns>
  581. public bool UpdateForCommandGeneration(VoiceContext context)
  582. {
  583. if (IsNew)
  584. {
  585. ResetResources(context);
  586. PreviousVolume = Volume;
  587. IsNew = false;
  588. }
  589. Memory<VoiceUpdateState>[] voiceUpdateStates = new Memory<VoiceUpdateState>[RendererConstants.VoiceChannelCountMax];
  590. for (int i = 0; i < ChannelsCount; i++)
  591. {
  592. voiceUpdateStates[i] = context.GetUpdateStateForDsp(ChannelResourceIds[i]);
  593. }
  594. return UpdateParametersForCommandGeneration(voiceUpdateStates);
  595. }
  596. }
  597. }