DataSourceHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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.Renderer.Common;
  19. using Ryujinx.Audio.Renderer.Dsp.State;
  20. using Ryujinx.Common.Logging;
  21. using Ryujinx.Memory;
  22. using System;
  23. using System.Buffers;
  24. using System.Diagnostics;
  25. using System.Runtime.CompilerServices;
  26. using System.Runtime.InteropServices;
  27. using System.Runtime.Intrinsics;
  28. using System.Runtime.Intrinsics.Arm;
  29. using System.Runtime.Intrinsics.X86;
  30. using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter;
  31. namespace Ryujinx.Audio.Renderer.Dsp
  32. {
  33. public static class DataSourceHelper
  34. {
  35. private const int FixedPointPrecision = 15;
  36. public class WaveBufferInformation
  37. {
  38. public Memory<VoiceUpdateState> State;
  39. public uint SourceSampleRate;
  40. public SampleFormat SampleFormat;
  41. public float Pitch;
  42. public DecodingBehaviour DecodingBehaviour;
  43. public WaveBuffer[] WaveBuffers;
  44. public ulong ExtraParameter;
  45. public ulong ExtraParameterSize;
  46. public int ChannelIndex;
  47. public int ChannelCount;
  48. public SampleRateConversionQuality SrcQuality;
  49. }
  50. private static int GetPitchLimitBySrcQuality(SampleRateConversionQuality quality)
  51. {
  52. switch (quality)
  53. {
  54. case SampleRateConversionQuality.Default:
  55. case SampleRateConversionQuality.Low:
  56. return 4;
  57. case SampleRateConversionQuality.High:
  58. return 8;
  59. default:
  60. throw new ArgumentException($"{quality}");
  61. }
  62. }
  63. public static void ProcessWaveBuffers(IVirtualMemoryManager memoryManager, Span<float> outputBuffer, WaveBufferInformation info, uint targetSampleRate, int sampleCount)
  64. {
  65. const int tempBufferSize = 0x3F00;
  66. ref VoiceUpdateState state = ref info.State.Span[0];
  67. short[] tempBuffer = ArrayPool<short>.Shared.Rent(tempBufferSize);
  68. float sampleRateRatio = ((float)info.SourceSampleRate / targetSampleRate * info.Pitch);
  69. float fraction = state.Fraction;
  70. int waveBufferIndex = (int)state.WaveBufferIndex;
  71. ulong playedSampleCount = state.PlayedSampleCount;
  72. int offset = state.Offset;
  73. uint waveBufferConsumed = state.WaveBufferConsumed;
  74. int pitchMaxLength = GetPitchLimitBySrcQuality(info.SrcQuality);
  75. int totalNeededSize = (int)MathF.Truncate(fraction + sampleRateRatio * sampleCount);
  76. if (totalNeededSize + pitchMaxLength <= tempBufferSize && totalNeededSize >= 0)
  77. {
  78. int sourceSampleCountToProcess = sampleCount;
  79. int maxSampleCountPerIteration = Math.Min((int)MathF.Truncate((tempBufferSize - fraction) / sampleRateRatio), sampleCount);
  80. bool isStarving = false;
  81. int i = 0;
  82. while (i < sourceSampleCountToProcess)
  83. {
  84. int tempBufferIndex = 0;
  85. if (!info.DecodingBehaviour.HasFlag(DecodingBehaviour.SkipPitchAndSampleRateConversion))
  86. {
  87. state.Pitch.ToSpan().Slice(0, pitchMaxLength).CopyTo(tempBuffer.AsSpan());
  88. tempBufferIndex += pitchMaxLength;
  89. }
  90. int sampleCountToProcess = Math.Min(sourceSampleCountToProcess, maxSampleCountPerIteration);
  91. int y = 0;
  92. int sampleCountToDecode = (int)MathF.Truncate(fraction + sampleRateRatio * sampleCountToProcess);
  93. while (y < sampleCountToDecode)
  94. {
  95. if (waveBufferIndex >= Constants.VoiceWaveBufferCount)
  96. {
  97. Logger.Error?.Print(LogClass.AudioRenderer, $"Invalid WaveBuffer index {waveBufferIndex}");
  98. waveBufferIndex = 0;
  99. playedSampleCount = 0;
  100. }
  101. if (!state.IsWaveBufferValid[waveBufferIndex])
  102. {
  103. isStarving = true;
  104. break;
  105. }
  106. ref WaveBuffer waveBuffer = ref info.WaveBuffers[waveBufferIndex];
  107. if (offset == 0 && info.SampleFormat == SampleFormat.Adpcm && waveBuffer.Context != 0)
  108. {
  109. state.LoopContext = memoryManager.Read<AdpcmLoopContext>(waveBuffer.Context);
  110. }
  111. Span<short> tempSpan = tempBuffer.AsSpan().Slice(tempBufferIndex + y);
  112. int decodedSampleCount = -1;
  113. int targetSampleStartOffset;
  114. int targetSampleEndOffset;
  115. if (state.LoopCount > 0 && waveBuffer.LoopStartSampleOffset != 0 && waveBuffer.LoopEndSampleOffset != 0 && waveBuffer.LoopStartSampleOffset <= waveBuffer.LoopEndSampleOffset)
  116. {
  117. targetSampleStartOffset = (int)waveBuffer.LoopStartSampleOffset;
  118. targetSampleEndOffset = (int)waveBuffer.LoopEndSampleOffset;
  119. }
  120. else
  121. {
  122. targetSampleStartOffset = (int)waveBuffer.StartSampleOffset;
  123. targetSampleEndOffset = (int)waveBuffer.EndSampleOffset;
  124. }
  125. int targetWaveBufferSampleCount = targetSampleEndOffset - targetSampleStartOffset;
  126. switch (info.SampleFormat)
  127. {
  128. case SampleFormat.Adpcm:
  129. ReadOnlySpan<byte> waveBufferAdpcm = ReadOnlySpan<byte>.Empty;
  130. if (waveBuffer.Buffer != 0 && waveBuffer.BufferSize != 0)
  131. {
  132. // TODO: we are possibly copying a lot of unneeded data here, we should only take what we need.
  133. waveBufferAdpcm = memoryManager.GetSpan(waveBuffer.Buffer, (int)waveBuffer.BufferSize);
  134. }
  135. ReadOnlySpan<short> coefficients = MemoryMarshal.Cast<byte, short>(memoryManager.GetSpan(info.ExtraParameter, (int)info.ExtraParameterSize));
  136. decodedSampleCount = AdpcmHelper.Decode(tempSpan, waveBufferAdpcm, targetSampleStartOffset, targetSampleEndOffset, offset, sampleCountToDecode - y, coefficients, ref state.LoopContext);
  137. break;
  138. case SampleFormat.PcmInt16:
  139. ReadOnlySpan<short> waveBufferPcm16 = ReadOnlySpan<short>.Empty;
  140. if (waveBuffer.Buffer != 0 && waveBuffer.BufferSize != 0)
  141. {
  142. ulong bufferOffset = waveBuffer.Buffer + PcmHelper.GetBufferOffset<short>(targetSampleStartOffset, offset, info.ChannelCount);
  143. int bufferSize = PcmHelper.GetBufferSize<short>(targetSampleStartOffset, targetSampleEndOffset, offset, sampleCountToDecode - y) * info.ChannelCount;
  144. waveBufferPcm16 = MemoryMarshal.Cast<byte, short>(memoryManager.GetSpan(bufferOffset, bufferSize));
  145. }
  146. decodedSampleCount = PcmHelper.Decode(tempSpan, waveBufferPcm16, targetSampleStartOffset, targetSampleEndOffset, info.ChannelIndex, info.ChannelCount);
  147. break;
  148. case SampleFormat.PcmFloat:
  149. ReadOnlySpan<float> waveBufferPcmFloat = ReadOnlySpan<float>.Empty;
  150. if (waveBuffer.Buffer != 0 && waveBuffer.BufferSize != 0)
  151. {
  152. ulong bufferOffset = waveBuffer.Buffer + PcmHelper.GetBufferOffset<float>(targetSampleStartOffset, offset, info.ChannelCount);
  153. int bufferSize = PcmHelper.GetBufferSize<float>(targetSampleStartOffset, targetSampleEndOffset, offset, sampleCountToDecode - y) * info.ChannelCount;
  154. waveBufferPcmFloat = MemoryMarshal.Cast<byte, float>(memoryManager.GetSpan(bufferOffset, bufferSize));
  155. }
  156. decodedSampleCount = PcmHelper.Decode(tempSpan, waveBufferPcmFloat, targetSampleStartOffset, targetSampleEndOffset, info.ChannelIndex, info.ChannelCount);
  157. break;
  158. default:
  159. Logger.Warning?.Print(LogClass.AudioRenderer, $"Unsupported sample format {info.SampleFormat}");
  160. break;
  161. }
  162. Debug.Assert(decodedSampleCount <= sampleCountToDecode);
  163. if (decodedSampleCount < 0)
  164. {
  165. Logger.Warning?.Print(LogClass.AudioRenderer, $"Decoding failed, skipping WaveBuffer");
  166. state.MarkEndOfBufferWaveBufferProcessing(ref waveBuffer, ref waveBufferIndex, ref waveBufferConsumed, ref playedSampleCount);
  167. decodedSampleCount = 0;
  168. }
  169. y += decodedSampleCount;
  170. offset += decodedSampleCount;
  171. playedSampleCount += (uint)decodedSampleCount;
  172. if (offset >= targetWaveBufferSampleCount || decodedSampleCount == 0)
  173. {
  174. offset = 0;
  175. if (waveBuffer.Looping)
  176. {
  177. state.LoopCount++;
  178. if (waveBuffer.LoopCount >= 0)
  179. {
  180. if (decodedSampleCount == 0 || state.LoopCount > waveBuffer.LoopCount)
  181. {
  182. state.MarkEndOfBufferWaveBufferProcessing(ref waveBuffer, ref waveBufferIndex, ref waveBufferConsumed, ref playedSampleCount);
  183. }
  184. }
  185. if (decodedSampleCount == 0)
  186. {
  187. isStarving = true;
  188. break;
  189. }
  190. if (info.DecodingBehaviour.HasFlag(DecodingBehaviour.PlayedSampleCountResetWhenLooping))
  191. {
  192. playedSampleCount = 0;
  193. }
  194. }
  195. else
  196. {
  197. state.MarkEndOfBufferWaveBufferProcessing(ref waveBuffer, ref waveBufferIndex, ref waveBufferConsumed, ref playedSampleCount);
  198. }
  199. }
  200. }
  201. Span<float> outputSpan = outputBuffer.Slice(i);
  202. Span<int> outputSpanInt = MemoryMarshal.Cast<float, int>(outputSpan);
  203. if (info.DecodingBehaviour.HasFlag(DecodingBehaviour.SkipPitchAndSampleRateConversion))
  204. {
  205. for (int j = 0; j < y; j++)
  206. {
  207. outputBuffer[j] = tempBuffer[j];
  208. }
  209. }
  210. else
  211. {
  212. Span<short> tempSpan = tempBuffer.AsSpan().Slice(tempBufferIndex + y);
  213. tempSpan.Slice(0, sampleCountToDecode - y).Fill(0);
  214. ToFloat(outputBuffer, outputSpanInt, sampleCountToProcess);
  215. ResamplerHelper.Resample(outputBuffer, tempBuffer, sampleRateRatio, ref fraction, sampleCountToProcess, info.SrcQuality, y != sourceSampleCountToProcess || info.Pitch != 1.0f);
  216. tempBuffer.AsSpan().Slice(sampleCountToDecode, pitchMaxLength).CopyTo(state.Pitch.ToSpan());
  217. }
  218. i += sampleCountToProcess;
  219. }
  220. Debug.Assert(sourceSampleCountToProcess == i || !isStarving);
  221. state.WaveBufferConsumed = waveBufferConsumed;
  222. state.Offset = offset;
  223. state.PlayedSampleCount = playedSampleCount;
  224. state.WaveBufferIndex = (uint)waveBufferIndex;
  225. state.Fraction = fraction;
  226. }
  227. ArrayPool<short>.Shared.Return(tempBuffer);
  228. }
  229. private static void ToFloatAvx(Span<float> output, ReadOnlySpan<int> input, int sampleCount)
  230. {
  231. ReadOnlySpan<Vector256<int>> inputVec = MemoryMarshal.Cast<int, Vector256<int>>(input);
  232. Span<Vector256<float>> outputVec = MemoryMarshal.Cast<float, Vector256<float>>(output);
  233. int sisdStart = inputVec.Length * 8;
  234. for (int i = 0; i < inputVec.Length; i++)
  235. {
  236. outputVec[i] = Avx.ConvertToVector256Single(inputVec[i]);
  237. }
  238. for (int i = sisdStart; i < sampleCount; i++)
  239. {
  240. output[i] = input[i];
  241. }
  242. }
  243. private static void ToFloatSse2(Span<float> output, ReadOnlySpan<int> input, int sampleCount)
  244. {
  245. ReadOnlySpan<Vector128<int>> inputVec = MemoryMarshal.Cast<int, Vector128<int>>(input);
  246. Span<Vector128<float>> outputVec = MemoryMarshal.Cast<float, Vector128<float>>(output);
  247. int sisdStart = inputVec.Length * 4;
  248. for (int i = 0; i < inputVec.Length; i++)
  249. {
  250. outputVec[i] = Sse2.ConvertToVector128Single(inputVec[i]);
  251. }
  252. for (int i = sisdStart; i < sampleCount; i++)
  253. {
  254. output[i] = input[i];
  255. }
  256. }
  257. private static void ToFloatAdvSimd(Span<float> output, ReadOnlySpan<int> input, int sampleCount)
  258. {
  259. ReadOnlySpan<Vector128<int>> inputVec = MemoryMarshal.Cast<int, Vector128<int>>(input);
  260. Span<Vector128<float>> outputVec = MemoryMarshal.Cast<float, Vector128<float>>(output);
  261. int sisdStart = inputVec.Length * 4;
  262. for (int i = 0; i < inputVec.Length; i++)
  263. {
  264. outputVec[i] = AdvSimd.ConvertToSingle(inputVec[i]);
  265. }
  266. for (int i = sisdStart; i < sampleCount; i++)
  267. {
  268. output[i] = input[i];
  269. }
  270. }
  271. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  272. public static void ToFloatSlow(Span<float> output, ReadOnlySpan<int> input, int sampleCount)
  273. {
  274. for (int i = 0; i < sampleCount; i++)
  275. {
  276. output[i] = input[i];
  277. }
  278. }
  279. public static void ToFloat(Span<float> output, ReadOnlySpan<int> input, int sampleCount)
  280. {
  281. if (Avx.IsSupported)
  282. {
  283. ToFloatAvx(output, input, sampleCount);
  284. }
  285. else if (Sse2.IsSupported)
  286. {
  287. ToFloatSse2(output, input, sampleCount);
  288. }
  289. else if (AdvSimd.IsSupported)
  290. {
  291. ToFloatAdvSimd(output, input, sampleCount);
  292. }
  293. else
  294. {
  295. ToFloatSlow(output, input, sampleCount);
  296. }
  297. }
  298. public static void ToIntAvx(Span<int> output, ReadOnlySpan<float> input, int sampleCount)
  299. {
  300. ReadOnlySpan<Vector256<float>> inputVec = MemoryMarshal.Cast<float, Vector256<float>>(input);
  301. Span<Vector256<int>> outputVec = MemoryMarshal.Cast<int, Vector256<int>>(output);
  302. int sisdStart = inputVec.Length * 8;
  303. for (int i = 0; i < inputVec.Length; i++)
  304. {
  305. outputVec[i] = Avx.ConvertToVector256Int32(inputVec[i]);
  306. }
  307. for (int i = sisdStart; i < sampleCount; i++)
  308. {
  309. output[i] = (int)input[i];
  310. }
  311. }
  312. public static void ToIntSse2(Span<int> output, ReadOnlySpan<float> input, int sampleCount)
  313. {
  314. ReadOnlySpan<Vector128<float>> inputVec = MemoryMarshal.Cast<float, Vector128<float>>(input);
  315. Span<Vector128<int>> outputVec = MemoryMarshal.Cast<int, Vector128<int>>(output);
  316. int sisdStart = inputVec.Length * 4;
  317. for (int i = 0; i < inputVec.Length; i++)
  318. {
  319. outputVec[i] = Sse2.ConvertToVector128Int32(inputVec[i]);
  320. }
  321. for (int i = sisdStart; i < sampleCount; i++)
  322. {
  323. output[i] = (int)input[i];
  324. }
  325. }
  326. public static void ToIntAdvSimd(Span<int> output, ReadOnlySpan<float> input, int sampleCount)
  327. {
  328. ReadOnlySpan<Vector128<float>> inputVec = MemoryMarshal.Cast<float, Vector128<float>>(input);
  329. Span<Vector128<int>> outputVec = MemoryMarshal.Cast<int, Vector128<int>>(output);
  330. int sisdStart = inputVec.Length * 4;
  331. for (int i = 0; i < inputVec.Length; i++)
  332. {
  333. outputVec[i] = AdvSimd.ConvertToInt32RoundToZero(inputVec[i]);
  334. }
  335. for (int i = sisdStart; i < sampleCount; i++)
  336. {
  337. output[i] = (int)input[i];
  338. }
  339. }
  340. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  341. public static void ToIntSlow(Span<int> output, ReadOnlySpan<float> input, int sampleCount)
  342. {
  343. for (int i = 0; i < sampleCount; i++)
  344. {
  345. output[i] = (int)input[i];
  346. }
  347. }
  348. public static void ToInt(Span<int> output, ReadOnlySpan<float> input, int sampleCount)
  349. {
  350. if (Avx.IsSupported)
  351. {
  352. ToIntAvx(output, input, sampleCount);
  353. }
  354. else if (Sse2.IsSupported)
  355. {
  356. ToIntSse2(output, input, sampleCount);
  357. }
  358. else if (AdvSimd.IsSupported)
  359. {
  360. ToIntAdvSimd(output, input, sampleCount);
  361. }
  362. else
  363. {
  364. ToIntSlow(output, input, sampleCount);
  365. }
  366. }
  367. }
  368. }