pshifter.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. ALdouble Real;
  35. ALdouble Imag;
  36. } ALcomplex;
  37. typedef struct ALphasor {
  38. ALdouble Amplitude;
  39. ALdouble Phase;
  40. } ALphasor;
  41. typedef struct ALFrequencyDomain {
  42. ALdouble Amplitude;
  43. ALdouble Frequency;
  44. } ALfrequencyDomain;
  45. typedef struct ALpshifterState {
  46. DERIVE_FROM_TYPE(ALeffectState);
  47. /* Effect parameters */
  48. ALsizei count;
  49. ALsizei PitchShiftI;
  50. ALfloat PitchShift;
  51. ALfloat FreqPerBin;
  52. /*Effects buffers*/
  53. ALfloat InFIFO[STFT_SIZE];
  54. ALfloat OutFIFO[STFT_STEP];
  55. ALdouble LastPhase[STFT_HALF_SIZE+1];
  56. ALdouble SumPhase[STFT_HALF_SIZE+1];
  57. ALdouble OutputAccum[STFT_SIZE];
  58. ALcomplex FFTbuffer[STFT_SIZE];
  59. ALfrequencyDomain Analysis_buffer[STFT_HALF_SIZE+1];
  60. ALfrequencyDomain Syntesis_buffer[STFT_HALF_SIZE+1];
  61. alignas(16) ALfloat BufferOut[BUFFERSIZE];
  62. /* Effect gains for each output channel */
  63. ALfloat CurrentGains[MAX_OUTPUT_CHANNELS];
  64. ALfloat TargetGains[MAX_OUTPUT_CHANNELS];
  65. } ALpshifterState;
  66. static ALvoid ALpshifterState_Destruct(ALpshifterState *state);
  67. static ALboolean ALpshifterState_deviceUpdate(ALpshifterState *state, ALCdevice *device);
  68. static ALvoid ALpshifterState_update(ALpshifterState *state, const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props);
  69. static ALvoid ALpshifterState_process(ALpshifterState *state, ALsizei SamplesToDo, const ALfloat (*restrict SamplesIn)[BUFFERSIZE], ALfloat (*restrict SamplesOut)[BUFFERSIZE], ALsizei NumChannels);
  70. DECLARE_DEFAULT_ALLOCATORS(ALpshifterState)
  71. DEFINE_ALEFFECTSTATE_VTABLE(ALpshifterState);
  72. /* Define a Hann window, used to filter the STFT input and output. */
  73. alignas(16) static ALdouble HannWindow[STFT_SIZE];
  74. static void InitHannWindow(void)
  75. {
  76. ALsizei i;
  77. /* Create lookup table of the Hann window for the desired size, i.e. STFT_SIZE */
  78. for(i = 0;i < STFT_SIZE>>1;i++)
  79. {
  80. ALdouble val = sin(M_PI * (ALdouble)i / (ALdouble)(STFT_SIZE-1));
  81. HannWindow[i] = HannWindow[STFT_SIZE-1-i] = val * val;
  82. }
  83. }
  84. static alonce_flag HannInitOnce = AL_ONCE_FLAG_INIT;
  85. /* Fast double-to-int conversion. Assumes the FPU is already in round-to-zero
  86. * mode. */
  87. static inline ALint fastd2i(ALdouble d)
  88. {
  89. /* NOTE: SSE2 is required for the efficient double-to-int opcodes on x86.
  90. * Otherwise, we need to rely on x87's fistp opcode with it already in
  91. * round-to-zero mode. x86-64 guarantees SSE2 support.
  92. */
  93. #if (defined(__i386__) && !defined(__SSE2_MATH__)) || (defined(_M_IX86_FP) && (_M_IX86_FP < 2))
  94. #ifdef HAVE_LRINTF
  95. return lrint(d);
  96. #elif defined(_MSC_VER) && defined(_M_IX86)
  97. ALint i;
  98. __asm fld d
  99. __asm fistp i
  100. return i;
  101. #else
  102. return (ALint)d;
  103. #endif
  104. #else
  105. return (ALint)d;
  106. #endif
  107. }
  108. /* Converts ALcomplex to ALphasor */
  109. static inline ALphasor rect2polar(ALcomplex number)
  110. {
  111. ALphasor polar;
  112. polar.Amplitude = sqrt(number.Real*number.Real + number.Imag*number.Imag);
  113. polar.Phase = atan2(number.Imag, number.Real);
  114. return polar;
  115. }
  116. /* Converts ALphasor to ALcomplex */
  117. static inline ALcomplex polar2rect(ALphasor number)
  118. {
  119. ALcomplex cartesian;
  120. cartesian.Real = number.Amplitude * cos(number.Phase);
  121. cartesian.Imag = number.Amplitude * sin(number.Phase);
  122. return cartesian;
  123. }
  124. /* Addition of two complex numbers (ALcomplex format) */
  125. static inline ALcomplex complex_add(ALcomplex a, ALcomplex b)
  126. {
  127. ALcomplex result;
  128. result.Real = a.Real + b.Real;
  129. result.Imag = a.Imag + b.Imag;
  130. return result;
  131. }
  132. /* Subtraction of two complex numbers (ALcomplex format) */
  133. static inline ALcomplex complex_sub(ALcomplex a, ALcomplex b)
  134. {
  135. ALcomplex result;
  136. result.Real = a.Real - b.Real;
  137. result.Imag = a.Imag - b.Imag;
  138. return result;
  139. }
  140. /* Multiplication of two complex numbers (ALcomplex format) */
  141. static inline ALcomplex complex_mult(ALcomplex a, ALcomplex b)
  142. {
  143. ALcomplex result;
  144. result.Real = a.Real*b.Real - a.Imag*b.Imag;
  145. result.Imag = a.Imag*b.Real + a.Real*b.Imag;
  146. return result;
  147. }
  148. /* Iterative implementation of 2-radix FFT (In-place algorithm). Sign = -1 is
  149. * FFT and 1 is iFFT (inverse). Fills FFTBuffer[0...FFTSize-1] with the
  150. * Discrete Fourier Transform (DFT) of the time domain data stored in
  151. * FFTBuffer[0...FFTSize-1]. FFTBuffer is an array of complex numbers
  152. * (ALcomplex), FFTSize MUST BE power of two.
  153. */
  154. static inline ALvoid FFT(ALcomplex *FFTBuffer, ALsizei FFTSize, ALdouble Sign)
  155. {
  156. ALsizei i, j, k, mask, step, step2;
  157. ALcomplex temp, u, w;
  158. ALdouble arg;
  159. /* Bit-reversal permutation applied to a sequence of FFTSize items */
  160. for(i = 1;i < FFTSize-1;i++)
  161. {
  162. for(mask = 0x1, j = 0;mask < FFTSize;mask <<= 1)
  163. {
  164. if((i&mask) != 0)
  165. j++;
  166. j <<= 1;
  167. }
  168. j >>= 1;
  169. if(i < j)
  170. {
  171. temp = FFTBuffer[i];
  172. FFTBuffer[i] = FFTBuffer[j];
  173. FFTBuffer[j] = temp;
  174. }
  175. }
  176. /* Iterative form of Danielson–Lanczos lemma */
  177. for(i = 1, step = 2;i < FFTSize;i<<=1, step<<=1)
  178. {
  179. step2 = step >> 1;
  180. arg = M_PI / step2;
  181. w.Real = cos(arg);
  182. w.Imag = sin(arg) * Sign;
  183. u.Real = 1.0;
  184. u.Imag = 0.0;
  185. for(j = 0;j < step2;j++)
  186. {
  187. for(k = j;k < FFTSize;k+=step)
  188. {
  189. temp = complex_mult(FFTBuffer[k+step2], u);
  190. FFTBuffer[k+step2] = complex_sub(FFTBuffer[k], temp);
  191. FFTBuffer[k] = complex_add(FFTBuffer[k], temp);
  192. }
  193. u = complex_mult(u, w);
  194. }
  195. }
  196. }
  197. static void ALpshifterState_Construct(ALpshifterState *state)
  198. {
  199. ALeffectState_Construct(STATIC_CAST(ALeffectState, state));
  200. SET_VTABLE2(ALpshifterState, ALeffectState, state);
  201. alcall_once(&HannInitOnce, InitHannWindow);
  202. }
  203. static ALvoid ALpshifterState_Destruct(ALpshifterState *state)
  204. {
  205. ALeffectState_Destruct(STATIC_CAST(ALeffectState,state));
  206. }
  207. static ALboolean ALpshifterState_deviceUpdate(ALpshifterState *state, ALCdevice *device)
  208. {
  209. /* (Re-)initializing parameters and clear the buffers. */
  210. state->count = FIFO_LATENCY;
  211. state->PitchShiftI = FRACTIONONE;
  212. state->PitchShift = 1.0f;
  213. state->FreqPerBin = device->Frequency / (ALfloat)STFT_SIZE;
  214. memset(state->InFIFO, 0, sizeof(state->InFIFO));
  215. memset(state->OutFIFO, 0, sizeof(state->OutFIFO));
  216. memset(state->FFTbuffer, 0, sizeof(state->FFTbuffer));
  217. memset(state->LastPhase, 0, sizeof(state->LastPhase));
  218. memset(state->SumPhase, 0, sizeof(state->SumPhase));
  219. memset(state->OutputAccum, 0, sizeof(state->OutputAccum));
  220. memset(state->Analysis_buffer, 0, sizeof(state->Analysis_buffer));
  221. memset(state->Syntesis_buffer, 0, sizeof(state->Syntesis_buffer));
  222. memset(state->CurrentGains, 0, sizeof(state->CurrentGains));
  223. memset(state->TargetGains, 0, sizeof(state->TargetGains));
  224. return AL_TRUE;
  225. }
  226. static ALvoid ALpshifterState_update(ALpshifterState *state, const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props)
  227. {
  228. const ALCdevice *device = context->Device;
  229. ALfloat coeffs[MAX_AMBI_COEFFS];
  230. float pitch;
  231. pitch = powf(2.0f,
  232. (ALfloat)(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f
  233. );
  234. state->PitchShiftI = (ALsizei)(pitch*FRACTIONONE + 0.5f);
  235. state->PitchShift = state->PitchShiftI * (1.0f/FRACTIONONE);
  236. CalcAngleCoeffs(0.0f, 0.0f, 0.0f, coeffs);
  237. ComputeDryPanGains(&device->Dry, coeffs, slot->Params.Gain, state->TargetGains);
  238. }
  239. static ALvoid ALpshifterState_process(ALpshifterState *state, ALsizei SamplesToDo, const ALfloat (*restrict SamplesIn)[BUFFERSIZE], ALfloat (*restrict SamplesOut)[BUFFERSIZE], ALsizei NumChannels)
  240. {
  241. /* Pitch shifter engine based on the work of Stephan Bernsee.
  242. * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/
  243. */
  244. static const ALdouble expected = M_PI*2.0 / OVERSAMP;
  245. const ALdouble freq_per_bin = state->FreqPerBin;
  246. ALfloat *restrict bufferOut = state->BufferOut;
  247. ALsizei count = state->count;
  248. ALsizei i, j, k;
  249. for(i = 0;i < SamplesToDo;)
  250. {
  251. do {
  252. /* Fill FIFO buffer with samples data */
  253. state->InFIFO[count] = SamplesIn[0][i];
  254. bufferOut[i] = state->OutFIFO[count - FIFO_LATENCY];
  255. count++;
  256. } while(++i < SamplesToDo && count < STFT_SIZE);
  257. /* Check whether FIFO buffer is filled */
  258. if(count < STFT_SIZE) break;
  259. count = FIFO_LATENCY;
  260. /* Real signal windowing and store in FFTbuffer */
  261. for(k = 0;k < STFT_SIZE;k++)
  262. {
  263. state->FFTbuffer[k].Real = state->InFIFO[k] * HannWindow[k];
  264. state->FFTbuffer[k].Imag = 0.0;
  265. }
  266. /* ANALYSIS */
  267. /* Apply FFT to FFTbuffer data */
  268. FFT(state->FFTbuffer, STFT_SIZE, -1.0);
  269. /* Analyze the obtained data. Since the real FFT is symmetric, only
  270. * STFT_HALF_SIZE+1 samples are needed.
  271. */
  272. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  273. {
  274. ALphasor component;
  275. ALdouble tmp;
  276. ALint qpd;
  277. /* Compute amplitude and phase */
  278. component = rect2polar(state->FFTbuffer[k]);
  279. /* Compute phase difference and subtract expected phase difference */
  280. tmp = (component.Phase - state->LastPhase[k]) - k*expected;
  281. /* Map delta phase into +/- Pi interval */
  282. qpd = fastd2i(tmp / M_PI);
  283. tmp -= M_PI * (qpd + (qpd%2));
  284. /* Get deviation from bin frequency from the +/- Pi interval */
  285. tmp /= expected;
  286. /* Compute the k-th partials' true frequency, twice the amplitude
  287. * for maintain the gain (because half of bins are used) and store
  288. * amplitude and true frequency in analysis buffer.
  289. */
  290. state->Analysis_buffer[k].Amplitude = 2.0 * component.Amplitude;
  291. state->Analysis_buffer[k].Frequency = (k + tmp) * freq_per_bin;
  292. /* Store actual phase[k] for the calculations in the next frame*/
  293. state->LastPhase[k] = component.Phase;
  294. }
  295. /* PROCESSING */
  296. /* pitch shifting */
  297. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  298. {
  299. state->Syntesis_buffer[k].Amplitude = 0.0;
  300. state->Syntesis_buffer[k].Frequency = 0.0;
  301. }
  302. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  303. {
  304. j = (k*state->PitchShiftI) >> FRACTIONBITS;
  305. if(j >= STFT_HALF_SIZE+1) break;
  306. state->Syntesis_buffer[j].Amplitude += state->Analysis_buffer[k].Amplitude;
  307. state->Syntesis_buffer[j].Frequency = state->Analysis_buffer[k].Frequency *
  308. state->PitchShift;
  309. }
  310. /* SYNTHESIS */
  311. /* Synthesis the processing data */
  312. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  313. {
  314. ALphasor component;
  315. ALdouble tmp;
  316. /* Compute bin deviation from scaled freq */
  317. tmp = state->Syntesis_buffer[k].Frequency/freq_per_bin - k;
  318. /* Calculate actual delta phase and accumulate it to get bin phase */
  319. state->SumPhase[k] += (k + tmp) * expected;
  320. component.Amplitude = state->Syntesis_buffer[k].Amplitude;
  321. component.Phase = state->SumPhase[k];
  322. /* Compute phasor component to cartesian complex number and storage it into FFTbuffer*/
  323. state->FFTbuffer[k] = polar2rect(component);
  324. }
  325. /* zero negative frequencies for recontruct a real signal */
  326. for(k = STFT_HALF_SIZE+1;k < STFT_SIZE;k++)
  327. {
  328. state->FFTbuffer[k].Real = 0.0;
  329. state->FFTbuffer[k].Imag = 0.0;
  330. }
  331. /* Apply iFFT to buffer data */
  332. FFT(state->FFTbuffer, STFT_SIZE, 1.0);
  333. /* Windowing and add to output */
  334. for(k = 0;k < STFT_SIZE;k++)
  335. state->OutputAccum[k] += HannWindow[k] * state->FFTbuffer[k].Real /
  336. (0.5 * STFT_HALF_SIZE * OVERSAMP);
  337. /* Shift accumulator, input & output FIFO */
  338. for(k = 0;k < STFT_STEP;k++) state->OutFIFO[k] = (ALfloat)state->OutputAccum[k];
  339. for(j = 0;k < STFT_SIZE;k++,j++) state->OutputAccum[j] = state->OutputAccum[k];
  340. for(;j < STFT_SIZE;j++) state->OutputAccum[j] = 0.0;
  341. for(k = 0;k < FIFO_LATENCY;k++)
  342. state->InFIFO[k] = state->InFIFO[k+STFT_STEP];
  343. }
  344. state->count = count;
  345. /* Now, mix the processed sound data to the output. */
  346. MixSamples(bufferOut, NumChannels, SamplesOut, state->CurrentGains, state->TargetGains,
  347. maxi(SamplesToDo, 512), 0, SamplesToDo);
  348. }
  349. typedef struct PshifterStateFactory {
  350. DERIVE_FROM_TYPE(EffectStateFactory);
  351. } PshifterStateFactory;
  352. static ALeffectState *PshifterStateFactory_create(PshifterStateFactory *UNUSED(factory))
  353. {
  354. ALpshifterState *state;
  355. NEW_OBJ0(state, ALpshifterState)();
  356. if(!state) return NULL;
  357. return STATIC_CAST(ALeffectState, state);
  358. }
  359. DEFINE_EFFECTSTATEFACTORY_VTABLE(PshifterStateFactory);
  360. EffectStateFactory *PshifterStateFactory_getFactory(void)
  361. {
  362. static PshifterStateFactory PshifterFactory = { { GET_VTABLE2(PshifterStateFactory, EffectStateFactory) } };
  363. return STATIC_CAST(EffectStateFactory, &PshifterFactory);
  364. }
  365. void ALpshifter_setParamf(ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat UNUSED(val))
  366. {
  367. alSetError( context, AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param );
  368. }
  369. void ALpshifter_setParamfv(ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, const ALfloat *UNUSED(vals))
  370. {
  371. alSetError( context, AL_INVALID_ENUM, "Invalid pitch shifter float-vector property 0x%04x", param );
  372. }
  373. void ALpshifter_setParami(ALeffect *effect, ALCcontext *context, ALenum param, ALint val)
  374. {
  375. ALeffectProps *props = &effect->Props;
  376. switch(param)
  377. {
  378. case AL_PITCH_SHIFTER_COARSE_TUNE:
  379. if(!(val >= AL_PITCH_SHIFTER_MIN_COARSE_TUNE && val <= AL_PITCH_SHIFTER_MAX_COARSE_TUNE))
  380. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter coarse tune out of range");
  381. props->Pshifter.CoarseTune = val;
  382. break;
  383. case AL_PITCH_SHIFTER_FINE_TUNE:
  384. if(!(val >= AL_PITCH_SHIFTER_MIN_FINE_TUNE && val <= AL_PITCH_SHIFTER_MAX_FINE_TUNE))
  385. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter fine tune out of range");
  386. props->Pshifter.FineTune = val;
  387. break;
  388. default:
  389. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", param);
  390. }
  391. }
  392. void ALpshifter_setParamiv(ALeffect *effect, ALCcontext *context, ALenum param, const ALint *vals)
  393. {
  394. ALpshifter_setParami(effect, context, param, vals[0]);
  395. }
  396. void ALpshifter_getParami(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *val)
  397. {
  398. const ALeffectProps *props = &effect->Props;
  399. switch(param)
  400. {
  401. case AL_PITCH_SHIFTER_COARSE_TUNE:
  402. *val = (ALint)props->Pshifter.CoarseTune;
  403. break;
  404. case AL_PITCH_SHIFTER_FINE_TUNE:
  405. *val = (ALint)props->Pshifter.FineTune;
  406. break;
  407. default:
  408. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", param);
  409. }
  410. }
  411. void ALpshifter_getParamiv(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *vals)
  412. {
  413. ALpshifter_getParami(effect, context, param, vals);
  414. }
  415. void ALpshifter_getParamf(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat *UNUSED(val))
  416. {
  417. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param);
  418. }
  419. void ALpshifter_getParamfv(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat *UNUSED(vals))
  420. {
  421. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter float vector-property 0x%04x", param);
  422. }
  423. DEFINE_ALEFFECT_VTABLE(ALpshifter);