pshifter.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2018 by Raul Herraiz.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include <math.h>
  22. #include <stdlib.h>
  23. #include "alMain.h"
  24. #include "alAuxEffectSlot.h"
  25. #include "alError.h"
  26. #include "alu.h"
  27. #include "filters/defs.h"
  28. #define STFT_SIZE 1024
  29. #define STFT_HALF_SIZE (STFT_SIZE>>1)
  30. #define OVERSAMP (1<<2)
  31. #define STFT_STEP (STFT_SIZE / OVERSAMP)
  32. #define FIFO_LATENCY (STFT_STEP * (OVERSAMP-1))
  33. typedef struct ALcomplex {
  34. ALfloat Real;
  35. ALfloat Imag;
  36. } ALcomplex;
  37. typedef struct ALphasor {
  38. ALfloat Amplitude;
  39. ALfloat Phase;
  40. } ALphasor;
  41. typedef struct ALFrequencyDomain {
  42. ALfloat Amplitude;
  43. ALfloat Frequency;
  44. } ALfrequencyDomain;
  45. typedef struct ALpshifterState {
  46. DERIVE_FROM_TYPE(ALeffectState);
  47. /* Effect parameters */
  48. ALsizei count;
  49. ALfloat PitchShift;
  50. ALfloat FreqPerBin;
  51. /*Effects buffers*/
  52. ALfloat InFIFO[STFT_SIZE];
  53. ALfloat OutFIFO[STFT_STEP];
  54. ALfloat LastPhase[STFT_HALF_SIZE+1];
  55. ALfloat SumPhase[STFT_HALF_SIZE+1];
  56. ALfloat OutputAccum[STFT_SIZE];
  57. ALcomplex FFTbuffer[STFT_SIZE];
  58. ALfrequencyDomain Analysis_buffer[STFT_HALF_SIZE+1];
  59. ALfrequencyDomain Syntesis_buffer[STFT_HALF_SIZE+1];
  60. alignas(16) ALfloat BufferOut[BUFFERSIZE];
  61. /* Effect gains for each output channel */
  62. ALfloat CurrentGains[MAX_OUTPUT_CHANNELS];
  63. ALfloat TargetGains[MAX_OUTPUT_CHANNELS];
  64. } ALpshifterState;
  65. static ALvoid ALpshifterState_Destruct(ALpshifterState *state);
  66. static ALboolean ALpshifterState_deviceUpdate(ALpshifterState *state, ALCdevice *device);
  67. static ALvoid ALpshifterState_update(ALpshifterState *state, const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props);
  68. static ALvoid ALpshifterState_process(ALpshifterState *state, ALsizei SamplesToDo, const ALfloat (*restrict SamplesIn)[BUFFERSIZE], ALfloat (*restrict SamplesOut)[BUFFERSIZE], ALsizei NumChannels);
  69. DECLARE_DEFAULT_ALLOCATORS(ALpshifterState)
  70. DEFINE_ALEFFECTSTATE_VTABLE(ALpshifterState);
  71. /* Define a Hann window, used to filter the STFT input and output. */
  72. alignas(16) static ALfloat HannWindow[STFT_SIZE];
  73. static void InitHannWindow(void)
  74. {
  75. ALsizei i;
  76. /* Create lookup table of the Hann window for the desired size, i.e. STFT_SIZE */
  77. for(i = 0;i < STFT_SIZE>>1;i++)
  78. {
  79. ALdouble val = sin(M_PI * (ALdouble)i / (ALdouble)(STFT_SIZE-1));
  80. HannWindow[i] = HannWindow[STFT_SIZE-(i+1)] = (ALfloat)(val * val);
  81. }
  82. }
  83. static alonce_flag HannInitOnce = AL_ONCE_FLAG_INIT;
  84. /* Converts ALcomplex to ALphasor */
  85. static inline ALphasor rect2polar(ALcomplex number)
  86. {
  87. ALphasor polar;
  88. polar.Amplitude = sqrtf(number.Real*number.Real + number.Imag*number.Imag);
  89. polar.Phase = atan2f(number.Imag , number.Real);
  90. return polar;
  91. }
  92. /* Converts ALphasor to ALcomplex */
  93. static inline ALcomplex polar2rect(ALphasor number)
  94. {
  95. ALcomplex cartesian;
  96. cartesian.Real = number.Amplitude * cosf(number.Phase);
  97. cartesian.Imag = number.Amplitude * sinf(number.Phase);
  98. return cartesian;
  99. }
  100. /* Addition of two complex numbers (ALcomplex format) */
  101. static inline ALcomplex complex_add(ALcomplex a, ALcomplex b)
  102. {
  103. ALcomplex result;
  104. result.Real = a.Real + b.Real;
  105. result.Imag = a.Imag + b.Imag;
  106. return result;
  107. }
  108. /* Subtraction of two complex numbers (ALcomplex format) */
  109. static inline ALcomplex complex_sub(ALcomplex a, ALcomplex b)
  110. {
  111. ALcomplex result;
  112. result.Real = a.Real - b.Real;
  113. result.Imag = a.Imag - b.Imag;
  114. return result;
  115. }
  116. /* Multiplication of two complex numbers (ALcomplex format) */
  117. static inline ALcomplex complex_mult(ALcomplex a, ALcomplex b)
  118. {
  119. ALcomplex result;
  120. result.Real = a.Real*b.Real - a.Imag*b.Imag;
  121. result.Imag = a.Imag*b.Real + a.Real*b.Imag;
  122. return result;
  123. }
  124. /* Iterative implementation of 2-radix FFT (In-place algorithm). Sign = -1 is
  125. * FFT and 1 is iFFT (inverse). Fills FFTBuffer[0...FFTSize-1] with the
  126. * Discrete Fourier Transform (DFT) of the time domain data stored in
  127. * FFTBuffer[0...FFTSize-1]. FFTBuffer is an array of complex numbers
  128. * (ALcomplex), FFTSize MUST BE power of two.
  129. */
  130. static inline ALvoid FFT(ALcomplex *FFTBuffer, ALsizei FFTSize, ALfloat Sign)
  131. {
  132. ALsizei i, j, k, mask, step, step2;
  133. ALcomplex temp, u, w;
  134. ALfloat arg;
  135. /* Bit-reversal permutation applied to a sequence of FFTSize items */
  136. for(i = 1;i < FFTSize-1;i++)
  137. {
  138. for(mask = 0x1, j = 0;mask < FFTSize;mask <<= 1)
  139. {
  140. if((i&mask) != 0)
  141. j++;
  142. j <<= 1;
  143. }
  144. j >>= 1;
  145. if(i < j)
  146. {
  147. temp = FFTBuffer[i];
  148. FFTBuffer[i] = FFTBuffer[j];
  149. FFTBuffer[j] = temp;
  150. }
  151. }
  152. /* Iterative form of Danielson–Lanczos lemma */
  153. for(i = 1, step = 2;i < FFTSize;i<<=1, step<<=1)
  154. {
  155. step2 = step >> 1;
  156. arg = F_PI / step2;
  157. w.Real = cosf(arg);
  158. w.Imag = sinf(arg) * Sign;
  159. u.Real = 1.0f;
  160. u.Imag = 0.0f;
  161. for(j = 0;j < step2;j++)
  162. {
  163. for(k = j;k < FFTSize;k+=step)
  164. {
  165. temp = complex_mult(FFTBuffer[k+step2], u);
  166. FFTBuffer[k+step2] = complex_sub(FFTBuffer[k], temp);
  167. FFTBuffer[k] = complex_add(FFTBuffer[k], temp);
  168. }
  169. u = complex_mult(u, w);
  170. }
  171. }
  172. }
  173. static void ALpshifterState_Construct(ALpshifterState *state)
  174. {
  175. ALeffectState_Construct(STATIC_CAST(ALeffectState, state));
  176. SET_VTABLE2(ALpshifterState, ALeffectState, state);
  177. alcall_once(&HannInitOnce, InitHannWindow);
  178. }
  179. static ALvoid ALpshifterState_Destruct(ALpshifterState *state)
  180. {
  181. ALeffectState_Destruct(STATIC_CAST(ALeffectState,state));
  182. }
  183. static ALboolean ALpshifterState_deviceUpdate(ALpshifterState *state, ALCdevice *device)
  184. {
  185. /* (Re-)initializing parameters and clear the buffers. */
  186. state->count = FIFO_LATENCY;
  187. state->PitchShift = 1.0f;
  188. state->FreqPerBin = device->Frequency / (ALfloat)STFT_SIZE;
  189. memset(state->InFIFO, 0, sizeof(state->InFIFO));
  190. memset(state->OutFIFO, 0, sizeof(state->OutFIFO));
  191. memset(state->FFTbuffer, 0, sizeof(state->FFTbuffer));
  192. memset(state->LastPhase, 0, sizeof(state->LastPhase));
  193. memset(state->SumPhase, 0, sizeof(state->SumPhase));
  194. memset(state->OutputAccum, 0, sizeof(state->OutputAccum));
  195. memset(state->Analysis_buffer, 0, sizeof(state->Analysis_buffer));
  196. memset(state->Syntesis_buffer, 0, sizeof(state->Syntesis_buffer));
  197. memset(state->CurrentGains, 0, sizeof(state->CurrentGains));
  198. memset(state->TargetGains, 0, sizeof(state->TargetGains));
  199. return AL_TRUE;
  200. }
  201. static ALvoid ALpshifterState_update(ALpshifterState *state, const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props)
  202. {
  203. const ALCdevice *device = context->Device;
  204. ALfloat coeffs[MAX_AMBI_COEFFS];
  205. state->PitchShift = powf(2.0f,
  206. (ALfloat)(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f
  207. );
  208. CalcAngleCoeffs(0.0f, 0.0f, 0.0f, coeffs);
  209. ComputeDryPanGains(&device->Dry, coeffs, slot->Params.Gain, state->TargetGains);
  210. }
  211. static ALvoid ALpshifterState_process(ALpshifterState *state, ALsizei SamplesToDo, const ALfloat (*restrict SamplesIn)[BUFFERSIZE], ALfloat (*restrict SamplesOut)[BUFFERSIZE], ALsizei NumChannels)
  212. {
  213. /* Pitch shifter engine based on the work of Stephan Bernsee.
  214. * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/
  215. */
  216. static const ALfloat expected = F_TAU / (ALfloat)OVERSAMP;
  217. const ALfloat freq_per_bin = state->FreqPerBin;
  218. ALfloat *restrict bufferOut = state->BufferOut;
  219. ALsizei count = state->count;
  220. ALsizei i, j, k;
  221. for(i = 0;i < SamplesToDo;)
  222. {
  223. do {
  224. /* Fill FIFO buffer with samples data */
  225. state->InFIFO[count] = SamplesIn[0][i];
  226. bufferOut[i] = state->OutFIFO[count - FIFO_LATENCY];
  227. count++;
  228. } while(++i < SamplesToDo && count < STFT_SIZE);
  229. /* Check whether FIFO buffer is filled */
  230. if(count < STFT_SIZE) break;
  231. count = FIFO_LATENCY;
  232. /* Real signal windowing and store in FFTbuffer */
  233. for(k = 0;k < STFT_SIZE;k++)
  234. {
  235. state->FFTbuffer[k].Real = state->InFIFO[k] * HannWindow[k];
  236. state->FFTbuffer[k].Imag = 0.0f;
  237. }
  238. /* ANALYSIS */
  239. /* Apply FFT to FFTbuffer data */
  240. FFT(state->FFTbuffer, STFT_SIZE, -1.0f);
  241. /* Analyze the obtained data. Since the real FFT is symmetric, only
  242. * STFT_HALF_SIZE+1 samples are needed.
  243. */
  244. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  245. {
  246. ALphasor component;
  247. ALfloat tmp;
  248. ALint qpd;
  249. /* Compute amplitude and phase */
  250. component = rect2polar(state->FFTbuffer[k]);
  251. /* Compute phase difference and subtract expected phase difference */
  252. tmp = (component.Phase - state->LastPhase[k]) - (ALfloat)k*expected;
  253. /* Map delta phase into +/- Pi interval */
  254. qpd = fastf2i(tmp / F_PI);
  255. tmp -= F_PI * (ALfloat)(qpd + (qpd%2));
  256. /* Get deviation from bin frequency from the +/- Pi interval */
  257. tmp /= expected;
  258. /* Compute the k-th partials' true frequency, twice the amplitude
  259. * for maintain the gain (because half of bins are used) and store
  260. * amplitude and true frequency in analysis buffer.
  261. */
  262. state->Analysis_buffer[k].Amplitude = 2.0f * component.Amplitude;
  263. state->Analysis_buffer[k].Frequency = ((ALfloat)k + tmp) * freq_per_bin;
  264. /* Store actual phase[k] for the calculations in the next frame*/
  265. state->LastPhase[k] = component.Phase;
  266. }
  267. /* PROCESSING */
  268. /* pitch shifting */
  269. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  270. {
  271. state->Syntesis_buffer[k].Amplitude = 0.0f;
  272. state->Syntesis_buffer[k].Frequency = 0.0f;
  273. }
  274. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  275. {
  276. j = fastf2i((ALfloat)k * state->PitchShift);
  277. if(j >= STFT_HALF_SIZE+1) break;
  278. state->Syntesis_buffer[j].Amplitude += state->Analysis_buffer[k].Amplitude;
  279. state->Syntesis_buffer[j].Frequency = state->Analysis_buffer[k].Frequency *
  280. state->PitchShift;
  281. }
  282. /* SYNTHESIS */
  283. /* Synthesis the processing data */
  284. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  285. {
  286. ALphasor component;
  287. ALfloat tmp;
  288. /* Compute bin deviation from scaled freq */
  289. tmp = state->Syntesis_buffer[k].Frequency/freq_per_bin - (ALfloat)k;
  290. /* Calculate actual delta phase and accumulate it to get bin phase */
  291. state->SumPhase[k] += ((ALfloat)k + tmp) * expected;
  292. component.Amplitude = state->Syntesis_buffer[k].Amplitude;
  293. component.Phase = state->SumPhase[k];
  294. /* Compute phasor component to cartesian complex number and storage it into FFTbuffer*/
  295. state->FFTbuffer[k] = polar2rect(component);
  296. }
  297. /* zero negative frequencies for recontruct a real signal */
  298. for(k = STFT_HALF_SIZE+1;k < STFT_SIZE;k++)
  299. {
  300. state->FFTbuffer[k].Real = 0.0f;
  301. state->FFTbuffer[k].Imag = 0.0f;
  302. }
  303. /* Apply iFFT to buffer data */
  304. FFT(state->FFTbuffer, STFT_SIZE, 1.0f);
  305. /* Windowing and add to output */
  306. for(k = 0;k < STFT_SIZE;k++)
  307. state->OutputAccum[k] += HannWindow[k] * state->FFTbuffer[k].Real /
  308. (0.5f * STFT_HALF_SIZE * OVERSAMP);
  309. /* Shift accumulator, input & output FIFO */
  310. for(k = 0;k < STFT_STEP;k++) state->OutFIFO[k] = state->OutputAccum[k];
  311. for(j = 0;k < STFT_SIZE;k++,j++) state->OutputAccum[j] = state->OutputAccum[k];
  312. for(;j < STFT_SIZE;j++) state->OutputAccum[j] = 0.0f;
  313. for(k = 0;k < FIFO_LATENCY;k++)
  314. state->InFIFO[k] = state->InFIFO[k+STFT_STEP];
  315. }
  316. state->count = count;
  317. /* Now, mix the processed sound data to the output. */
  318. MixSamples(bufferOut, NumChannels, SamplesOut, state->CurrentGains, state->TargetGains,
  319. maxi(SamplesToDo, 512), 0, SamplesToDo);
  320. }
  321. typedef struct PshifterStateFactory {
  322. DERIVE_FROM_TYPE(EffectStateFactory);
  323. } PshifterStateFactory;
  324. static ALeffectState *PshifterStateFactory_create(PshifterStateFactory *UNUSED(factory))
  325. {
  326. ALpshifterState *state;
  327. NEW_OBJ0(state, ALpshifterState)();
  328. if(!state) return NULL;
  329. return STATIC_CAST(ALeffectState, state);
  330. }
  331. DEFINE_EFFECTSTATEFACTORY_VTABLE(PshifterStateFactory);
  332. EffectStateFactory *PshifterStateFactory_getFactory(void)
  333. {
  334. static PshifterStateFactory PshifterFactory = { { GET_VTABLE2(PshifterStateFactory, EffectStateFactory) } };
  335. return STATIC_CAST(EffectStateFactory, &PshifterFactory);
  336. }
  337. void ALpshifter_setParamf(ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat UNUSED(val))
  338. {
  339. alSetError( context, AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param );
  340. }
  341. void ALpshifter_setParamfv(ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, const ALfloat *UNUSED(vals))
  342. {
  343. alSetError( context, AL_INVALID_ENUM, "Invalid pitch shifter float-vector property 0x%04x", param );
  344. }
  345. void ALpshifter_setParami(ALeffect *effect, ALCcontext *context, ALenum param, ALint val)
  346. {
  347. ALeffectProps *props = &effect->Props;
  348. switch(param)
  349. {
  350. case AL_PITCH_SHIFTER_COARSE_TUNE:
  351. if(!(val >= AL_PITCH_SHIFTER_MIN_COARSE_TUNE && val <= AL_PITCH_SHIFTER_MAX_COARSE_TUNE))
  352. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter coarse tune out of range");
  353. props->Pshifter.CoarseTune = val;
  354. break;
  355. case AL_PITCH_SHIFTER_FINE_TUNE:
  356. if(!(val >= AL_PITCH_SHIFTER_MIN_FINE_TUNE && val <= AL_PITCH_SHIFTER_MAX_FINE_TUNE))
  357. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter fine tune out of range");
  358. props->Pshifter.FineTune = val;
  359. break;
  360. default:
  361. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", param);
  362. }
  363. }
  364. void ALpshifter_setParamiv(ALeffect *effect, ALCcontext *context, ALenum param, const ALint *vals)
  365. {
  366. ALpshifter_setParami(effect, context, param, vals[0]);
  367. }
  368. void ALpshifter_getParami(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *val)
  369. {
  370. const ALeffectProps *props = &effect->Props;
  371. switch(param)
  372. {
  373. case AL_PITCH_SHIFTER_COARSE_TUNE:
  374. *val = (ALint)props->Pshifter.CoarseTune;
  375. break;
  376. case AL_PITCH_SHIFTER_FINE_TUNE:
  377. *val = (ALint)props->Pshifter.FineTune;
  378. break;
  379. default:
  380. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", param);
  381. }
  382. }
  383. void ALpshifter_getParamiv(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *vals)
  384. {
  385. ALpshifter_getParami(effect, context, param, vals);
  386. }
  387. void ALpshifter_getParamf(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat *UNUSED(val))
  388. {
  389. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param);
  390. }
  391. void ALpshifter_getParamfv(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat *UNUSED(vals))
  392. {
  393. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter float vector-property 0x%04x", param);
  394. }
  395. DEFINE_ALEFFECT_VTABLE(ALpshifter);