2
0

pshifter.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. #include "alcomplex.h"
  29. #define STFT_SIZE 1024
  30. #define STFT_HALF_SIZE (STFT_SIZE>>1)
  31. #define OVERSAMP (1<<2)
  32. #define STFT_STEP (STFT_SIZE / OVERSAMP)
  33. #define FIFO_LATENCY (STFT_STEP * (OVERSAMP-1))
  34. typedef struct ALphasor {
  35. ALdouble Amplitude;
  36. ALdouble Phase;
  37. } ALphasor;
  38. typedef struct ALFrequencyDomain {
  39. ALdouble Amplitude;
  40. ALdouble Frequency;
  41. } ALfrequencyDomain;
  42. typedef struct ALpshifterState {
  43. DERIVE_FROM_TYPE(ALeffectState);
  44. /* Effect parameters */
  45. ALsizei count;
  46. ALsizei PitchShiftI;
  47. ALfloat PitchShift;
  48. ALfloat FreqPerBin;
  49. /*Effects buffers*/
  50. ALfloat InFIFO[STFT_SIZE];
  51. ALfloat OutFIFO[STFT_STEP];
  52. ALdouble LastPhase[STFT_HALF_SIZE+1];
  53. ALdouble SumPhase[STFT_HALF_SIZE+1];
  54. ALdouble OutputAccum[STFT_SIZE];
  55. ALcomplex FFTbuffer[STFT_SIZE];
  56. ALfrequencyDomain Analysis_buffer[STFT_HALF_SIZE+1];
  57. ALfrequencyDomain Syntesis_buffer[STFT_HALF_SIZE+1];
  58. alignas(16) ALfloat BufferOut[BUFFERSIZE];
  59. /* Effect gains for each output channel */
  60. ALfloat CurrentGains[MAX_OUTPUT_CHANNELS];
  61. ALfloat TargetGains[MAX_OUTPUT_CHANNELS];
  62. } ALpshifterState;
  63. static ALvoid ALpshifterState_Destruct(ALpshifterState *state);
  64. static ALboolean ALpshifterState_deviceUpdate(ALpshifterState *state, ALCdevice *device);
  65. static ALvoid ALpshifterState_update(ALpshifterState *state, const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props);
  66. static ALvoid ALpshifterState_process(ALpshifterState *state, ALsizei SamplesToDo, const ALfloat (*restrict SamplesIn)[BUFFERSIZE], ALfloat (*restrict SamplesOut)[BUFFERSIZE], ALsizei NumChannels);
  67. DECLARE_DEFAULT_ALLOCATORS(ALpshifterState)
  68. DEFINE_ALEFFECTSTATE_VTABLE(ALpshifterState);
  69. /* Define a Hann window, used to filter the STFT input and output. */
  70. alignas(16) static ALdouble HannWindow[STFT_SIZE];
  71. static void InitHannWindow(void)
  72. {
  73. ALsizei i;
  74. /* Create lookup table of the Hann window for the desired size, i.e. STFT_SIZE */
  75. for(i = 0;i < STFT_SIZE>>1;i++)
  76. {
  77. ALdouble val = sin(M_PI * (ALdouble)i / (ALdouble)(STFT_SIZE-1));
  78. HannWindow[i] = HannWindow[STFT_SIZE-1-i] = val * val;
  79. }
  80. }
  81. static alonce_flag HannInitOnce = AL_ONCE_FLAG_INIT;
  82. static inline ALint double2int(ALdouble d)
  83. {
  84. #if ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) && \
  85. !defined(__SSE2_MATH__)) || (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP < 2)
  86. ALint sign, shift;
  87. ALint64 mant;
  88. union {
  89. ALdouble d;
  90. ALint64 i64;
  91. } conv;
  92. conv.d = d;
  93. sign = (conv.i64>>63) | 1;
  94. shift = ((conv.i64>>52)&0x7ff) - (1023+52);
  95. /* Over/underflow */
  96. if(UNLIKELY(shift >= 63 || shift < -52))
  97. return 0;
  98. mant = (conv.i64&I64(0xfffffffffffff)) | I64(0x10000000000000);
  99. if(LIKELY(shift < 0))
  100. return (ALint)(mant >> -shift) * sign;
  101. return (ALint)(mant << shift) * sign;
  102. #else
  103. return (ALint)d;
  104. #endif
  105. }
  106. /* Converts ALcomplex to ALphasor */
  107. static inline ALphasor rect2polar(ALcomplex number)
  108. {
  109. ALphasor polar;
  110. polar.Amplitude = sqrt(number.Real*number.Real + number.Imag*number.Imag);
  111. polar.Phase = atan2(number.Imag, number.Real);
  112. return polar;
  113. }
  114. /* Converts ALphasor to ALcomplex */
  115. static inline ALcomplex polar2rect(ALphasor number)
  116. {
  117. ALcomplex cartesian;
  118. cartesian.Real = number.Amplitude * cos(number.Phase);
  119. cartesian.Imag = number.Amplitude * sin(number.Phase);
  120. return cartesian;
  121. }
  122. static void ALpshifterState_Construct(ALpshifterState *state)
  123. {
  124. ALeffectState_Construct(STATIC_CAST(ALeffectState, state));
  125. SET_VTABLE2(ALpshifterState, ALeffectState, state);
  126. alcall_once(&HannInitOnce, InitHannWindow);
  127. }
  128. static ALvoid ALpshifterState_Destruct(ALpshifterState *state)
  129. {
  130. ALeffectState_Destruct(STATIC_CAST(ALeffectState,state));
  131. }
  132. static ALboolean ALpshifterState_deviceUpdate(ALpshifterState *state, ALCdevice *device)
  133. {
  134. /* (Re-)initializing parameters and clear the buffers. */
  135. state->count = FIFO_LATENCY;
  136. state->PitchShiftI = FRACTIONONE;
  137. state->PitchShift = 1.0f;
  138. state->FreqPerBin = device->Frequency / (ALfloat)STFT_SIZE;
  139. memset(state->InFIFO, 0, sizeof(state->InFIFO));
  140. memset(state->OutFIFO, 0, sizeof(state->OutFIFO));
  141. memset(state->FFTbuffer, 0, sizeof(state->FFTbuffer));
  142. memset(state->LastPhase, 0, sizeof(state->LastPhase));
  143. memset(state->SumPhase, 0, sizeof(state->SumPhase));
  144. memset(state->OutputAccum, 0, sizeof(state->OutputAccum));
  145. memset(state->Analysis_buffer, 0, sizeof(state->Analysis_buffer));
  146. memset(state->Syntesis_buffer, 0, sizeof(state->Syntesis_buffer));
  147. memset(state->CurrentGains, 0, sizeof(state->CurrentGains));
  148. memset(state->TargetGains, 0, sizeof(state->TargetGains));
  149. return AL_TRUE;
  150. }
  151. static ALvoid ALpshifterState_update(ALpshifterState *state, const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props)
  152. {
  153. const ALCdevice *device = context->Device;
  154. ALfloat coeffs[MAX_AMBI_COEFFS];
  155. float pitch;
  156. pitch = powf(2.0f,
  157. (ALfloat)(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f
  158. );
  159. state->PitchShiftI = fastf2i(pitch*FRACTIONONE);
  160. state->PitchShift = state->PitchShiftI * (1.0f/FRACTIONONE);
  161. CalcAngleCoeffs(0.0f, 0.0f, 0.0f, coeffs);
  162. ComputePanGains(&device->Dry, coeffs, slot->Params.Gain, state->TargetGains);
  163. }
  164. static ALvoid ALpshifterState_process(ALpshifterState *state, ALsizei SamplesToDo, const ALfloat (*restrict SamplesIn)[BUFFERSIZE], ALfloat (*restrict SamplesOut)[BUFFERSIZE], ALsizei NumChannels)
  165. {
  166. /* Pitch shifter engine based on the work of Stephan Bernsee.
  167. * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/
  168. */
  169. static const ALdouble expected = M_PI*2.0 / OVERSAMP;
  170. const ALdouble freq_per_bin = state->FreqPerBin;
  171. ALfloat *restrict bufferOut = state->BufferOut;
  172. ALsizei count = state->count;
  173. ALsizei i, j, k;
  174. for(i = 0;i < SamplesToDo;)
  175. {
  176. do {
  177. /* Fill FIFO buffer with samples data */
  178. state->InFIFO[count] = SamplesIn[0][i];
  179. bufferOut[i] = state->OutFIFO[count - FIFO_LATENCY];
  180. count++;
  181. } while(++i < SamplesToDo && count < STFT_SIZE);
  182. /* Check whether FIFO buffer is filled */
  183. if(count < STFT_SIZE) break;
  184. count = FIFO_LATENCY;
  185. /* Real signal windowing and store in FFTbuffer */
  186. for(k = 0;k < STFT_SIZE;k++)
  187. {
  188. state->FFTbuffer[k].Real = state->InFIFO[k] * HannWindow[k];
  189. state->FFTbuffer[k].Imag = 0.0;
  190. }
  191. /* ANALYSIS */
  192. /* Apply FFT to FFTbuffer data */
  193. complex_fft(state->FFTbuffer, STFT_SIZE, -1.0);
  194. /* Analyze the obtained data. Since the real FFT is symmetric, only
  195. * STFT_HALF_SIZE+1 samples are needed.
  196. */
  197. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  198. {
  199. ALphasor component;
  200. ALdouble tmp;
  201. ALint qpd;
  202. /* Compute amplitude and phase */
  203. component = rect2polar(state->FFTbuffer[k]);
  204. /* Compute phase difference and subtract expected phase difference */
  205. tmp = (component.Phase - state->LastPhase[k]) - k*expected;
  206. /* Map delta phase into +/- Pi interval */
  207. qpd = double2int(tmp / M_PI);
  208. tmp -= M_PI * (qpd + (qpd%2));
  209. /* Get deviation from bin frequency from the +/- Pi interval */
  210. tmp /= expected;
  211. /* Compute the k-th partials' true frequency, twice the amplitude
  212. * for maintain the gain (because half of bins are used) and store
  213. * amplitude and true frequency in analysis buffer.
  214. */
  215. state->Analysis_buffer[k].Amplitude = 2.0 * component.Amplitude;
  216. state->Analysis_buffer[k].Frequency = (k + tmp) * freq_per_bin;
  217. /* Store actual phase[k] for the calculations in the next frame*/
  218. state->LastPhase[k] = component.Phase;
  219. }
  220. /* PROCESSING */
  221. /* pitch shifting */
  222. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  223. {
  224. state->Syntesis_buffer[k].Amplitude = 0.0;
  225. state->Syntesis_buffer[k].Frequency = 0.0;
  226. }
  227. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  228. {
  229. j = (k*state->PitchShiftI) >> FRACTIONBITS;
  230. if(j >= STFT_HALF_SIZE+1) break;
  231. state->Syntesis_buffer[j].Amplitude += state->Analysis_buffer[k].Amplitude;
  232. state->Syntesis_buffer[j].Frequency = state->Analysis_buffer[k].Frequency *
  233. state->PitchShift;
  234. }
  235. /* SYNTHESIS */
  236. /* Synthesis the processing data */
  237. for(k = 0;k < STFT_HALF_SIZE+1;k++)
  238. {
  239. ALphasor component;
  240. ALdouble tmp;
  241. /* Compute bin deviation from scaled freq */
  242. tmp = state->Syntesis_buffer[k].Frequency/freq_per_bin - k;
  243. /* Calculate actual delta phase and accumulate it to get bin phase */
  244. state->SumPhase[k] += (k + tmp) * expected;
  245. component.Amplitude = state->Syntesis_buffer[k].Amplitude;
  246. component.Phase = state->SumPhase[k];
  247. /* Compute phasor component to cartesian complex number and storage it into FFTbuffer*/
  248. state->FFTbuffer[k] = polar2rect(component);
  249. }
  250. /* zero negative frequencies for recontruct a real signal */
  251. for(k = STFT_HALF_SIZE+1;k < STFT_SIZE;k++)
  252. {
  253. state->FFTbuffer[k].Real = 0.0;
  254. state->FFTbuffer[k].Imag = 0.0;
  255. }
  256. /* Apply iFFT to buffer data */
  257. complex_fft(state->FFTbuffer, STFT_SIZE, 1.0);
  258. /* Windowing and add to output */
  259. for(k = 0;k < STFT_SIZE;k++)
  260. state->OutputAccum[k] += HannWindow[k] * state->FFTbuffer[k].Real /
  261. (0.5 * STFT_HALF_SIZE * OVERSAMP);
  262. /* Shift accumulator, input & output FIFO */
  263. for(k = 0;k < STFT_STEP;k++) state->OutFIFO[k] = (ALfloat)state->OutputAccum[k];
  264. for(j = 0;k < STFT_SIZE;k++,j++) state->OutputAccum[j] = state->OutputAccum[k];
  265. for(;j < STFT_SIZE;j++) state->OutputAccum[j] = 0.0;
  266. for(k = 0;k < FIFO_LATENCY;k++)
  267. state->InFIFO[k] = state->InFIFO[k+STFT_STEP];
  268. }
  269. state->count = count;
  270. /* Now, mix the processed sound data to the output. */
  271. MixSamples(bufferOut, NumChannels, SamplesOut, state->CurrentGains, state->TargetGains,
  272. maxi(SamplesToDo, 512), 0, SamplesToDo);
  273. }
  274. typedef struct PshifterStateFactory {
  275. DERIVE_FROM_TYPE(EffectStateFactory);
  276. } PshifterStateFactory;
  277. static ALeffectState *PshifterStateFactory_create(PshifterStateFactory *UNUSED(factory))
  278. {
  279. ALpshifterState *state;
  280. NEW_OBJ0(state, ALpshifterState)();
  281. if(!state) return NULL;
  282. return STATIC_CAST(ALeffectState, state);
  283. }
  284. DEFINE_EFFECTSTATEFACTORY_VTABLE(PshifterStateFactory);
  285. EffectStateFactory *PshifterStateFactory_getFactory(void)
  286. {
  287. static PshifterStateFactory PshifterFactory = { { GET_VTABLE2(PshifterStateFactory, EffectStateFactory) } };
  288. return STATIC_CAST(EffectStateFactory, &PshifterFactory);
  289. }
  290. void ALpshifter_setParamf(ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat UNUSED(val))
  291. {
  292. alSetError( context, AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param );
  293. }
  294. void ALpshifter_setParamfv(ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, const ALfloat *UNUSED(vals))
  295. {
  296. alSetError( context, AL_INVALID_ENUM, "Invalid pitch shifter float-vector property 0x%04x", param );
  297. }
  298. void ALpshifter_setParami(ALeffect *effect, ALCcontext *context, ALenum param, ALint val)
  299. {
  300. ALeffectProps *props = &effect->Props;
  301. switch(param)
  302. {
  303. case AL_PITCH_SHIFTER_COARSE_TUNE:
  304. if(!(val >= AL_PITCH_SHIFTER_MIN_COARSE_TUNE && val <= AL_PITCH_SHIFTER_MAX_COARSE_TUNE))
  305. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter coarse tune out of range");
  306. props->Pshifter.CoarseTune = val;
  307. break;
  308. case AL_PITCH_SHIFTER_FINE_TUNE:
  309. if(!(val >= AL_PITCH_SHIFTER_MIN_FINE_TUNE && val <= AL_PITCH_SHIFTER_MAX_FINE_TUNE))
  310. SETERR_RETURN(context, AL_INVALID_VALUE,,"Pitch shifter fine tune out of range");
  311. props->Pshifter.FineTune = val;
  312. break;
  313. default:
  314. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", param);
  315. }
  316. }
  317. void ALpshifter_setParamiv(ALeffect *effect, ALCcontext *context, ALenum param, const ALint *vals)
  318. {
  319. ALpshifter_setParami(effect, context, param, vals[0]);
  320. }
  321. void ALpshifter_getParami(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *val)
  322. {
  323. const ALeffectProps *props = &effect->Props;
  324. switch(param)
  325. {
  326. case AL_PITCH_SHIFTER_COARSE_TUNE:
  327. *val = (ALint)props->Pshifter.CoarseTune;
  328. break;
  329. case AL_PITCH_SHIFTER_FINE_TUNE:
  330. *val = (ALint)props->Pshifter.FineTune;
  331. break;
  332. default:
  333. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", param);
  334. }
  335. }
  336. void ALpshifter_getParamiv(const ALeffect *effect, ALCcontext *context, ALenum param, ALint *vals)
  337. {
  338. ALpshifter_getParami(effect, context, param, vals);
  339. }
  340. void ALpshifter_getParamf(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat *UNUSED(val))
  341. {
  342. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param);
  343. }
  344. void ALpshifter_getParamfv(const ALeffect *UNUSED(effect), ALCcontext *context, ALenum param, ALfloat *UNUSED(vals))
  345. {
  346. alSetError(context, AL_INVALID_ENUM, "Invalid pitch shifter float vector-property 0x%04x", param);
  347. }
  348. DEFINE_ALEFFECT_VTABLE(ALpshifter);