UpsamplerTests.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using NUnit.Framework;
  2. using Ryujinx.Audio.Renderer.Dsp;
  3. using Ryujinx.Audio.Renderer.Parameter;
  4. using Ryujinx.Audio.Renderer.Server.Upsampler;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Runtime.CompilerServices;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace Ryujinx.Tests.Audio.Renderer.Dsp
  13. {
  14. class UpsamplerTests
  15. {
  16. [Test]
  17. public void TestUpsamplerConsistency()
  18. {
  19. UpsamplerBufferState bufferState = new UpsamplerBufferState();
  20. int inputBlockSize = 160;
  21. int numInputSamples = 32000;
  22. int numOutputSamples = 48000;
  23. float inputSampleRate = numInputSamples;
  24. float outputSampleRate = numOutputSamples;
  25. float[] inputBuffer = new float[numInputSamples + 100];
  26. float[] outputBuffer = new float[numOutputSamples + 100];
  27. for (int sample = 0; sample < inputBuffer.Length; sample++)
  28. {
  29. // 440 hz sine wave with amplitude = 0.5f at input sample rate
  30. inputBuffer[sample] = MathF.Sin((440 / inputSampleRate) * (float)sample * MathF.PI * 2f) * 0.5f;
  31. }
  32. int inputIdx = 0;
  33. int outputIdx = 0;
  34. while (inputIdx + inputBlockSize < numInputSamples)
  35. {
  36. int outputBufLength = (int)Math.Round((float)(inputIdx + inputBlockSize) * outputSampleRate / inputSampleRate) - outputIdx;
  37. UpsamplerHelper.Upsample(
  38. outputBuffer.AsSpan(outputIdx),
  39. inputBuffer.AsSpan(inputIdx),
  40. outputBufLength,
  41. inputBlockSize,
  42. ref bufferState);
  43. inputIdx += inputBlockSize;
  44. outputIdx += outputBufLength;
  45. }
  46. float[] expectedOutput = new float[numOutputSamples];
  47. float sumDifference = 0;
  48. for (int sample = 0; sample < numOutputSamples; sample++)
  49. {
  50. // 440 hz sine wave with amplitude = 0.5f at output sample rate with an offset of 15
  51. expectedOutput[sample] = MathF.Sin((440 / outputSampleRate) * (float)(sample - 15) * MathF.PI * 2f) * 0.5f;
  52. sumDifference += Math.Abs(expectedOutput[sample] - outputBuffer[sample]);
  53. }
  54. sumDifference = sumDifference / (float)expectedOutput.Length;
  55. // Expect the output to be 98% similar to the expected resampled sine wave
  56. Assert.IsTrue(sumDifference < 0.02f);
  57. }
  58. }
  59. }