OSSIA
Open Scenario System for Interactive Application
Loading...
Searching...
No Matches
rubberband_stretcher.hpp
1#pragma once
2#include <ossia/detail/config.hpp>
3
4#if defined(OSSIA_ENABLE_RUBBERBAND)
5#include <ossia/dataflow/audio_port.hpp>
6#include <ossia/dataflow/audio_stretch_mode.hpp>
7#include <ossia/dataflow/graph_node.hpp>
8#include <ossia/dataflow/nodes/media.hpp>
9#include <ossia/dataflow/token_request.hpp>
10
11#if __has_include(<RubberBandStretcher.h>)
12#include <RubberBandStretcher.h>
13#elif __has_include(<rubberband/RubberBandStretcher.h>)
14#include <rubberband/RubberBandStretcher.h>
15#endif
16
17#include <algorithm>
18#include <cmath>
19#include <vector>
20
21namespace ossia
22{
23static constexpr auto get_rubberband_preset(ossia::audio_stretch_mode mode)
24{
25 using opt_t = RubberBand::RubberBandStretcher::Option;
26 using preset_t = RubberBand::RubberBandStretcher::PresetOption;
27 uint32_t preset = opt_t::OptionProcessRealTime | opt_t::OptionThreadingNever;
28 switch(mode)
29 {
30 case ossia::audio_stretch_mode::RubberBandStandard:
31 break;
32
33 case ossia::audio_stretch_mode::RubberBandPercussive:
34 preset |= preset_t::PercussiveOptions;
35 break;
36
37 case ossia::audio_stretch_mode::RubberBandStandardHQ:
38 preset |= RubberBand::RubberBandStretcher::OptionEngineFiner;
39 preset |= RubberBand::RubberBandStretcher::OptionPitchHighConsistency;
40 break;
41
42 case ossia::audio_stretch_mode::RubberBandPercussiveHQ:
43 preset |= preset_t::PercussiveOptions;
44 preset |= RubberBand::RubberBandStretcher::OptionEngineFiner;
45 preset |= RubberBand::RubberBandStretcher::OptionPitchHighConsistency;
46 break;
47
48 default:
49 break;
50 }
51
52 return preset;
53}
54
55struct rubberband_stretcher
56{
57 // Priming variants exposed for the sound sync test sweeps; production uses
58 // BareRecipe, the recipe the RubberBand documentation prescribes for
59 // real-time mode: pad the input with getPreferredStartPad() zeros and trim
60 // getStartDelay() samples from the output. ZeroPadOnly, the previous
61 // default, skips the trim and therefore plays every stretched sound
62 // getStartDelay() samples (~23 ms at 44.1 kHz) late - late relative to raw
63 // and repitched sounds, and late by a ratio-dependent amount, so two
64 // stretched files at different source tempos flam against each other too.
65 enum class prime_strategy : uint8_t
66 {
67 NoPrime,
68 ZeroPadOnly,
69 BareRecipe,
70 ExtendedDrain,
71 PreRollRealAudio,
72 };
73 static inline prime_strategy s_prime_strategy{prime_strategy::BareRecipe};
74
75 rubberband_stretcher(
76 uint32_t opt, std::size_t channels, std::size_t sampleRate, int64_t pos)
77 : m_rubberBand{std::make_unique<RubberBand::RubberBandStretcher>(
78 sampleRate, channels, opt)}
79 , next_sample_to_read{pos}
80 , options{opt}
81 {
82 // Pre-size the prime() zero-pad here so the audio thread never allocates.
83 // If a later setPitchScale() inflates the required size, prime() no-ops.
84 const std::size_t pad
85 = m_rubberBand ? m_rubberBand->getPreferredStartPad() : 0;
86 if(channels > 0 && pad > 0)
87 {
88 m_prime_zero_storage.assign(channels * pad, 0.f);
89 m_prime_zero_ptrs.resize(channels);
90 for(std::size_t c = 0; c < channels; ++c)
91 {
92 m_prime_zero_ptrs[c] = m_prime_zero_storage.data() + c * pad;
93 }
94 }
95 }
96
97 rubberband_stretcher(const rubberband_stretcher&) = delete;
98 rubberband_stretcher& operator=(const rubberband_stretcher&) = delete;
99 rubberband_stretcher(rubberband_stretcher&&) = default;
100 rubberband_stretcher& operator=(rubberband_stretcher&&) = default;
101
102 std::unique_ptr<RubberBand::RubberBandStretcher> m_rubberBand;
103 int64_t next_sample_to_read = 0;
104 uint32_t options{};
105 bool m_needs_prime{true};
106
107 // Zero-pad scratch buffer for prime(), sized in the ctor.
108 std::vector<float> m_prime_zero_storage;
109 std::vector<float*> m_prime_zero_ptrs;
110
111 [[nodiscard]] int64_t start_delay() const noexcept
112 {
113 return m_rubberBand ? int64_t(m_rubberBand->getStartDelay()) : 0;
114 }
115
116 void transport(int64_t date)
117 {
118 m_rubberBand->reset();
119 next_sample_to_read = date;
120 m_needs_prime = true;
121 }
122
123 template <typename T>
124 void
125 run(T& audio_fetcher, const ossia::token_request& t, ossia::exec_state_facade e,
126 double tempo_ratio, const std::size_t chan, const std::size_t len,
127 int64_t samples_to_read, const int64_t samples_to_write,
128 const int64_t samples_offset, const ossia::mutable_audio_span<double>& ap) noexcept
129 {
130 const double abs_tempo_ratio = std::min(70., std::abs(tempo_ratio));
131 if(abs_tempo_ratio != m_rubberBand->getTimeRatio())
132 {
133 m_rubberBand->setTimeRatio(abs_tempo_ratio);
134 }
135
136 // Lazy pre-roll on first run after ctor/transport(); see prime().
137 if(m_needs_prime) [[unlikely]]
138 {
139 prime(audio_fetcher, chan, t.forward());
140 m_needs_prime = false;
141 }
142
143 // TODO : if T::sample_type == float we could leverage it directly as
144 // input
145 const int max_chan = std::max(chan, m_rubberBand->getChannelCount());
146 const int frames = std::max((int64_t)16, samples_to_read);
147 float** const input = (float**)alloca(sizeof(float*) * max_chan);
148 float** const output = (float**)alloca(sizeof(float*) * max_chan);
149 for(std::size_t i = 0; i < chan; i++)
150 {
151 input[i] = (float*)alloca(sizeof(float) * frames);
152 output[i] = (float*)alloca(sizeof(float) * samples_to_write);
153 }
154 for(std::size_t i = chan; i < m_rubberBand->getChannelCount(); i++)
155 {
156 input[i] = (float*)alloca(sizeof(float) * frames);
157 std::fill_n(input[i], frames, 0.f);
158 output[i] = (float*)alloca(sizeof(float) * samples_to_write);
159 }
160
161 if(t.forward())
162 {
163 while(m_rubberBand->available() < samples_to_write)
164 {
165 audio_fetcher.fetch_audio(next_sample_to_read, samples_to_read, input);
166
167 m_rubberBand->process(input, samples_to_read, false);
168
169 next_sample_to_read += samples_to_read;
170 samples_to_read = 16;
171 }
172
173 m_rubberBand->retrieve(
174 output, std::min((int)samples_to_write, m_rubberBand->available()));
175
176 for(std::size_t i = 0; i < chan; i++)
177 {
178 for(int64_t j = 0; j < samples_to_write; j++)
179 {
180 ap[i][j + samples_offset] = double(output[i][j]);
181 }
182 }
183 }
184 else
185 {
186 // Backward playback:
187 while(m_rubberBand->available() < samples_to_write)
188 {
189 audio_fetcher.fetch_audio_backward(next_sample_to_read, samples_to_read, input);
190
191 m_rubberBand->process(input, samples_to_read, false);
192
193 next_sample_to_read -= samples_to_read;
194 samples_to_read = 16;
195 }
196
197 const int retrieved = m_rubberBand->retrieve(
198 output, std::min((int)samples_to_write, m_rubberBand->available()));
199
200 for(std::size_t i = 0; i < chan; i++)
201 {
202 for(int64_t j = 0; j < samples_to_write; j++)
203 {
204 ap[i][j + samples_offset] = double(output[i][j]);
205 }
206 }
207 }
208 }
209
210private:
211 // Run the s_prime_strategy variant before the first audible frame.
212 template <typename T>
213 void prime(T& audio_fetcher, std::size_t chan, bool forward) noexcept
214 {
215 if(!m_rubberBand || chan == 0)
216 return;
217
218 const auto strategy = s_prime_strategy;
219 if(strategy == prime_strategy::NoPrime)
220 return;
221
222 if(strategy == prime_strategy::PreRollRealAudio)
223 {
224 // pad ≈ windowSize/2 per RubberBand::getPreferredStartPad docs.
225 const int64_t window = 2 * int64_t(m_rubberBand->getPreferredStartPad());
226
227 // Fall through to ZeroPadOnly if there isn't enough past content.
228 if(window > 0 && (forward ? next_sample_to_read >= window : true))
229 {
230 constexpr int prime_fetch_chunk = 256;
231 float** const input
232 = (float**)alloca(sizeof(float*) * m_rubberBand->getChannelCount());
233 float** const output
234 = (float**)alloca(sizeof(float*) * m_rubberBand->getChannelCount());
235 for(std::size_t i = 0; i < m_rubberBand->getChannelCount(); i++)
236 {
237 input[i] = (float*)alloca(sizeof(float) * prime_fetch_chunk);
238 output[i] = (float*)alloca(sizeof(float) * prime_fetch_chunk);
239 }
240
241 if(forward)
242 next_sample_to_read -= window;
243 else
244 next_sample_to_read += window;
245
246 int64_t fed = 0;
247 while(fed < window)
248 {
249 const int64_t chunk
250 = std::min<int64_t>(prime_fetch_chunk, window - fed);
251 if(forward)
252 {
253 audio_fetcher.fetch_audio(next_sample_to_read, chunk, input);
254 next_sample_to_read += chunk;
255 }
256 else
257 {
258 audio_fetcher.fetch_audio_backward(next_sample_to_read, chunk, input);
259 next_sample_to_read -= chunk;
260 }
261 m_rubberBand->process(input, int(chunk), false);
262 fed += chunk;
263 }
264
265 // Drain pre-K outputs; feed zeros once real input is exhausted
266 // to avoid consuming the file beyond K.
267 const int64_t target_drain
268 = std::max<int64_t>(0, window - int64_t(m_rubberBand->getStartDelay()));
269 int64_t drained = 0;
270 int safety = 0;
271 while(drained < target_drain && safety++ < 4096)
272 {
273 while(m_rubberBand->available() <= 0)
274 {
275 std::fill_n(input[0], prime_fetch_chunk, 0.f);
276 for(std::size_t i = 1; i < m_rubberBand->getChannelCount(); i++)
277 std::fill_n(input[i], prime_fetch_chunk, 0.f);
278 m_rubberBand->process(input, prime_fetch_chunk, false);
279 }
280 const int avail = m_rubberBand->available();
281 const int to_take = int(std::min<int64_t>(
282 target_drain - drained,
283 std::min<int64_t>(avail, prime_fetch_chunk)));
284 m_rubberBand->retrieve(output, to_take);
285 drained += to_take;
286 }
287 return;
288 }
289 }
290
291 const int64_t toPad = int64_t(m_rubberBand->getPreferredStartPad());
292 if(toPad <= 0)
293 return;
294
295 // Bail without allocating if a later setPitchScale() outgrew the buffer.
296 if(int64_t(m_prime_zero_storage.size()) < int64_t(chan) * toPad
297 || int64_t(m_prime_zero_ptrs.size()) < int64_t(chan))
298 {
299 return;
300 }
301
302 m_rubberBand->process(
303 m_prime_zero_ptrs.data(), int(toPad), /*final=*/false);
304
305 if(strategy == prime_strategy::ZeroPadOnly
306 || strategy == prime_strategy::PreRollRealAudio)
307 return;
308
309 int64_t drain_target;
310 if(strategy == prime_strategy::ExtendedDrain)
311 {
312 drain_target = 2 * toPad;
313 }
314 else
315 {
316 drain_target = int64_t(m_rubberBand->getStartDelay());
317
318 // The R2 engine reports aWindowSize/2 scaled only by the pitch, never
319 // by the time ratio, but the sample where input 0 actually surfaces in
320 // the output moves with the ratio. Measured with the click-track
321 // harness (SoundSyncTest) over ratios 0.52..1.17, the position is
322 // startDelay + ~0.375 * pad * (1 - ratio) within R2's own transient
323 // jitter, so trim that much more (or less). R3 accounts for the ratio
324 // itself.
325 if(!(options & RubberBand::RubberBandStretcher::OptionEngineFiner))
326 {
327 drain_target += int64_t(std::llround(
328 0.375 * double(toPad) * (1.0 - m_rubberBand->getTimeRatio())));
329 }
330 if(drain_target < 0)
331 drain_target = 0;
332 }
333 if(drain_target <= 0)
334 return;
335
336 constexpr int prime_fetch_chunk = 256;
337 float** const input
338 = (float**)alloca(sizeof(float*) * m_rubberBand->getChannelCount());
339 float** const output
340 = (float**)alloca(sizeof(float*) * m_rubberBand->getChannelCount());
341 for(std::size_t i = 0; i < m_rubberBand->getChannelCount(); i++)
342 {
343 input[i] = (float*)alloca(sizeof(float) * prime_fetch_chunk);
344 output[i] = (float*)alloca(sizeof(float) * prime_fetch_chunk);
345 std::fill_n(input[i], prime_fetch_chunk, 0.f);
346 }
347
348 int64_t drained = 0;
349 int safety = 0;
350 while(drained < drain_target && safety++ < 4096)
351 {
352 while(m_rubberBand->available() <= 0)
353 {
354 if(forward)
355 {
356 audio_fetcher.fetch_audio(
357 next_sample_to_read, prime_fetch_chunk, input);
358 next_sample_to_read += prime_fetch_chunk;
359 }
360 else
361 {
362 audio_fetcher.fetch_audio_backward(
363 next_sample_to_read, prime_fetch_chunk, input);
364 next_sample_to_read -= prime_fetch_chunk;
365 }
366 m_rubberBand->process(input, prime_fetch_chunk, false);
367 }
368
369 const int available = m_rubberBand->available();
370 const int to_take = int(std::min<int64_t>(
371 drain_target - drained, std::min<int64_t>(available, prime_fetch_chunk)));
372 m_rubberBand->retrieve(output, to_take);
373 drained += to_take;
374 }
375 }
376};
377}
378#else
379#include <ossia/dataflow/nodes/timestretch/raw_stretcher.hpp>
380
381namespace ossia
382{
383static constexpr uint32_t get_rubberband_preset(ossia::audio_stretch_mode mode)
384{
385 return 0;
386}
387using rubberband_stretcher = raw_stretcher;
388}
389#endif
Definition git_info.h:7