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.

1015 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. res = s->sofa.hrtf->DataIR.values + nearest * s->sofa.hrtf->N * s->sofa.hrtf->R;
  535. }
  536. *delay_left = delays[0];
  537. *delay_right = delays[1];
  538. fl = res;
  539. fr = res + s->sofa.hrtf->N;
  540. memcpy(left, fl, sizeof(float) * s->sofa.hrtf->N);
  541. memcpy(right, fr, sizeof(float) * s->sofa.hrtf->N);
  542. return 0;
  543. }
  544. static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
  545. {
  546. struct SOFAlizerContext *s = ctx->priv;
  547. int n_samples;
  548. int ir_samples;
  549. int n_conv = s->n_conv; /* no. channels to convolve */
  550. int n_fft;
  551. float delay_l; /* broadband delay for each IR */
  552. float delay_r;
  553. int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
  554. float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
  555. FFTComplex *data_hrtf_l = NULL;
  556. FFTComplex *data_hrtf_r = NULL;
  557. FFTComplex *fft_in_l = NULL;
  558. FFTComplex *fft_in_r = NULL;
  559. float *data_ir_l = NULL;
  560. float *data_ir_r = NULL;
  561. int offset = 0; /* used for faster pointer arithmetics in for-loop */
  562. int i, j, azim_orig = azim, elev_orig = elev;
  563. int ret = 0;
  564. int n_current;
  565. int n_max = 0;
  566. av_log(ctx, AV_LOG_DEBUG, "IR length: %d.\n", s->sofa.hrtf->N);
  567. s->sofa.ir_samples = s->sofa.hrtf->N;
  568. s->sofa.n_samples = 1 << (32 - ff_clz(s->sofa.ir_samples));
  569. n_samples = s->sofa.n_samples;
  570. ir_samples = s->sofa.ir_samples;
  571. s->data_ir[0] = av_calloc(n_samples, sizeof(float) * s->n_conv);
  572. s->data_ir[1] = av_calloc(n_samples, sizeof(float) * s->n_conv);
  573. s->delay[0] = av_calloc(s->n_conv, sizeof(int));
  574. s->delay[1] = av_calloc(s->n_conv, sizeof(int));
  575. if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
  576. ret = AVERROR(ENOMEM);
  577. goto fail;
  578. }
  579. /* get temporary IR for L and R channel */
  580. data_ir_l = av_calloc(n_conv * n_samples, sizeof(*data_ir_l));
  581. data_ir_r = av_calloc(n_conv * n_samples, sizeof(*data_ir_r));
  582. if (!data_ir_r || !data_ir_l) {
  583. ret = AVERROR(ENOMEM);
  584. goto fail;
  585. }
  586. if (s->type == TIME_DOMAIN) {
  587. s->temp_src[0] = av_calloc(n_samples, sizeof(float));
  588. s->temp_src[1] = av_calloc(n_samples, sizeof(float));
  589. if (!s->temp_src[0] || !s->temp_src[1]) {
  590. ret = AVERROR(ENOMEM);
  591. goto fail;
  592. }
  593. }
  594. s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
  595. s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
  596. if (!s->speaker_azim || !s->speaker_elev) {
  597. ret = AVERROR(ENOMEM);
  598. goto fail;
  599. }
  600. /* get speaker positions */
  601. if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
  602. av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
  603. goto fail;
  604. }
  605. for (i = 0; i < s->n_conv; i++) {
  606. float coordinates[3];
  607. /* load and store IRs and corresponding delays */
  608. azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
  609. elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
  610. coordinates[0] = azim;
  611. coordinates[1] = elev;
  612. coordinates[2] = radius;
  613. mysofa_s2c(coordinates);
  614. /* get id of IR closest to desired position */
  615. ret = getfilter_float(ctx, coordinates[0], coordinates[1], coordinates[2],
  616. data_ir_l + n_samples * i,
  617. data_ir_r + n_samples * i,
  618. &delay_l, &delay_r);
  619. if (ret < 0)
  620. return ret;
  621. s->delay[0][i] = delay_l * sample_rate;
  622. s->delay[1][i] = delay_r * sample_rate;
  623. s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
  624. }
  625. /* get size of ringbuffer (longest IR plus max. delay) */
  626. /* then choose next power of 2 for performance optimization */
  627. n_current = n_samples + s->sofa.max_delay;
  628. /* length of longest IR plus max. delay */
  629. n_max = FFMAX(n_max, n_current);
  630. /* buffer length is longest IR plus max. delay -> next power of 2
  631. (32 - count leading zeros gives required exponent) */
  632. s->buffer_length = 1 << (32 - ff_clz(n_max));
  633. s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
  634. if (s->type == FREQUENCY_DOMAIN) {
  635. av_fft_end(s->fft[0]);
  636. av_fft_end(s->fft[1]);
  637. s->fft[0] = av_fft_init(log2(s->n_fft), 0);
  638. s->fft[1] = av_fft_init(log2(s->n_fft), 0);
  639. av_fft_end(s->ifft[0]);
  640. av_fft_end(s->ifft[1]);
  641. s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
  642. s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
  643. if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
  644. av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
  645. ret = AVERROR(ENOMEM);
  646. goto fail;
  647. }
  648. }
  649. if (s->type == TIME_DOMAIN) {
  650. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  651. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  652. } else {
  653. /* get temporary HRTF memory for L and R channel */
  654. data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
  655. data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
  656. if (!data_hrtf_r || !data_hrtf_l) {
  657. ret = AVERROR(ENOMEM);
  658. goto fail;
  659. }
  660. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
  661. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
  662. s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  663. s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  664. if (!s->temp_fft[0] || !s->temp_fft[1]) {
  665. ret = AVERROR(ENOMEM);
  666. goto fail;
  667. }
  668. }
  669. if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
  670. ret = AVERROR(ENOMEM);
  671. goto fail;
  672. }
  673. if (s->type == FREQUENCY_DOMAIN) {
  674. fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
  675. fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
  676. if (!fft_in_l || !fft_in_r) {
  677. ret = AVERROR(ENOMEM);
  678. goto fail;
  679. }
  680. }
  681. for (i = 0; i < s->n_conv; i++) {
  682. float *lir, *rir;
  683. offset = i * n_samples; /* no. samples already written */
  684. lir = data_ir_l + offset;
  685. rir = data_ir_r + offset;
  686. if (s->type == TIME_DOMAIN) {
  687. for (j = 0; j < ir_samples; j++) {
  688. /* load reversed IRs of the specified source position
  689. * sample-by-sample for left and right ear; and apply gain */
  690. s->data_ir[0][offset + j] = lir[ir_samples - 1 - j] * gain_lin;
  691. s->data_ir[1][offset + j] = rir[ir_samples - 1 - j] * gain_lin;
  692. }
  693. } else {
  694. memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
  695. memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
  696. offset = i * n_fft; /* no. samples already written */
  697. for (j = 0; j < ir_samples; j++) {
  698. /* load non-reversed IRs of the specified source position
  699. * sample-by-sample and apply gain,
  700. * L channel is loaded to real part, R channel to imag part,
  701. * IRs ared shifted by L and R delay */
  702. fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
  703. fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
  704. }
  705. /* actually transform to frequency domain (IRs -> HRTFs) */
  706. av_fft_permute(s->fft[0], fft_in_l);
  707. av_fft_calc(s->fft[0], fft_in_l);
  708. memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
  709. av_fft_permute(s->fft[0], fft_in_r);
  710. av_fft_calc(s->fft[0], fft_in_r);
  711. memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
  712. }
  713. }
  714. if (s->type == FREQUENCY_DOMAIN) {
  715. s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  716. s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  717. if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
  718. ret = AVERROR(ENOMEM);
  719. goto fail;
  720. }
  721. memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
  722. sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
  723. memcpy(s->data_hrtf[1], data_hrtf_r,
  724. sizeof(FFTComplex) * n_conv * n_fft);
  725. }
  726. fail:
  727. av_freep(&data_hrtf_l); /* free temporary HRTF memory */
  728. av_freep(&data_hrtf_r);
  729. av_freep(&data_ir_l); /* free temprary IR memory */
  730. av_freep(&data_ir_r);
  731. av_freep(&fft_in_l); /* free temporary FFT memory */
  732. av_freep(&fft_in_r);
  733. return ret;
  734. }
  735. static av_cold int init(AVFilterContext *ctx)
  736. {
  737. SOFAlizerContext *s = ctx->priv;
  738. int ret;
  739. if (!s->filename) {
  740. av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
  741. return AVERROR(EINVAL);
  742. }
  743. /* preload SOFA file, */
  744. ret = preload_sofa(ctx, s->filename, &s->sample_rate);
  745. if (ret) {
  746. /* file loading error */
  747. av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
  748. } else { /* no file loading error, resampling not required */
  749. av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
  750. }
  751. if (ret) {
  752. av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
  753. return ret;
  754. }
  755. s->fdsp = avpriv_float_dsp_alloc(0);
  756. if (!s->fdsp)
  757. return AVERROR(ENOMEM);
  758. return 0;
  759. }
  760. static int config_input(AVFilterLink *inlink)
  761. {
  762. AVFilterContext *ctx = inlink->dst;
  763. SOFAlizerContext *s = ctx->priv;
  764. int ret;
  765. if (s->type == FREQUENCY_DOMAIN) {
  766. inlink->partial_buf_size =
  767. inlink->min_samples =
  768. inlink->max_samples = s->framesize;
  769. }
  770. /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
  771. s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
  772. s->n_conv = inlink->channels;
  773. /* load IRs to data_ir[0] and data_ir[1] for required directions */
  774. if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
  775. return ret;
  776. av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
  777. inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
  778. return 0;
  779. }
  780. static av_cold void uninit(AVFilterContext *ctx)
  781. {
  782. SOFAlizerContext *s = ctx->priv;
  783. close_sofa(&s->sofa);
  784. av_fft_end(s->ifft[0]);
  785. av_fft_end(s->ifft[1]);
  786. av_fft_end(s->fft[0]);
  787. av_fft_end(s->fft[1]);
  788. s->ifft[0] = NULL;
  789. s->ifft[1] = NULL;
  790. s->fft[0] = NULL;
  791. s->fft[1] = NULL;
  792. av_freep(&s->delay[0]);
  793. av_freep(&s->delay[1]);
  794. av_freep(&s->data_ir[0]);
  795. av_freep(&s->data_ir[1]);
  796. av_freep(&s->ringbuffer[0]);
  797. av_freep(&s->ringbuffer[1]);
  798. av_freep(&s->speaker_azim);
  799. av_freep(&s->speaker_elev);
  800. av_freep(&s->temp_src[0]);
  801. av_freep(&s->temp_src[1]);
  802. av_freep(&s->temp_fft[0]);
  803. av_freep(&s->temp_fft[1]);
  804. av_freep(&s->data_hrtf[0]);
  805. av_freep(&s->data_hrtf[1]);
  806. av_freep(&s->fdsp);
  807. }
  808. #define OFFSET(x) offsetof(SOFAlizerContext, x)
  809. #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  810. static const AVOption sofalizer_options[] = {
  811. { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
  812. { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
  813. { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
  814. { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
  815. { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 5, .flags = FLAGS },
  816. { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
  817. { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
  818. { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
  819. { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
  820. { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20,40, .flags = FLAGS },
  821. { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT, {.i64=1024},1024,96000, .flags = FLAGS },
  822. { "normalize", "normalize IRs", OFFSET(normalize), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, .flags = FLAGS },
  823. { "interpolate","interpolate IRs from neighbors", OFFSET(interpolate),AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
  824. { "minphase", "minphase IRs", OFFSET(minphase), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
  825. { "anglestep", "set neighbor search angle step", OFFSET(anglestep), AV_OPT_TYPE_FLOAT, {.dbl=.5}, 0.01, 10, .flags = FLAGS },
  826. { "radstep", "set neighbor search radius step", OFFSET(radstep), AV_OPT_TYPE_FLOAT, {.dbl=.01}, 0.01, 1, .flags = FLAGS },
  827. { NULL }
  828. };
  829. AVFILTER_DEFINE_CLASS(sofalizer);
  830. static const AVFilterPad inputs[] = {
  831. {
  832. .name = "default",
  833. .type = AVMEDIA_TYPE_AUDIO,
  834. .config_props = config_input,
  835. .filter_frame = filter_frame,
  836. },
  837. { NULL }
  838. };
  839. static const AVFilterPad outputs[] = {
  840. {
  841. .name = "default",
  842. .type = AVMEDIA_TYPE_AUDIO,
  843. },
  844. { NULL }
  845. };
  846. AVFilter ff_af_sofalizer = {
  847. .name = "sofalizer",
  848. .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
  849. .priv_size = sizeof(SOFAlizerContext),
  850. .priv_class = &sofalizer_class,
  851. .init = init,
  852. .uninit = uninit,
  853. .query_formats = query_formats,
  854. .inputs = inputs,
  855. .outputs = outputs,
  856. .flags = AVFILTER_FLAG_SLICE_THREADS,
  857. };