Resampler.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (c) 2022, kleines Filmröllchen <filmroellchen@serenityos.org>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Concepts.h>
  8. #include <AK/Types.h>
  9. #include <AK/Vector.h>
  10. namespace Audio {
  11. // Small helper to resample from one playback rate to another
  12. // This isn't really "smart", in that we just insert (or drop) samples.
  13. // Should do better...
  14. template<typename SampleType>
  15. class ResampleHelper {
  16. public:
  17. ResampleHelper(u32 source, u32 target)
  18. : m_source(source)
  19. , m_target(target)
  20. {
  21. VERIFY(source > 0);
  22. VERIFY(target > 0);
  23. }
  24. // To be used as follows:
  25. // while the resampler doesn't need a new sample, read_sample(current) and store the resulting samples.
  26. // as long as the resampler needs a new sample, process_sample(current)
  27. // Stores a new sample
  28. void process_sample(SampleType sample_l, SampleType sample_r)
  29. {
  30. m_last_sample_l = sample_l;
  31. m_last_sample_r = sample_r;
  32. m_current_ratio += m_target;
  33. }
  34. // Assigns the given sample to its correct value and returns false if there is a new sample required
  35. bool read_sample(SampleType& next_l, SampleType& next_r)
  36. {
  37. if (m_current_ratio >= m_source) {
  38. m_current_ratio -= m_source;
  39. next_l = m_last_sample_l;
  40. next_r = m_last_sample_r;
  41. return true;
  42. }
  43. return false;
  44. }
  45. template<ArrayLike<SampleType> Samples>
  46. Vector<SampleType> resample(Samples&& to_resample)
  47. {
  48. Vector<SampleType> resampled;
  49. resampled.ensure_capacity(to_resample.size() * ceil_div(m_source, m_target));
  50. for (auto sample : to_resample) {
  51. process_sample(sample, sample);
  52. while (read_sample(sample, sample))
  53. resampled.unchecked_append(sample);
  54. }
  55. return resampled;
  56. }
  57. void reset()
  58. {
  59. m_current_ratio = 0;
  60. m_last_sample_l = {};
  61. m_last_sample_r = {};
  62. }
  63. u32 source() const { return m_source; }
  64. u32 target() const { return m_target; }
  65. private:
  66. const u32 m_source;
  67. const u32 m_target;
  68. u32 m_current_ratio { 0 };
  69. SampleType m_last_sample_l {};
  70. SampleType m_last_sample_r {};
  71. };
  72. class LegacyBuffer;
  73. ErrorOr<NonnullRefPtr<LegacyBuffer>> resample_buffer(ResampleHelper<double>& resampler, LegacyBuffer const& to_resample);
  74. }