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.

921 lines
33KB

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