PcmHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. namespace Ryujinx.Audio.Renderer.Dsp
  4. {
  5. public static class PcmHelper
  6. {
  7. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  8. public static int GetCountToDecode(int startSampleOffset, int endSampleOffset, int offset, int count)
  9. {
  10. return Math.Min(count, endSampleOffset - startSampleOffset - offset);
  11. }
  12. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  13. public static ulong GetBufferOffset<T>(int startSampleOffset, int offset, int channelCount) where T : unmanaged
  14. {
  15. return (ulong)(Unsafe.SizeOf<T>() * channelCount * (startSampleOffset + offset));
  16. }
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public static int GetBufferSize<T>(int startSampleOffset, int endSampleOffset, int offset, int count) where T : unmanaged
  19. {
  20. return GetCountToDecode(startSampleOffset, endSampleOffset, offset, count) * Unsafe.SizeOf<T>();
  21. }
  22. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  23. public static int Decode(Span<short> output, ReadOnlySpan<short> input, int startSampleOffset, int endSampleOffset, int channelIndex, int channelCount)
  24. {
  25. if (input.IsEmpty || endSampleOffset < startSampleOffset)
  26. {
  27. return 0;
  28. }
  29. int decodedCount = input.Length / channelCount;
  30. for (int i = 0; i < decodedCount; i++)
  31. {
  32. output[i] = input[i * channelCount + channelIndex];
  33. }
  34. return decodedCount;
  35. }
  36. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  37. public static int Decode(Span<short> output, ReadOnlySpan<float> input, int startSampleOffset, int endSampleOffset, int channelIndex, int channelCount)
  38. {
  39. if (input.IsEmpty || endSampleOffset < startSampleOffset)
  40. {
  41. return 0;
  42. }
  43. int decodedCount = input.Length / channelCount;
  44. for (int i = 0; i < decodedCount; i++)
  45. {
  46. output[i] = (short)(input[i * channelCount + channelIndex] * short.MaxValue);
  47. }
  48. return decodedCount;
  49. }
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. public static short Saturate(float value)
  52. {
  53. if (value > short.MaxValue)
  54. {
  55. return short.MaxValue;
  56. }
  57. if (value < short.MinValue)
  58. {
  59. return short.MinValue;
  60. }
  61. return (short)value;
  62. }
  63. }
  64. }