You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

915 lines
33KB

  1. /*****************************************************************************
  2. * sofalizer.c : SOFAlizer filter for virtual binaural acoustics
  3. *****************************************************************************
  4. * Copyright (C) 2013-2015 Andreas Fuchs, Wolfgang Hrauda,
  5. * Acoustics Research Institute (ARI), Vienna, Austria
  6. *
  7. * Authors: Andreas Fuchs <andi.fuchs.mail@gmail.com>
  8. * Wolfgang Hrauda <wolfgang.hrauda@gmx.at>
  9. *
  10. * SOFAlizer project coordinator at ARI, main developer of SOFA:
  11. * Piotr Majdak <piotr@majdak.at>
  12. *
  13. * This program is free software; you can redistribute it and/or modify it
  14. * under the terms of the GNU Lesser General Public License as published by
  15. * the Free Software Foundation; either version 2.1 of the License, or
  16. * (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Lesser General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Lesser General Public License
  24. * along with this program; if not, write to the Free Software Foundation,
  25. * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  26. *****************************************************************************/
  27. #include <math.h>
  28. #include <mysofa.h>
  29. #include "libavcodec/avfft.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/channel_layout.h"
  32. #include "libavutil/float_dsp.h"
  33. #include "libavutil/intmath.h"
  34. #include "libavutil/opt.h"
  35. #include "avfilter.h"
  36. #include "internal.h"
  37. #include "audio.h"
  38. #define TIME_DOMAIN 0
  39. #define FREQUENCY_DOMAIN 1
  40. typedef struct MySofa { /* contains data of one SOFA file */
  41. struct MYSOFA_EASY *easy;
  42. int n_samples; /* length of one impulse response (IR) */
  43. float *lir, *rir; /* IRs (time-domain) */
  44. int max_delay;
  45. } MySofa;
  46. typedef struct VirtualSpeaker {
  47. uint8_t set;
  48. float azim;
  49. float elev;
  50. } VirtualSpeaker;
  51. typedef struct SOFAlizerContext {
  52. const AVClass *class;
  53. char *filename; /* name of SOFA file */
  54. MySofa sofa; /* contains data of the SOFA file */
  55. int sample_rate; /* sample rate from SOFA file */
  56. float *speaker_azim; /* azimuth of the virtual loudspeakers */
  57. float *speaker_elev; /* elevation of the virtual loudspeakers */
  58. char *speakers_pos; /* custom positions of the virtual loudspeakers */
  59. float lfe_gain; /* initial gain for the LFE channel */
  60. float gain_lfe; /* gain applied to LFE channel */
  61. int lfe_channel; /* LFE channel position in channel layout */
  62. int n_conv; /* number of channels to convolute */
  63. /* buffer variables (for convolution) */
  64. float *ringbuffer[2]; /* buffers input samples, length of one buffer: */
  65. /* no. input ch. (incl. LFE) x buffer_length */
  66. int write[2]; /* current write position to ringbuffer */
  67. int buffer_length; /* is: longest IR plus max. delay in all SOFA files */
  68. /* then choose next power of 2 */
  69. int n_fft; /* number of samples in one FFT block */
  70. /* netCDF variables */
  71. int *delay[2]; /* broadband delay for each channel/IR to be convolved */
  72. float *data_ir[2]; /* IRs for all channels to be convolved */
  73. /* (this excludes the LFE) */
  74. float *temp_src[2];
  75. FFTComplex *temp_fft[2];
  76. /* control variables */
  77. float gain; /* filter gain (in dB) */
  78. float rotation; /* rotation of virtual loudspeakers (in degrees) */
  79. float elevation; /* elevation of virtual loudspeakers (in deg.) */
  80. float radius; /* distance virtual loudspeakers to listener (in metres) */
  81. int type; /* processing type */
  82. VirtualSpeaker vspkrpos[64];
  83. FFTContext *fft[2], *ifft[2];
  84. FFTComplex *data_hrtf[2];
  85. AVFloatDSPContext *fdsp;
  86. } SOFAlizerContext;
  87. static int close_sofa(struct MySofa *sofa)
  88. {
  89. mysofa_close(sofa->easy);
  90. sofa->easy = NULL;
  91. return 0;
  92. }
  93. static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
  94. {
  95. struct SOFAlizerContext *s = ctx->priv;
  96. struct MYSOFA_HRTF *mysofa;
  97. int ret;
  98. mysofa = mysofa_load(filename, &ret);
  99. if (ret || !mysofa) {
  100. av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
  101. return AVERROR(EINVAL);
  102. }
  103. if (mysofa->DataSamplingRate.elements != 1)
  104. return AVERROR(EINVAL);
  105. *samplingrate = mysofa->DataSamplingRate.values[0];
  106. s->sofa.n_samples = mysofa->N;
  107. mysofa_free(mysofa);
  108. return 0;
  109. }
  110. static int parse_channel_name(char **arg, int *rchannel, char *buf)
  111. {
  112. int len, i, channel_id = 0;
  113. int64_t layout, layout0;
  114. /* try to parse a channel name, e.g. "FL" */
  115. if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
  116. layout0 = layout = av_get_channel_layout(buf);
  117. /* channel_id <- first set bit in layout */
  118. for (i = 32; i > 0; i >>= 1) {
  119. if (layout >= 1LL << i) {
  120. channel_id += i;
  121. layout >>= i;
  122. }
  123. }
  124. /* reject layouts that are not a single channel */
  125. if (channel_id >= 64 || layout0 != 1LL << channel_id)
  126. return AVERROR(EINVAL);
  127. *rchannel = channel_id;
  128. *arg += len;
  129. return 0;
  130. }
  131. return AVERROR(EINVAL);
  132. }
  133. static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
  134. {
  135. SOFAlizerContext *s = ctx->priv;
  136. char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
  137. if (!args)
  138. return;
  139. p = args;
  140. while ((arg = av_strtok(p, "|", &tokenizer))) {
  141. char buf[8];
  142. float azim, elev;
  143. int out_ch_id;
  144. p = NULL;
  145. if (parse_channel_name(&arg, &out_ch_id, buf)) {
  146. av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
  147. continue;
  148. }
  149. if (sscanf(arg, "%f %f", &azim, &elev) == 2) {
  150. s->vspkrpos[out_ch_id].set = 1;
  151. s->vspkrpos[out_ch_id].azim = azim;
  152. s->vspkrpos[out_ch_id].elev = elev;
  153. } else if (sscanf(arg, "%f", &azim) == 1) {
  154. s->vspkrpos[out_ch_id].set = 1;
  155. s->vspkrpos[out_ch_id].azim = azim;
  156. s->vspkrpos[out_ch_id].elev = 0;
  157. }
  158. }
  159. av_free(args);
  160. }
  161. static int get_speaker_pos(AVFilterContext *ctx,
  162. float *speaker_azim, float *speaker_elev)
  163. {
  164. struct SOFAlizerContext *s = ctx->priv;
  165. uint64_t channels_layout = ctx->inputs[0]->channel_layout;
  166. float azim[16] = { 0 };
  167. float elev[16] = { 0 };
  168. int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
  169. if (n_conv > 16)
  170. return AVERROR(EINVAL);
  171. s->lfe_channel = -1;
  172. if (s->speakers_pos)
  173. parse_speaker_pos(ctx, channels_layout);
  174. /* set speaker positions according to input channel configuration: */
  175. for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
  176. uint64_t mask = channels_layout & (1ULL << m);
  177. switch (mask) {
  178. case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
  179. case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
  180. case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
  181. case AV_CH_LOW_FREQUENCY:
  182. case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
  183. case AV_CH_BACK_LEFT: azim[ch] = 150; break;
  184. case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
  185. case AV_CH_BACK_CENTER: azim[ch] = 180; break;
  186. case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
  187. case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
  188. case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
  189. case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
  190. case AV_CH_TOP_CENTER: azim[ch] = 0;
  191. elev[ch] = 90; break;
  192. case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
  193. elev[ch] = 45; break;
  194. case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
  195. elev[ch] = 45; break;
  196. case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
  197. elev[ch] = 45; break;
  198. case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
  199. elev[ch] = 45; break;
  200. case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
  201. elev[ch] = 45; break;
  202. case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
  203. elev[ch] = 45; break;
  204. case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
  205. case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
  206. case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
  207. case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
  208. case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
  209. case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
  210. case 0: break;
  211. default:
  212. return AVERROR(EINVAL);
  213. }
  214. if (s->vspkrpos[m].set) {
  215. azim[ch] = s->vspkrpos[m].azim;
  216. elev[ch] = s->vspkrpos[m].elev;
  217. }
  218. if (mask)
  219. ch++;
  220. }
  221. memcpy(speaker_azim, azim, n_conv * sizeof(float));
  222. memcpy(speaker_elev, elev, n_conv * sizeof(float));
  223. return 0;
  224. }
  225. typedef struct ThreadData {
  226. AVFrame *in, *out;
  227. int *write;
  228. int **delay;
  229. float **ir;
  230. int *n_clippings;
  231. float **ringbuffer;
  232. float **temp_src;
  233. FFTComplex **temp_fft;
  234. } ThreadData;
  235. static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  236. {
  237. SOFAlizerContext *s = ctx->priv;
  238. ThreadData *td = arg;
  239. AVFrame *in = td->in, *out = td->out;
  240. int offset = jobnr;
  241. int *write = &td->write[jobnr];
  242. const int *const delay = td->delay[jobnr];
  243. const float *const ir = td->ir[jobnr];
  244. int *n_clippings = &td->n_clippings[jobnr];
  245. float *ringbuffer = td->ringbuffer[jobnr];
  246. float *temp_src = td->temp_src[jobnr];
  247. const int n_samples = s->sofa.n_samples; /* length of one IR */
  248. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  249. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  250. const int in_channels = s->n_conv; /* number of input channels */
  251. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  252. const int buffer_length = s->buffer_length;
  253. /* -1 for AND instead of MODULO (applied to powers of 2): */
  254. const uint32_t modulo = (uint32_t)buffer_length - 1;
  255. float *buffer[16]; /* holds ringbuffer for each input channel */
  256. int wr = *write;
  257. int read;
  258. int i, l;
  259. dst += offset;
  260. for (l = 0; l < in_channels; l++) {
  261. /* get starting address of ringbuffer for each input channel */
  262. buffer[l] = ringbuffer + l * buffer_length;
  263. }
  264. for (i = 0; i < in->nb_samples; i++) {
  265. const float *temp_ir = ir; /* using same set of IRs for each sample */
  266. dst[0] = 0;
  267. for (l = 0; l < in_channels; l++) {
  268. /* write current input sample to ringbuffer (for each channel) */
  269. buffer[l][wr] = src[l];
  270. }
  271. /* loop goes through all channels to be convolved */
  272. for (l = 0; l < in_channels; l++) {
  273. const float *const bptr = buffer[l];
  274. if (l == s->lfe_channel) {
  275. /* LFE is an input channel but requires no convolution */
  276. /* apply gain to LFE signal and add to output buffer */
  277. *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
  278. temp_ir += FFALIGN(n_samples, 32);
  279. continue;
  280. }
  281. /* current read position in ringbuffer: input sample write position
  282. * - delay for l-th ch. + diff. betw. IR length and buffer length
  283. * (mod buffer length) */
  284. read = (wr - delay[l] - (n_samples - 1) + buffer_length) & modulo;
  285. if (read + n_samples < buffer_length) {
  286. memmove(temp_src, bptr + read, n_samples * sizeof(*temp_src));
  287. } else {
  288. int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
  289. memmove(temp_src, bptr + read, len * sizeof(*temp_src));
  290. memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
  291. }
  292. /* multiply signal and IR, and add up the results */
  293. dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
  294. temp_ir += FFALIGN(n_samples, 32);
  295. }
  296. /* clippings counter */
  297. if (fabs(dst[0]) > 1)
  298. *n_clippings += 1;
  299. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  300. dst += 2;
  301. src += in_channels;
  302. wr = (wr + 1) & modulo; /* update ringbuffer write position */
  303. }
  304. *write = wr; /* remember write position in ringbuffer for next call */
  305. return 0;
  306. }
  307. static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  308. {
  309. SOFAlizerContext *s = ctx->priv;
  310. ThreadData *td = arg;
  311. AVFrame *in = td->in, *out = td->out;
  312. int offset = jobnr;
  313. int *write = &td->write[jobnr];
  314. FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
  315. int *n_clippings = &td->n_clippings[jobnr];
  316. float *ringbuffer = td->ringbuffer[jobnr];
  317. const int n_samples = s->sofa.n_samples; /* length of one IR */
  318. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  319. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  320. const int in_channels = s->n_conv; /* number of input channels */
  321. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  322. const int buffer_length = s->buffer_length;
  323. /* -1 for AND instead of MODULO (applied to powers of 2): */
  324. const uint32_t modulo = (uint32_t)buffer_length - 1;
  325. FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
  326. FFTContext *ifft = s->ifft[jobnr];
  327. FFTContext *fft = s->fft[jobnr];
  328. const int n_conv = s->n_conv;
  329. const int n_fft = s->n_fft;
  330. const float fft_scale = 1.0f / s->n_fft;
  331. FFTComplex *hrtf_offset;
  332. int wr = *write;
  333. int n_read;
  334. int i, j;
  335. dst += offset;
  336. /* find minimum between number of samples and output buffer length:
  337. * (important, if one IR is longer than the output buffer) */
  338. n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
  339. for (j = 0; j < n_read; j++) {
  340. /* initialize output buf with saved signal from overflow buf */
  341. dst[2 * j] = ringbuffer[wr];
  342. ringbuffer[wr] = 0.0; /* re-set read samples to zero */
  343. /* update ringbuffer read/write position */
  344. wr = (wr + 1) & modulo;
  345. }
  346. /* initialize rest of output buffer with 0 */
  347. for (j = n_read; j < in->nb_samples; j++) {
  348. dst[2 * j] = 0;
  349. }
  350. for (i = 0; i < n_conv; i++) {
  351. if (i == s->lfe_channel) { /* LFE */
  352. for (j = 0; j < in->nb_samples; j++) {
  353. /* apply gain to LFE signal and add to output buffer */
  354. dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
  355. }
  356. continue;
  357. }
  358. /* outer loop: go through all input channels to be convolved */
  359. offset = i * n_fft; /* no. samples already processed */
  360. hrtf_offset = hrtf + offset;
  361. /* fill FFT input with 0 (we want to zero-pad) */
  362. memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
  363. for (j = 0; j < in->nb_samples; j++) {
  364. /* prepare input for FFT */
  365. /* write all samples of current input channel to FFT input array */
  366. fft_in[j].re = src[j * in_channels + i];
  367. }
  368. /* transform input signal of current channel to frequency domain */
  369. av_fft_permute(fft, fft_in);
  370. av_fft_calc(fft, fft_in);
  371. for (j = 0; j < n_fft; j++) {
  372. const FFTComplex *hcomplex = hrtf_offset + j;
  373. const float re = fft_in[j].re;
  374. const float im = fft_in[j].im;
  375. /* complex multiplication of input signal and HRTFs */
  376. /* output channel (real): */
  377. fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
  378. /* output channel (imag): */
  379. fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
  380. }
  381. /* transform output signal of current channel back to time domain */
  382. av_fft_permute(ifft, fft_in);
  383. av_fft_calc(ifft, fft_in);
  384. for (j = 0; j < in->nb_samples; j++) {
  385. /* write output signal of current channel to output buffer */
  386. dst[2 * j] += fft_in[j].re * fft_scale;
  387. }
  388. for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
  389. /* write the rest of output signal to overflow buffer */
  390. int write_pos = (wr + j) & modulo;
  391. *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
  392. }
  393. }
  394. /* go through all samples of current output buffer: count clippings */
  395. for (i = 0; i < out->nb_samples; i++) {
  396. /* clippings counter */
  397. if (fabs(*dst) > 1) { /* if current output sample > 1 */
  398. n_clippings[0]++;
  399. }
  400. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  401. dst += 2;
  402. }
  403. /* remember read/write position in ringbuffer for next call */
  404. *write = wr;
  405. return 0;
  406. }
  407. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  408. {
  409. AVFilterContext *ctx = inlink->dst;
  410. SOFAlizerContext *s = ctx->priv;
  411. AVFilterLink *outlink = ctx->outputs[0];
  412. int n_clippings[2] = { 0 };
  413. ThreadData td;
  414. AVFrame *out;
  415. out = ff_get_audio_buffer(outlink, in->nb_samples);
  416. if (!out) {
  417. av_frame_free(&in);
  418. return AVERROR(ENOMEM);
  419. }
  420. av_frame_copy_props(out, in);
  421. td.in = in; td.out = out; td.write = s->write;
  422. td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
  423. td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
  424. td.temp_fft = s->temp_fft;
  425. if (s->type == TIME_DOMAIN) {
  426. ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
  427. } else {
  428. ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
  429. }
  430. emms_c();
  431. /* display error message if clipping occurred */
  432. if (n_clippings[0] + n_clippings[1] > 0) {
  433. av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
  434. n_clippings[0] + n_clippings[1], out->nb_samples * 2);
  435. }
  436. av_frame_free(&in);
  437. return ff_filter_frame(outlink, out);
  438. }
  439. static int query_formats(AVFilterContext *ctx)
  440. {
  441. struct SOFAlizerContext *s = ctx->priv;
  442. AVFilterFormats *formats = NULL;
  443. AVFilterChannelLayouts *layouts = NULL;
  444. int ret, sample_rates[] = { 48000, -1 };
  445. ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  446. if (ret)
  447. return ret;
  448. ret = ff_set_common_formats(ctx, formats);
  449. if (ret)
  450. return ret;
  451. layouts = ff_all_channel_layouts();
  452. if (!layouts)
  453. return AVERROR(ENOMEM);
  454. ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
  455. if (ret)
  456. return ret;
  457. layouts = NULL;
  458. ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
  459. if (ret)
  460. return ret;
  461. ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
  462. if (ret)
  463. return ret;
  464. sample_rates[0] = s->sample_rate;
  465. formats = ff_make_format_list(sample_rates);
  466. if (!formats)
  467. return AVERROR(ENOMEM);
  468. return ff_set_common_samplerates(ctx, formats);
  469. }
  470. static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
  471. {
  472. struct SOFAlizerContext *s = ctx->priv;
  473. int n_samples;
  474. int n_conv = s->n_conv; /* no. channels to convolve */
  475. int n_fft;
  476. float delay_l; /* broadband delay for each IR */
  477. float delay_r;
  478. int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
  479. float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
  480. FFTComplex *data_hrtf_l = NULL;
  481. FFTComplex *data_hrtf_r = NULL;
  482. FFTComplex *fft_in_l = NULL;
  483. FFTComplex *fft_in_r = NULL;
  484. float *data_ir_l = NULL;
  485. float *data_ir_r = NULL;
  486. int offset = 0; /* used for faster pointer arithmetics in for-loop */
  487. int i, j, azim_orig = azim, elev_orig = elev;
  488. int filter_length, ret = 0;
  489. int n_current;
  490. int n_max = 0;
  491. s->sofa.easy = mysofa_open(s->filename, sample_rate, &filter_length, &ret);
  492. if (!s->sofa.easy || ret) { /* if an invalid SOFA file has been selected */
  493. av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
  494. return AVERROR_INVALIDDATA;
  495. }
  496. n_samples = s->sofa.n_samples;
  497. s->data_ir[0] = av_calloc(FFALIGN(n_samples, 32), sizeof(float) * s->n_conv);
  498. s->data_ir[1] = av_calloc(FFALIGN(n_samples, 32), sizeof(float) * s->n_conv);
  499. s->delay[0] = av_calloc(s->n_conv, sizeof(int));
  500. s->delay[1] = av_calloc(s->n_conv, sizeof(int));
  501. if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
  502. ret = AVERROR(ENOMEM);
  503. goto fail;
  504. }
  505. /* get temporary IR for L and R channel */
  506. data_ir_l = av_calloc(n_conv * FFALIGN(n_samples, 32), sizeof(*data_ir_l));
  507. data_ir_r = av_calloc(n_conv * FFALIGN(n_samples, 32), sizeof(*data_ir_r));
  508. if (!data_ir_r || !data_ir_l) {
  509. ret = AVERROR(ENOMEM);
  510. goto fail;
  511. }
  512. if (s->type == TIME_DOMAIN) {
  513. s->temp_src[0] = av_calloc(FFALIGN(n_samples, 32), sizeof(float));
  514. s->temp_src[1] = av_calloc(FFALIGN(n_samples, 32), sizeof(float));
  515. if (!s->temp_src[0] || !s->temp_src[1]) {
  516. ret = AVERROR(ENOMEM);
  517. goto fail;
  518. }
  519. }
  520. s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
  521. s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
  522. if (!s->speaker_azim || !s->speaker_elev) {
  523. ret = AVERROR(ENOMEM);
  524. goto fail;
  525. }
  526. /* get speaker positions */
  527. if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
  528. av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
  529. goto fail;
  530. }
  531. for (i = 0; i < s->n_conv; i++) {
  532. float coordinates[3];
  533. /* load and store IRs and corresponding delays */
  534. azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
  535. elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
  536. coordinates[0] = azim;
  537. coordinates[1] = elev;
  538. coordinates[2] = radius;
  539. mysofa_s2c(coordinates);
  540. /* get id of IR closest to desired position */
  541. mysofa_getfilter_float(s->sofa.easy, coordinates[0], coordinates[1], coordinates[2],
  542. data_ir_l + FFALIGN(n_samples, 32) * i,
  543. data_ir_r + FFALIGN(n_samples, 32) * i,
  544. &delay_l, &delay_r);
  545. s->delay[0][i] = delay_l * sample_rate;
  546. s->delay[1][i] = delay_r * sample_rate;
  547. s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
  548. }
  549. /* get size of ringbuffer (longest IR plus max. delay) */
  550. /* then choose next power of 2 for performance optimization */
  551. n_current = s->sofa.n_samples + s->sofa.max_delay;
  552. /* length of longest IR plus max. delay */
  553. n_max = FFMAX(n_max, n_current);
  554. /* buffer length is longest IR plus max. delay -> next power of 2
  555. (32 - count leading zeros gives required exponent) */
  556. s->buffer_length = 1 << (32 - ff_clz(n_max));
  557. s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + sample_rate));
  558. if (s->type == FREQUENCY_DOMAIN) {
  559. av_fft_end(s->fft[0]);
  560. av_fft_end(s->fft[1]);
  561. s->fft[0] = av_fft_init(log2(s->n_fft), 0);
  562. s->fft[1] = av_fft_init(log2(s->n_fft), 0);
  563. av_fft_end(s->ifft[0]);
  564. av_fft_end(s->ifft[1]);
  565. s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
  566. s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
  567. if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
  568. av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
  569. ret = AVERROR(ENOMEM);
  570. goto fail;
  571. }
  572. }
  573. if (s->type == TIME_DOMAIN) {
  574. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  575. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  576. } else {
  577. /* get temporary HRTF memory for L and R channel */
  578. data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
  579. data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
  580. if (!data_hrtf_r || !data_hrtf_l) {
  581. ret = AVERROR(ENOMEM);
  582. goto fail;
  583. }
  584. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
  585. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
  586. s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  587. s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  588. if (!s->temp_fft[0] || !s->temp_fft[1]) {
  589. ret = AVERROR(ENOMEM);
  590. goto fail;
  591. }
  592. }
  593. if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
  594. ret = AVERROR(ENOMEM);
  595. goto fail;
  596. }
  597. if (s->type == FREQUENCY_DOMAIN) {
  598. fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
  599. fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
  600. if (!fft_in_l || !fft_in_r) {
  601. ret = AVERROR(ENOMEM);
  602. goto fail;
  603. }
  604. }
  605. for (i = 0; i < s->n_conv; i++) {
  606. float *lir, *rir;
  607. offset = i * FFALIGN(n_samples, 32); /* no. samples already written */
  608. lir = data_ir_l + offset;
  609. rir = data_ir_r + offset;
  610. if (s->type == TIME_DOMAIN) {
  611. for (j = 0; j < n_samples; j++) {
  612. /* load reversed IRs of the specified source position
  613. * sample-by-sample for left and right ear; and apply gain */
  614. s->data_ir[0][offset + j] = lir[n_samples - 1 - j] * gain_lin;
  615. s->data_ir[1][offset + j] = rir[n_samples - 1 - j] * gain_lin;
  616. }
  617. } else {
  618. memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
  619. memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
  620. offset = i * n_fft; /* no. samples already written */
  621. for (j = 0; j < n_samples; j++) {
  622. /* load non-reversed IRs of the specified source position
  623. * sample-by-sample and apply gain,
  624. * L channel is loaded to real part, R channel to imag part,
  625. * IRs ared shifted by L and R delay */
  626. fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
  627. fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
  628. }
  629. /* actually transform to frequency domain (IRs -> HRTFs) */
  630. av_fft_permute(s->fft[0], fft_in_l);
  631. av_fft_calc(s->fft[0], fft_in_l);
  632. memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
  633. av_fft_permute(s->fft[0], fft_in_r);
  634. av_fft_calc(s->fft[0], fft_in_r);
  635. memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
  636. }
  637. }
  638. if (s->type == FREQUENCY_DOMAIN) {
  639. s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  640. s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  641. if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
  642. ret = AVERROR(ENOMEM);
  643. goto fail;
  644. }
  645. memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
  646. sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
  647. memcpy(s->data_hrtf[1], data_hrtf_r,
  648. sizeof(FFTComplex) * n_conv * n_fft);
  649. }
  650. fail:
  651. av_freep(&data_hrtf_l); /* free temporary HRTF memory */
  652. av_freep(&data_hrtf_r);
  653. av_freep(&data_ir_l); /* free temprary IR memory */
  654. av_freep(&data_ir_r);
  655. av_freep(&fft_in_l); /* free temporary FFT memory */
  656. av_freep(&fft_in_r);
  657. return ret;
  658. }
  659. static av_cold int init(AVFilterContext *ctx)
  660. {
  661. SOFAlizerContext *s = ctx->priv;
  662. int ret;
  663. if (!s->filename) {
  664. av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
  665. return AVERROR(EINVAL);
  666. }
  667. /* preload SOFA file, */
  668. ret = preload_sofa(ctx, s->filename, &s->sample_rate);
  669. if (ret) {
  670. /* file loading error */
  671. av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
  672. } else { /* no file loading error, resampling not required */
  673. av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
  674. }
  675. if (ret) {
  676. av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
  677. return ret;
  678. }
  679. s->fdsp = avpriv_float_dsp_alloc(0);
  680. if (!s->fdsp)
  681. return AVERROR(ENOMEM);
  682. return 0;
  683. }
  684. static int config_input(AVFilterLink *inlink)
  685. {
  686. AVFilterContext *ctx = inlink->dst;
  687. SOFAlizerContext *s = ctx->priv;
  688. int ret;
  689. if (s->type == FREQUENCY_DOMAIN) {
  690. inlink->partial_buf_size =
  691. inlink->min_samples =
  692. inlink->max_samples = inlink->sample_rate;
  693. }
  694. /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
  695. s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
  696. s->n_conv = inlink->channels;
  697. /* load IRs to data_ir[0] and data_ir[1] for required directions */
  698. if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
  699. return ret;
  700. av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
  701. inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
  702. return 0;
  703. }
  704. static av_cold void uninit(AVFilterContext *ctx)
  705. {
  706. SOFAlizerContext *s = ctx->priv;
  707. close_sofa(&s->sofa);
  708. av_fft_end(s->ifft[0]);
  709. av_fft_end(s->ifft[1]);
  710. av_fft_end(s->fft[0]);
  711. av_fft_end(s->fft[1]);
  712. av_freep(&s->delay[0]);
  713. av_freep(&s->delay[1]);
  714. av_freep(&s->data_ir[0]);
  715. av_freep(&s->data_ir[1]);
  716. av_freep(&s->ringbuffer[0]);
  717. av_freep(&s->ringbuffer[1]);
  718. av_freep(&s->speaker_azim);
  719. av_freep(&s->speaker_elev);
  720. av_freep(&s->temp_src[0]);
  721. av_freep(&s->temp_src[1]);
  722. av_freep(&s->temp_fft[0]);
  723. av_freep(&s->temp_fft[1]);
  724. av_freep(&s->data_hrtf[0]);
  725. av_freep(&s->data_hrtf[1]);
  726. av_freep(&s->fdsp);
  727. }
  728. #define OFFSET(x) offsetof(SOFAlizerContext, x)
  729. #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  730. static const AVOption sofalizer_options[] = {
  731. { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
  732. { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
  733. { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
  734. { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
  735. { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
  736. { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
  737. { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
  738. { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
  739. { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
  740. { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -9, 9, .flags = FLAGS },
  741. { NULL }
  742. };
  743. AVFILTER_DEFINE_CLASS(sofalizer);
  744. static const AVFilterPad inputs[] = {
  745. {
  746. .name = "default",
  747. .type = AVMEDIA_TYPE_AUDIO,
  748. .config_props = config_input,
  749. .filter_frame = filter_frame,
  750. },
  751. { NULL }
  752. };
  753. static const AVFilterPad outputs[] = {
  754. {
  755. .name = "default",
  756. .type = AVMEDIA_TYPE_AUDIO,
  757. },
  758. { NULL }
  759. };
  760. AVFilter ff_af_sofalizer = {
  761. .name = "sofalizer",
  762. .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
  763. .priv_size = sizeof(SOFAlizerContext),
  764. .priv_class = &sofalizer_class,
  765. .init = init,
  766. .uninit = uninit,
  767. .query_formats = query_formats,
  768. .inputs = inputs,
  769. .outputs = outputs,
  770. .flags = AVFILTER_FLAG_SLICE_THREADS,
  771. };