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.

1260 lines
48KB

  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 <netcdf.h>
  29. #include "libavcodec/avfft.h"
  30. #include "libavutil/float_dsp.h"
  31. #include "libavutil/opt.h"
  32. #include "avfilter.h"
  33. #include "internal.h"
  34. #include "audio.h"
  35. #define TIME_DOMAIN 0
  36. #define FREQUENCY_DOMAIN 1
  37. typedef struct NCSofa { /* contains data of one SOFA file */
  38. int ncid; /* netCDF ID of the opened SOFA file */
  39. int n_samples; /* length of one impulse response (IR) */
  40. int m_dim; /* number of measurement positions */
  41. int *data_delay; /* broadband delay of each IR */
  42. /* all measurement positions for each receiver (i.e. ear): */
  43. float *sp_a; /* azimuth angles */
  44. float *sp_e; /* elevation angles */
  45. float *sp_r; /* radii */
  46. /* data at each measurement position for each receiver: */
  47. float *data_ir; /* IRs (time-domain) */
  48. } NCSofa;
  49. typedef struct SOFAlizerContext {
  50. const AVClass *class;
  51. char *filename; /* name of SOFA file */
  52. NCSofa sofa; /* contains data of the SOFA file */
  53. int sample_rate; /* sample rate from SOFA file */
  54. float *speaker_azim; /* azimuth of the virtual loudspeakers */
  55. float *speaker_elev; /* elevation of the virtual loudspeakers */
  56. float gain_lfe; /* gain applied to LFE channel */
  57. int lfe_channel; /* LFE channel position in channel layout */
  58. int n_conv; /* number of channels to convolute */
  59. /* buffer variables (for convolution) */
  60. float *ringbuffer[2]; /* buffers input samples, length of one buffer: */
  61. /* no. input ch. (incl. LFE) x buffer_length */
  62. int write[2]; /* current write position to ringbuffer */
  63. int buffer_length; /* is: longest IR plus max. delay in all SOFA files */
  64. /* then choose next power of 2 */
  65. int n_fft; /* number of samples in one FFT block */
  66. /* netCDF variables */
  67. int *delay[2]; /* broadband delay for each channel/IR to be convolved */
  68. float *data_ir[2]; /* IRs for all channels to be convolved */
  69. /* (this excludes the LFE) */
  70. float *temp_src[2];
  71. FFTComplex *temp_fft[2];
  72. /* control variables */
  73. float gain; /* filter gain (in dB) */
  74. float rotation; /* rotation of virtual loudspeakers (in degrees) */
  75. float elevation; /* elevation of virtual loudspeakers (in deg.) */
  76. float radius; /* distance virtual loudspeakers to listener (in metres) */
  77. int type; /* processing type */
  78. FFTContext *fft[2], *ifft[2];
  79. FFTComplex *data_hrtf[2];
  80. AVFloatDSPContext *fdsp;
  81. } SOFAlizerContext;
  82. static int close_sofa(struct NCSofa *sofa)
  83. {
  84. av_freep(&sofa->data_delay);
  85. av_freep(&sofa->sp_a);
  86. av_freep(&sofa->sp_e);
  87. av_freep(&sofa->sp_r);
  88. av_freep(&sofa->data_ir);
  89. nc_close(sofa->ncid);
  90. sofa->ncid = 0;
  91. return 0;
  92. }
  93. static int load_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
  94. {
  95. struct SOFAlizerContext *s = ctx->priv;
  96. /* variables associated with content of SOFA file: */
  97. int ncid, n_dims, n_vars, n_gatts, n_unlim_dim_id, status;
  98. char data_delay_dim_name[NC_MAX_NAME];
  99. float *sp_a, *sp_e, *sp_r, *data_ir;
  100. char *sofa_conventions;
  101. char dim_name[NC_MAX_NAME]; /* names of netCDF dimensions */
  102. size_t *dim_length; /* lengths of netCDF dimensions */
  103. char *text;
  104. unsigned int sample_rate;
  105. int data_delay_dim_id[2];
  106. int samplingrate_id;
  107. int data_delay_id;
  108. int n_samples;
  109. int m_dim_id = -1;
  110. int n_dim_id = -1;
  111. int data_ir_id;
  112. size_t att_len;
  113. int m_dim;
  114. int *data_delay;
  115. int sp_id;
  116. int i, ret;
  117. s->sofa.ncid = 0;
  118. status = nc_open(filename, NC_NOWRITE, &ncid); /* open SOFA file read-only */
  119. if (status != NC_NOERR) {
  120. av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
  121. return AVERROR(EINVAL);
  122. }
  123. /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
  124. nc_inq(ncid, &n_dims, &n_vars, &n_gatts, &n_unlim_dim_id);
  125. /* -- get number of measurements ("M") and length of one IR ("N") -- */
  126. dim_length = av_malloc_array(n_dims, sizeof(*dim_length));
  127. if (!dim_length) {
  128. nc_close(ncid);
  129. return AVERROR(ENOMEM);
  130. }
  131. for (i = 0; i < n_dims; i++) { /* go through all dimensions of file */
  132. nc_inq_dim(ncid, i, (char *)&dim_name, &dim_length[i]); /* get dimensions */
  133. if (!strncmp("M", (const char *)&dim_name, 1)) /* get ID of dimension "M" */
  134. m_dim_id = i;
  135. if (!strncmp("N", (const char *)&dim_name, 1)) /* get ID of dimension "N" */
  136. n_dim_id = i;
  137. }
  138. if ((m_dim_id == -1) || (n_dim_id == -1)) { /* dimension "M" or "N" couldn't be found */
  139. av_log(ctx, AV_LOG_ERROR, "Can't find required dimensions in SOFA file.\n");
  140. av_freep(&dim_length);
  141. nc_close(ncid);
  142. return AVERROR(EINVAL);
  143. }
  144. n_samples = dim_length[n_dim_id]; /* get length of one IR */
  145. m_dim = dim_length[m_dim_id]; /* get number of measurements */
  146. av_freep(&dim_length);
  147. /* -- check file type -- */
  148. /* get length of attritube "Conventions" */
  149. status = nc_inq_attlen(ncid, NC_GLOBAL, "Conventions", &att_len);
  150. if (status != NC_NOERR) {
  151. av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
  152. nc_close(ncid);
  153. return AVERROR_INVALIDDATA;
  154. }
  155. /* check whether file is SOFA file */
  156. text = av_malloc(att_len + 1);
  157. if (!text) {
  158. nc_close(ncid);
  159. return AVERROR(ENOMEM);
  160. }
  161. nc_get_att_text(ncid, NC_GLOBAL, "Conventions", text);
  162. *(text + att_len) = 0;
  163. if (strncmp("SOFA", text, 4)) {
  164. av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
  165. av_freep(&text);
  166. nc_close(ncid);
  167. return AVERROR(EINVAL);
  168. }
  169. av_freep(&text);
  170. status = nc_inq_attlen(ncid, NC_GLOBAL, "License", &att_len);
  171. if (status == NC_NOERR) {
  172. text = av_malloc(att_len + 1);
  173. if (text) {
  174. nc_get_att_text(ncid, NC_GLOBAL, "License", text);
  175. *(text + att_len) = 0;
  176. av_log(ctx, AV_LOG_INFO, "SOFA file License: %s\n", text);
  177. av_freep(&text);
  178. }
  179. }
  180. status = nc_inq_attlen(ncid, NC_GLOBAL, "SourceDescription", &att_len);
  181. if (status == NC_NOERR) {
  182. text = av_malloc(att_len + 1);
  183. if (text) {
  184. nc_get_att_text(ncid, NC_GLOBAL, "SourceDescription", text);
  185. *(text + att_len) = 0;
  186. av_log(ctx, AV_LOG_INFO, "SOFA file SourceDescription: %s\n", text);
  187. av_freep(&text);
  188. }
  189. }
  190. status = nc_inq_attlen(ncid, NC_GLOBAL, "Comment", &att_len);
  191. if (status == NC_NOERR) {
  192. text = av_malloc(att_len + 1);
  193. if (text) {
  194. nc_get_att_text(ncid, NC_GLOBAL, "Comment", text);
  195. *(text + att_len) = 0;
  196. av_log(ctx, AV_LOG_INFO, "SOFA file Comment: %s\n", text);
  197. av_freep(&text);
  198. }
  199. }
  200. status = nc_inq_attlen(ncid, NC_GLOBAL, "SOFAConventions", &att_len);
  201. if (status != NC_NOERR) {
  202. av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"SOFAConventions\".\n");
  203. nc_close(ncid);
  204. return AVERROR_INVALIDDATA;
  205. }
  206. sofa_conventions = av_malloc(att_len + 1);
  207. if (!sofa_conventions) {
  208. nc_close(ncid);
  209. return AVERROR(ENOMEM);
  210. }
  211. nc_get_att_text(ncid, NC_GLOBAL, "SOFAConventions", sofa_conventions);
  212. *(sofa_conventions + att_len) = 0;
  213. if (strncmp("SimpleFreeFieldHRIR", sofa_conventions, att_len)) {
  214. av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
  215. av_freep(&sofa_conventions);
  216. nc_close(ncid);
  217. return AVERROR(EINVAL);
  218. }
  219. av_freep(&sofa_conventions);
  220. /* -- get sampling rate of HRTFs -- */
  221. /* read ID, then value */
  222. status = nc_inq_varid(ncid, "Data.SamplingRate", &samplingrate_id);
  223. status += nc_get_var_uint(ncid, samplingrate_id, &sample_rate);
  224. if (status != NC_NOERR) {
  225. av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
  226. nc_close(ncid);
  227. return AVERROR(EINVAL);
  228. }
  229. *samplingrate = sample_rate; /* remember sampling rate */
  230. /* -- allocate memory for one value for each measurement position: -- */
  231. sp_a = s->sofa.sp_a = av_malloc_array(m_dim, sizeof(float));
  232. sp_e = s->sofa.sp_e = av_malloc_array(m_dim, sizeof(float));
  233. sp_r = s->sofa.sp_r = av_malloc_array(m_dim, sizeof(float));
  234. /* delay and IR values required for each ear and measurement position: */
  235. data_delay = s->sofa.data_delay = av_calloc(m_dim, 2 * sizeof(int));
  236. data_ir = s->sofa.data_ir = av_malloc_array(m_dim * n_samples, sizeof(float) * 2);
  237. if (!data_delay || !sp_a || !sp_e || !sp_r || !data_ir) {
  238. /* if memory could not be allocated */
  239. close_sofa(&s->sofa);
  240. return AVERROR(ENOMEM);
  241. }
  242. /* get impulse responses (HRTFs): */
  243. /* get corresponding ID */
  244. status = nc_inq_varid(ncid, "Data.IR", &data_ir_id);
  245. status += nc_get_var_float(ncid, data_ir_id, data_ir); /* read and store IRs */
  246. if (status != NC_NOERR) {
  247. av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.IR!\n");
  248. ret = AVERROR(EINVAL);
  249. goto error;
  250. }
  251. /* get source positions of the HRTFs in the SOFA file: */
  252. status = nc_inq_varid(ncid, "SourcePosition", &sp_id); /* get corresponding ID */
  253. status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 0 } ,
  254. (size_t[2]){ m_dim, 1}, sp_a); /* read & store azimuth angles */
  255. status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 1 } ,
  256. (size_t[2]){ m_dim, 1}, sp_e); /* read & store elevation angles */
  257. status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 2 } ,
  258. (size_t[2]){ m_dim, 1}, sp_r); /* read & store radii */
  259. if (status != NC_NOERR) { /* if any source position variable coudn't be read */
  260. av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
  261. ret = AVERROR(EINVAL);
  262. goto error;
  263. }
  264. /* read Data.Delay, check for errors and fit it to data_delay */
  265. status = nc_inq_varid(ncid, "Data.Delay", &data_delay_id);
  266. status += nc_inq_vardimid(ncid, data_delay_id, &data_delay_dim_id[0]);
  267. status += nc_inq_dimname(ncid, data_delay_dim_id[0], data_delay_dim_name);
  268. if (status != NC_NOERR) {
  269. av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
  270. ret = AVERROR(EINVAL);
  271. goto error;
  272. }
  273. /* Data.Delay dimension check */
  274. /* dimension of Data.Delay is [I R]: */
  275. if (!strncmp(data_delay_dim_name, "I", 2)) {
  276. /* check 2 characters to assure string is 0-terminated after "I" */
  277. int delay[2]; /* delays get from SOFA file: */
  278. av_log(ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n");
  279. status = nc_get_var_int(ncid, data_delay_id, &delay[0]);
  280. if (status != NC_NOERR) {
  281. av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
  282. ret = AVERROR(EINVAL);
  283. goto error;
  284. }
  285. int *data_delay_r = data_delay + m_dim;
  286. for (i = 0; i < m_dim; i++) { /* extend given dimension [I R] to [M R] */
  287. /* assign constant delay value for all measurements to data_delay fields */
  288. data_delay[i] = delay[0];
  289. data_delay_r[i] = delay[1];
  290. }
  291. /* dimension of Data.Delay is [M R] */
  292. } else if (!strncmp(data_delay_dim_name, "M", 2)) {
  293. av_log(ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
  294. /* get delays from SOFA file: */
  295. status = nc_get_var_int(ncid, data_delay_id, data_delay);
  296. if (status != NC_NOERR) {
  297. av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
  298. ret = AVERROR(EINVAL);
  299. goto error;
  300. }
  301. } else { /* dimension of Data.Delay is neither [I R] nor [M R] */
  302. av_log(ctx, AV_LOG_ERROR, "Data.Delay does not have the required dimensions [I R] or [M R].\n");
  303. ret = AVERROR(EINVAL);
  304. goto error;
  305. }
  306. /* save information in SOFA struct: */
  307. s->sofa.m_dim = m_dim; /* no. measurement positions */
  308. s->sofa.n_samples = n_samples; /* length on one IR */
  309. s->sofa.ncid = ncid; /* netCDF ID of SOFA file */
  310. nc_close(ncid); /* close SOFA file */
  311. return 0;
  312. error:
  313. close_sofa(&s->sofa);
  314. return ret;
  315. }
  316. static int get_speaker_pos(AVFilterContext *ctx,
  317. float *speaker_azim, float *speaker_elev)
  318. {
  319. struct SOFAlizerContext *s = ctx->priv;
  320. uint64_t channels_layout = ctx->inputs[0]->channel_layout;
  321. float azim[10] = { 0 };
  322. float elev[10] = { 0 };
  323. int n_conv = ctx->inputs[0]->channels; /* get no. input channels */
  324. s->lfe_channel = -1;
  325. /* set speaker positions according to input channel configuration: */
  326. switch (channels_layout) {
  327. case AV_CH_LAYOUT_MONO:
  328. azim[0] = 0;
  329. break;
  330. case AV_CH_LAYOUT_2POINT1:
  331. s->lfe_channel = 2;
  332. case AV_CH_LAYOUT_STEREO:
  333. azim[0] = 30;
  334. azim[1] = 330;
  335. break;
  336. case AV_CH_LAYOUT_3POINT1:
  337. s->lfe_channel = 3;
  338. case AV_CH_LAYOUT_SURROUND:
  339. azim[0] = 30;
  340. azim[1] = 330;
  341. azim[2] = 0;
  342. break;
  343. case AV_CH_LAYOUT_2_1:
  344. azim[0] = 30;
  345. azim[1] = 330;
  346. azim[2] = 180;
  347. break;
  348. case AV_CH_LAYOUT_2_2:
  349. azim[0] = 30;
  350. azim[1] = 330;
  351. azim[2] = 90;
  352. azim[3] = 270;
  353. break;
  354. case AV_CH_LAYOUT_QUAD:
  355. azim[0] = 30;
  356. azim[1] = 330;
  357. azim[2] = 120;
  358. azim[3] = 240;
  359. break;
  360. case AV_CH_LAYOUT_4POINT1:
  361. s->lfe_channel = 3;
  362. azim[0] = 30;
  363. azim[1] = 330;
  364. azim[2] = 0;
  365. azim[4] = 180;
  366. break;
  367. case AV_CH_LAYOUT_4POINT0:
  368. azim[0] = 30;
  369. azim[1] = 330;
  370. azim[2] = 0;
  371. azim[3] = 180;
  372. break;
  373. case AV_CH_LAYOUT_5POINT1:
  374. s->lfe_channel = 3;
  375. azim[0] = 30;
  376. azim[1] = 330;
  377. azim[2] = 0;
  378. azim[4] = 90;
  379. azim[5] = 270;
  380. break;
  381. case AV_CH_LAYOUT_5POINT0:
  382. azim[0] = 30;
  383. azim[1] = 330;
  384. azim[2] = 0;
  385. azim[3] = 90;
  386. azim[4] = 270;
  387. break;
  388. case AV_CH_LAYOUT_5POINT1_BACK:
  389. s->lfe_channel = 3;
  390. azim[0] = 30;
  391. azim[1] = 330;
  392. azim[2] = 0;
  393. azim[4] = 120;
  394. azim[5] = 240;
  395. break;
  396. case AV_CH_LAYOUT_5POINT0_BACK:
  397. azim[0] = 30;
  398. azim[1] = 330;
  399. azim[2] = 0;
  400. azim[3] = 120;
  401. azim[4] = 240;
  402. break;
  403. case AV_CH_LAYOUT_6POINT1:
  404. s->lfe_channel = 3;
  405. azim[0] = 30;
  406. azim[1] = 330;
  407. azim[2] = 0;
  408. azim[4] = 180;
  409. azim[5] = 90;
  410. azim[6] = 270;
  411. break;
  412. case AV_CH_LAYOUT_6POINT0:
  413. azim[0] = 30;
  414. azim[1] = 330;
  415. azim[2] = 0;
  416. azim[3] = 180;
  417. azim[4] = 90;
  418. azim[5] = 270;
  419. break;
  420. case AV_CH_LAYOUT_6POINT1_BACK:
  421. s->lfe_channel = 3;
  422. azim[0] = 30;
  423. azim[1] = 330;
  424. azim[2] = 0;
  425. azim[4] = 120;
  426. azim[5] = 240;
  427. azim[6] = 180;
  428. break;
  429. case AV_CH_LAYOUT_HEXAGONAL:
  430. azim[0] = 30;
  431. azim[1] = 330;
  432. azim[2] = 0;
  433. azim[3] = 120;
  434. azim[4] = 240;
  435. azim[5] = 180;
  436. break;
  437. case AV_CH_LAYOUT_7POINT1:
  438. s->lfe_channel = 3;
  439. azim[0] = 30;
  440. azim[1] = 330;
  441. azim[2] = 0;
  442. azim[4] = 150;
  443. azim[5] = 210;
  444. azim[6] = 90;
  445. azim[7] = 270;
  446. break;
  447. case AV_CH_LAYOUT_7POINT0:
  448. azim[0] = 30;
  449. azim[1] = 330;
  450. azim[2] = 0;
  451. azim[3] = 150;
  452. azim[4] = 210;
  453. azim[5] = 90;
  454. azim[6] = 270;
  455. break;
  456. case AV_CH_LAYOUT_OCTAGONAL:
  457. azim[0] = 30;
  458. azim[1] = 330;
  459. azim[2] = 0;
  460. azim[3] = 150;
  461. azim[4] = 210;
  462. azim[5] = 180;
  463. azim[6] = 90;
  464. azim[7] = 270;
  465. break;
  466. default:
  467. return -1;
  468. }
  469. memcpy(speaker_azim, azim, n_conv * sizeof(float));
  470. memcpy(speaker_elev, elev, n_conv * sizeof(float));
  471. return 0;
  472. }
  473. static int max_delay(struct NCSofa *sofa)
  474. {
  475. int i, max = 0;
  476. for (i = 0; i < sofa->m_dim * 2; i++) {
  477. /* search maximum delay in given SOFA file */
  478. max = FFMAX(max, sofa->data_delay[i]);
  479. }
  480. return max;
  481. }
  482. static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
  483. {
  484. /* get source positions and M of currently selected SOFA file */
  485. float *sp_a = s->sofa.sp_a; /* azimuth angle */
  486. float *sp_e = s->sofa.sp_e; /* elevation angle */
  487. float *sp_r = s->sofa.sp_r; /* radius */
  488. int m_dim = s->sofa.m_dim; /* no. measurements */
  489. int best_id = 0; /* index m currently closest to desired source pos. */
  490. float delta = 1000; /* offset between desired and currently best pos. */
  491. float current;
  492. int i;
  493. for (i = 0; i < m_dim; i++) {
  494. /* search through all measurements in currently selected SOFA file */
  495. /* distance of current to desired source position: */
  496. current = fabs(sp_a[i] - azim) +
  497. fabs(sp_e[i] - elev) +
  498. fabs(sp_r[i] - radius);
  499. if (current <= delta) {
  500. /* if current distance is smaller than smallest distance so far */
  501. delta = current;
  502. best_id = i; /* remember index */
  503. }
  504. }
  505. return best_id;
  506. }
  507. static int compensate_volume(AVFilterContext *ctx)
  508. {
  509. struct SOFAlizerContext *s = ctx->priv;
  510. float compensate;
  511. float energy = 0;
  512. float *ir;
  513. int m, j;
  514. if (s->sofa.ncid) {
  515. /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
  516. struct NCSofa *sofa = &s->sofa;
  517. m = find_m(s, 0, 0, 1);
  518. /* get energy of that IR and compensate volume */
  519. ir = sofa->data_ir + 2 * m * sofa->n_samples;
  520. for (j = 0; j < sofa->n_samples; j++) {
  521. energy += *(ir + j) * *(ir + j);
  522. }
  523. compensate = 256 / (sofa->n_samples * sqrt(energy));
  524. av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
  525. ir = sofa->data_ir;
  526. for (j = 0; j < sofa->n_samples * sofa->m_dim * 2; j++) {
  527. ir[j] *= compensate; /* apply volume compensation to IRs */
  528. }
  529. }
  530. return 0;
  531. }
  532. typedef struct ThreadData {
  533. AVFrame *in, *out;
  534. int *write;
  535. int **delay;
  536. float **ir;
  537. int *n_clippings;
  538. float **ringbuffer;
  539. float **temp_src;
  540. FFTComplex **temp_fft;
  541. } ThreadData;
  542. static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  543. {
  544. SOFAlizerContext *s = ctx->priv;
  545. ThreadData *td = arg;
  546. AVFrame *in = td->in, *out = td->out;
  547. int offset = jobnr;
  548. int *write = &td->write[jobnr];
  549. const int *const delay = td->delay[jobnr];
  550. const float *const ir = td->ir[jobnr];
  551. int *n_clippings = &td->n_clippings[jobnr];
  552. float *ringbuffer = td->ringbuffer[jobnr];
  553. float *temp_src = td->temp_src[jobnr];
  554. const int n_samples = s->sofa.n_samples; /* length of one IR */
  555. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  556. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  557. const int in_channels = s->n_conv; /* number of input channels */
  558. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  559. const int buffer_length = s->buffer_length;
  560. /* -1 for AND instead of MODULO (applied to powers of 2): */
  561. const uint32_t modulo = (uint32_t)buffer_length - 1;
  562. float *buffer[10]; /* holds ringbuffer for each input channel */
  563. int wr = *write;
  564. int read;
  565. int i, l;
  566. dst += offset;
  567. for (l = 0; l < in_channels; l++) {
  568. /* get starting address of ringbuffer for each input channel */
  569. buffer[l] = ringbuffer + l * buffer_length;
  570. }
  571. for (i = 0; i < in->nb_samples; i++) {
  572. const float *temp_ir = ir; /* using same set of IRs for each sample */
  573. *dst = 0;
  574. for (l = 0; l < in_channels; l++) {
  575. /* write current input sample to ringbuffer (for each channel) */
  576. *(buffer[l] + wr) = src[l];
  577. }
  578. /* loop goes through all channels to be convolved */
  579. for (l = 0; l < in_channels; l++) {
  580. const float *const bptr = buffer[l];
  581. if (l == s->lfe_channel) {
  582. /* LFE is an input channel but requires no convolution */
  583. /* apply gain to LFE signal and add to output buffer */
  584. *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
  585. temp_ir += n_samples;
  586. continue;
  587. }
  588. /* current read position in ringbuffer: input sample write position
  589. * - delay for l-th ch. + diff. betw. IR length and buffer length
  590. * (mod buffer length) */
  591. read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
  592. if (read + n_samples < buffer_length) {
  593. memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
  594. } else {
  595. int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
  596. memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
  597. memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
  598. }
  599. /* multiply signal and IR, and add up the results */
  600. dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
  601. temp_ir += n_samples;
  602. }
  603. /* clippings counter */
  604. if (fabs(*dst) > 1)
  605. *n_clippings += 1;
  606. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  607. dst += 2;
  608. src += in_channels;
  609. wr = (wr + 1) & modulo; /* update ringbuffer write position */
  610. }
  611. *write = wr; /* remember write position in ringbuffer for next call */
  612. return 0;
  613. }
  614. static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  615. {
  616. SOFAlizerContext *s = ctx->priv;
  617. ThreadData *td = arg;
  618. AVFrame *in = td->in, *out = td->out;
  619. int offset = jobnr;
  620. int *write = &td->write[jobnr];
  621. FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
  622. int *n_clippings = &td->n_clippings[jobnr];
  623. float *ringbuffer = td->ringbuffer[jobnr];
  624. const int n_samples = s->sofa.n_samples; /* length of one IR */
  625. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  626. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  627. const int in_channels = s->n_conv; /* number of input channels */
  628. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  629. const int buffer_length = s->buffer_length;
  630. /* -1 for AND instead of MODULO (applied to powers of 2): */
  631. const uint32_t modulo = (uint32_t)buffer_length - 1;
  632. FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
  633. FFTContext *ifft = s->ifft[jobnr];
  634. FFTContext *fft = s->fft[jobnr];
  635. const int n_conv = s->n_conv;
  636. const int n_fft = s->n_fft;
  637. int wr = *write;
  638. int n_read;
  639. int i, j;
  640. dst += offset;
  641. /* find minimum between number of samples and output buffer length:
  642. * (important, if one IR is longer than the output buffer) */
  643. n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
  644. for (j = 0; j < n_read; j++) {
  645. /* initialize output buf with saved signal from overflow buf */
  646. dst[2 * j] = ringbuffer[wr];
  647. ringbuffer[wr] = 0.0; /* re-set read samples to zero */
  648. /* update ringbuffer read/write position */
  649. wr = (wr + 1) & modulo;
  650. }
  651. /* initialize rest of output buffer with 0 */
  652. for (j = n_read; j < in->nb_samples; j++) {
  653. dst[2 * j] = 0;
  654. }
  655. for (i = 0; i < n_conv; i++) {
  656. if (i == s->lfe_channel) { /* LFE */
  657. for (j = 0; j < in->nb_samples; j++) {
  658. /* apply gain to LFE signal and add to output buffer */
  659. dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
  660. }
  661. continue;
  662. }
  663. /* outer loop: go through all input channels to be convolved */
  664. offset = i * n_fft; /* no. samples already processed */
  665. /* fill FFT input with 0 (we want to zero-pad) */
  666. memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
  667. for (j = 0; j < in->nb_samples; j++) {
  668. /* prepare input for FFT */
  669. /* write all samples of current input channel to FFT input array */
  670. fft_in[j].re = src[j * in_channels + i];
  671. }
  672. /* transform input signal of current channel to frequency domain */
  673. av_fft_permute(fft, fft_in);
  674. av_fft_calc(fft, fft_in);
  675. for (j = 0; j < n_fft; j++) {
  676. const float re = fft_in[j].re;
  677. const float im = fft_in[j].im;
  678. /* complex multiplication of input signal and HRTFs */
  679. /* output channel (real): */
  680. fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
  681. /* output channel (imag): */
  682. fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
  683. }
  684. /* transform output signal of current channel back to time domain */
  685. av_fft_permute(ifft, fft_in);
  686. av_fft_calc(ifft, fft_in);
  687. for (j = 0; j < in->nb_samples; j++) {
  688. /* write output signal of current channel to output buffer */
  689. dst[2 * j] += fft_in[j].re / (float)n_fft;
  690. }
  691. for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
  692. /* write the rest of output signal to overflow buffer */
  693. int write_pos = (wr + j) & modulo;
  694. *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
  695. }
  696. }
  697. /* go through all samples of current output buffer: count clippings */
  698. for (i = 0; i < out->nb_samples; i++) {
  699. /* clippings counter */
  700. if (fabs(*dst) > 1) { /* if current output sample > 1 */
  701. *n_clippings = *n_clippings + 1;
  702. }
  703. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  704. dst += 2;
  705. }
  706. /* remember read/write position in ringbuffer for next call */
  707. *write = wr;
  708. return 0;
  709. }
  710. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  711. {
  712. AVFilterContext *ctx = inlink->dst;
  713. SOFAlizerContext *s = ctx->priv;
  714. AVFilterLink *outlink = ctx->outputs[0];
  715. int n_clippings[2] = { 0 };
  716. ThreadData td;
  717. AVFrame *out;
  718. out = ff_get_audio_buffer(outlink, in->nb_samples);
  719. if (!out) {
  720. av_frame_free(&in);
  721. return AVERROR(ENOMEM);
  722. }
  723. av_frame_copy_props(out, in);
  724. td.in = in; td.out = out; td.write = s->write;
  725. td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
  726. td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
  727. td.temp_fft = s->temp_fft;
  728. if (s->type == TIME_DOMAIN) {
  729. ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
  730. } else {
  731. ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
  732. }
  733. emms_c();
  734. /* display error message if clipping occured */
  735. if (n_clippings[0] + n_clippings[1] > 0) {
  736. av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
  737. n_clippings[0] + n_clippings[1], out->nb_samples * 2);
  738. }
  739. av_frame_free(&in);
  740. return ff_filter_frame(outlink, out);
  741. }
  742. static int query_formats(AVFilterContext *ctx)
  743. {
  744. struct SOFAlizerContext *s = ctx->priv;
  745. AVFilterFormats *formats = NULL;
  746. AVFilterChannelLayouts *layouts = NULL;
  747. int ret, sample_rates[] = { 48000, -1 };
  748. static const uint64_t channel_layouts[] = { AV_CH_LAYOUT_MONO,
  749. AV_CH_LAYOUT_STEREO,
  750. AV_CH_LAYOUT_2POINT1,
  751. AV_CH_LAYOUT_SURROUND,
  752. AV_CH_LAYOUT_2_1,
  753. AV_CH_LAYOUT_4POINT0,
  754. AV_CH_LAYOUT_QUAD,
  755. AV_CH_LAYOUT_2_2,
  756. AV_CH_LAYOUT_3POINT1,
  757. AV_CH_LAYOUT_5POINT0_BACK,
  758. AV_CH_LAYOUT_5POINT0,
  759. AV_CH_LAYOUT_4POINT1,
  760. AV_CH_LAYOUT_5POINT1_BACK,
  761. AV_CH_LAYOUT_5POINT1,
  762. AV_CH_LAYOUT_6POINT0,
  763. AV_CH_LAYOUT_HEXAGONAL,
  764. AV_CH_LAYOUT_6POINT1,
  765. AV_CH_LAYOUT_6POINT1_BACK,
  766. AV_CH_LAYOUT_7POINT0,
  767. AV_CH_LAYOUT_7POINT1,
  768. AV_CH_LAYOUT_OCTAGONAL,
  769. 0, };
  770. ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  771. if (ret)
  772. return ret;
  773. ret = ff_set_common_formats(ctx, formats);
  774. if (ret)
  775. return ret;
  776. layouts = ff_make_formatu64_list(channel_layouts);
  777. if (!layouts)
  778. return AVERROR(ENOMEM);
  779. ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
  780. if (ret)
  781. return ret;
  782. layouts = NULL;
  783. ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
  784. if (ret)
  785. return ret;
  786. ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
  787. if (ret)
  788. return ret;
  789. sample_rates[0] = s->sample_rate;
  790. formats = ff_make_format_list(sample_rates);
  791. if (!formats)
  792. return AVERROR(ENOMEM);
  793. return ff_set_common_samplerates(ctx, formats);
  794. }
  795. static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
  796. {
  797. struct SOFAlizerContext *s = ctx->priv;
  798. const int n_samples = s->sofa.n_samples;
  799. int n_conv = s->n_conv; /* no. channels to convolve */
  800. int n_fft = s->n_fft;
  801. int delay_l[10]; /* broadband delay for each IR */
  802. int delay_r[10];
  803. int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
  804. float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
  805. FFTComplex *data_hrtf_l = NULL;
  806. FFTComplex *data_hrtf_r = NULL;
  807. FFTComplex *fft_in_l = NULL;
  808. FFTComplex *fft_in_r = NULL;
  809. float *data_ir_l = NULL;
  810. float *data_ir_r = NULL;
  811. int offset = 0; /* used for faster pointer arithmetics in for-loop */
  812. int m[10]; /* measurement index m of IR closest to required source positions */
  813. int i, j, azim_orig = azim, elev_orig = elev;
  814. if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
  815. av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
  816. return AVERROR_INVALIDDATA;
  817. }
  818. if (s->type == TIME_DOMAIN) {
  819. s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
  820. s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
  821. /* get temporary IR for L and R channel */
  822. data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
  823. data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
  824. if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
  825. av_free(data_ir_l);
  826. av_free(data_ir_r);
  827. return AVERROR(ENOMEM);
  828. }
  829. } else {
  830. /* get temporary HRTF memory for L and R channel */
  831. data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
  832. data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
  833. if (!data_hrtf_r || !data_hrtf_l) {
  834. av_free(data_hrtf_l);
  835. av_free(data_hrtf_r);
  836. return AVERROR(ENOMEM);
  837. }
  838. }
  839. for (i = 0; i < s->n_conv; i++) {
  840. /* load and store IRs and corresponding delays */
  841. azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
  842. elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
  843. /* get id of IR closest to desired position */
  844. m[i] = find_m(s, azim, elev, radius);
  845. /* load the delays associated with the current IRs */
  846. delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
  847. delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
  848. if (s->type == TIME_DOMAIN) {
  849. offset = i * n_samples; /* no. samples already written */
  850. for (j = 0; j < n_samples; j++) {
  851. /* load reversed IRs of the specified source position
  852. * sample-by-sample for left and right ear; and apply gain */
  853. *(data_ir_l + offset + j) = /* left channel */
  854. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
  855. *(data_ir_r + offset + j) = /* right channel */
  856. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
  857. }
  858. } else {
  859. fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
  860. fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
  861. if (!fft_in_l || !fft_in_r) {
  862. av_free(data_hrtf_l);
  863. av_free(data_hrtf_r);
  864. av_free(fft_in_l);
  865. av_free(fft_in_r);
  866. return AVERROR(ENOMEM);
  867. }
  868. offset = i * n_fft; /* no. samples already written */
  869. for (j = 0; j < n_samples; j++) {
  870. /* load non-reversed IRs of the specified source position
  871. * sample-by-sample and apply gain,
  872. * L channel is loaded to real part, R channel to imag part,
  873. * IRs ared shifted by L and R delay */
  874. fft_in_l[delay_l[i] + j].re = /* left channel */
  875. *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
  876. fft_in_r[delay_r[i] + j].re = /* right channel */
  877. *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
  878. }
  879. /* actually transform to frequency domain (IRs -> HRTFs) */
  880. av_fft_permute(s->fft[0], fft_in_l);
  881. av_fft_calc(s->fft[0], fft_in_l);
  882. memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
  883. av_fft_permute(s->fft[0], fft_in_r);
  884. av_fft_calc(s->fft[0], fft_in_r);
  885. memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
  886. }
  887. av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
  888. m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
  889. }
  890. if (s->type == TIME_DOMAIN) {
  891. /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
  892. memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
  893. memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);
  894. av_freep(&data_ir_l); /* free temporary IR memory */
  895. av_freep(&data_ir_r);
  896. } else {
  897. s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  898. s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  899. if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
  900. av_freep(&data_hrtf_l);
  901. av_freep(&data_hrtf_r);
  902. av_freep(&fft_in_l);
  903. av_freep(&fft_in_r);
  904. return AVERROR(ENOMEM); /* memory allocation failed */
  905. }
  906. memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
  907. sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
  908. memcpy(s->data_hrtf[1], data_hrtf_r,
  909. sizeof(FFTComplex) * n_conv * n_fft);
  910. av_freep(&data_hrtf_l); /* free temporary HRTF memory */
  911. av_freep(&data_hrtf_r);
  912. av_freep(&fft_in_l); /* free temporary FFT memory */
  913. av_freep(&fft_in_r);
  914. }
  915. memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
  916. memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
  917. return 0;
  918. }
  919. static av_cold int init(AVFilterContext *ctx)
  920. {
  921. SOFAlizerContext *s = ctx->priv;
  922. int ret;
  923. /* load SOFA file, */
  924. /* initialize file IDs to 0 before attempting to load SOFA files,
  925. * this assures that in case of error, only the memory of already
  926. * loaded files is free'd */
  927. s->sofa.ncid = 0;
  928. ret = load_sofa(ctx, s->filename, &s->sample_rate);
  929. if (ret) {
  930. /* file loading error */
  931. av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
  932. } else { /* no file loading error, resampling not required */
  933. av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
  934. }
  935. if (ret) {
  936. av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
  937. return ret;
  938. }
  939. s->fdsp = avpriv_float_dsp_alloc(0);
  940. if (!s->fdsp)
  941. return AVERROR(ENOMEM);
  942. return 0;
  943. }
  944. static inline unsigned clz(unsigned x)
  945. {
  946. unsigned i = sizeof(x) * 8;
  947. while (x) {
  948. x >>= 1;
  949. i--;
  950. }
  951. return i;
  952. }
  953. static int config_input(AVFilterLink *inlink)
  954. {
  955. AVFilterContext *ctx = inlink->dst;
  956. SOFAlizerContext *s = ctx->priv;
  957. int nb_input_channels = inlink->channels; /* no. input channels */
  958. int n_max_ir = 0;
  959. int n_current;
  960. int n_max = 0;
  961. int ret;
  962. if (s->type == FREQUENCY_DOMAIN) {
  963. inlink->partial_buf_size =
  964. inlink->min_samples =
  965. inlink->max_samples = inlink->sample_rate;
  966. }
  967. /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
  968. s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
  969. s->n_conv = nb_input_channels;
  970. /* get size of ringbuffer (longest IR plus max. delay) */
  971. /* then choose next power of 2 for performance optimization */
  972. n_current = s->sofa.n_samples + max_delay(&s->sofa);
  973. if (n_current > n_max) {
  974. /* length of longest IR plus max. delay (in all SOFA files) */
  975. n_max = n_current;
  976. /* length of longest IR (without delay, in all SOFA files) */
  977. n_max_ir = s->sofa.n_samples;
  978. }
  979. /* buffer length is longest IR plus max. delay -> next power of 2
  980. (32 - count leading zeros gives required exponent) */
  981. s->buffer_length = exp2(32 - clz((uint32_t)n_max));
  982. s->n_fft = exp2(32 - clz((uint32_t)(n_max + inlink->sample_rate)));
  983. if (s->type == FREQUENCY_DOMAIN) {
  984. av_fft_end(s->fft[0]);
  985. av_fft_end(s->fft[1]);
  986. s->fft[0] = av_fft_init(log2(s->n_fft), 0);
  987. s->fft[1] = av_fft_init(log2(s->n_fft), 0);
  988. av_fft_end(s->ifft[0]);
  989. av_fft_end(s->ifft[1]);
  990. s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
  991. s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
  992. }
  993. /* Allocate memory for the impulse responses, delays and the ringbuffers */
  994. /* size: (longest IR) * (number of channels to convolute) */
  995. s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
  996. s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
  997. /* length: number of channels to convolute */
  998. s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
  999. s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
  1000. /* length: (buffer length) * (number of input channels),
  1001. * OR: buffer length (if frequency domain processing)
  1002. * calloc zero-initializes the buffer */
  1003. if (s->type == TIME_DOMAIN) {
  1004. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  1005. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  1006. } else {
  1007. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
  1008. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
  1009. s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  1010. s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  1011. if (!s->temp_fft[0] || !s->temp_fft[1])
  1012. return AVERROR(ENOMEM);
  1013. }
  1014. /* length: number of channels to convolute */
  1015. s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
  1016. s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
  1017. /* memory allocation failed: */
  1018. if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
  1019. !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
  1020. !s->speaker_azim || !s->speaker_elev)
  1021. return AVERROR(ENOMEM);
  1022. compensate_volume(ctx);
  1023. /* get speaker positions */
  1024. if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
  1025. av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
  1026. return ret;
  1027. }
  1028. /* load IRs to data_ir[0] and data_ir[1] for required directions */
  1029. if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
  1030. return ret;
  1031. av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
  1032. inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
  1033. return 0;
  1034. }
  1035. static av_cold void uninit(AVFilterContext *ctx)
  1036. {
  1037. SOFAlizerContext *s = ctx->priv;
  1038. if (s->sofa.ncid) {
  1039. av_freep(&s->sofa.sp_a);
  1040. av_freep(&s->sofa.sp_e);
  1041. av_freep(&s->sofa.sp_r);
  1042. av_freep(&s->sofa.data_delay);
  1043. av_freep(&s->sofa.data_ir);
  1044. }
  1045. av_fft_end(s->ifft[0]);
  1046. av_fft_end(s->ifft[1]);
  1047. av_fft_end(s->fft[0]);
  1048. av_fft_end(s->fft[1]);
  1049. av_freep(&s->delay[0]);
  1050. av_freep(&s->delay[1]);
  1051. av_freep(&s->data_ir[0]);
  1052. av_freep(&s->data_ir[1]);
  1053. av_freep(&s->ringbuffer[0]);
  1054. av_freep(&s->ringbuffer[1]);
  1055. av_freep(&s->speaker_azim);
  1056. av_freep(&s->speaker_elev);
  1057. av_freep(&s->temp_src[0]);
  1058. av_freep(&s->temp_src[1]);
  1059. av_freep(&s->temp_fft[0]);
  1060. av_freep(&s->temp_fft[1]);
  1061. av_freep(&s->data_hrtf[0]);
  1062. av_freep(&s->data_hrtf[1]);
  1063. av_freep(&s->fdsp);
  1064. }
  1065. #define OFFSET(x) offsetof(SOFAlizerContext, x)
  1066. #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  1067. static const AVOption sofalizer_options[] = {
  1068. { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
  1069. { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
  1070. { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
  1071. { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
  1072. { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
  1073. { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
  1074. { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
  1075. { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
  1076. { NULL }
  1077. };
  1078. AVFILTER_DEFINE_CLASS(sofalizer);
  1079. static const AVFilterPad inputs[] = {
  1080. {
  1081. .name = "default",
  1082. .type = AVMEDIA_TYPE_AUDIO,
  1083. .config_props = config_input,
  1084. .filter_frame = filter_frame,
  1085. },
  1086. { NULL }
  1087. };
  1088. static const AVFilterPad outputs[] = {
  1089. {
  1090. .name = "default",
  1091. .type = AVMEDIA_TYPE_AUDIO,
  1092. },
  1093. { NULL }
  1094. };
  1095. AVFilter ff_af_sofalizer = {
  1096. .name = "sofalizer",
  1097. .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
  1098. .priv_size = sizeof(SOFAlizerContext),
  1099. .priv_class = &sofalizer_class,
  1100. .init = init,
  1101. .uninit = uninit,
  1102. .query_formats = query_formats,
  1103. .inputs = inputs,
  1104. .outputs = outputs,
  1105. .flags = AVFILTER_FLAG_SLICE_THREADS,
  1106. };