Path: blob/master/servers/audio/effects/audio_effect_pitch_shift.cpp
10278 views
/**************************************************************************/1/* audio_effect_pitch_shift.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "audio_effect_pitch_shift.h"3132#include "core/math/math_funcs.h"33#include "servers/audio_server.h"3435/* Thirdparty code, so disable clang-format with Godot style */36/* clang-format off */3738/****************************************************************************39*40* NAME: smbPitchShift.cpp41* VERSION: 1.242* HOME URL: https://blogs.zynaptiq.com/bernsee43* KNOWN BUGS: none44*45* SYNOPSIS: Routine for doing pitch shifting while maintaining46* duration using the Short Time Fourier Transform.47*48* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.549* (one octave down) and 2. (one octave up). A value of exactly 1 does not change50* the pitch. numSampsToProcess tells the routine how many samples in indata[0...51* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...52* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the53* data in-place). fftFrameSize defines the FFT frame size used for the54* processing. Typical values are 1024, 2048 and 4096. It may be any value <=55* MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT56* oversampling factor which also determines the overlap between adjacent STFT57* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is58* recommended for best quality. sampleRate takes the sample rate for the signal59* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in60* indata[] should be in the range [-1.0, 1.0), which is also the output range61* for the data, make sure you scale the data accordingly (for 16bit signed integers62* you would have to divide (and multiply) by 32768).63*64* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>65*66* The Wide Open License (WOL)67*68* Permission to use, copy, modify, distribute and sell this software and its69* documentation for any purpose is hereby granted without fee, provided that70* the above copyright notice and this license appear in all source copies.71* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF72* ANY KIND. See https://dspguru.com/wide-open-license/ for more information.73*74*****************************************************************************/7576void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long fftFrameSize, long osamp, float sampleRate, float *indata, float *outdata,int stride) {777879/*80Routine smbPitchShift(). See top of file for explanation81Purpose: doing pitch shifting while maintaining duration using the Short82Time Fourier Transform.83Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>84*/8586double magn, phase, tmp, window, real, imag;87double freqPerBin, expct;88long i,k, qpd, index, inFifoLatency, stepSize, fftFrameSize2;8990/* set up some handy variables */91fftFrameSize2 = fftFrameSize/2;92stepSize = fftFrameSize/osamp;93freqPerBin = sampleRate/(double)fftFrameSize;94expct = 2.*Math::PI*(double)stepSize/(double)fftFrameSize;95inFifoLatency = fftFrameSize-stepSize;96if (gRover == 0) { gRover = inFifoLatency;97}9899/* initialize our static arrays */100101/* main processing loop */102for (i = 0; i < numSampsToProcess; i++){103/* As long as we have not yet collected enough data just read in */104gInFIFO[gRover] = indata[i*stride];105outdata[i*stride] = gOutFIFO[gRover-inFifoLatency];106gRover++;107108/* now we have enough data for processing */109if (gRover >= fftFrameSize) {110gRover = inFifoLatency;111112/* do windowing and re,im interleave */113for (k = 0; k < fftFrameSize;k++) {114window = -.5*std::cos(2.*Math::PI*(double)k/(double)fftFrameSize)+.5;115gFFTworksp[2*k] = gInFIFO[k] * window;116gFFTworksp[2*k+1] = 0.;117}118119120/* ***************** ANALYSIS ******************* */121/* do transform */122smbFft(gFFTworksp, fftFrameSize, -1);123124/* this is the analysis step */125for (k = 0; k <= fftFrameSize2; k++) {126/* de-interlace FFT buffer */127real = gFFTworksp[2*k];128imag = gFFTworksp[2*k+1];129130/* compute magnitude and phase */131magn = 2.*std::sqrt(real*real + imag*imag);132phase = std::atan2(imag,real);133134/* compute phase difference */135tmp = phase - gLastPhase[k];136gLastPhase[k] = phase;137138/* subtract expected phase difference */139tmp -= (double)k*expct;140141/* map delta phase into +/- Pi interval */142qpd = tmp/Math::PI;143if (qpd >= 0) { qpd += qpd&1;144} else { qpd -= qpd&1;145}146tmp -= Math::PI*(double)qpd;147148/* get deviation from bin frequency from the +/- Pi interval */149tmp = osamp*tmp/(2.*Math::PI);150151/* compute the k-th partials' true frequency */152tmp = (double)k*freqPerBin + tmp*freqPerBin;153154/* store magnitude and true frequency in analysis arrays */155gAnaMagn[k] = magn;156gAnaFreq[k] = tmp;157158}159160/* ***************** PROCESSING ******************* */161/* this does the actual pitch shifting */162size_t fftBufferSize = static_cast<size_t>(fftFrameSize) * sizeof(float);163if (unlikely(fftBufferSize > MAX_FRAME_LENGTH)) {164ERR_PRINT_ONCE("Invalid FFT frame size for PitchShift. This is a bug, please report.");165return;166}167memset(gSynMagn, 0, fftBufferSize);168memset(gSynFreq, 0, fftBufferSize);169for (k = 0; k <= fftFrameSize2; k++) {170index = k*pitchShift;171if (index <= fftFrameSize2) {172gSynMagn[index] += gAnaMagn[k];173gSynFreq[index] = gAnaFreq[k] * pitchShift;174}175}176177/* ***************** SYNTHESIS ******************* */178/* this is the synthesis step */179for (k = 0; k <= fftFrameSize2; k++) {180/* get magnitude and true frequency from synthesis arrays */181magn = gSynMagn[k];182tmp = gSynFreq[k];183184/* subtract bin mid frequency */185tmp -= (double)k*freqPerBin;186187/* get bin deviation from freq deviation */188tmp /= freqPerBin;189190/* take osamp into account */191tmp = 2.*Math::PI*tmp/osamp;192193/* add the overlap phase advance back in */194tmp += (double)k*expct;195196/* accumulate delta phase to get bin phase */197gSumPhase[k] += tmp;198phase = gSumPhase[k];199200/* get real and imag part and re-interleave */201gFFTworksp[2*k] = magn*std::cos(phase);202gFFTworksp[2*k+1] = magn*std::sin(phase);203}204205/* zero negative frequencies */206for (k = fftFrameSize+2; k < 2*fftFrameSize; k++) { gFFTworksp[k] = 0.;207}208209/* do inverse transform */210smbFft(gFFTworksp, fftFrameSize, 1);211212/* do windowing and add to output accumulator */213for(k=0; k < fftFrameSize; k++) {214window = -.5*std::cos(2.*Math::PI*(double)k/(double)fftFrameSize)+.5;215gOutputAccum[k] += 2.*window*gFFTworksp[2*k]/(fftFrameSize2*osamp);216}217for (k = 0; k < stepSize; k++) { gOutFIFO[k] = gOutputAccum[k];218}219220/* shift accumulator */221memmove(gOutputAccum, gOutputAccum+stepSize, fftBufferSize);222223/* move input FIFO */224for (k = 0; k < inFifoLatency; k++) { gInFIFO[k] = gInFIFO[k+stepSize];225}226}227}228}229230231232void SMBPitchShift::smbFft(float *fftBuffer, long fftFrameSize, long sign)233/*234FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)235Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the236time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes237and returns the cosine and sine parts in an interleaved manner, ie.238fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize239must be a power of 2. It expects a complex input signal (see footnote 2),240ie. when working with 'common' audio signals our input signal has to be241passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform242of the frequencies of interest is in fftBuffer[0...fftFrameSize].243*/244{245float wr, wi, arg, *p1, *p2, temp;246float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;247long i, bitm, j, le, le2, k;248249for (i = 2; i < 2*fftFrameSize-2; i += 2) {250for (bitm = 2, j = 0; bitm < 2*fftFrameSize; bitm <<= 1) {251if (i & bitm) { j++;252}253j <<= 1;254}255if (i < j) {256p1 = fftBuffer+i; p2 = fftBuffer+j;257temp = *p1; *(p1++) = *p2;258*(p2++) = temp; temp = *p1;259*p1 = *p2; *p2 = temp;260}261}262for (k = 0, le = 2; k < (long)(std::log((double)fftFrameSize)/std::log(2.)+.5); k++) {263le <<= 1;264le2 = le>>1;265ur = 1.0;266ui = 0.0;267arg = Math::PI / (le2>>1);268wr = std::cos(arg);269wi = sign*std::sin(arg);270for (j = 0; j < le2; j += 2) {271p1r = fftBuffer+j; p1i = p1r+1;272p2r = p1r+le2; p2i = p2r+1;273for (i = j; i < 2*fftFrameSize; i += le) {274tr = *p2r * ur - *p2i * ui;275ti = *p2r * ui + *p2i * ur;276*p2r = *p1r - tr; *p2i = *p1i - ti;277*p1r += tr; *p1i += ti;278p1r += le; p1i += le;279p2r += le; p2i += le;280}281tr = ur*wr - ui*wi;282ui = ur*wi + ui*wr;283ur = tr;284}285}286}287288289/* Godot code again */290/* clang-format on */291292void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {293// Avoid distortion by skipping processing if pitch_scale is 1.0.294if (Math::is_equal_approx(base->pitch_scale, 1.0f)) {295for (int i = 0; i < p_frame_count; i++) {296p_dst_frames[i] = p_src_frames[i];297}298return;299}300301float sample_rate = AudioServer::get_singleton()->get_mix_rate();302303float *in_l = (float *)p_src_frames;304float *in_r = in_l + 1;305306float *out_l = (float *)p_dst_frames;307float *out_r = out_l + 1;308309shift_l.PitchShift(base->pitch_scale, p_frame_count, fft_size, base->oversampling, sample_rate, in_l, out_l, 2);310shift_r.PitchShift(base->pitch_scale, p_frame_count, fft_size, base->oversampling, sample_rate, in_r, out_r, 2);311}312313Ref<AudioEffectInstance> AudioEffectPitchShift::instantiate() {314Ref<AudioEffectPitchShiftInstance> ins;315ins.instantiate();316ins->base = Ref<AudioEffectPitchShift>(this);317static const int fft_sizes[FFT_SIZE_MAX] = { 256, 512, 1024, 2048, 4096 };318ins->fft_size = fft_sizes[fft_size];319320return ins;321}322323void AudioEffectPitchShift::set_pitch_scale(float p_pitch_scale) {324ERR_FAIL_COND(!(p_pitch_scale > 0.0));325pitch_scale = p_pitch_scale;326}327328float AudioEffectPitchShift::get_pitch_scale() const {329return pitch_scale;330}331332void AudioEffectPitchShift::set_oversampling(int p_oversampling) {333ERR_FAIL_COND(p_oversampling < 4);334oversampling = p_oversampling;335}336337int AudioEffectPitchShift::get_oversampling() const {338return oversampling;339}340341void AudioEffectPitchShift::set_fft_size(FFTSize p_fft_size) {342ERR_FAIL_INDEX(p_fft_size, FFT_SIZE_MAX);343fft_size = p_fft_size;344}345346AudioEffectPitchShift::FFTSize AudioEffectPitchShift::get_fft_size() const {347return fft_size;348}349350void AudioEffectPitchShift::_bind_methods() {351ClassDB::bind_method(D_METHOD("set_pitch_scale", "rate"), &AudioEffectPitchShift::set_pitch_scale);352ClassDB::bind_method(D_METHOD("get_pitch_scale"), &AudioEffectPitchShift::get_pitch_scale);353354ClassDB::bind_method(D_METHOD("set_oversampling", "amount"), &AudioEffectPitchShift::set_oversampling);355ClassDB::bind_method(D_METHOD("get_oversampling"), &AudioEffectPitchShift::get_oversampling);356357ClassDB::bind_method(D_METHOD("set_fft_size", "size"), &AudioEffectPitchShift::set_fft_size);358ClassDB::bind_method(D_METHOD("get_fft_size"), &AudioEffectPitchShift::get_fft_size);359360ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_pitch_scale", "get_pitch_scale");361ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "oversampling", PROPERTY_HINT_RANGE, "4,32,1"), "set_oversampling", "get_oversampling");362ADD_PROPERTY(PropertyInfo(Variant::INT, "fft_size", PROPERTY_HINT_ENUM, "256,512,1024,2048,4096"), "set_fft_size", "get_fft_size");363364BIND_ENUM_CONSTANT(FFT_SIZE_256);365BIND_ENUM_CONSTANT(FFT_SIZE_512);366BIND_ENUM_CONSTANT(FFT_SIZE_1024);367BIND_ENUM_CONSTANT(FFT_SIZE_2048);368BIND_ENUM_CONSTANT(FFT_SIZE_4096);369BIND_ENUM_CONSTANT(FFT_SIZE_MAX);370}371372373