DataSourceHelper.cs 17 KB

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