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.

1022 lines
37KB

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