time_stretch.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <cstddef>
  7. #include "audio_core/time_stretch.h"
  8. #include "common/logging/log.h"
  9. namespace AudioCore {
  10. TimeStretcher::TimeStretcher(u32 sample_rate, u32 channel_count)
  11. : m_sample_rate(sample_rate), m_channel_count(channel_count) {
  12. m_sound_touch.setChannels(channel_count);
  13. m_sound_touch.setSampleRate(sample_rate);
  14. m_sound_touch.setPitch(1.0);
  15. m_sound_touch.setTempo(1.0);
  16. }
  17. void TimeStretcher::Clear() {
  18. m_sound_touch.clear();
  19. }
  20. void TimeStretcher::Flush() {
  21. m_sound_touch.flush();
  22. }
  23. std::size_t TimeStretcher::Process(const s16* in, std::size_t num_in, s16* out,
  24. std::size_t num_out) {
  25. const double time_delta = static_cast<double>(num_out) / m_sample_rate; // seconds
  26. // We were given actual_samples number of samples, and num_samples were requested from us.
  27. double current_ratio = static_cast<double>(num_in) / static_cast<double>(num_out);
  28. const double max_latency = 1.0; // seconds
  29. const double max_backlog = m_sample_rate * max_latency;
  30. const double backlog_fullness = m_sound_touch.numSamples() / max_backlog;
  31. if (backlog_fullness > 5.0) {
  32. // Too many samples in backlog: Don't push anymore on
  33. num_in = 0;
  34. }
  35. // We ideally want the backlog to be about 50% full.
  36. // This gives some headroom both ways to prevent underflow and overflow.
  37. // We tweak current_ratio to encourage this.
  38. constexpr double tweak_time_scale = 0.05; // seconds
  39. const double tweak_correction = (backlog_fullness - 0.5) * (time_delta / tweak_time_scale);
  40. current_ratio *= std::pow(1.0 + 2.0 * tweak_correction, tweak_correction < 0 ? 3.0 : 1.0);
  41. // This low-pass filter smoothes out variance in the calculated stretch ratio.
  42. // The time-scale determines how responsive this filter is.
  43. constexpr double lpf_time_scale = 2.0; // seconds
  44. const double lpf_gain = 1.0 - std::exp(-time_delta / lpf_time_scale);
  45. m_stretch_ratio += lpf_gain * (current_ratio - m_stretch_ratio);
  46. // Place a lower limit of 5% speed. When a game boots up, there will be
  47. // many silence samples. These do not need to be timestretched.
  48. m_stretch_ratio = std::max(m_stretch_ratio, 0.05);
  49. m_sound_touch.setTempo(m_stretch_ratio);
  50. LOG_DEBUG(Audio, "{:5}/{:5} ratio:{:0.6f} backlog:{:0.6f}", num_in, num_out, m_stretch_ratio,
  51. backlog_fullness);
  52. m_sound_touch.putSamples(in, static_cast<u32>(num_in));
  53. return m_sound_touch.receiveSamples(out, static_cast<u32>(num_out));
  54. }
  55. } // namespace AudioCore