time_stretch.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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) : m_sample_rate{sample_rate} {
  11. m_sound_touch.setChannels(channel_count);
  12. m_sound_touch.setSampleRate(sample_rate);
  13. m_sound_touch.setPitch(1.0);
  14. m_sound_touch.setTempo(1.0);
  15. }
  16. void TimeStretcher::Clear() {
  17. m_sound_touch.clear();
  18. }
  19. void TimeStretcher::Flush() {
  20. m_sound_touch.flush();
  21. }
  22. std::size_t TimeStretcher::Process(const s16* in, std::size_t num_in, s16* out,
  23. std::size_t num_out) {
  24. const double time_delta = static_cast<double>(num_out) / m_sample_rate; // seconds
  25. // We were given actual_samples number of samples, and num_samples were requested from us.
  26. double current_ratio = static_cast<double>(num_in) / static_cast<double>(num_out);
  27. const double max_latency = 0.25; // seconds
  28. const double max_backlog = m_sample_rate * max_latency;
  29. const double backlog_fullness = m_sound_touch.numSamples() / max_backlog;
  30. if (backlog_fullness > 4.0) {
  31. // Too many samples in backlog: Don't push anymore on
  32. num_in = 0;
  33. }
  34. // We ideally want the backlog to be about 50% full.
  35. // This gives some headroom both ways to prevent underflow and overflow.
  36. // We tweak current_ratio to encourage this.
  37. constexpr double tweak_time_scale = 0.05; // seconds
  38. const double tweak_correction = (backlog_fullness - 0.5) * (time_delta / tweak_time_scale);
  39. current_ratio *= std::pow(1.0 + 2.0 * tweak_correction, tweak_correction < 0 ? 3.0 : 1.0);
  40. // This low-pass filter smoothes out variance in the calculated stretch ratio.
  41. // The time-scale determines how responsive this filter is.
  42. constexpr double lpf_time_scale = 0.712; // seconds
  43. const double lpf_gain = 1.0 - std::exp(-time_delta / lpf_time_scale);
  44. m_stretch_ratio += lpf_gain * (current_ratio - m_stretch_ratio);
  45. // Place a lower limit of 5% speed. When a game boots up, there will be
  46. // many silence samples. These do not need to be timestretched.
  47. m_stretch_ratio = std::max(m_stretch_ratio, 0.05);
  48. m_sound_touch.setTempo(m_stretch_ratio);
  49. LOG_TRACE(Audio, "{:5}/{:5} ratio:{:0.6f} backlog:{:0.6f}", num_in, num_out, m_stretch_ratio,
  50. backlog_fullness);
  51. m_sound_touch.putSamples(in, static_cast<u32>(num_in));
  52. return m_sound_touch.receiveSamples(out, static_cast<u32>(num_out));
  53. }
  54. } // namespace AudioCore