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.

1075 lines
39KB

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