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.

1267 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;
  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. if (sofa->n_samples & 31) {
  521. energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
  522. } else {
  523. energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
  524. }
  525. compensate = 256 / (sofa->n_samples * sqrt(energy));
  526. av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
  527. ir = sofa->data_ir;
  528. /* apply volume compensation to IRs */
  529. s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
  530. emms_c();
  531. }
  532. return 0;
  533. }
  534. typedef struct ThreadData {
  535. AVFrame *in, *out;
  536. int *write;
  537. int **delay;
  538. float **ir;
  539. int *n_clippings;
  540. float **ringbuffer;
  541. float **temp_src;
  542. FFTComplex **temp_fft;
  543. } ThreadData;
  544. static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  545. {
  546. SOFAlizerContext *s = ctx->priv;
  547. ThreadData *td = arg;
  548. AVFrame *in = td->in, *out = td->out;
  549. int offset = jobnr;
  550. int *write = &td->write[jobnr];
  551. const int *const delay = td->delay[jobnr];
  552. const float *const ir = td->ir[jobnr];
  553. int *n_clippings = &td->n_clippings[jobnr];
  554. float *ringbuffer = td->ringbuffer[jobnr];
  555. float *temp_src = td->temp_src[jobnr];
  556. const int n_samples = s->sofa.n_samples; /* length of one IR */
  557. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  558. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  559. const int in_channels = s->n_conv; /* number of input channels */
  560. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  561. const int buffer_length = s->buffer_length;
  562. /* -1 for AND instead of MODULO (applied to powers of 2): */
  563. const uint32_t modulo = (uint32_t)buffer_length - 1;
  564. float *buffer[10]; /* holds ringbuffer for each input channel */
  565. int wr = *write;
  566. int read;
  567. int i, l;
  568. dst += offset;
  569. for (l = 0; l < in_channels; l++) {
  570. /* get starting address of ringbuffer for each input channel */
  571. buffer[l] = ringbuffer + l * buffer_length;
  572. }
  573. for (i = 0; i < in->nb_samples; i++) {
  574. const float *temp_ir = ir; /* using same set of IRs for each sample */
  575. *dst = 0;
  576. for (l = 0; l < in_channels; l++) {
  577. /* write current input sample to ringbuffer (for each channel) */
  578. *(buffer[l] + wr) = src[l];
  579. }
  580. /* loop goes through all channels to be convolved */
  581. for (l = 0; l < in_channels; l++) {
  582. const float *const bptr = buffer[l];
  583. if (l == s->lfe_channel) {
  584. /* LFE is an input channel but requires no convolution */
  585. /* apply gain to LFE signal and add to output buffer */
  586. *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
  587. temp_ir += n_samples;
  588. continue;
  589. }
  590. /* current read position in ringbuffer: input sample write position
  591. * - delay for l-th ch. + diff. betw. IR length and buffer length
  592. * (mod buffer length) */
  593. read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
  594. if (read + n_samples < buffer_length) {
  595. memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
  596. } else {
  597. int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
  598. memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
  599. memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
  600. }
  601. /* multiply signal and IR, and add up the results */
  602. dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
  603. temp_ir += n_samples;
  604. }
  605. /* clippings counter */
  606. if (fabs(*dst) > 1)
  607. *n_clippings += 1;
  608. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  609. dst += 2;
  610. src += in_channels;
  611. wr = (wr + 1) & modulo; /* update ringbuffer write position */
  612. }
  613. *write = wr; /* remember write position in ringbuffer for next call */
  614. return 0;
  615. }
  616. static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  617. {
  618. SOFAlizerContext *s = ctx->priv;
  619. ThreadData *td = arg;
  620. AVFrame *in = td->in, *out = td->out;
  621. int offset = jobnr;
  622. int *write = &td->write[jobnr];
  623. FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
  624. int *n_clippings = &td->n_clippings[jobnr];
  625. float *ringbuffer = td->ringbuffer[jobnr];
  626. const int n_samples = s->sofa.n_samples; /* length of one IR */
  627. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  628. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  629. const int in_channels = s->n_conv; /* number of input channels */
  630. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  631. const int buffer_length = s->buffer_length;
  632. /* -1 for AND instead of MODULO (applied to powers of 2): */
  633. const uint32_t modulo = (uint32_t)buffer_length - 1;
  634. FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
  635. FFTContext *ifft = s->ifft[jobnr];
  636. FFTContext *fft = s->fft[jobnr];
  637. const int n_conv = s->n_conv;
  638. const int n_fft = s->n_fft;
  639. int wr = *write;
  640. int n_read;
  641. int i, j;
  642. dst += offset;
  643. /* find minimum between number of samples and output buffer length:
  644. * (important, if one IR is longer than the output buffer) */
  645. n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
  646. for (j = 0; j < n_read; j++) {
  647. /* initialize output buf with saved signal from overflow buf */
  648. dst[2 * j] = ringbuffer[wr];
  649. ringbuffer[wr] = 0.0; /* re-set read samples to zero */
  650. /* update ringbuffer read/write position */
  651. wr = (wr + 1) & modulo;
  652. }
  653. /* initialize rest of output buffer with 0 */
  654. for (j = n_read; j < in->nb_samples; j++) {
  655. dst[2 * j] = 0;
  656. }
  657. for (i = 0; i < n_conv; i++) {
  658. if (i == s->lfe_channel) { /* LFE */
  659. for (j = 0; j < in->nb_samples; j++) {
  660. /* apply gain to LFE signal and add to output buffer */
  661. dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
  662. }
  663. continue;
  664. }
  665. /* outer loop: go through all input channels to be convolved */
  666. offset = i * n_fft; /* no. samples already processed */
  667. /* fill FFT input with 0 (we want to zero-pad) */
  668. memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
  669. for (j = 0; j < in->nb_samples; j++) {
  670. /* prepare input for FFT */
  671. /* write all samples of current input channel to FFT input array */
  672. fft_in[j].re = src[j * in_channels + i];
  673. }
  674. /* transform input signal of current channel to frequency domain */
  675. av_fft_permute(fft, fft_in);
  676. av_fft_calc(fft, fft_in);
  677. for (j = 0; j < n_fft; j++) {
  678. const float re = fft_in[j].re;
  679. const float im = fft_in[j].im;
  680. /* complex multiplication of input signal and HRTFs */
  681. /* output channel (real): */
  682. fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
  683. /* output channel (imag): */
  684. fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
  685. }
  686. /* transform output signal of current channel back to time domain */
  687. av_fft_permute(ifft, fft_in);
  688. av_fft_calc(ifft, fft_in);
  689. for (j = 0; j < in->nb_samples; j++) {
  690. /* write output signal of current channel to output buffer */
  691. dst[2 * j] += fft_in[j].re / (float)n_fft;
  692. }
  693. for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
  694. /* write the rest of output signal to overflow buffer */
  695. int write_pos = (wr + j) & modulo;
  696. *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
  697. }
  698. }
  699. /* go through all samples of current output buffer: count clippings */
  700. for (i = 0; i < out->nb_samples; i++) {
  701. /* clippings counter */
  702. if (fabs(*dst) > 1) { /* if current output sample > 1 */
  703. *n_clippings = *n_clippings + 1;
  704. }
  705. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  706. dst += 2;
  707. }
  708. /* remember read/write position in ringbuffer for next call */
  709. *write = wr;
  710. return 0;
  711. }
  712. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  713. {
  714. AVFilterContext *ctx = inlink->dst;
  715. SOFAlizerContext *s = ctx->priv;
  716. AVFilterLink *outlink = ctx->outputs[0];
  717. int n_clippings[2] = { 0 };
  718. ThreadData td;
  719. AVFrame *out;
  720. out = ff_get_audio_buffer(outlink, in->nb_samples);
  721. if (!out) {
  722. av_frame_free(&in);
  723. return AVERROR(ENOMEM);
  724. }
  725. av_frame_copy_props(out, in);
  726. td.in = in; td.out = out; td.write = s->write;
  727. td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
  728. td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
  729. td.temp_fft = s->temp_fft;
  730. if (s->type == TIME_DOMAIN) {
  731. ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
  732. } else {
  733. ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
  734. }
  735. emms_c();
  736. /* display error message if clipping occurred */
  737. if (n_clippings[0] + n_clippings[1] > 0) {
  738. av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
  739. n_clippings[0] + n_clippings[1], out->nb_samples * 2);
  740. }
  741. av_frame_free(&in);
  742. return ff_filter_frame(outlink, out);
  743. }
  744. static int query_formats(AVFilterContext *ctx)
  745. {
  746. struct SOFAlizerContext *s = ctx->priv;
  747. AVFilterFormats *formats = NULL;
  748. AVFilterChannelLayouts *layouts = NULL;
  749. int ret, sample_rates[] = { 48000, -1 };
  750. static const uint64_t channel_layouts[] = { AV_CH_LAYOUT_MONO,
  751. AV_CH_LAYOUT_STEREO,
  752. AV_CH_LAYOUT_2POINT1,
  753. AV_CH_LAYOUT_SURROUND,
  754. AV_CH_LAYOUT_2_1,
  755. AV_CH_LAYOUT_4POINT0,
  756. AV_CH_LAYOUT_QUAD,
  757. AV_CH_LAYOUT_2_2,
  758. AV_CH_LAYOUT_3POINT1,
  759. AV_CH_LAYOUT_5POINT0_BACK,
  760. AV_CH_LAYOUT_5POINT0,
  761. AV_CH_LAYOUT_4POINT1,
  762. AV_CH_LAYOUT_5POINT1_BACK,
  763. AV_CH_LAYOUT_5POINT1,
  764. AV_CH_LAYOUT_6POINT0,
  765. AV_CH_LAYOUT_HEXAGONAL,
  766. AV_CH_LAYOUT_6POINT1,
  767. AV_CH_LAYOUT_6POINT1_BACK,
  768. AV_CH_LAYOUT_7POINT0,
  769. AV_CH_LAYOUT_7POINT1,
  770. AV_CH_LAYOUT_OCTAGONAL,
  771. 0, };
  772. ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  773. if (ret)
  774. return ret;
  775. ret = ff_set_common_formats(ctx, formats);
  776. if (ret)
  777. return ret;
  778. layouts = ff_make_formatu64_list(channel_layouts);
  779. if (!layouts)
  780. return AVERROR(ENOMEM);
  781. ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
  782. if (ret)
  783. return ret;
  784. layouts = NULL;
  785. ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
  786. if (ret)
  787. return ret;
  788. ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
  789. if (ret)
  790. return ret;
  791. sample_rates[0] = s->sample_rate;
  792. formats = ff_make_format_list(sample_rates);
  793. if (!formats)
  794. return AVERROR(ENOMEM);
  795. return ff_set_common_samplerates(ctx, formats);
  796. }
  797. static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
  798. {
  799. struct SOFAlizerContext *s = ctx->priv;
  800. const int n_samples = s->sofa.n_samples;
  801. int n_conv = s->n_conv; /* no. channels to convolve */
  802. int n_fft = s->n_fft;
  803. int delay_l[10]; /* broadband delay for each IR */
  804. int delay_r[10];
  805. int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
  806. float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
  807. FFTComplex *data_hrtf_l = NULL;
  808. FFTComplex *data_hrtf_r = NULL;
  809. FFTComplex *fft_in_l = NULL;
  810. FFTComplex *fft_in_r = NULL;
  811. float *data_ir_l = NULL;
  812. float *data_ir_r = NULL;
  813. int offset = 0; /* used for faster pointer arithmetics in for-loop */
  814. int m[10]; /* measurement index m of IR closest to required source positions */
  815. int i, j, azim_orig = azim, elev_orig = elev;
  816. if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
  817. av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
  818. return AVERROR_INVALIDDATA;
  819. }
  820. if (s->type == TIME_DOMAIN) {
  821. s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
  822. s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
  823. /* get temporary IR for L and R channel */
  824. data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
  825. data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
  826. if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
  827. av_free(data_ir_l);
  828. av_free(data_ir_r);
  829. return AVERROR(ENOMEM);
  830. }
  831. } else {
  832. /* get temporary HRTF memory for L and R channel */
  833. data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
  834. data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
  835. if (!data_hrtf_r || !data_hrtf_l) {
  836. av_free(data_hrtf_l);
  837. av_free(data_hrtf_r);
  838. return AVERROR(ENOMEM);
  839. }
  840. }
  841. for (i = 0; i < s->n_conv; i++) {
  842. /* load and store IRs and corresponding delays */
  843. azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
  844. elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
  845. /* get id of IR closest to desired position */
  846. m[i] = find_m(s, azim, elev, radius);
  847. /* load the delays associated with the current IRs */
  848. delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
  849. delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
  850. if (s->type == TIME_DOMAIN) {
  851. offset = i * n_samples; /* no. samples already written */
  852. for (j = 0; j < n_samples; j++) {
  853. /* load reversed IRs of the specified source position
  854. * sample-by-sample for left and right ear; and apply gain */
  855. *(data_ir_l + offset + j) = /* left channel */
  856. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
  857. *(data_ir_r + offset + j) = /* right channel */
  858. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
  859. }
  860. } else {
  861. fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
  862. fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
  863. if (!fft_in_l || !fft_in_r) {
  864. av_free(data_hrtf_l);
  865. av_free(data_hrtf_r);
  866. av_free(fft_in_l);
  867. av_free(fft_in_r);
  868. return AVERROR(ENOMEM);
  869. }
  870. offset = i * n_fft; /* no. samples already written */
  871. for (j = 0; j < n_samples; j++) {
  872. /* load non-reversed IRs of the specified source position
  873. * sample-by-sample and apply gain,
  874. * L channel is loaded to real part, R channel to imag part,
  875. * IRs ared shifted by L and R delay */
  876. fft_in_l[delay_l[i] + j].re = /* left channel */
  877. *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
  878. fft_in_r[delay_r[i] + j].re = /* right channel */
  879. *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
  880. }
  881. /* actually transform to frequency domain (IRs -> HRTFs) */
  882. av_fft_permute(s->fft[0], fft_in_l);
  883. av_fft_calc(s->fft[0], fft_in_l);
  884. memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
  885. av_fft_permute(s->fft[0], fft_in_r);
  886. av_fft_calc(s->fft[0], fft_in_r);
  887. memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
  888. }
  889. av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
  890. m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
  891. }
  892. if (s->type == TIME_DOMAIN) {
  893. /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
  894. memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
  895. memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);
  896. av_freep(&data_ir_l); /* free temporary IR memory */
  897. av_freep(&data_ir_r);
  898. } else {
  899. s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  900. s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  901. if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
  902. av_freep(&data_hrtf_l);
  903. av_freep(&data_hrtf_r);
  904. av_freep(&fft_in_l);
  905. av_freep(&fft_in_r);
  906. return AVERROR(ENOMEM); /* memory allocation failed */
  907. }
  908. memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
  909. sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
  910. memcpy(s->data_hrtf[1], data_hrtf_r,
  911. sizeof(FFTComplex) * n_conv * n_fft);
  912. av_freep(&data_hrtf_l); /* free temporary HRTF memory */
  913. av_freep(&data_hrtf_r);
  914. av_freep(&fft_in_l); /* free temporary FFT memory */
  915. av_freep(&fft_in_r);
  916. }
  917. memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
  918. memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
  919. return 0;
  920. }
  921. static av_cold int init(AVFilterContext *ctx)
  922. {
  923. SOFAlizerContext *s = ctx->priv;
  924. int ret;
  925. /* load SOFA file, */
  926. /* initialize file IDs to 0 before attempting to load SOFA files,
  927. * this assures that in case of error, only the memory of already
  928. * loaded files is free'd */
  929. s->sofa.ncid = 0;
  930. ret = load_sofa(ctx, s->filename, &s->sample_rate);
  931. if (ret) {
  932. /* file loading error */
  933. av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
  934. } else { /* no file loading error, resampling not required */
  935. av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
  936. }
  937. if (ret) {
  938. av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
  939. return ret;
  940. }
  941. s->fdsp = avpriv_float_dsp_alloc(0);
  942. if (!s->fdsp)
  943. return AVERROR(ENOMEM);
  944. return 0;
  945. }
  946. static inline unsigned clz(unsigned x)
  947. {
  948. unsigned i = sizeof(x) * 8;
  949. while (x) {
  950. x >>= 1;
  951. i--;
  952. }
  953. return i;
  954. }
  955. static int config_input(AVFilterLink *inlink)
  956. {
  957. AVFilterContext *ctx = inlink->dst;
  958. SOFAlizerContext *s = ctx->priv;
  959. int nb_input_channels = inlink->channels; /* no. input channels */
  960. int n_max_ir = 0;
  961. int n_current;
  962. int n_max = 0;
  963. int ret;
  964. if (s->type == FREQUENCY_DOMAIN) {
  965. inlink->partial_buf_size =
  966. inlink->min_samples =
  967. inlink->max_samples = inlink->sample_rate;
  968. }
  969. /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
  970. s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
  971. s->n_conv = nb_input_channels;
  972. /* get size of ringbuffer (longest IR plus max. delay) */
  973. /* then choose next power of 2 for performance optimization */
  974. n_current = s->sofa.n_samples + max_delay(&s->sofa);
  975. if (n_current > n_max) {
  976. /* length of longest IR plus max. delay (in all SOFA files) */
  977. n_max = n_current;
  978. /* length of longest IR (without delay, in all SOFA files) */
  979. n_max_ir = s->sofa.n_samples;
  980. }
  981. /* buffer length is longest IR plus max. delay -> next power of 2
  982. (32 - count leading zeros gives required exponent) */
  983. s->buffer_length = exp2(32 - clz((uint32_t)n_max));
  984. s->n_fft = exp2(32 - clz((uint32_t)(n_max + inlink->sample_rate)));
  985. if (s->type == FREQUENCY_DOMAIN) {
  986. av_fft_end(s->fft[0]);
  987. av_fft_end(s->fft[1]);
  988. s->fft[0] = av_fft_init(log2(s->n_fft), 0);
  989. s->fft[1] = av_fft_init(log2(s->n_fft), 0);
  990. av_fft_end(s->ifft[0]);
  991. av_fft_end(s->ifft[1]);
  992. s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
  993. s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
  994. if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
  995. av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts.\n");
  996. return AVERROR(ENOMEM);
  997. }
  998. }
  999. /* Allocate memory for the impulse responses, delays and the ringbuffers */
  1000. /* size: (longest IR) * (number of channels to convolute) */
  1001. s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
  1002. s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
  1003. /* length: number of channels to convolute */
  1004. s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
  1005. s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
  1006. /* length: (buffer length) * (number of input channels),
  1007. * OR: buffer length (if frequency domain processing)
  1008. * calloc zero-initializes the buffer */
  1009. if (s->type == TIME_DOMAIN) {
  1010. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  1011. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  1012. } else {
  1013. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
  1014. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
  1015. s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  1016. s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  1017. if (!s->temp_fft[0] || !s->temp_fft[1])
  1018. return AVERROR(ENOMEM);
  1019. }
  1020. /* length: number of channels to convolute */
  1021. s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
  1022. s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
  1023. /* memory allocation failed: */
  1024. if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
  1025. !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
  1026. !s->speaker_azim || !s->speaker_elev)
  1027. return AVERROR(ENOMEM);
  1028. compensate_volume(ctx);
  1029. /* get speaker positions */
  1030. if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
  1031. av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
  1032. return ret;
  1033. }
  1034. /* load IRs to data_ir[0] and data_ir[1] for required directions */
  1035. if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
  1036. return ret;
  1037. av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
  1038. inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
  1039. return 0;
  1040. }
  1041. static av_cold void uninit(AVFilterContext *ctx)
  1042. {
  1043. SOFAlizerContext *s = ctx->priv;
  1044. if (s->sofa.ncid) {
  1045. av_freep(&s->sofa.sp_a);
  1046. av_freep(&s->sofa.sp_e);
  1047. av_freep(&s->sofa.sp_r);
  1048. av_freep(&s->sofa.data_delay);
  1049. av_freep(&s->sofa.data_ir);
  1050. }
  1051. av_fft_end(s->ifft[0]);
  1052. av_fft_end(s->ifft[1]);
  1053. av_fft_end(s->fft[0]);
  1054. av_fft_end(s->fft[1]);
  1055. av_freep(&s->delay[0]);
  1056. av_freep(&s->delay[1]);
  1057. av_freep(&s->data_ir[0]);
  1058. av_freep(&s->data_ir[1]);
  1059. av_freep(&s->ringbuffer[0]);
  1060. av_freep(&s->ringbuffer[1]);
  1061. av_freep(&s->speaker_azim);
  1062. av_freep(&s->speaker_elev);
  1063. av_freep(&s->temp_src[0]);
  1064. av_freep(&s->temp_src[1]);
  1065. av_freep(&s->temp_fft[0]);
  1066. av_freep(&s->temp_fft[1]);
  1067. av_freep(&s->data_hrtf[0]);
  1068. av_freep(&s->data_hrtf[1]);
  1069. av_freep(&s->fdsp);
  1070. }
  1071. #define OFFSET(x) offsetof(SOFAlizerContext, x)
  1072. #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  1073. static const AVOption sofalizer_options[] = {
  1074. { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
  1075. { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
  1076. { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
  1077. { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
  1078. { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
  1079. { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
  1080. { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
  1081. { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
  1082. { NULL }
  1083. };
  1084. AVFILTER_DEFINE_CLASS(sofalizer);
  1085. static const AVFilterPad inputs[] = {
  1086. {
  1087. .name = "default",
  1088. .type = AVMEDIA_TYPE_AUDIO,
  1089. .config_props = config_input,
  1090. .filter_frame = filter_frame,
  1091. },
  1092. { NULL }
  1093. };
  1094. static const AVFilterPad outputs[] = {
  1095. {
  1096. .name = "default",
  1097. .type = AVMEDIA_TYPE_AUDIO,
  1098. },
  1099. { NULL }
  1100. };
  1101. AVFilter ff_af_sofalizer = {
  1102. .name = "sofalizer",
  1103. .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
  1104. .priv_size = sizeof(SOFAlizerContext),
  1105. .priv_class = &sofalizer_class,
  1106. .init = init,
  1107. .uninit = uninit,
  1108. .query_formats = query_formats,
  1109. .inputs = inputs,
  1110. .outputs = outputs,
  1111. .flags = AVFILTER_FLAG_SLICE_THREADS,
  1112. };