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.

919 lines
33KB

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