-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathR3Stretcher.cpp
1443 lines (1196 loc) · 48.3 KB
/
R3Stretcher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Rubber Band Library
An audio time-stretching and pitch-shifting library.
Copyright 2007-2022 Particular Programs Ltd.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
Alternatively, if you have a valid commercial licence for the
Rubber Band Library obtained by agreement with the copyright
holders, you may redistribute and/or modify it under the terms
described in that licence.
If you wish to distribute code using the Rubber Band Library
under terms other than those of the GNU General Public License,
you must obtain a valid commercial licence before doing so.
*/
#include "R3Stretcher.h"
#include "../common/VectorOpsComplex.h"
#include "../common/Profiler.h"
#include <array>
namespace RubberBand {
R3Stretcher::R3Stretcher(Parameters parameters,
double initialTimeRatio,
double initialPitchScale,
Log log) :
m_log(log),
m_parameters(validateSampleRate(parameters)),
m_limits(parameters.options, m_parameters.sampleRate),
m_timeRatio(initialTimeRatio),
m_pitchScale(initialPitchScale),
m_formantScale(0.0),
m_guide(Guide::Parameters
(m_parameters.sampleRate,
m_parameters.options & RubberBandStretcher::OptionWindowShort),
m_log),
m_guideConfiguration(m_guide.getConfiguration()),
m_channelAssembly(m_parameters.channels),
m_useReadahead(true),
m_inhop(1),
m_prevInhop(1),
m_prevOuthop(1),
m_unityCount(0),
m_startSkip(0),
m_studyInputDuration(0),
m_suppliedInputDuration(0),
m_totalTargetDuration(0),
m_consumedInputDuration(0),
m_lastKeyFrameSurpassed(0),
m_totalOutputDuration(0),
m_mode(ProcessMode::JustCreated)
{
Profiler profiler("R3Stretcher::R3Stretcher");
m_log.log(1, "R3Stretcher::R3Stretcher: rate, options",
m_parameters.sampleRate, m_parameters.options);
m_log.log(1, "R3Stretcher::R3Stretcher: initial time ratio and pitch scale",
m_timeRatio, m_pitchScale);
if (isRealTime()) {
m_log.log(1, "R3Stretcher::R3Stretcher: real-time mode");
} else {
m_log.log(1, "R3Stretcher::R3Stretcher: offline mode");
}
if (isSingleWindowed()) {
m_log.log(1, "R3Stretcher::R3Stretcher: intermediate shorter-window mode requested");
}
double maxClassifierFrequency = 16000.0;
if (maxClassifierFrequency > m_parameters.sampleRate/2) {
maxClassifierFrequency = m_parameters.sampleRate/2;
}
int classificationBins =
int(floor(m_guideConfiguration.classificationFftSize *
maxClassifierFrequency / m_parameters.sampleRate));
BinSegmenter::Parameters segmenterParameters
(m_guideConfiguration.classificationFftSize,
classificationBins, m_parameters.sampleRate, 18);
BinClassifier::Parameters classifierParameters
(classificationBins, 9, 1, 10, 2.0, 2.0);
if (isSingleWindowed()) {
classifierParameters.horizontalFilterLength = 7;
}
int inRingBufferSize = getWindowSourceSize() * 2;
int outRingBufferSize = getWindowSourceSize() * 16;
for (int c = 0; c < m_parameters.channels; ++c) {
m_channelData.push_back(std::make_shared<ChannelData>
(segmenterParameters,
classifierParameters,
m_guideConfiguration.longestFftSize,
getWindowSourceSize(),
inRingBufferSize,
outRingBufferSize));
for (int b = 0; b < m_guideConfiguration.fftBandLimitCount; ++b) {
const auto &band = m_guideConfiguration.fftBandLimits[b];
int fftSize = band.fftSize;
m_channelData[c]->scales[fftSize] =
std::make_shared<ChannelScaleData>
(fftSize, m_guideConfiguration.longestFftSize);
}
}
for (int b = 0; b < m_guideConfiguration.fftBandLimitCount; ++b) {
const auto &band = m_guideConfiguration.fftBandLimits[b];
int fftSize = band.fftSize;
GuidedPhaseAdvance::Parameters guidedParameters
(fftSize, m_parameters.sampleRate, m_parameters.channels,
isSingleWindowed());
m_scaleData[fftSize] = std::make_shared<ScaleData>
(guidedParameters, m_log);
}
m_calculator = std::unique_ptr<StretchCalculator>
(new StretchCalculator(int(round(m_parameters.sampleRate)), //!!! which is a double...
1, false, // no fixed inputIncrement
m_log));
if (isRealTime()) {
createResampler();
// In offline mode we don't create the resampler yet - we
// don't want to have one at all if the pitch ratio is 1.0,
// but that could change before the first process call, so we
// create the resampler if needed then
}
calculateHop();
m_prevInhop = m_inhop;
m_prevOuthop = int(round(m_inhop * getEffectiveRatio()));
if (!m_inhop.is_lock_free()) {
m_log.log(0, "R3Stretcher: WARNING: std::atomic<int> is not lock-free");
}
if (!m_timeRatio.is_lock_free()) {
m_log.log(0, "R3Stretcher: WARNING: std::atomic<double> is not lock-free");
}
}
WindowType
R3Stretcher::ScaleData::analysisWindowShape()
{
if (singleWindowMode) {
return HannWindow;
} else {
if (fftSize < 1024 || fftSize > 2048) return HannWindow;
else return NiemitaloForwardWindow;
}
}
int
R3Stretcher::ScaleData::analysisWindowLength()
{
return fftSize;
}
WindowType
R3Stretcher::ScaleData::synthesisWindowShape()
{
if (singleWindowMode) {
return HannWindow;
} else {
if (fftSize < 1024 || fftSize > 2048) return HannWindow;
else return NiemitaloReverseWindow;
}
}
int
R3Stretcher::ScaleData::synthesisWindowLength()
{
if (singleWindowMode) {
return fftSize;
} else {
if (fftSize > 2048) return fftSize/2;
else return fftSize;
}
}
void
R3Stretcher::setTimeRatio(double ratio)
{
if (!isRealTime()) {
if (m_mode == ProcessMode::Studying ||
m_mode == ProcessMode::Processing) {
m_log.log(0, "R3Stretcher::setTimeRatio: Cannot set time ratio while studying or processing in non-RT mode");
return;
}
}
if (ratio == m_timeRatio) return;
m_timeRatio = ratio;
calculateHop();
}
void
R3Stretcher::setPitchScale(double scale)
{
if (!isRealTime()) {
if (m_mode == ProcessMode::Studying ||
m_mode == ProcessMode::Processing) {
m_log.log(0, "R3Stretcher::setTimeRatio: Cannot set pitch scale while studying or processing in non-RT mode");
return;
}
}
if (scale == m_pitchScale) return;
m_pitchScale = scale;
calculateHop();
}
void
R3Stretcher::setFormantScale(double scale)
{
if (!isRealTime()) {
if (m_mode == ProcessMode::Studying ||
m_mode == ProcessMode::Processing) {
m_log.log(0, "R3Stretcher::setTimeRatio: Cannot set formant scale while studying or processing in non-RT mode");
return;
}
}
m_formantScale = scale;
}
void
R3Stretcher::setFormantOption(RubberBandStretcher::Options options)
{
int mask = (RubberBandStretcher::OptionFormantShifted |
RubberBandStretcher::OptionFormantPreserved);
m_parameters.options &= ~mask;
options &= mask;
m_parameters.options |= options;
}
void
R3Stretcher::setPitchOption(RubberBandStretcher::Options)
{
m_log.log(0, "R3Stretcher::setPitchOption: Option change after construction is not supported in R3 engine");
}
void
R3Stretcher::setKeyFrameMap(const std::map<size_t, size_t> &mapping)
{
if (isRealTime()) {
m_log.log(0, "R3Stretcher::setKeyFrameMap: Cannot specify key frame map in RT mode");
return;
}
if (m_mode == ProcessMode::Processing || m_mode == ProcessMode::Finished) {
m_log.log(0, "R3Stretcher::setKeyFrameMap: Cannot specify key frame map after process() has begun");
return;
}
m_keyFrameMap = mapping;
}
void
R3Stretcher::createResampler()
{
Profiler profiler("R3Stretcher::createResampler");
Resampler::Parameters resamplerParameters;
resamplerParameters.quality = Resampler::FastestTolerable;
resamplerParameters.initialSampleRate = m_parameters.sampleRate;
resamplerParameters.maxBufferSize = m_guideConfiguration.longestFftSize;
if (isRealTime()) {
// If we knew the caller would never change ratio, we could
// supply RatioMostlyFixed - but it can have such overhead
// when the ratio *does* change (and it's not RT-safe overhead
// either) that a single call would kill RT use
resamplerParameters.dynamism = Resampler::RatioOftenChanging;
resamplerParameters.ratioChange = Resampler::SmoothRatioChange;
} else {
resamplerParameters.dynamism = Resampler::RatioMostlyFixed;
resamplerParameters.ratioChange = Resampler::SuddenRatioChange;
}
m_resampler = std::unique_ptr<Resampler>
(new Resampler(resamplerParameters, m_parameters.channels));
bool before, after;
areWeResampling(&before, &after);
if (before) {
if (after) {
m_log.log(0, "R3Stretcher: WARNING: we think we are resampling both before and after!");
} else {
m_log.log(1, "createResampler: resampling before");
}
} else {
if (after) {
m_log.log(1, "createResampler: resampling after");
}
}
}
void
R3Stretcher::calculateHop()
{
double ratio = getEffectiveRatio();
// In R2 we generally targeted a certain inhop, and calculated
// outhop from that. Here we are the other way around. We aim for
// outhop = 256 at ratios around 1, reducing down to 128 for
// ratios far below 1 and up to 512 for ratios far above. As soon
// as outhop exceeds 256 we have to drop the 1024-bin FFT, as the
// overlap will be inadequate for it (that's among the jobs of the
// Guide class) so we don't want to go above 256 until at least
// factor 1.5. Also we can't go above 512 without changing the
// window shape or dropping the 2048-bin FFT, and we can't do
// either of those dynamically.
double proposedOuthop = 256.0;
if (ratio > 1.5) {
proposedOuthop = pow(2.0, 8.0 + 2.0 * log10(ratio - 0.5));
} else if (ratio < 1.0) {
proposedOuthop = pow(2.0, 8.0 + 2.0 * log10(ratio));
}
if (isSingleWindowed()) {
// the single (shorter) window mode actually uses a longer
// synthesis window for the 2048-bin FFT and drops the
// 1024-bin one, so it can survive longer hops, which is good
// because reduced CPU consumption is the whole motivation
proposedOuthop *= 2.0;
}
if (proposedOuthop > m_limits.maxPreferredOuthop) {
proposedOuthop = m_limits.maxPreferredOuthop;
}
if (proposedOuthop < m_limits.minPreferredOuthop) {
proposedOuthop = m_limits.minPreferredOuthop;
}
m_log.log(1, "calculateHop: ratio and proposed outhop", ratio, proposedOuthop);
double inhop = proposedOuthop / ratio;
if (inhop < m_limits.minInhop) {
m_log.log(0, "R3Stretcher: WARNING: Ratio yields ideal inhop < minimum, results may be suspect", inhop, m_limits.minInhop);
inhop = m_limits.minInhop;
}
if (inhop > m_limits.maxInhop) {
// Log level 1, this is not as big a deal as < minInhop above
m_log.log(1, "R3Stretcher: WARNING: Ratio yields ideal inhop > maximum, results may be suspect", inhop, m_limits.maxInhop);
inhop = m_limits.maxInhop;
}
m_inhop = int(floor(inhop));
m_log.log(1, "calculateHop: inhop and mean outhop", m_inhop, m_inhop * ratio);
if (m_inhop < m_limits.maxInhopWithReadahead) {
m_log.log(1, "calculateHop: using readahead");
m_useReadahead = true;
} else {
m_log.log(1, "calculateHop: not using readahead, inhop too long for buffer in current configuration");
m_useReadahead = false;
}
}
void
R3Stretcher::updateRatioFromMap()
{
if (m_keyFrameMap.empty()) return;
if (m_consumedInputDuration == 0) {
m_timeRatio = double(m_keyFrameMap.begin()->second) /
double(m_keyFrameMap.begin()->first);
m_log.log(1, "initial key-frame map entry ",
double(m_keyFrameMap.begin()->first),
double(m_keyFrameMap.begin()->second));
m_log.log(1, "giving initial ratio ", m_timeRatio);
calculateHop();
m_lastKeyFrameSurpassed = 0;
return;
}
auto i0 = m_keyFrameMap.upper_bound(m_lastKeyFrameSurpassed);
if (i0 == m_keyFrameMap.end()) {
return;
}
if (m_consumedInputDuration >= i0->first) {
m_log.log(1, "input duration surpasses pending key frame",
double(m_consumedInputDuration), double(i0->first));
auto i1 = m_keyFrameMap.upper_bound(m_consumedInputDuration);
size_t keyFrameAtInput, keyFrameAtOutput;
if (i1 != m_keyFrameMap.end()) {
keyFrameAtInput = i1->first;
keyFrameAtOutput = i1->second;
} else {
keyFrameAtInput = m_studyInputDuration;
keyFrameAtOutput = m_totalTargetDuration;
}
m_log.log(1, "current input and output",
double(m_consumedInputDuration), double(m_totalOutputDuration));
m_log.log(1, "next key frame input and output",
double(keyFrameAtInput), double(keyFrameAtOutput));
double ratio;
if (keyFrameAtInput > i0->first) {
size_t toKeyFrameAtInput, toKeyFrameAtOutput;
toKeyFrameAtInput = keyFrameAtInput - i0->first;
if (keyFrameAtOutput > i0->second) {
toKeyFrameAtOutput = keyFrameAtOutput - i0->second;
} else {
m_log.log(1, "previous target key frame overruns next key frame (or total output duration)", i0->second, keyFrameAtOutput);
toKeyFrameAtOutput = 1;
}
m_log.log(1, "diff to next key frame input and output",
double(toKeyFrameAtInput), double(toKeyFrameAtOutput));
ratio = double(toKeyFrameAtOutput) / double(toKeyFrameAtInput);
} else {
m_log.log(1, "source key frame overruns following key frame or total input duration", i0->first, keyFrameAtInput);
ratio = 1.0;
}
m_log.log(1, "new ratio", ratio);
m_timeRatio = ratio;
calculateHop();
m_lastKeyFrameSurpassed = i0->first;
}
}
double
R3Stretcher::getTimeRatio() const
{
return m_timeRatio;
}
double
R3Stretcher::getPitchScale() const
{
return m_pitchScale;
}
double
R3Stretcher::getFormantScale() const
{
return m_formantScale;
}
size_t
R3Stretcher::getPreferredStartPad() const
{
if (!isRealTime()) {
return 0;
} else {
return getWindowSourceSize() / 2;
}
}
size_t
R3Stretcher::getStartDelay() const
{
if (!isRealTime()) {
return 0;
} else {
double factor = 0.5 / m_pitchScale;
return size_t(ceil(getWindowSourceSize() * factor));
}
}
size_t
R3Stretcher::getChannelCount() const
{
return m_parameters.channels;
}
void
R3Stretcher::reset()
{
m_calculator->reset();
if (m_resampler) {
m_resampler->reset();
}
for (auto &it : m_scaleData) {
it.second->guided.reset();
}
for (auto &cd : m_channelData) {
cd->reset();
}
m_prevInhop = m_inhop;
m_prevOuthop = int(round(m_inhop * getEffectiveRatio()));
m_studyInputDuration = 0;
m_suppliedInputDuration = 0;
m_totalTargetDuration = 0;
m_consumedInputDuration = 0;
m_lastKeyFrameSurpassed = 0;
m_totalOutputDuration = 0;
m_keyFrameMap.clear();
m_mode = ProcessMode::JustCreated;
}
void
R3Stretcher::study(const float *const *, size_t samples, bool)
{
Profiler profiler("R3Stretcher::study");
if (isRealTime()) {
m_log.log(0, "R3Stretcher::study: Not meaningful in realtime mode");
return;
}
if (m_mode == ProcessMode::Processing || m_mode == ProcessMode::Finished) {
m_log.log(0, "R3Stretcher::study: Cannot study after processing");
return;
}
if (m_mode == ProcessMode::JustCreated) {
m_studyInputDuration = 0;
}
m_mode = ProcessMode::Studying;
m_studyInputDuration += samples;
}
void
R3Stretcher::setExpectedInputDuration(size_t samples)
{
m_suppliedInputDuration = samples;
}
size_t
R3Stretcher::getSamplesRequired() const
{
if (available() != 0) return 0;
int rs = m_channelData[0]->inbuf->getReadSpace();
if (rs < getWindowSourceSize()) {
return getWindowSourceSize() - rs;
} else {
return 0;
}
}
void
R3Stretcher::setMaxProcessSize(size_t n)
{
size_t oldSize = m_channelData[0]->inbuf->getSize();
size_t newSize = getWindowSourceSize() + n;
if (newSize > oldSize) {
m_log.log(1, "setMaxProcessSize: resizing from and to", oldSize, newSize);
for (int c = 0; c < m_parameters.channels; ++c) {
m_channelData[c]->inbuf = std::unique_ptr<RingBuffer<float>>
(m_channelData[c]->inbuf->resized(newSize));
}
} else {
m_log.log(1, "setMaxProcessSize: nothing to be done, newSize <= oldSize", newSize, oldSize);
}
}
void
R3Stretcher::process(const float *const *input, size_t samples, bool final)
{
Profiler profiler("R3Stretcher::process");
if (m_mode == ProcessMode::Finished) {
m_log.log(0, "R3Stretcher::process: Cannot process again after final chunk");
return;
}
if (!isRealTime()) {
if (m_mode == ProcessMode::Studying) {
m_totalTargetDuration =
size_t(round(m_studyInputDuration * m_timeRatio));
m_log.log(1, "study duration and target duration",
m_studyInputDuration, m_totalTargetDuration);
} else if (m_mode == ProcessMode::JustCreated) {
if (m_suppliedInputDuration != 0) {
m_totalTargetDuration =
size_t(round(m_suppliedInputDuration * m_timeRatio));
m_log.log(1, "supplied duration and target duration",
m_suppliedInputDuration, m_totalTargetDuration);
}
}
// Update this on every process round, checking whether we've
// surpassed the next key frame yet. This must follow the
// overall target calculation above, which uses the "global"
// time ratio, but precede any other use of the time ratio.
if (!m_keyFrameMap.empty()) {
updateRatioFromMap();
}
if (m_mode == ProcessMode::JustCreated ||
m_mode == ProcessMode::Studying) {
if (m_pitchScale != 1.0 && !m_resampler) {
createResampler();
}
// Pad to half the frame. As with R2, in real-time mode we
// don't do this -- it's better to start with a swoosh
// than introduce more latency, and we don't want gaps
// when the ratio changes.
int pad = getWindowSourceSize() / 2;
m_log.log(1, "offline mode: prefilling with", pad);
for (int c = 0; c < m_parameters.channels; ++c) {
m_channelData[c]->inbuf->zero(pad);
}
// NB by the time we skip this later we may have resampled
// as well as stretched
m_startSkip = int(round(pad / m_pitchScale));
m_log.log(1, "start skip is", m_startSkip);
}
}
if (final) {
// We don't distinguish between Finished and "draining, but
// haven't yet delivered all the samples" because the
// distinction is meaningless internally - it only affects
// whether available() finds any samples in the buffer
m_mode = ProcessMode::Finished;
} else {
m_mode = ProcessMode::Processing;
}
bool resamplingBefore = false;
areWeResampling(&resamplingBefore, nullptr);
int channels = m_parameters.channels;
int inputIx = 0;
while (inputIx < int(samples)) {
int remaining = int(samples) - inputIx;
int ws = m_channelData[0]->inbuf->getWriteSpace();
if (ws == 0) {
consume();
ws = m_channelData[0]->inbuf->getWriteSpace();
}
if (ws == 0) {
m_log.log(0, "R3Stretcher::process: WARNING: Forced to increase input buffer size. Either setMaxProcessSize was not properly called, process is being called repeatedly without retrieve, or an internal error has led to an incorrect resampler output calculation. Samples to write", remaining);
size_t newSize = m_channelData[0]->inbuf->getSize() + remaining;
for (int c = 0; c < m_parameters.channels; ++c) {
auto newBuf = m_channelData[c]->inbuf->resized(newSize);
m_channelData[c]->inbuf =
std::unique_ptr<RingBuffer<float>>(newBuf);
}
continue;
}
if (resamplingBefore) {
for (int c = 0; c < channels; ++c) {
auto &cd = m_channelData.at(c);
m_channelAssembly.resampled[c] = cd->resampled.data();
}
int resampleBufSize = int(m_channelData.at(0)->resampled.size());
int maxResampleOutput = std::min(ws, resampleBufSize);
int maxResampleInput = int(floor(maxResampleOutput * m_pitchScale));
int resampleInput = std::min(remaining, maxResampleInput);
if (resampleInput == 0) resampleInput = 1;
int resampleOutput = m_resampler->resample
(m_channelAssembly.resampled.data(),
maxResampleOutput,
input,
resampleInput,
1.0 / m_pitchScale,
final);
inputIx += resampleInput;
for (int c = 0; c < m_parameters.channels; ++c) {
m_channelData[c]->inbuf->write
(m_channelData.at(c)->resampled.data(),
resampleOutput);
}
} else {
int toWrite = std::min(ws, remaining);
for (int c = 0; c < m_parameters.channels; ++c) {
m_channelData[c]->inbuf->write (input[c] + inputIx, toWrite);
}
inputIx += toWrite;
}
consume();
}
}
int
R3Stretcher::available() const
{
int av = int(m_channelData[0]->outbuf->getReadSpace());
if (av == 0 && m_mode == ProcessMode::Finished) {
return -1;
} else {
return av;
}
}
size_t
R3Stretcher::retrieve(float *const *output, size_t samples) const
{
Profiler profiler("R3Stretcher::retrieve");
int got = samples;
for (int c = 0; c < m_parameters.channels; ++c) {
int gotHere = m_channelData[c]->outbuf->read(output[c], got);
if (gotHere < got) {
if (c > 0) {
m_log.log(0, "R3Stretcher::retrieve: WARNING: channel imbalance detected");
}
got = std::min(got, std::max(gotHere, 0));
}
}
return got;
}
void
R3Stretcher::consume()
{
Profiler profiler("R3Stretcher::consume");
int longest = m_guideConfiguration.longestFftSize;
int channels = m_parameters.channels;
int inhop = m_inhop;
bool resamplingAfter = false;
areWeResampling(nullptr, &resamplingAfter);
double effectivePitchRatio = 1.0 / m_pitchScale;
if (m_resampler) {
effectivePitchRatio =
m_resampler->getEffectiveRatio(effectivePitchRatio);
}
int outhop = m_calculator->calculateSingle(m_timeRatio,
effectivePitchRatio,
1.f,
inhop,
longest,
longest,
true);
if (outhop < 1) {
m_log.log(0, "R3Stretcher::consume: WARNING: outhop calculated as", outhop);
outhop = 1;
}
// Now inhop is the distance by which the input stream will be
// advanced after our current frame has been read, and outhop is
// the distance by which the output will be advanced after it has
// been emitted; m_prevInhop and m_prevOuthop are the
// corresponding values the last time a frame was processed (*not*
// just the last time this function was called, since we can
// return without doing anything if the output buffer is full).
//
// Our phase adjustments need to be based on the distances we have
// advanced the input and output since the previous frame, not the
// distances we are about to advance them, so they use the m_prev
// values.
if (inhop != m_prevInhop) {
m_log.log(2, "change in inhop", double(m_prevInhop), double(inhop));
}
if (outhop != m_prevOuthop) {
m_log.log(2, "change in outhop", double(m_prevOuthop), double(outhop));
}
auto &cd0 = m_channelData.at(0);
while (cd0->outbuf->getWriteSpace() >= outhop) {
Profiler profiler("R3Stretcher::consume/loop");
// NB our ChannelData, ScaleData, and ChannelScaleData maps
// contain shared_ptrs; whenever we retain one of them in a
// variable, we do so by reference to avoid copying the
// shared_ptr (as that is not realtime safe). Same goes for
// the map iterators
int readSpace = cd0->inbuf->getReadSpace();
if (readSpace < getWindowSourceSize()) {
if (m_mode == ProcessMode::Finished) {
if (readSpace == 0) {
int fill = cd0->scales.at(longest)->accumulatorFill;
if (fill == 0) {
break;
} else {
m_log.log(1, "finished reading input, but samples remaining in output accumulator", fill);
}
}
} else {
// await more input
break;
}
}
// Analysis
for (int c = 0; c < channels; ++c) {
analyseChannel(c, inhop, m_prevInhop, m_prevOuthop);
}
// Phase update. This is synchronised across all channels
for (auto &it : m_channelData[0]->scales) {
int fftSize = it.first;
for (int c = 0; c < channels; ++c) {
auto &cd = m_channelData.at(c);
auto &scale = cd->scales.at(fftSize);
m_channelAssembly.mag[c] = scale->mag.data();
m_channelAssembly.phase[c] = scale->phase.data();
m_channelAssembly.prevMag[c] = scale->prevMag.data();
m_channelAssembly.guidance[c] = &cd->guidance;
m_channelAssembly.outPhase[c] = scale->advancedPhase.data();
}
m_scaleData.at(fftSize)->guided.advance
(m_channelAssembly.outPhase.data(),
m_channelAssembly.mag.data(),
m_channelAssembly.phase.data(),
m_channelAssembly.prevMag.data(),
m_guideConfiguration,
m_channelAssembly.guidance.data(),
m_prevInhop,
m_prevOuthop);
}
for (int c = 0; c < channels; ++c) {
adjustPreKick(c);
}
// Resynthesis
for (int c = 0; c < channels; ++c) {
synthesiseChannel(c, outhop, readSpace == 0);
}
// Resample
int resampledCount = 0;
if (resamplingAfter) {
for (int c = 0; c < channels; ++c) {
auto &cd = m_channelData.at(c);
m_channelAssembly.mixdown[c] = cd->mixdown.data();
m_channelAssembly.resampled[c] = cd->resampled.data();
}
resampledCount = m_resampler->resample
(m_channelAssembly.resampled.data(),
m_channelData[0]->resampled.size(),
m_channelAssembly.mixdown.data(),
outhop,
1.0 / m_pitchScale,
m_mode == ProcessMode::Finished && readSpace < inhop);
}
// Emit
int writeCount = outhop;
if (resamplingAfter) {
writeCount = resampledCount;
}
if (!isRealTime()) {
if (m_totalTargetDuration > 0 &&
m_totalOutputDuration + writeCount > m_totalTargetDuration) {
m_log.log(1, "writeCount would take output beyond target",
m_totalOutputDuration, m_totalTargetDuration);
auto reduced = m_totalTargetDuration - m_totalOutputDuration;
m_log.log(1, "reducing writeCount from and to", writeCount, reduced);
writeCount = reduced;
}
}
int advanceCount = inhop;
if (advanceCount > readSpace) {
// This should happen only when draining (Finished)
if (m_mode != ProcessMode::Finished) {
m_log.log(0, "R3Stretcher: WARNING: readSpace < inhop when processing is not yet finished", readSpace, inhop);
}
advanceCount = readSpace;
}
for (int c = 0; c < channels; ++c) {
auto &cd = m_channelData.at(c);
if (resamplingAfter) {
cd->outbuf->write(cd->resampled.data(), writeCount);
} else {
cd->outbuf->write(cd->mixdown.data(), writeCount);
}
cd->inbuf->skip(advanceCount);
}
m_consumedInputDuration += advanceCount;
m_totalOutputDuration += writeCount;
if (m_startSkip > 0) {
int rs = cd0->outbuf->getReadSpace();
int toSkip = std::min(m_startSkip, rs);
for (int c = 0; c < channels; ++c) {
m_channelData.at(c)->outbuf->skip(toSkip);
}
m_startSkip -= toSkip;
m_totalOutputDuration = rs - toSkip;
}
m_prevInhop = inhop;
m_prevOuthop = outhop;
}
}
void
R3Stretcher::analyseChannel(int c, int inhop, int prevInhop, int prevOuthop)
{
Profiler profiler("R3Stretcher::analyseChannel");
auto &cd = m_channelData.at(c);
int sourceSize = cd->windowSource.size();
process_t *buf = cd->windowSource.data();
int readSpace = cd->inbuf->getReadSpace();
if (readSpace < sourceSize) {
cd->inbuf->peek(buf, readSpace);
v_zero(buf + readSpace, sourceSize - readSpace);
} else {
cd->inbuf->peek(buf, sourceSize);
}
// We have an unwindowed time-domain frame in buf that is as long
// as required for the union of all FFT sizes and readahead
// hops. Populate the various sizes from it with aligned centres,
// windowing as we copy. The classification scale is handled
// separately because it has readahead, so skip it here. (In
// single-window mode that means we do nothing here, since the
// classification scale is the only one.)
int longest = m_guideConfiguration.longestFftSize;
int classify = m_guideConfiguration.classificationFftSize;
for (auto &it: cd->scales) {
int fftSize = it.first;
if (fftSize == classify) continue;
int offset = (longest - fftSize) / 2;
m_scaleData.at(fftSize)->analysisWindow.cut
(buf + offset, it.second->timeDomain.data());
}
auto &classifyScale = cd->scales.at(classify);
ClassificationReadaheadData &readahead = cd->readahead;
bool copyFromReadahead = false;
if (m_useReadahead) {
// The classification scale has a one-hop readahead, so
// populate the readahead from further down the long
// unwindowed frame.
m_scaleData.at(classify)->analysisWindow.cut
(buf + (longest - classify) / 2 + inhop,
readahead.timeDomain.data());
// If inhop has changed since the previous frame, we must