audio_effect_spectrum_analyzer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /**************************************************************************/
  2. /* audio_effect_spectrum_analyzer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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_spectrum_analyzer.h"
  31. #include "servers/audio_server.h"
  32. static void smbFft(float *fftBuffer, long fftFrameSize, long sign)
  33. /*
  34. FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse)
  35. Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the
  36. time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes
  37. and returns the cosine and sine parts in an interleaved manner, ie.
  38. fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize
  39. must be a power of 2. It expects a complex input signal (see footnote 2),
  40. ie. when working with 'common' audio signals our input signal has to be
  41. passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform
  42. of the frequencies of interest is in fftBuffer[0...fftFrameSize].
  43. */
  44. {
  45. float wr, wi, arg, *p1, *p2, temp;
  46. float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;
  47. long i, bitm, j, le, le2, k;
  48. for (i = 2; i < 2 * fftFrameSize - 2; i += 2) {
  49. for (bitm = 2, j = 0; bitm < 2 * fftFrameSize; bitm <<= 1) {
  50. if (i & bitm) {
  51. j++;
  52. }
  53. j <<= 1;
  54. }
  55. if (i < j) {
  56. p1 = fftBuffer + i;
  57. p2 = fftBuffer + j;
  58. temp = *p1;
  59. *(p1++) = *p2;
  60. *(p2++) = temp;
  61. temp = *p1;
  62. *p1 = *p2;
  63. *p2 = temp;
  64. }
  65. }
  66. for (k = 0, le = 2; k < (long)(log((double)fftFrameSize) / log(2.) + .5); k++) {
  67. le <<= 1;
  68. le2 = le >> 1;
  69. ur = 1.0;
  70. ui = 0.0;
  71. arg = Math_PI / (le2 >> 1);
  72. wr = cos(arg);
  73. wi = sign * sin(arg);
  74. for (j = 0; j < le2; j += 2) {
  75. p1r = fftBuffer + j;
  76. p1i = p1r + 1;
  77. p2r = p1r + le2;
  78. p2i = p2r + 1;
  79. for (i = j; i < 2 * fftFrameSize; i += le) {
  80. tr = *p2r * ur - *p2i * ui;
  81. ti = *p2r * ui + *p2i * ur;
  82. *p2r = *p1r - tr;
  83. *p2i = *p1i - ti;
  84. *p1r += tr;
  85. *p1i += ti;
  86. p1r += le;
  87. p1i += le;
  88. p2r += le;
  89. p2i += le;
  90. }
  91. tr = ur * wr - ui * wi;
  92. ui = ur * wi + ui * wr;
  93. ur = tr;
  94. }
  95. }
  96. }
  97. void AudioEffectSpectrumAnalyzerInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
  98. uint64_t time = OS::get_singleton()->get_ticks_usec();
  99. //copy everything over first, since this only really does capture
  100. for (int i = 0; i < p_frame_count; i++) {
  101. p_dst_frames[i] = p_src_frames[i];
  102. }
  103. //capture spectrum
  104. while (p_frame_count) {
  105. int to_fill = fft_size * 2 - temporal_fft_pos;
  106. to_fill = MIN(to_fill, p_frame_count);
  107. const double to_fill_step = Math_TAU / (double)fft_size;
  108. float *fftw = temporal_fft.ptrw();
  109. for (int i = 0; i < to_fill; i++) { //left and right buffers
  110. float window = -0.5 * Math::cos(to_fill_step * (double)temporal_fft_pos) + 0.5;
  111. fftw[temporal_fft_pos * 2] = window * p_src_frames->left;
  112. fftw[temporal_fft_pos * 2 + 1] = 0;
  113. fftw[(temporal_fft_pos + fft_size * 2) * 2] = window * p_src_frames->right;
  114. fftw[(temporal_fft_pos + fft_size * 2) * 2 + 1] = 0;
  115. ++p_src_frames;
  116. ++temporal_fft_pos;
  117. }
  118. p_frame_count -= to_fill;
  119. if (temporal_fft_pos == fft_size * 2) {
  120. //time to do a FFT
  121. smbFft(fftw, fft_size * 2, -1);
  122. smbFft(fftw + fft_size * 4, fft_size * 2, -1);
  123. int next = (fft_pos + 1) % fft_count;
  124. AudioFrame *hw = (AudioFrame *)fft_history[next].ptr(); //do not use write, avoid cow
  125. for (int i = 0; i < fft_size; i++) {
  126. //abs(vec)/fft_size normalizes each frequency
  127. hw[i].left = Vector2(fftw[i * 2], fftw[i * 2 + 1]).length() / float(fft_size);
  128. hw[i].right = Vector2(fftw[fft_size * 4 + i * 2], fftw[fft_size * 4 + i * 2 + 1]).length() / float(fft_size);
  129. }
  130. fft_pos = next; //swap
  131. temporal_fft_pos = 0;
  132. }
  133. }
  134. //determine time of capture
  135. double remainer_sec = (temporal_fft_pos / mix_rate); //subtract remainder from mix time
  136. last_fft_time = time - uint64_t(remainer_sec * 1000000.0);
  137. }
  138. void AudioEffectSpectrumAnalyzerInstance::_bind_methods() {
  139. ClassDB::bind_method(D_METHOD("get_magnitude_for_frequency_range", "from_hz", "to_hz", "mode"), &AudioEffectSpectrumAnalyzerInstance::get_magnitude_for_frequency_range, DEFVAL(MAGNITUDE_MAX));
  140. BIND_ENUM_CONSTANT(MAGNITUDE_AVERAGE);
  141. BIND_ENUM_CONSTANT(MAGNITUDE_MAX);
  142. }
  143. Vector2 AudioEffectSpectrumAnalyzerInstance::get_magnitude_for_frequency_range(float p_begin, float p_end, MagnitudeMode p_mode) const {
  144. if (last_fft_time == 0) {
  145. return Vector2();
  146. }
  147. uint64_t time = OS::get_singleton()->get_ticks_usec();
  148. float diff = double(time - last_fft_time) / 1000000.0 + base->get_tap_back_pos();
  149. diff -= AudioServer::get_singleton()->get_output_latency();
  150. float fft_time_size = float(fft_size) / mix_rate;
  151. int fft_index = fft_pos;
  152. while (diff > fft_time_size) {
  153. diff -= fft_time_size;
  154. fft_index -= 1;
  155. if (fft_index < 0) {
  156. fft_index = fft_count - 1;
  157. }
  158. }
  159. int begin_pos = p_begin * fft_size / (mix_rate * 0.5);
  160. int end_pos = p_end * fft_size / (mix_rate * 0.5);
  161. begin_pos = CLAMP(begin_pos, 0, fft_size - 1);
  162. end_pos = CLAMP(end_pos, 0, fft_size - 1);
  163. if (begin_pos > end_pos) {
  164. SWAP(begin_pos, end_pos);
  165. }
  166. const AudioFrame *r = fft_history[fft_index].ptr();
  167. if (p_mode == MAGNITUDE_AVERAGE) {
  168. Vector2 avg;
  169. for (int i = begin_pos; i <= end_pos; i++) {
  170. avg += Vector2(r[i]);
  171. }
  172. avg /= float(end_pos - begin_pos + 1);
  173. return avg;
  174. } else {
  175. Vector2 max;
  176. for (int i = begin_pos; i <= end_pos; i++) {
  177. max.x = MAX(max.x, r[i].left);
  178. max.y = MAX(max.y, r[i].right);
  179. }
  180. return max;
  181. }
  182. }
  183. Ref<AudioEffectInstance> AudioEffectSpectrumAnalyzer::instantiate() {
  184. Ref<AudioEffectSpectrumAnalyzerInstance> ins;
  185. ins.instantiate();
  186. ins->base = Ref<AudioEffectSpectrumAnalyzer>(this);
  187. static const int fft_sizes[FFT_SIZE_MAX] = { 256, 512, 1024, 2048, 4096 };
  188. ins->fft_size = fft_sizes[fft_size];
  189. ins->mix_rate = AudioServer::get_singleton()->get_mix_rate();
  190. ins->fft_count = (buffer_length / (float(ins->fft_size) / ins->mix_rate)) + 1;
  191. ins->fft_pos = 0;
  192. ins->last_fft_time = 0;
  193. ins->fft_history.resize(ins->fft_count);
  194. ins->temporal_fft.resize(ins->fft_size * 8); //x2 stereo, x2 amount of samples for freqs, x2 for input
  195. ins->temporal_fft_pos = 0;
  196. for (int i = 0; i < ins->fft_count; i++) {
  197. ins->fft_history.write[i].resize(ins->fft_size); //only magnitude matters
  198. for (int j = 0; j < ins->fft_size; j++) {
  199. ins->fft_history.write[i].write[j] = AudioFrame(0, 0);
  200. }
  201. }
  202. return ins;
  203. }
  204. void AudioEffectSpectrumAnalyzer::set_buffer_length(float p_seconds) {
  205. buffer_length = p_seconds;
  206. }
  207. float AudioEffectSpectrumAnalyzer::get_buffer_length() const {
  208. return buffer_length;
  209. }
  210. void AudioEffectSpectrumAnalyzer::set_tap_back_pos(float p_seconds) {
  211. tapback_pos = p_seconds;
  212. }
  213. float AudioEffectSpectrumAnalyzer::get_tap_back_pos() const {
  214. return tapback_pos;
  215. }
  216. void AudioEffectSpectrumAnalyzer::set_fft_size(FFTSize p_fft_size) {
  217. ERR_FAIL_INDEX(p_fft_size, FFT_SIZE_MAX);
  218. fft_size = p_fft_size;
  219. }
  220. AudioEffectSpectrumAnalyzer::FFTSize AudioEffectSpectrumAnalyzer::get_fft_size() const {
  221. return fft_size;
  222. }
  223. void AudioEffectSpectrumAnalyzer::_bind_methods() {
  224. ClassDB::bind_method(D_METHOD("set_buffer_length", "seconds"), &AudioEffectSpectrumAnalyzer::set_buffer_length);
  225. ClassDB::bind_method(D_METHOD("get_buffer_length"), &AudioEffectSpectrumAnalyzer::get_buffer_length);
  226. ClassDB::bind_method(D_METHOD("set_tap_back_pos", "seconds"), &AudioEffectSpectrumAnalyzer::set_tap_back_pos);
  227. ClassDB::bind_method(D_METHOD("get_tap_back_pos"), &AudioEffectSpectrumAnalyzer::get_tap_back_pos);
  228. ClassDB::bind_method(D_METHOD("set_fft_size", "size"), &AudioEffectSpectrumAnalyzer::set_fft_size);
  229. ClassDB::bind_method(D_METHOD("get_fft_size"), &AudioEffectSpectrumAnalyzer::get_fft_size);
  230. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "buffer_length", PROPERTY_HINT_RANGE, "0.1,4,0.1,suffix:s"), "set_buffer_length", "get_buffer_length");
  231. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "tap_back_pos", PROPERTY_HINT_RANGE, "0.1,4,0.1"), "set_tap_back_pos", "get_tap_back_pos");
  232. ADD_PROPERTY(PropertyInfo(Variant::INT, "fft_size", PROPERTY_HINT_ENUM, "256,512,1024,2048,4096"), "set_fft_size", "get_fft_size");
  233. BIND_ENUM_CONSTANT(FFT_SIZE_256);
  234. BIND_ENUM_CONSTANT(FFT_SIZE_512);
  235. BIND_ENUM_CONSTANT(FFT_SIZE_1024);
  236. BIND_ENUM_CONSTANT(FFT_SIZE_2048);
  237. BIND_ENUM_CONSTANT(FFT_SIZE_4096);
  238. BIND_ENUM_CONSTANT(FFT_SIZE_MAX);
  239. }
  240. AudioEffectSpectrumAnalyzer::AudioEffectSpectrumAnalyzer() {
  241. buffer_length = 2;
  242. tapback_pos = 0.01;
  243. fft_size = FFT_SIZE_1024;
  244. }