audio_effect_pitch_shift.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /*************************************************************************/
  2. /* audio_effect_pitch_shift.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "audio_effect_pitch_shift.h"
  31. #include "core/math/math_funcs.h"
  32. #include "servers/audio_server.h"
  33. /* Thirdparty code, so disable clang-format with Godot style */
  34. /* clang-format off */
  35. /****************************************************************************
  36. *
  37. * NAME: smbPitchShift.cpp
  38. * VERSION: 1.2
  39. * HOME URL: http://blogs.zynaptiq.com/bernsee
  40. * KNOWN BUGS: none
  41. *
  42. * SYNOPSIS: Routine for doing pitch shifting while maintaining
  43. * duration using the Short Time Fourier Transform.
  44. *
  45. * DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
  46. * (one octave down) and 2. (one octave up). A value of exactly 1 does not change
  47. * the pitch. numSampsToProcess tells the routine how many samples in indata[0...
  48. * numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...
  49. * numSampsToProcess-1]. The two buffers can be identical (ie. it can process the
  50. * data in-place). fftFrameSize defines the FFT frame size used for the
  51. * processing. Typical values are 1024, 2048 and 4096. It may be any value <=
  52. * MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT
  53. * oversampling factor which also determines the overlap between adjacent STFT
  54. * frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
  55. * recommended for best quality. sampleRate takes the sample rate for the signal
  56. * in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
  57. * indata[] should be in the range [-1.0, 1.0), which is also the output range
  58. * for the data, make sure you scale the data accordingly (for 16bit signed integers
  59. * you would have to divide (and multiply) by 32768).
  60. *
  61. * COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
  62. *
  63. * The Wide Open License (WOL)
  64. *
  65. * Permission to use, copy, modify, distribute and sell this software and its
  66. * documentation for any purpose is hereby granted without fee, provided that
  67. * the above copyright notice and this license appear in all source copies.
  68. * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
  69. * ANY KIND. See https://dspguru.com/wide-open-license/ for more information.
  70. *
  71. *****************************************************************************/
  72. void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long fftFrameSize, long osamp, float sampleRate, float *indata, float *outdata,int stride) {
  73. /*
  74. Routine smbPitchShift(). See top of file for explanation
  75. Purpose: doing pitch shifting while maintaining duration using the Short
  76. Time Fourier Transform.
  77. Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
  78. */
  79. double magn, phase, tmp, window, real, imag;
  80. double freqPerBin, expct;
  81. long i,k, qpd, index, inFifoLatency, stepSize, fftFrameSize2;
  82. /* set up some handy variables */
  83. fftFrameSize2 = fftFrameSize/2;
  84. stepSize = fftFrameSize/osamp;
  85. freqPerBin = sampleRate/(double)fftFrameSize;
  86. expct = 2.*Math_PI*(double)stepSize/(double)fftFrameSize;
  87. inFifoLatency = fftFrameSize-stepSize;
  88. if (gRover == 0) gRover = inFifoLatency;
  89. /* initialize our static arrays */
  90. /* main processing loop */
  91. for (i = 0; i < numSampsToProcess; i++){
  92. /* As long as we have not yet collected enough data just read in */
  93. gInFIFO[gRover] = indata[i*stride];
  94. outdata[i*stride] = gOutFIFO[gRover-inFifoLatency];
  95. gRover++;
  96. /* now we have enough data for processing */
  97. if (gRover >= fftFrameSize) {
  98. gRover = inFifoLatency;
  99. /* do windowing and re,im interleave */
  100. for (k = 0; k < fftFrameSize;k++) {
  101. window = -.5*cos(2.*Math_PI*(double)k/(double)fftFrameSize)+.5;
  102. gFFTworksp[2*k] = gInFIFO[k] * window;
  103. gFFTworksp[2*k+1] = 0.;
  104. }
  105. /* ***************** ANALYSIS ******************* */
  106. /* do transform */
  107. smbFft(gFFTworksp, fftFrameSize, -1);
  108. /* this is the analysis step */
  109. for (k = 0; k <= fftFrameSize2; k++) {
  110. /* de-interlace FFT buffer */
  111. real = gFFTworksp[2*k];
  112. imag = gFFTworksp[2*k+1];
  113. /* compute magnitude and phase */
  114. magn = 2.*sqrt(real*real + imag*imag);
  115. phase = atan2(imag,real);
  116. /* compute phase difference */
  117. tmp = phase - gLastPhase[k];
  118. gLastPhase[k] = phase;
  119. /* subtract expected phase difference */
  120. tmp -= (double)k*expct;
  121. /* map delta phase into +/- Pi interval */
  122. qpd = tmp/Math_PI;
  123. if (qpd >= 0) qpd += qpd&1;
  124. else qpd -= qpd&1;
  125. tmp -= Math_PI*(double)qpd;
  126. /* get deviation from bin frequency from the +/- Pi interval */
  127. tmp = osamp*tmp/(2.*Math_PI);
  128. /* compute the k-th partials' true frequency */
  129. tmp = (double)k*freqPerBin + tmp*freqPerBin;
  130. /* store magnitude and true frequency in analysis arrays */
  131. gAnaMagn[k] = magn;
  132. gAnaFreq[k] = tmp;
  133. }
  134. /* ***************** PROCESSING ******************* */
  135. /* this does the actual pitch shifting */
  136. memset(gSynMagn, 0, fftFrameSize*sizeof(float));
  137. memset(gSynFreq, 0, fftFrameSize*sizeof(float));
  138. for (k = 0; k <= fftFrameSize2; k++) {
  139. index = k*pitchShift;
  140. if (index <= fftFrameSize2) {
  141. gSynMagn[index] += gAnaMagn[k];
  142. gSynFreq[index] = gAnaFreq[k] * pitchShift;
  143. }
  144. }
  145. /* ***************** SYNTHESIS ******************* */
  146. /* this is the synthesis step */
  147. for (k = 0; k <= fftFrameSize2; k++) {
  148. /* get magnitude and true frequency from synthesis arrays */
  149. magn = gSynMagn[k];
  150. tmp = gSynFreq[k];
  151. /* subtract bin mid frequency */
  152. tmp -= (double)k*freqPerBin;
  153. /* get bin deviation from freq deviation */
  154. tmp /= freqPerBin;
  155. /* take osamp into account */
  156. tmp = 2.*Math_PI*tmp/osamp;
  157. /* add the overlap phase advance back in */
  158. tmp += (double)k*expct;
  159. /* accumulate delta phase to get bin phase */
  160. gSumPhase[k] += tmp;
  161. phase = gSumPhase[k];
  162. /* get real and imag part and re-interleave */
  163. gFFTworksp[2*k] = magn*cos(phase);
  164. gFFTworksp[2*k+1] = magn*sin(phase);
  165. }
  166. /* zero negative frequencies */
  167. for (k = fftFrameSize+2; k < 2*fftFrameSize; k++) gFFTworksp[k] = 0.;
  168. /* do inverse transform */
  169. smbFft(gFFTworksp, fftFrameSize, 1);
  170. /* do windowing and add to output accumulator */
  171. for(k=0; k < fftFrameSize; k++) {
  172. window = -.5*cos(2.*Math_PI*(double)k/(double)fftFrameSize)+.5;
  173. gOutputAccum[k] += 2.*window*gFFTworksp[2*k]/(fftFrameSize2*osamp);
  174. }
  175. for (k = 0; k < stepSize; k++) gOutFIFO[k] = gOutputAccum[k];
  176. /* shift accumulator */
  177. memmove(gOutputAccum, gOutputAccum+stepSize, fftFrameSize*sizeof(float));
  178. /* move input FIFO */
  179. for (k = 0; k < inFifoLatency; k++) gInFIFO[k] = gInFIFO[k+stepSize];
  180. }
  181. }
  182. }
  183. void SMBPitchShift::smbFft(float *fftBuffer, long fftFrameSize, long sign)
  184. /*
  185. FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)
  186. Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the
  187. time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes
  188. and returns the cosine and sine parts in an interleaved manner, ie.
  189. fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize
  190. must be a power of 2. It expects a complex input signal (see footnote 2),
  191. ie. when working with 'common' audio signals our input signal has to be
  192. passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform
  193. of the frequencies of interest is in fftBuffer[0...fftFrameSize].
  194. */
  195. {
  196. float wr, wi, arg, *p1, *p2, temp;
  197. float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;
  198. long i, bitm, j, le, le2, k;
  199. for (i = 2; i < 2*fftFrameSize-2; i += 2) {
  200. for (bitm = 2, j = 0; bitm < 2*fftFrameSize; bitm <<= 1) {
  201. if (i & bitm) j++;
  202. j <<= 1;
  203. }
  204. if (i < j) {
  205. p1 = fftBuffer+i; p2 = fftBuffer+j;
  206. temp = *p1; *(p1++) = *p2;
  207. *(p2++) = temp; temp = *p1;
  208. *p1 = *p2; *p2 = temp;
  209. }
  210. }
  211. for (k = 0, le = 2; k < (long)(log((double)fftFrameSize)/log(2.)+.5); k++) {
  212. le <<= 1;
  213. le2 = le>>1;
  214. ur = 1.0;
  215. ui = 0.0;
  216. arg = Math_PI / (le2>>1);
  217. wr = cos(arg);
  218. wi = sign*sin(arg);
  219. for (j = 0; j < le2; j += 2) {
  220. p1r = fftBuffer+j; p1i = p1r+1;
  221. p2r = p1r+le2; p2i = p2r+1;
  222. for (i = j; i < 2*fftFrameSize; i += le) {
  223. tr = *p2r * ur - *p2i * ui;
  224. ti = *p2r * ui + *p2i * ur;
  225. *p2r = *p1r - tr; *p2i = *p1i - ti;
  226. *p1r += tr; *p1i += ti;
  227. p1r += le; p1i += le;
  228. p2r += le; p2i += le;
  229. }
  230. tr = ur*wr - ui*wi;
  231. ui = ur*wi + ui*wr;
  232. ur = tr;
  233. }
  234. }
  235. }
  236. /* Godot code again */
  237. /* clang-format on */
  238. void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
  239. float sample_rate = AudioServer::get_singleton()->get_mix_rate();
  240. float *in_l = (float *)p_src_frames;
  241. float *in_r = in_l + 1;
  242. float *out_l = (float *)p_dst_frames;
  243. float *out_r = out_l + 1;
  244. shift_l.PitchShift(base->pitch_scale, p_frame_count, fft_size, base->oversampling, sample_rate, in_l, out_l, 2);
  245. shift_r.PitchShift(base->pitch_scale, p_frame_count, fft_size, base->oversampling, sample_rate, in_r, out_r, 2);
  246. }
  247. Ref<AudioEffectInstance> AudioEffectPitchShift::instance() {
  248. Ref<AudioEffectPitchShiftInstance> ins;
  249. ins.instance();
  250. ins->base = Ref<AudioEffectPitchShift>(this);
  251. static const int fft_sizes[FFT_SIZE_MAX] = { 256, 512, 1024, 2048, 4096 };
  252. ins->fft_size = fft_sizes[fft_size];
  253. return ins;
  254. }
  255. void AudioEffectPitchShift::set_pitch_scale(float p_pitch_scale) {
  256. ERR_FAIL_COND(p_pitch_scale <= 0.0);
  257. pitch_scale = p_pitch_scale;
  258. }
  259. float AudioEffectPitchShift::get_pitch_scale() const {
  260. return pitch_scale;
  261. }
  262. void AudioEffectPitchShift::set_oversampling(int p_oversampling) {
  263. ERR_FAIL_COND(p_oversampling < 4);
  264. oversampling = p_oversampling;
  265. }
  266. int AudioEffectPitchShift::get_oversampling() const {
  267. return oversampling;
  268. }
  269. void AudioEffectPitchShift::set_fft_size(FFT_Size p_fft_size) {
  270. ERR_FAIL_INDEX(p_fft_size, FFT_SIZE_MAX);
  271. fft_size = p_fft_size;
  272. }
  273. AudioEffectPitchShift::FFT_Size AudioEffectPitchShift::get_fft_size() const {
  274. return fft_size;
  275. }
  276. void AudioEffectPitchShift::_bind_methods() {
  277. ClassDB::bind_method(D_METHOD("set_pitch_scale", "rate"), &AudioEffectPitchShift::set_pitch_scale);
  278. ClassDB::bind_method(D_METHOD("get_pitch_scale"), &AudioEffectPitchShift::get_pitch_scale);
  279. ClassDB::bind_method(D_METHOD("set_oversampling", "amount"), &AudioEffectPitchShift::set_oversampling);
  280. ClassDB::bind_method(D_METHOD("get_oversampling"), &AudioEffectPitchShift::get_oversampling);
  281. ClassDB::bind_method(D_METHOD("set_fft_size", "size"), &AudioEffectPitchShift::set_fft_size);
  282. ClassDB::bind_method(D_METHOD("get_fft_size"), &AudioEffectPitchShift::get_fft_size);
  283. ADD_PROPERTY(PropertyInfo(Variant::REAL, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_pitch_scale", "get_pitch_scale");
  284. ADD_PROPERTY(PropertyInfo(Variant::REAL, "oversampling", PROPERTY_HINT_RANGE, "4,32,1"), "set_oversampling", "get_oversampling");
  285. ADD_PROPERTY(PropertyInfo(Variant::INT, "fft_size", PROPERTY_HINT_ENUM, "256,512,1024,2048,4096"), "set_fft_size", "get_fft_size");
  286. BIND_ENUM_CONSTANT(FFT_SIZE_256);
  287. BIND_ENUM_CONSTANT(FFT_SIZE_512);
  288. BIND_ENUM_CONSTANT(FFT_SIZE_1024);
  289. BIND_ENUM_CONSTANT(FFT_SIZE_2048);
  290. BIND_ENUM_CONSTANT(FFT_SIZE_4096);
  291. BIND_ENUM_CONSTANT(FFT_SIZE_MAX);
  292. }
  293. AudioEffectPitchShift::AudioEffectPitchShift() {
  294. pitch_scale = 1.0;
  295. oversampling = 4;
  296. fft_size = FFT_SIZE_2048;
  297. }