blob: 54b99f8215c7c1298d66769e57841b6b4f9b2b2f [file] [log] [blame]
Richard Burton00553462021-11-10 16:27:14 +00001/*
2 * Copyright (c) 2021 Arm Limited. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#include "RNNoiseProcess.hpp"
18#include <algorithm>
19#include <cmath>
20#include <cstring>
21
22namespace arm {
23namespace app {
24namespace rnn {
25
26#define VERIFY(x) \
27do { \
28 if (!(x)) { \
29 printf_err("Assert failed:" #x "\n"); \
30 exit(1); \
31 } \
32} while(0)
33
34RNNoiseProcess::RNNoiseProcess() :
35 m_halfWindow(FRAME_SIZE, 0),
36 m_dctTable(NB_BANDS * NB_BANDS),
37 m_analysisMem(FRAME_SIZE, 0),
38 m_cepstralMem(CEPS_MEM, vec1D32F(NB_BANDS, 0)),
39 m_memId{0},
40 m_synthesisMem(FRAME_SIZE, 0),
41 m_pitchBuf(PITCH_BUF_SIZE, 0),
42 m_lastGain{0.0},
43 m_lastPeriod{0},
44 m_memHpX{},
45 m_lastGVec(NB_BANDS, 0)
46{
47 constexpr uint32_t numFFt = 2 * FRAME_SIZE;
48 static_assert(numFFt != 0, "Num FFT can't be 0");
49
50 math::MathUtils::FftInitF32(numFFt, this->m_fftInstReal, FftType::real);
51 math::MathUtils::FftInitF32(numFFt, this->m_fftInstCmplx, FftType::complex);
52 this->InitTables();
53}
54
55void RNNoiseProcess::PreprocessFrame(const float* audioData,
56 const size_t audioLen,
57 FrameFeatures& features)
58{
59 /* Note audioWindow is modified in place */
60 const arrHp aHp {-1.99599, 0.99600 };
61 const arrHp bHp {-2.00000, 1.00000 };
62
63 vec1D32F audioWindow{audioData, audioData + audioLen};
64
65 this->BiQuad(bHp, aHp, this->m_memHpX, audioWindow);
66 this->ComputeFrameFeatures(audioWindow, features);
67}
68
69void RNNoiseProcess::PostProcessFrame(vec1D32F& modelOutput, FrameFeatures& features, vec1D32F& outFrame)
70{
George Gekova2b0fc22021-11-08 16:30:43 +000071 std::vector<float> outputBands = modelOutput;
72 std::vector<float> gain(FREQ_SIZE, 0);
Richard Burton00553462021-11-10 16:27:14 +000073
74 if (!features.m_silence) {
George Gekova2b0fc22021-11-08 16:30:43 +000075 PitchFilter(features, outputBands);
Richard Burton00553462021-11-10 16:27:14 +000076 for (size_t i = 0; i < NB_BANDS; i++) {
77 float alpha = .6f;
George Gekova2b0fc22021-11-08 16:30:43 +000078 outputBands[i] = std::max(outputBands[i], alpha * m_lastGVec[i]);
79 m_lastGVec[i] = outputBands[i];
Richard Burton00553462021-11-10 16:27:14 +000080 }
George Gekova2b0fc22021-11-08 16:30:43 +000081 InterpBandGain(gain, outputBands);
Richard Burton00553462021-11-10 16:27:14 +000082 for (size_t i = 0; i < FREQ_SIZE; i++) {
George Gekova2b0fc22021-11-08 16:30:43 +000083 features.m_fftX[2 * i] *= gain[i]; /* Real. */
84 features.m_fftX[2 * i + 1] *= gain[i]; /*imaginary. */
Richard Burton00553462021-11-10 16:27:14 +000085
86 }
87
88 }
89
90 FrameSynthesis(outFrame, features.m_fftX);
91}
92
93void RNNoiseProcess::InitTables()
94{
95 constexpr float pi = M_PI;
96 constexpr float halfPi = M_PI / 2;
97 constexpr float halfPiOverFrameSz = halfPi/FRAME_SIZE;
98
99 for (uint32_t i = 0; i < FRAME_SIZE; i++) {
100 const float sinVal = math::MathUtils::SineF32(halfPiOverFrameSz * (i + 0.5f));
101 m_halfWindow[i] = math::MathUtils::SineF32(halfPi * sinVal * sinVal);
102 }
103
104 for (uint32_t i = 0; i < NB_BANDS; i++) {
105 for (uint32_t j = 0; j < NB_BANDS; j++) {
106 m_dctTable[i * NB_BANDS + j] = math::MathUtils::CosineF32((i + 0.5f) * j * pi / NB_BANDS);
107 }
108 m_dctTable[i * NB_BANDS] *= math::MathUtils::SqrtF32(0.5f);
109 }
110}
111
112void RNNoiseProcess::BiQuad(
113 const arrHp& bHp,
114 const arrHp& aHp,
115 arrHp& memHpX,
116 vec1D32F& audioWindow)
117{
118 for (float& audioElement : audioWindow) {
119 const auto xi = audioElement;
120 const auto yi = audioElement + memHpX[0];
121 memHpX[0] = memHpX[1] + (bHp[0] * xi - aHp[0] * yi);
122 memHpX[1] = (bHp[1] * xi - aHp[1] * yi);
123 audioElement = yi;
124 }
125}
126
127void RNNoiseProcess::ComputeFrameFeatures(vec1D32F& audioWindow,
128 FrameFeatures& features)
129{
130 this->FrameAnalysis(audioWindow,
131 features.m_fftX,
132 features.m_Ex,
133 this->m_analysisMem);
134
George Gekova2b0fc22021-11-08 16:30:43 +0000135 float energy = 0.0;
Richard Burton00553462021-11-10 16:27:14 +0000136
137 vec1D32F Ly(NB_BANDS, 0);
138 vec1D32F p(WINDOW_SIZE, 0);
139 vec1D32F pitchBuf(PITCH_BUF_SIZE >> 1, 0);
140
141 VERIFY(PITCH_BUF_SIZE >= this->m_pitchBuf.size());
142 std::copy_n(this->m_pitchBuf.begin() + FRAME_SIZE,
143 PITCH_BUF_SIZE - FRAME_SIZE,
144 this->m_pitchBuf.begin());
145
146 VERIFY(FRAME_SIZE <= audioWindow.size() && PITCH_BUF_SIZE > FRAME_SIZE);
147 std::copy_n(audioWindow.begin(),
148 FRAME_SIZE,
149 this->m_pitchBuf.begin() + PITCH_BUF_SIZE - FRAME_SIZE);
150
151 this->PitchDownsample(pitchBuf, PITCH_BUF_SIZE);
152
153 VERIFY(pitchBuf.size() > PITCH_MAX_PERIOD/2);
154 vec1D32F xLp(pitchBuf.size() - PITCH_MAX_PERIOD/2, 0);
155 std::copy_n(pitchBuf.begin() + PITCH_MAX_PERIOD/2, xLp.size(), xLp.begin());
156
157 int pitchIdx = this->PitchSearch(xLp, pitchBuf,
158 PITCH_FRAME_SIZE, (PITCH_MAX_PERIOD - (3*PITCH_MIN_PERIOD)));
159
160 pitchIdx = this->RemoveDoubling(
161 pitchBuf,
162 PITCH_MAX_PERIOD,
163 PITCH_MIN_PERIOD,
164 PITCH_FRAME_SIZE,
165 PITCH_MAX_PERIOD - pitchIdx);
166
167 size_t stIdx = PITCH_BUF_SIZE - WINDOW_SIZE - pitchIdx;
168 VERIFY((static_cast<int>(PITCH_BUF_SIZE) - static_cast<int>(WINDOW_SIZE) - pitchIdx) >= 0);
169 std::copy_n(this->m_pitchBuf.begin() + stIdx, WINDOW_SIZE, p.begin());
170
171 this->ApplyWindow(p);
172 this->ForwardTransform(p, features.m_fftP);
173 this->ComputeBandEnergy(features.m_fftP, features.m_Ep);
174 this->ComputeBandCorr(features.m_fftX, features.m_fftP, features.m_Exp);
175
176 for (uint32_t i = 0 ; i < NB_BANDS; ++i) {
177 features.m_Exp[i] /= math::MathUtils::SqrtF32(
178 0.001f + features.m_Ex[i] * features.m_Ep[i]);
179 }
180
181 vec1D32F dctVec(NB_BANDS, 0);
182 this->DCT(features.m_Exp, dctVec);
183
184 features.m_featuresVec = vec1D32F (NB_FEATURES, 0);
185 for (uint32_t i = 0; i < NB_DELTA_CEPS; ++i) {
186 features.m_featuresVec[NB_BANDS + 2*NB_DELTA_CEPS + i] = dctVec[i];
187 }
188
189 features.m_featuresVec[NB_BANDS + 2*NB_DELTA_CEPS] -= 1.3;
190 features.m_featuresVec[NB_BANDS + 2*NB_DELTA_CEPS + 1] -= 0.9;
191 features.m_featuresVec[NB_BANDS + 3*NB_DELTA_CEPS] = 0.01 * (static_cast<int>(pitchIdx) - 300);
192
193 float logMax = -2.f;
194 float follow = -2.f;
195 for (uint32_t i = 0; i < NB_BANDS; ++i) {
196 Ly[i] = log10f(1e-2f + features.m_Ex[i]);
197 Ly[i] = std::max<float>(logMax - 7, std::max<float>(follow - 1.5, Ly[i]));
198 logMax = std::max<float>(logMax, Ly[i]);
199 follow = std::max<float>(follow - 1.5, Ly[i]);
George Gekova2b0fc22021-11-08 16:30:43 +0000200 energy += features.m_Ex[i];
Richard Burton00553462021-11-10 16:27:14 +0000201 }
202
203 /* If there's no audio avoid messing up the state. */
204 features.m_silence = true;
George Gekova2b0fc22021-11-08 16:30:43 +0000205 if (energy < 0.04) {
Richard Burton00553462021-11-10 16:27:14 +0000206 return;
207 } else {
208 features.m_silence = false;
209 }
210
211 this->DCT(Ly, features.m_featuresVec);
212 features.m_featuresVec[0] -= 12.0;
213 features.m_featuresVec[1] -= 4.0;
214
215 VERIFY(CEPS_MEM > 2);
216 uint32_t stIdx1 = this->m_memId < 1 ? CEPS_MEM + this->m_memId - 1 : this->m_memId - 1;
217 uint32_t stIdx2 = this->m_memId < 2 ? CEPS_MEM + this->m_memId - 2 : this->m_memId - 2;
George Gekova2b0fc22021-11-08 16:30:43 +0000218 VERIFY(stIdx1 < this->m_cepstralMem.size());
219 VERIFY(stIdx2 < this->m_cepstralMem.size());
Richard Burton00553462021-11-10 16:27:14 +0000220 auto ceps1 = this->m_cepstralMem[stIdx1];
221 auto ceps2 = this->m_cepstralMem[stIdx2];
222
223 /* Ceps 0 */
224 for (uint32_t i = 0; i < NB_BANDS; ++i) {
225 this->m_cepstralMem[this->m_memId][i] = features.m_featuresVec[i];
226 }
227
228 for (uint32_t i = 0; i < NB_DELTA_CEPS; ++i) {
229 features.m_featuresVec[i] = this->m_cepstralMem[this->m_memId][i] + ceps1[i] + ceps2[i];
230 features.m_featuresVec[NB_BANDS + i] = this->m_cepstralMem[this->m_memId][i] - ceps2[i];
231 features.m_featuresVec[NB_BANDS + NB_DELTA_CEPS + i] =
232 this->m_cepstralMem[this->m_memId][i] - 2 * ceps1[i] + ceps2[i];
233 }
234
235 /* Spectral variability features. */
236 this->m_memId += 1;
237 if (this->m_memId == CEPS_MEM) {
238 this->m_memId = 0;
239 }
240
241 float specVariability = 0.f;
242
243 VERIFY(this->m_cepstralMem.size() >= CEPS_MEM);
244 for (size_t i = 0; i < CEPS_MEM; ++i) {
245 float minDist = 1e15;
246 for (size_t j = 0; j < CEPS_MEM; ++j) {
247 float dist = 0.f;
248 for (size_t k = 0; k < NB_BANDS; ++k) {
249 VERIFY(this->m_cepstralMem[i].size() >= NB_BANDS);
250 auto tmp = this->m_cepstralMem[i][k] - this->m_cepstralMem[j][k];
251 dist += tmp * tmp;
252 }
253
254 if (j != i) {
255 minDist = std::min<float>(minDist, dist);
256 }
257 }
258 specVariability += minDist;
259 }
260
261 VERIFY(features.m_featuresVec.size() >= NB_BANDS + 3 * NB_DELTA_CEPS + 1);
262 features.m_featuresVec[NB_BANDS + 3 * NB_DELTA_CEPS + 1] = specVariability / CEPS_MEM - 2.1;
263}
264
265void RNNoiseProcess::FrameAnalysis(
266 const vec1D32F& audioWindow,
267 vec1D32F& fft,
268 vec1D32F& energy,
269 vec1D32F& analysisMem)
270{
271 vec1D32F x(WINDOW_SIZE, 0);
272
273 /* Move old audio down and populate end with latest audio window. */
274 VERIFY(x.size() >= FRAME_SIZE && analysisMem.size() >= FRAME_SIZE);
275 VERIFY(audioWindow.size() >= FRAME_SIZE);
276
277 std::copy_n(analysisMem.begin(), FRAME_SIZE, x.begin());
278 std::copy_n(audioWindow.begin(), x.size() - FRAME_SIZE, x.begin() + FRAME_SIZE);
279 std::copy_n(audioWindow.begin(), FRAME_SIZE, analysisMem.begin());
280
281 this->ApplyWindow(x);
282
283 /* Calculate FFT. */
284 ForwardTransform(x, fft);
285
286 /* Compute band energy. */
287 ComputeBandEnergy(fft, energy);
288}
289
290void RNNoiseProcess::ApplyWindow(vec1D32F& x)
291{
292 if (WINDOW_SIZE != x.size()) {
293 printf_err("Invalid size for vector to be windowed\n");
294 return;
295 }
296
297 VERIFY(this->m_halfWindow.size() >= FRAME_SIZE);
298
299 /* Multiply input by sinusoidal function. */
300 for (size_t i = 0; i < FRAME_SIZE; i++) {
301 x[i] *= this->m_halfWindow[i];
302 x[WINDOW_SIZE - 1 - i] *= this->m_halfWindow[i];
303 }
304}
305
306void RNNoiseProcess::ForwardTransform(
307 vec1D32F& x,
308 vec1D32F& fft)
309{
310 /* The input vector can be modified by the fft function. */
311 fft.reserve(x.size() + 2);
312 fft.resize(x.size() + 2, 0);
313 math::MathUtils::FftF32(x, fft, this->m_fftInstReal);
314
315 /* Normalise. */
316 for (auto& f : fft) {
317 f /= this->m_fftInstReal.m_fftLen;
318 }
319
320 /* Place the last freq element correctly */
321 fft[fft.size()-2] = fft[1];
322 fft[1] = 0;
323
324 /* NOTE: We don't truncate out FFT vector as it already contains only the
325 * first half of the FFT's. The conjugates are not present. */
326}
327
328void RNNoiseProcess::ComputeBandEnergy(const vec1D32F& fftX, vec1D32F& bandE)
329{
330 bandE = vec1D32F(NB_BANDS, 0);
331
332 VERIFY(this->m_eband5ms.size() >= NB_BANDS);
333 for (uint32_t i = 0; i < NB_BANDS - 1; i++) {
334 const auto bandSize = (this->m_eband5ms[i + 1] - this->m_eband5ms[i])
335 << FRAME_SIZE_SHIFT;
336
337 for (uint32_t j = 0; j < bandSize; j++) {
338 const auto frac = static_cast<float>(j) / bandSize;
339 const auto idx = (this->m_eband5ms[i] << FRAME_SIZE_SHIFT) + j;
340
341 auto tmp = fftX[2 * idx] * fftX[2 * idx]; /* Real part */
342 tmp += fftX[2 * idx + 1] * fftX[2 * idx + 1]; /* Imaginary part */
343
344 bandE[i] += (1 - frac) * tmp;
345 bandE[i + 1] += frac * tmp;
346 }
347 }
348 bandE[0] *= 2;
349 bandE[NB_BANDS - 1] *= 2;
350}
351
352void RNNoiseProcess::ComputeBandCorr(const vec1D32F& X, const vec1D32F& P, vec1D32F& bandC)
353{
354 bandC = vec1D32F(NB_BANDS, 0);
355 VERIFY(this->m_eband5ms.size() >= NB_BANDS);
356
357 for (uint32_t i = 0; i < NB_BANDS - 1; i++) {
358 const auto bandSize = (this->m_eband5ms[i + 1] - this->m_eband5ms[i]) << FRAME_SIZE_SHIFT;
359
360 for (uint32_t j = 0; j < bandSize; j++) {
361 const auto frac = static_cast<float>(j) / bandSize;
362 const auto idx = (this->m_eband5ms[i] << FRAME_SIZE_SHIFT) + j;
363
364 auto tmp = X[2 * idx] * P[2 * idx]; /* Real part */
365 tmp += X[2 * idx + 1] * P[2 * idx + 1]; /* Imaginary part */
366
367 bandC[i] += (1 - frac) * tmp;
368 bandC[i + 1] += frac * tmp;
369 }
370 }
371 bandC[0] *= 2;
372 bandC[NB_BANDS - 1] *= 2;
373}
374
375void RNNoiseProcess::DCT(vec1D32F& input, vec1D32F& output)
376{
377 VERIFY(this->m_dctTable.size() >= NB_BANDS * NB_BANDS);
378 for (uint32_t i = 0; i < NB_BANDS; ++i) {
379 float sum = 0;
380
381 for (uint32_t j = 0, k = 0; j < NB_BANDS; ++j, k += NB_BANDS) {
382 sum += input[j] * this->m_dctTable[k + i];
383 }
384 output[i] = sum * math::MathUtils::SqrtF32(2.0/22);
385 }
386}
387
388void RNNoiseProcess::PitchDownsample(vec1D32F& pitchBuf, size_t pitchBufSz) {
389 for (size_t i = 1; i < (pitchBufSz >> 1); ++i) {
390 pitchBuf[i] = 0.5 * (
391 0.5 * (this->m_pitchBuf[2 * i - 1] + this->m_pitchBuf[2 * i + 1])
392 + this->m_pitchBuf[2 * i]);
393 }
394
395 pitchBuf[0] = 0.5*(0.5*(this->m_pitchBuf[1]) + this->m_pitchBuf[0]);
396
397 vec1D32F ac(5, 0);
398 size_t numLags = 4;
399
400 this->AutoCorr(pitchBuf, ac, numLags, pitchBufSz >> 1);
401
402 /* Noise floor -40db */
403 ac[0] *= 1.0001;
404
405 /* Lag windowing. */
406 for (size_t i = 1; i < numLags + 1; ++i) {
407 ac[i] -= ac[i] * (0.008 * i) * (0.008 * i);
408 }
409
410 vec1D32F lpc(numLags, 0);
411 this->LPC(ac, numLags, lpc);
412
413 float tmp = 1.0;
414 for (size_t i = 0; i < numLags; ++i) {
415 tmp = 0.9f * tmp;
416 lpc[i] = lpc[i] * tmp;
417 }
418
419 vec1D32F lpc2(numLags + 1, 0);
420 float c1 = 0.8;
421
422 /* Add a zero. */
423 lpc2[0] = lpc[0] + 0.8;
424 lpc2[1] = lpc[1] + (c1 * lpc[0]);
425 lpc2[2] = lpc[2] + (c1 * lpc[1]);
426 lpc2[3] = lpc[3] + (c1 * lpc[2]);
427 lpc2[4] = (c1 * lpc[3]);
428
429 this->Fir5(lpc2, pitchBufSz >> 1, pitchBuf);
430}
431
432int RNNoiseProcess::PitchSearch(vec1D32F& xLp, vec1D32F& y, uint32_t len, uint32_t maxPitch) {
433 uint32_t lag = len + maxPitch;
434 vec1D32F xLp4(len >> 2, 0);
435 vec1D32F yLp4(lag >> 2, 0);
436 vec1D32F xCorr(maxPitch >> 1, 0);
437
438 /* Downsample by 2 again. */
439 for (size_t j = 0; j < (len >> 2); ++j) {
440 xLp4[j] = xLp[2*j];
441 }
442 for (size_t j = 0; j < (lag >> 2); ++j) {
443 yLp4[j] = y[2*j];
444 }
445
446 this->PitchXCorr(xLp4, yLp4, xCorr, len >> 2, maxPitch >> 2);
447
448 /* Coarse search with 4x decimation. */
449 arrHp bestPitch = this->FindBestPitch(xCorr, yLp4, len >> 2, maxPitch >> 2);
450
451 /* Finer search with 2x decimation. */
452 const int maxIdx = (maxPitch >> 1);
453 for (int i = 0; i < maxIdx; ++i) {
454 xCorr[i] = 0;
455 if (std::abs(i - 2*bestPitch[0]) > 2 and std::abs(i - 2*bestPitch[1]) > 2) {
456 continue;
457 }
458 float sum = 0;
459 for (size_t j = 0; j < len >> 1; ++j) {
460 sum += xLp[j] * y[i+j];
461 }
462
463 xCorr[i] = std::max(-1.0f, sum);
464 }
465
466 bestPitch = this->FindBestPitch(xCorr, y, len >> 1, maxPitch >> 1);
467
468 int offset;
469 /* Refine by pseudo-interpolation. */
470 if ( 0 < bestPitch[0] && bestPitch[0] < ((maxPitch >> 1) - 1)) {
471 float a = xCorr[bestPitch[0] - 1];
472 float b = xCorr[bestPitch[0]];
473 float c = xCorr[bestPitch[0] + 1];
474
475 if ( (c-a) > 0.7*(b-a) ) {
476 offset = 1;
477 } else if ( (a-c) > 0.7*(b-c) ) {
478 offset = -1;
479 } else {
480 offset = 0;
481 }
482 } else {
483 offset = 0;
484 }
485
486 return 2*bestPitch[0] - offset;
487}
488
489arrHp RNNoiseProcess::FindBestPitch(vec1D32F& xCorr, vec1D32F& y, uint32_t len, uint32_t maxPitch)
490{
491 float Syy = 1;
492 arrHp bestNum {-1, -1};
493 arrHp bestDen {0, 0};
494 arrHp bestPitch {0, 1};
495
496 for (size_t j = 0; j < len; ++j) {
497 Syy += (y[j] * y[j]);
498 }
499
500 for (size_t i = 0; i < maxPitch; ++i ) {
501 if (xCorr[i] > 0) {
502 float xCorr16 = xCorr[i] * 1e-12f; /* Avoid problems when squaring. */
503
504 float num = xCorr16 * xCorr16;
505 if (num*bestDen[1] > bestNum[1]*Syy) {
506 if (num*bestDen[0] > bestNum[0]*Syy) {
507 bestNum[1] = bestNum[0];
508 bestDen[1] = bestDen[0];
509 bestPitch[1] = bestPitch[0];
510 bestNum[0] = num;
511 bestDen[0] = Syy;
512 bestPitch[0] = i;
513 } else {
514 bestNum[1] = num;
515 bestDen[1] = Syy;
516 bestPitch[1] = i;
517 }
518 }
519 }
520
521 Syy += (y[i+len]*y[i+len]) - (y[i]*y[i]);
522 Syy = std::max(1.0f, Syy);
523 }
524
525 return bestPitch;
526}
527
528int RNNoiseProcess::RemoveDoubling(
529 vec1D32F& pitchBuf,
530 uint32_t maxPeriod,
531 uint32_t minPeriod,
532 uint32_t frameSize,
533 size_t pitchIdx0_)
534{
535 constexpr std::array<size_t, 16> secondCheck {0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2};
536 uint32_t minPeriod0 = minPeriod;
537 float lastPeriod = static_cast<float>(this->m_lastPeriod)/2;
538 float lastGain = static_cast<float>(this->m_lastGain);
539
540 maxPeriod /= 2;
541 minPeriod /= 2;
542 pitchIdx0_ /= 2;
543 frameSize /= 2;
544 uint32_t xStart = maxPeriod;
545
546 if (pitchIdx0_ >= maxPeriod) {
547 pitchIdx0_ = maxPeriod - 1;
548 }
549
550 size_t pitchIdx = pitchIdx0_;
George Gekova2b0fc22021-11-08 16:30:43 +0000551 const size_t pitchIdx0 = pitchIdx0_;
Richard Burton00553462021-11-10 16:27:14 +0000552
553 float xx = 0;
554 for ( size_t i = xStart; i < xStart+frameSize; ++i) {
555 xx += (pitchBuf[i] * pitchBuf[i]);
556 }
557
558 float xy = 0;
559 for ( size_t i = xStart; i < xStart+frameSize; ++i) {
560 xy += (pitchBuf[i] * pitchBuf[i-pitchIdx0]);
561 }
562
563 vec1D32F yyLookup (maxPeriod+1, 0);
564 yyLookup[0] = xx;
565 float yy = xx;
566
George Gekova2b0fc22021-11-08 16:30:43 +0000567 for ( size_t i = 1; i < yyLookup.size(); ++i) {
Richard Burton00553462021-11-10 16:27:14 +0000568 yy = yy + (pitchBuf[xStart-i] * pitchBuf[xStart-i]) -
569 (pitchBuf[xStart+frameSize-i] * pitchBuf[xStart+frameSize-i]);
570 yyLookup[i] = std::max(0.0f, yy);
571 }
572
573 yy = yyLookup[pitchIdx0];
574 float bestXy = xy;
575 float bestYy = yy;
576
577 float g = this->ComputePitchGain(xy, xx, yy);
578 float g0 = g;
579
580 /* Look for any pitch at pitchIndex/k. */
581 for ( size_t k = 2; k < 16; ++k) {
582 size_t pitchIdx1 = (2*pitchIdx0+k) / (2*k);
583 if (pitchIdx1 < minPeriod) {
584 break;
585 }
586
587 size_t pitchIdx1b;
588 /* Look for another strong correlation at T1b. */
589 if (k == 2) {
590 if ((pitchIdx1 + pitchIdx0) > maxPeriod) {
591 pitchIdx1b = pitchIdx0;
592 } else {
593 pitchIdx1b = pitchIdx0 + pitchIdx1;
594 }
595 } else {
596 pitchIdx1b = (2*(secondCheck[k])*pitchIdx0 + k) / (2*k);
597 }
598
599 xy = 0;
600 for ( size_t i = xStart; i < xStart+frameSize; ++i) {
601 xy += (pitchBuf[i] * pitchBuf[i-pitchIdx1]);
602 }
603
604 float xy2 = 0;
605 for ( size_t i = xStart; i < xStart+frameSize; ++i) {
606 xy2 += (pitchBuf[i] * pitchBuf[i-pitchIdx1b]);
607 }
608 xy = 0.5f * (xy + xy2);
George Gekova2b0fc22021-11-08 16:30:43 +0000609 VERIFY(pitchIdx1b < maxPeriod+1);
Richard Burton00553462021-11-10 16:27:14 +0000610 yy = 0.5f * (yyLookup[pitchIdx1] + yyLookup[pitchIdx1b]);
611
612 float g1 = this->ComputePitchGain(xy, xx, yy);
613
614 float cont;
615 if (std::abs(pitchIdx1-lastPeriod) <= 1) {
616 cont = lastGain;
617 } else if (std::abs(pitchIdx1-lastPeriod) <= 2 and 5*k*k < pitchIdx0) {
618 cont = 0.5f*lastGain;
619 } else {
620 cont = 0.0f;
621 }
622
623 float thresh = std::max(0.3, 0.7*g0-cont);
624
625 /* Bias against very high pitch (very short period) to avoid false-positives
626 * due to short-term correlation */
627 if (pitchIdx1 < 3*minPeriod) {
628 thresh = std::max(0.4, 0.85*g0-cont);
629 } else if (pitchIdx1 < 2*minPeriod) {
630 thresh = std::max(0.5, 0.9*g0-cont);
631 }
632 if (g1 > thresh) {
633 bestXy = xy;
634 bestYy = yy;
635 pitchIdx = pitchIdx1;
636 g = g1;
637 }
638 }
639
640 bestXy = std::max(0.0f, bestXy);
641 float pg;
642 if (bestYy <= bestXy) {
643 pg = 1.0;
644 } else {
645 pg = bestXy/(bestYy+1);
646 }
647
648 std::array<float, 3> xCorr {0};
649 for ( size_t k = 0; k < 3; ++k ) {
650 for ( size_t i = xStart; i < xStart+frameSize; ++i) {
651 xCorr[k] += (pitchBuf[i] * pitchBuf[i-(pitchIdx+k-1)]);
652 }
653 }
654
655 size_t offset;
656 if ((xCorr[2]-xCorr[0]) > 0.7*(xCorr[1]-xCorr[0])) {
657 offset = 1;
658 } else if ((xCorr[0]-xCorr[2]) > 0.7*(xCorr[1]-xCorr[2])) {
659 offset = -1;
660 } else {
661 offset = 0;
662 }
663
664 if (pg > g) {
665 pg = g;
666 }
667
668 pitchIdx0_ = 2*pitchIdx + offset;
669
670 if (pitchIdx0_ < minPeriod0) {
671 pitchIdx0_ = minPeriod0;
672 }
673
674 this->m_lastPeriod = pitchIdx0_;
675 this->m_lastGain = pg;
676
677 return this->m_lastPeriod;
678}
679
680float RNNoiseProcess::ComputePitchGain(float xy, float xx, float yy)
681{
682 return xy / math::MathUtils::SqrtF32(1+xx*yy);
683}
684
685void RNNoiseProcess::AutoCorr(
686 const vec1D32F& x,
687 vec1D32F& ac,
688 size_t lag,
689 size_t n)
690{
691 if (n < lag) {
692 printf_err("Invalid parameters for AutoCorr\n");
693 return;
694 }
695
696 auto fastN = n - lag;
697
698 /* Auto-correlation - can be done by PlatformMath functions */
699 this->PitchXCorr(x, x, ac, fastN, lag + 1);
700
701 /* Modify auto-correlation by summing with auto-correlation for different lags. */
702 for (size_t k = 0; k < lag + 1; k++) {
703 float d = 0;
704 for (size_t i = k + fastN; i < n; i++) {
705 d += x[i] * x[i - k];
706 }
707 ac[k] += d;
708 }
709}
710
711
712void RNNoiseProcess::PitchXCorr(
713 const vec1D32F& x,
714 const vec1D32F& y,
George Gekova2b0fc22021-11-08 16:30:43 +0000715 vec1D32F& xCorr,
Richard Burton00553462021-11-10 16:27:14 +0000716 size_t len,
717 size_t maxPitch)
718{
719 for (size_t i = 0; i < maxPitch; i++) {
720 float sum = 0;
721 for (size_t j = 0; j < len; j++) {
722 sum += x[j] * y[i + j];
723 }
George Gekova2b0fc22021-11-08 16:30:43 +0000724 xCorr[i] = sum;
Richard Burton00553462021-11-10 16:27:14 +0000725 }
726}
727
728/* Linear predictor coefficients */
729void RNNoiseProcess::LPC(
George Gekova2b0fc22021-11-08 16:30:43 +0000730 const vec1D32F& correlation,
Richard Burton00553462021-11-10 16:27:14 +0000731 int32_t p,
732 vec1D32F& lpc)
733{
George Gekova2b0fc22021-11-08 16:30:43 +0000734 auto error = correlation[0];
Richard Burton00553462021-11-10 16:27:14 +0000735
736 if (error != 0) {
737 for (int i = 0; i < p; i++) {
738
739 /* Sum up this iteration's reflection coefficient */
740 float rr = 0;
741 for (int j = 0; j < i; j++) {
George Gekova2b0fc22021-11-08 16:30:43 +0000742 rr += lpc[j] * correlation[i - j];
Richard Burton00553462021-11-10 16:27:14 +0000743 }
744
George Gekova2b0fc22021-11-08 16:30:43 +0000745 rr += correlation[i + 1];
Richard Burton00553462021-11-10 16:27:14 +0000746 auto r = -rr / error;
747
748 /* Update LP coefficients and total error */
749 lpc[i] = r;
750 for (int j = 0; j < ((i + 1) >> 1); j++) {
751 auto tmp1 = lpc[j];
752 auto tmp2 = lpc[i - 1 - j];
753 lpc[j] = tmp1 + (r * tmp2);
754 lpc[i - 1 - j] = tmp2 + (r * tmp1);
755 }
756
757 error = error - (r * r * error);
758
759 /* Bail out once we get 30dB gain */
George Gekova2b0fc22021-11-08 16:30:43 +0000760 if (error < (0.001 * correlation[0])) {
Richard Burton00553462021-11-10 16:27:14 +0000761 break;
762 }
763 }
764 }
765}
766
767void RNNoiseProcess::Fir5(
768 const vec1D32F &num,
769 uint32_t N,
770 vec1D32F &x)
771{
772 auto num0 = num[0];
773 auto num1 = num[1];
774 auto num2 = num[2];
775 auto num3 = num[3];
776 auto num4 = num[4];
777 auto mem0 = 0;
778 auto mem1 = 0;
779 auto mem2 = 0;
780 auto mem3 = 0;
781 auto mem4 = 0;
782 for (uint32_t i = 0; i < N; i++)
783 {
784 auto sum_ = x[i] + (num0 * mem0) + (num1 * mem1) +
785 (num2 * mem2) + (num3 * mem3) + (num4 * mem4);
786 mem4 = mem3;
787 mem3 = mem2;
788 mem2 = mem1;
789 mem1 = mem0;
790 mem0 = x[i];
791 x[i] = sum_;
792 }
793}
794
George Gekova2b0fc22021-11-08 16:30:43 +0000795void RNNoiseProcess::PitchFilter(FrameFeatures &features, vec1D32F &gain) {
Richard Burton00553462021-11-10 16:27:14 +0000796 std::vector<float> r(NB_BANDS, 0);
797 std::vector<float> rf(FREQ_SIZE, 0);
798 std::vector<float> newE(NB_BANDS);
799
800 for (size_t i = 0; i < NB_BANDS; i++) {
George Gekova2b0fc22021-11-08 16:30:43 +0000801 if (features.m_Exp[i] > gain[i]) {
Richard Burton00553462021-11-10 16:27:14 +0000802 r[i] = 1;
803 } else {
804
805
George Gekova2b0fc22021-11-08 16:30:43 +0000806 r[i] = std::pow(features.m_Exp[i], 2) * (1 - std::pow(gain[i], 2)) /
807 (.001 + std::pow(gain[i], 2) * (1 - std::pow(features.m_Exp[i], 2)));
Richard Burton00553462021-11-10 16:27:14 +0000808 }
809
810
811 r[i] = math::MathUtils::SqrtF32(std::min(1.0f, std::max(0.0f, r[i])));
812 r[i] *= math::MathUtils::SqrtF32(features.m_Ex[i] / (1e-8f + features.m_Ep[i]));
813 }
814
815 InterpBandGain(rf, r);
816 for (size_t i = 0; i < FREQ_SIZE - 1; i++) {
817 features.m_fftX[2 * i] += rf[i] * features.m_fftP[2 * i]; /* Real. */
818 features.m_fftX[2 * i + 1] += rf[i] * features.m_fftP[2 * i + 1]; /* Imaginary. */
819
820 }
821 ComputeBandEnergy(features.m_fftX, newE);
822 std::vector<float> norm(NB_BANDS);
823 std::vector<float> normf(FRAME_SIZE, 0);
824 for (size_t i = 0; i < NB_BANDS; i++) {
825 norm[i] = math::MathUtils::SqrtF32(features.m_Ex[i] / (1e-8f + newE[i]));
826 }
827
828 InterpBandGain(normf, norm);
829 for (size_t i = 0; i < FREQ_SIZE - 1; i++) {
830 features.m_fftX[2 * i] *= normf[i]; /* Real. */
831 features.m_fftX[2 * i + 1] *= normf[i]; /* Imaginary. */
832
833 }
834}
835
836void RNNoiseProcess::FrameSynthesis(vec1D32F& outFrame, vec1D32F& fftY) {
837 std::vector<float> x(WINDOW_SIZE, 0);
838 InverseTransform(x, fftY);
839 ApplyWindow(x);
840 for (size_t i = 0; i < FRAME_SIZE; i++) {
841 outFrame[i] = x[i] + m_synthesisMem[i];
842 }
843 memcpy((m_synthesisMem.data()), &x[FRAME_SIZE], FRAME_SIZE*sizeof(float));
844}
845
846void RNNoiseProcess::InterpBandGain(vec1D32F& g, vec1D32F& bandE) {
847 for (size_t i = 0; i < NB_BANDS - 1; i++) {
848 int bandSize = (m_eband5ms[i + 1] - m_eband5ms[i]) << FRAME_SIZE_SHIFT;
849 for (int j = 0; j < bandSize; j++) {
850 float frac = static_cast<float>(j) / bandSize;
851 g[(m_eband5ms[i] << FRAME_SIZE_SHIFT) + j] = (1 - frac) * bandE[i] + frac * bandE[i + 1];
852 }
853 }
854}
855
856void RNNoiseProcess::InverseTransform(vec1D32F& out, vec1D32F& fftXIn) {
857
858 std::vector<float> x(WINDOW_SIZE * 2); /* This is complex. */
859 vec1D32F newFFT; /* This is complex. */
860
861 size_t i;
862 for (i = 0; i < FREQ_SIZE * 2; i++) {
863 x[i] = fftXIn[i];
864 }
865 for (i = FREQ_SIZE; i < WINDOW_SIZE; i++) {
866 x[2 * i] = x[2 * (WINDOW_SIZE - i)]; /* Real. */
867 x[2 * i + 1] = -x[2 * (WINDOW_SIZE - i) + 1]; /* Imaginary. */
868 }
869
870 constexpr uint32_t numFFt = 2 * FRAME_SIZE;
871 static_assert(numFFt != 0);
872
873 vec1D32F fftOut = vec1D32F(x.size(), 0);
874 math::MathUtils::FftF32(x,fftOut, m_fftInstCmplx);
875
876 /* Normalize. */
877 for (auto &f: fftOut) {
878 f /= numFFt;
879 }
880
881 out[0] = WINDOW_SIZE * fftOut[0]; /* Real. */
882 for (i = 1; i < WINDOW_SIZE; i++) {
883 out[i] = WINDOW_SIZE * fftOut[(WINDOW_SIZE * 2) - (2 * i)]; /* Real. */
884 }
885}
886
887
888} /* namespace rnn */
889} /* namespace app */
890} /* namspace arm */