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.

1019 lines
38KB

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