forked from audacity/audacity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundTouchEffect.cpp
More file actions
442 lines (364 loc) · 15.2 KB
/
Copy pathSoundTouchEffect.cpp
File metadata and controls
442 lines (364 loc) · 15.2 KB
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
/**********************************************************************
Audacity: A Digital Audio Editor
SoundTouchEffect.cpp
Dominic Mazzoni, Vaughan Johnson
This abstract class contains all of the common code for an
effect that uses SoundTouch to do its processing (ChangeTempo
and ChangePitch).
**********************************************************************/
#include "../Audacity.h" // for USE_* macros
#if USE_SOUNDTOUCH
#include "SoundTouchEffect.h"
#include <math.h>
#include "../LabelTrack.h"
#include "../WaveClip.h"
#include "../WaveTrack.h"
#include "../NoteTrack.h"
#include "TimeWarper.h"
// Soundtouch defines these as well, which are also in generated configmac.h
// and configunix.h, so get rid of them before including,
// to avoid compiler warnings, and be sure to do this
// after all other #includes, to avoid any mischief that might result
// from doing the un-definitions before seeing any wx headers.
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
#undef PACKAGE_BUGREPORT
#undef PACKAGE
#undef VERSION
#include "SoundTouch.h"
#ifdef USE_MIDI
EffectSoundTouch::EffectSoundTouch()
{
mSemitones = 0;
}
#endif
EffectSoundTouch::~EffectSoundTouch()
{
}
bool EffectSoundTouch::ProcessLabelTrack(
LabelTrack *lt, const TimeWarper &warper)
{
// SetTimeWarper(std::make_unique<RegionTimeWarper>(mCurT0, mCurT1,
// std::make_unique<LinearTimeWarper>(mCurT0, mCurT0,
// mCurT1, mCurT0 + (mCurT1-mCurT0)*mFactor)));
lt->WarpLabels(warper);
return true;
}
#ifdef USE_MIDI
bool EffectSoundTouch::ProcessNoteTrack(NoteTrack *nt, const TimeWarper &warper)
{
nt->WarpAndTransposeNotes(mCurT0, mCurT1, warper, mSemitones);
return true;
}
#endif
bool EffectSoundTouch::ProcessWithTimeWarper(InitFunction initer,
const TimeWarper &warper,
bool preserveLength)
{
// Assumes that mSoundTouch has already been initialized
// by the subclass for subclass-specific parameters. The
// time warper should also be set.
// Check if this effect will alter the selection length; if so, we need
// to operate on sync-lock selected tracks.
bool mustSync = true;
if (mT1 == warper.Warp(mT1)) {
mustSync = false;
}
//Iterate over each track
// Needs all for sync-lock grouping.
this->CopyInputTracks(true);
bool bGoodResult = true;
mPreserveLength = preserveLength;
mCurTrackNum = 0;
m_maxNewLength = 0.0;
mOutputTracks->Leaders().VisitWhile( bGoodResult,
[&]( LabelTrack *lt, const Track::Fallthrough &fallthrough ) {
if ( !(lt->GetSelected() || (mustSync && lt->IsSyncLockSelected())) )
return fallthrough();
if (!ProcessLabelTrack(lt, warper))
bGoodResult = false;
},
#ifdef USE_MIDI
[&]( NoteTrack *nt, const Track::Fallthrough &fallthrough ) {
if ( !(nt->GetSelected() || (mustSync && nt->IsSyncLockSelected())) )
return fallthrough();
if (!ProcessNoteTrack(nt, warper))
bGoodResult = false;
},
#endif
[&]( WaveTrack *leftTrack, const Track::Fallthrough &fallthrough ) {
if (!leftTrack->GetSelected())
return fallthrough();
//Get start and end times from selection
mCurT0 = mT0;
mCurT1 = mT1;
//Set the current bounds to whichever left marker is
//greater and whichever right marker is less
mCurT0 = wxMax(mT0, mCurT0);
mCurT1 = wxMin(mT1, mCurT1);
// Process only if the right marker is to the right of the left marker
if (mCurT1 > mCurT0) {
mSoundTouch = std::make_unique<soundtouch::SoundTouch>();
initer(mSoundTouch.get());
// TODO: more-than-two-channels
auto channels = TrackList::Channels(leftTrack);
auto rightTrack = (channels.size() > 1)
? * ++ channels.first
: nullptr;
if ( rightTrack ) {
double t;
//Adjust bounds by the right tracks markers
t = rightTrack->GetStartTime();
t = wxMax(mT0, t);
mCurT0 = wxMin(mCurT0, t);
t = rightTrack->GetEndTime();
t = wxMin(mT1, t);
mCurT1 = wxMax(mCurT1, t);
//Transform the marker timepoints to samples
auto start = leftTrack->TimeToLongSamples(mCurT0);
auto end = leftTrack->TimeToLongSamples(mCurT1);
//Inform soundtouch there's 2 channels
mSoundTouch->setChannels(2);
//ProcessStereo() (implemented below) processes a stereo track
if (!ProcessStereo(leftTrack, rightTrack, start, end, warper))
bGoodResult = false;
mCurTrackNum++; // Increment for rightTrack, too.
} else {
//Transform the marker timepoints to samples
auto start = leftTrack->TimeToLongSamples(mCurT0);
auto end = leftTrack->TimeToLongSamples(mCurT1);
//Inform soundtouch there's a single channel
mSoundTouch->setChannels(1);
//ProcessOne() (implemented below) processes a single track
if (!ProcessOne(leftTrack, start, end, warper))
bGoodResult = false;
}
mSoundTouch.reset();
}
mCurTrackNum++;
},
[&]( Track *t ) {
if (mustSync && t->IsSyncLockSelected()) {
t->SyncLockAdjust(mT1, warper.Warp(mT1));
}
}
);
if (bGoodResult) {
ReplaceProcessedTracks(bGoodResult);
}
return bGoodResult;
}
void EffectSoundTouch::End()
{
mSoundTouch.reset();
}
//ProcessOne() takes a track, transforms it to bunch of buffer-blocks,
//and executes ProcessSoundTouch on these blocks
bool EffectSoundTouch::ProcessOne(WaveTrack *track,
sampleCount start, sampleCount end,
const TimeWarper &warper)
{
mSoundTouch->setSampleRate((unsigned int)(track->GetRate()+0.5));
auto outputTrack = track->EmptyCopy();
//Get the length of the buffer (as double). len is
//used simple to calculate a progress meter, so it is easier
//to make it a double now than it is to do it later
auto len = (end - start).as_double();
{
//Initiate a processing buffer. This buffer will (most likely)
//be shorter than the length of the track being processed.
Floats buffer{ track->GetMaxBlockSize() };
//Go through the track one buffer at a time. s counts which
//sample the current buffer starts at.
auto s = start;
while (s < end) {
//Get a block of samples (smaller than the size of the buffer)
const auto block = wxMin(8192,
limitSampleBufferSize( track->GetBestBlockSize(s), end - s ));
//Get the samples from the track and put them in the buffer
track->Get((samplePtr)buffer.get(), floatSample, s, block);
//Add samples to SoundTouch
mSoundTouch->putSamples(buffer.get(), block);
//Get back samples from SoundTouch
unsigned int outputCount = mSoundTouch->numSamples();
if (outputCount > 0) {
Floats buffer2{ outputCount };
mSoundTouch->receiveSamples(buffer2.get(), outputCount);
outputTrack->Append((samplePtr)buffer2.get(), floatSample, outputCount);
}
//Increment s one blockfull of samples
s += block;
//Update the Progress meter
if (TrackProgress(mCurTrackNum, (s - start).as_double() / len))
return false;
}
// Tell SoundTouch to finish processing any remaining samples
mSoundTouch->flush(); // this should only be used for changeTempo - it dumps data otherwise with pRateTransposer->clear();
unsigned int outputCount = mSoundTouch->numSamples();
if (outputCount > 0) {
Floats buffer2{ outputCount };
mSoundTouch->receiveSamples(buffer2.get(), outputCount);
outputTrack->Append((samplePtr)buffer2.get(), floatSample, outputCount);
}
// Flush the output WaveTrack (since it's buffered, too)
outputTrack->Flush();
}
// Transfer output samples to the original
Finalize(track, outputTrack.get(), warper);
double newLength = outputTrack->GetEndTime();
m_maxNewLength = wxMax(m_maxNewLength, newLength);
//Return true because the effect processing succeeded.
return true;
}
bool EffectSoundTouch::ProcessStereo(
WaveTrack* leftTrack, WaveTrack* rightTrack,
sampleCount start, sampleCount end, const TimeWarper &warper)
{
mSoundTouch->setSampleRate((unsigned int)(leftTrack->GetRate() + 0.5));
auto outputLeftTrack = leftTrack->EmptyCopy();
auto outputRightTrack = rightTrack->EmptyCopy();
//Get the length of the buffer (as double). len is
//used simple to calculate a progress meter, so it is easier
//to make it a double now than it is to do it later
double len = (end - start).as_double();
//Initiate a processing buffer. This buffer will (most likely)
//be shorter than the length of the track being processed.
// Make soundTouchBuffer twice as big as MaxBlockSize for each channel,
// because Soundtouch wants them interleaved, i.e., each
// Soundtouch sample is left-right pair.
auto maxBlockSize = leftTrack->GetMaxBlockSize();
{
Floats leftBuffer{ maxBlockSize };
Floats rightBuffer{ maxBlockSize };
Floats soundTouchBuffer{ maxBlockSize * 2 };
// Go through the track one stereo buffer at a time.
// sourceSampleCount counts the sample at which the current buffer starts,
// per channel.
auto sourceSampleCount = start;
while (sourceSampleCount < end) {
auto blockSize = limitSampleBufferSize(
leftTrack->GetBestBlockSize(sourceSampleCount),
end - sourceSampleCount
);
// Get the samples from the tracks and put them in the buffers.
leftTrack->Get((samplePtr)(leftBuffer.get()), floatSample, sourceSampleCount, blockSize);
rightTrack->Get((samplePtr)(rightBuffer.get()), floatSample, sourceSampleCount, blockSize);
// Interleave into soundTouchBuffer.
for (decltype(blockSize) index = 0; index < blockSize; index++) {
soundTouchBuffer[index * 2] = leftBuffer[index];
soundTouchBuffer[(index * 2) + 1] = rightBuffer[index];
}
//Add samples to SoundTouch
mSoundTouch->putSamples(soundTouchBuffer.get(), blockSize);
//Get back samples from SoundTouch
unsigned int outputCount = mSoundTouch->numSamples();
if (outputCount > 0)
this->ProcessStereoResults(outputCount, outputLeftTrack.get(), outputRightTrack.get());
//Increment sourceSampleCount one blockfull of samples
sourceSampleCount += blockSize;
//Update the Progress meter
// mCurTrackNum is left track. Include right track.
int nWhichTrack = mCurTrackNum;
double frac = (sourceSampleCount - start).as_double() / len;
if (frac < 0.5)
frac *= 2.0; // Show twice as far for each track, because we're doing 2 at once.
else
{
nWhichTrack++;
frac -= 0.5;
frac *= 2.0; // Show twice as far for each track, because we're doing 2 at once.
}
if (TrackProgress(nWhichTrack, frac))
return false;
}
// Tell SoundTouch to finish processing any remaining samples
mSoundTouch->flush();
unsigned int outputCount = mSoundTouch->numSamples();
if (outputCount > 0)
this->ProcessStereoResults(outputCount, outputLeftTrack.get(), outputRightTrack.get());
// Flush the output WaveTracks (since they're buffered, too)
outputLeftTrack->Flush();
outputRightTrack->Flush();
}
// Transfer output samples to the original
Finalize(leftTrack, outputLeftTrack.get(), warper);
Finalize(rightTrack, outputRightTrack.get(), warper);
// Track the longest result length
double newLength = outputLeftTrack->GetEndTime();
m_maxNewLength = wxMax(m_maxNewLength, newLength);
newLength = outputRightTrack->GetEndTime();
m_maxNewLength = wxMax(m_maxNewLength, newLength);
//Return true because the effect processing succeeded.
return true;
}
bool EffectSoundTouch::ProcessStereoResults(const size_t outputCount,
WaveTrack* outputLeftTrack,
WaveTrack* outputRightTrack)
{
Floats outputSoundTouchBuffer{ outputCount * 2 };
mSoundTouch->receiveSamples(outputSoundTouchBuffer.get(), outputCount);
// Dis-interleave outputSoundTouchBuffer into separate track buffers.
Floats outputLeftBuffer{ outputCount };
Floats outputRightBuffer{ outputCount };
for (unsigned int index = 0; index < outputCount; index++)
{
outputLeftBuffer[index] = outputSoundTouchBuffer[index*2];
outputRightBuffer[index] = outputSoundTouchBuffer[(index*2)+1];
}
outputLeftTrack->Append((samplePtr)outputLeftBuffer.get(), floatSample, outputCount);
outputRightTrack->Append((samplePtr)outputRightBuffer.get(), floatSample, outputCount);
return true;
}
void EffectSoundTouch::Finalize(WaveTrack* orig, WaveTrack* out, const TimeWarper &warper)
{
if (mPreserveLength) {
auto newLen = out->GetNumSamples();
auto oldLen = out->TimeToLongSamples(mCurT1) - out->TimeToLongSamples(mCurT0);
// Pad output track to original length since SoundTouch may remove samples
if (newLen < oldLen) {
out->InsertSilence(out->LongSamplesToTime(newLen - 1),
out->LongSamplesToTime(oldLen - newLen));
}
// Trim output track to original length since SoundTouch may add extra samples
else if (newLen > oldLen) {
out->Trim(0, out->LongSamplesToTime(oldLen));
}
}
// Silenced samples will be inserted in gaps between clips, so capture where these
// gaps are for later deletion
std::vector<std::pair<double, double>> gaps;
double last = 0.0;
auto clips = orig->SortedClipArray();
auto front = clips.front();
auto back = clips.back();
for (auto &clip : clips) {
auto st = clip->GetStartTime();
auto et = clip->GetEndTime();
if (st >= mCurT0 || et < mCurT1) {
if (mCurT0 < st && clip == front) {
gaps.push_back(std::make_pair(mCurT0, st));
}
if (mCurT1 > et && clip == back) {
gaps.push_back(std::make_pair(et, mCurT1));
}
if (last >= mCurT0) {
gaps.push_back(std::make_pair(last, st));
}
}
last = et;
}
// Take the output track and insert it in place of the original sample data
orig->ClearAndPaste(mCurT0, mCurT1, out, true, true, &warper);
// Finally, recreate the gaps
for (auto gap : gaps) {
auto st = orig->LongSamplesToTime(orig->TimeToLongSamples(gap.first));
auto et = orig->LongSamplesToTime(orig->TimeToLongSamples(gap.second));
if (st >= mCurT0 && et <= mCurT1 && st != et)
{
orig->SplitDelete(warper.Warp(st), warper.Warp(et));
}
}
}
#endif // USE_SOUNDTOUCH