DelayLine.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //
  2. // Copyright (c) 2019-2020 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 System;
  18. namespace Ryujinx.Audio.Renderer.Dsp.Effect
  19. {
  20. public class DelayLine : IDelayLine
  21. {
  22. private float[] _workBuffer;
  23. private uint _sampleRate;
  24. private uint _currentSampleIndex;
  25. private uint _lastSampleIndex;
  26. public uint CurrentSampleCount { get; private set; }
  27. public uint SampleCountMax { get; private set; }
  28. public DelayLine(uint sampleRate, float delayTimeMax)
  29. {
  30. _sampleRate = sampleRate;
  31. SampleCountMax = IDelayLine.GetSampleCount(_sampleRate, delayTimeMax);
  32. _workBuffer = new float[SampleCountMax];
  33. SetDelay(delayTimeMax);
  34. }
  35. private void ConfigureDelay(uint targetSampleCount)
  36. {
  37. CurrentSampleCount = Math.Min(SampleCountMax, targetSampleCount);
  38. _currentSampleIndex = 0;
  39. _lastSampleIndex = CurrentSampleCount - 1;
  40. }
  41. public void SetDelay(float delayTime)
  42. {
  43. ConfigureDelay(IDelayLine.GetSampleCount(_sampleRate, delayTime));
  44. }
  45. public float Read()
  46. {
  47. return _workBuffer[_currentSampleIndex];
  48. }
  49. public float Update(float value)
  50. {
  51. float output = Read();
  52. _workBuffer[_currentSampleIndex++] = value;
  53. if (_currentSampleIndex >= _lastSampleIndex)
  54. {
  55. _currentSampleIndex = 0;
  56. }
  57. return output;
  58. }
  59. public float TapUnsafe(uint sampleIndex, int offset)
  60. {
  61. return IDelayLine.Tap(_workBuffer, (int)_currentSampleIndex, (int)sampleIndex + offset, (int)CurrentSampleCount);
  62. }
  63. public float Tap(uint sampleIndex)
  64. {
  65. if (sampleIndex >= CurrentSampleCount)
  66. {
  67. sampleIndex = CurrentSampleCount - 1;
  68. }
  69. return TapUnsafe(sampleIndex, -1);
  70. }
  71. }
  72. }