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.

1052 lines
39KB

  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. const int8_t *reorder; /* reorder in SOFA channel order */
  51. int sample_rate; /* sample rate from SOFA file */
  52. float *speaker_pos; /* positions of the virtual loudspekaers */
  53. float gain_lfe; /* gain applied to LFE channel */
  54. int n_conv; /* number of channels to convolute */
  55. /* buffer variables (for convolution) */
  56. float *ringbuffer[2]; /* buffers input samples, length of one buffer: */
  57. /* no. input ch. (incl. LFE) x buffer_length */
  58. int write[2]; /* current write position to ringbuffer */
  59. int buffer_length; /* is: longest IR plus max. delay in all SOFA files */
  60. /* then choose next power of 2 */
  61. /* netCDF variables */
  62. int *delay[2]; /* broadband delay for each channel/IR to be convolved */
  63. float *data_ir[2]; /* IRs for all channels to be convolved */
  64. /* (this excludes the LFE) */
  65. float *temp_src[2];
  66. /* control variables */
  67. float gain; /* filter gain (in dB) */
  68. float rotation; /* rotation of virtual loudspeakers (in degrees) */
  69. float elevation; /* elevation of virtual loudspeakers (in deg.) */
  70. float radius; /* distance virtual loudspeakers to listener (in metres) */
  71. int lfe; /* whether or not the LFE channel is used */
  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 number of measurements */
  137. m_dim = dim_length[m_dim_id]; /* get length of one IR */
  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 const int8_t reorder[18][9] = {
  312. { 0, -1, -1, -1, -1, -1, -1, -1, -1 },
  313. { 0, 1, -1, -1, -1, -1, -1, -1, -1 },
  314. { 0, 1, 2, -1, -1, -1, -1, -1, -1 },
  315. { 0, 1, 2, -1, -1, -1, -1, -1, -1 },
  316. { 0, 1, 2, 3, -1, -1, -1, -1, -1 },
  317. { 0, 1, 2, 3, -1, -1, -1, -1, -1 },
  318. { 0, 1, 2, 3, -1, -1, -1, -1, -1 },
  319. { 0, 1, 3, 4, 2, -1, -1, -1, -1 },
  320. { 0, 1, 3, 4, 2, -1, -1, -1, -1 },
  321. { 0, 1, 4, 5, 2, 3, -1, -1, -1 },
  322. { 0, 1, 4, 5, 2, 3, -1, -1, -1 },
  323. { 0, 1, 5, 6, 4, 2, 3, -1, -1 },
  324. { 0, 1, 5, 6, 3, 4, 2, -1, -1 },
  325. { 0, 1, 6, 7, 4, 5, 2, 3, -1 },
  326. { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
  327. { 0, 1, 2, 3, 4, 5, 6, 7, -1 },
  328. { 0, 1, 3, 4, 2, 5, -1, -1, -1 },
  329. { 0, 1, 4, 5, 2, 6, 3, -1, -1 },
  330. };
  331. static int get_speaker_pos(AVFilterContext *ctx, float *speaker_pos)
  332. {
  333. struct SOFAlizerContext *s = ctx->priv;
  334. uint64_t channels_layout = ctx->inputs[0]->channel_layout;
  335. float pos_temp[9];
  336. int nb_input_channels = ctx->inputs[0]->channels; /* get no. input channels */
  337. int n_conv = nb_input_channels;
  338. if (channels_layout & AV_CH_LOW_FREQUENCY) { /* if LFE is used */
  339. /* decrease number of channels to be convolved: */
  340. n_conv = nb_input_channels - 1;
  341. }
  342. /* set speaker positions according to input channel configuration: */
  343. switch (channels_layout) {
  344. case AV_CH_LAYOUT_MONO:
  345. pos_temp[0] = 0;
  346. break;
  347. case AV_CH_LAYOUT_STEREO:
  348. case AV_CH_LAYOUT_2POINT1:
  349. pos_temp[0] = 30;
  350. pos_temp[1] = 330;
  351. break;
  352. case AV_CH_LAYOUT_SURROUND:
  353. case AV_CH_LAYOUT_3POINT1:
  354. pos_temp[0] = 30;
  355. pos_temp[1] = 330;
  356. pos_temp[2] = 0;
  357. break;
  358. case AV_CH_LAYOUT_2_1:
  359. pos_temp[0] = 30;
  360. pos_temp[1] = 330;
  361. pos_temp[2] = 180;
  362. break;
  363. case AV_CH_LAYOUT_2_2:
  364. pos_temp[0] = 30;
  365. pos_temp[1] = 330;
  366. pos_temp[2] = 90;
  367. pos_temp[3] = 270;
  368. break;
  369. case AV_CH_LAYOUT_QUAD:
  370. pos_temp[0] = 30;
  371. pos_temp[1] = 330;
  372. pos_temp[2] = 120;
  373. pos_temp[3] = 240;
  374. break;
  375. case AV_CH_LAYOUT_4POINT0:
  376. case AV_CH_LAYOUT_4POINT1:
  377. pos_temp[0] = 30;
  378. pos_temp[1] = 330;
  379. pos_temp[2] = 0;
  380. pos_temp[3] = 180;
  381. break;
  382. case AV_CH_LAYOUT_5POINT0:
  383. case AV_CH_LAYOUT_5POINT1:
  384. pos_temp[0] = 30;
  385. pos_temp[1] = 330;
  386. pos_temp[2] = 90;
  387. pos_temp[3] = 270;
  388. pos_temp[4] = 0;
  389. break;
  390. case AV_CH_LAYOUT_5POINT0_BACK:
  391. case AV_CH_LAYOUT_5POINT1_BACK:
  392. pos_temp[0] = 30;
  393. pos_temp[1] = 330;
  394. pos_temp[2] = 120;
  395. pos_temp[3] = 240;
  396. pos_temp[4] = 0;
  397. break;
  398. case AV_CH_LAYOUT_6POINT0:
  399. case AV_CH_LAYOUT_6POINT1:
  400. pos_temp[0] = 30;
  401. pos_temp[1] = 330;
  402. pos_temp[2] = 90;
  403. pos_temp[3] = 270;
  404. pos_temp[4] = 0;
  405. pos_temp[5] = 180;
  406. break;
  407. case AV_CH_LAYOUT_6POINT1_BACK:
  408. pos_temp[0] = 30;
  409. pos_temp[1] = 330;
  410. pos_temp[2] = 120;
  411. pos_temp[3] = 240;
  412. pos_temp[4] = 0;
  413. pos_temp[4] = 180;
  414. break;
  415. case AV_CH_LAYOUT_HEXAGONAL:
  416. pos_temp[0] = 30;
  417. pos_temp[1] = 330;
  418. pos_temp[2] = 120;
  419. pos_temp[3] = 240;
  420. pos_temp[4] = 0;
  421. pos_temp[5] = 180;
  422. break;
  423. case AV_CH_LAYOUT_7POINT0:
  424. case AV_CH_LAYOUT_7POINT1:
  425. pos_temp[0] = 30;
  426. pos_temp[1] = 330;
  427. pos_temp[2] = 90;
  428. pos_temp[3] = 270;
  429. pos_temp[4] = 150;
  430. pos_temp[5] = 210;
  431. pos_temp[6] = 0;
  432. break;
  433. case AV_CH_LAYOUT_OCTAGONAL:
  434. pos_temp[0] = 30;
  435. pos_temp[1] = 330;
  436. pos_temp[2] = 0;
  437. pos_temp[3] = 150;
  438. pos_temp[4] = 210;
  439. pos_temp[5] = 180;
  440. pos_temp[6] = 90;
  441. pos_temp[7] = 270;
  442. break;
  443. default:
  444. return -1;
  445. }
  446. switch (channels_layout) {
  447. case AV_CH_LAYOUT_MONO:
  448. s->reorder = reorder[0];
  449. break;
  450. case AV_CH_LAYOUT_STEREO:
  451. s->reorder = reorder[1];
  452. break;
  453. case AV_CH_LAYOUT_2_1:
  454. case AV_CH_LAYOUT_2POINT1:
  455. s->reorder = reorder[2];
  456. break;
  457. case AV_CH_LAYOUT_SURROUND:
  458. s->reorder = reorder[3];
  459. break;
  460. case AV_CH_LAYOUT_3POINT1:
  461. case AV_CH_LAYOUT_2_2:
  462. s->reorder = reorder[4];
  463. break;
  464. case AV_CH_LAYOUT_QUAD:
  465. s->reorder = reorder[5];
  466. break;
  467. case AV_CH_LAYOUT_4POINT0:
  468. s->reorder = reorder[6];
  469. break;
  470. case AV_CH_LAYOUT_4POINT1:
  471. s->reorder = reorder[7];
  472. break;
  473. case AV_CH_LAYOUT_5POINT0:
  474. case AV_CH_LAYOUT_5POINT0_BACK:
  475. s->reorder = reorder[8];
  476. break;
  477. case AV_CH_LAYOUT_5POINT1:
  478. case AV_CH_LAYOUT_5POINT1_BACK:
  479. s->reorder = reorder[9];
  480. break;
  481. case AV_CH_LAYOUT_6POINT0:
  482. s->reorder = reorder[10];
  483. break;
  484. case AV_CH_LAYOUT_HEXAGONAL:
  485. s->reorder = reorder[16];
  486. break;
  487. case AV_CH_LAYOUT_6POINT1:
  488. s->reorder = reorder[11];
  489. break;
  490. case AV_CH_LAYOUT_6POINT1_BACK:
  491. s->reorder = reorder[17];
  492. break;
  493. case AV_CH_LAYOUT_7POINT0:
  494. s->reorder = reorder[12];
  495. break;
  496. case AV_CH_LAYOUT_7POINT1:
  497. s->reorder = reorder[13];
  498. break;
  499. case AV_CH_LAYOUT_OCTAGONAL:
  500. s->reorder = reorder[15];
  501. break;
  502. default:
  503. return -1;
  504. }
  505. memcpy(speaker_pos, pos_temp, n_conv * sizeof(float));
  506. return 0;
  507. }
  508. static int max_delay(struct NCSofa *sofa)
  509. {
  510. int i, max = 0;
  511. for (i = 0; i < sofa->m_dim * 2; i++) {
  512. /* search maximum delay in given SOFA file */
  513. max = FFMAX(max, sofa->data_delay[i]);
  514. }
  515. return max;
  516. }
  517. static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
  518. {
  519. /* get source positions and M of currently selected SOFA file */
  520. float *sp_a = s->sofa.sp_a; /* azimuth angle */
  521. float *sp_e = s->sofa.sp_e; /* elevation angle */
  522. float *sp_r = s->sofa.sp_r; /* radius */
  523. int m_dim = s->sofa.m_dim; /* no. measurements */
  524. int best_id = 0; /* index m currently closest to desired source pos. */
  525. float delta = 1000; /* offset between desired and currently best pos. */
  526. float current;
  527. int i;
  528. for (i = 0; i < m_dim; i++) {
  529. /* search through all measurements in currently selected SOFA file */
  530. /* distance of current to desired source position: */
  531. current = fabs(sp_a[i] - azim) +
  532. fabs(sp_e[i] - elev) +
  533. fabs(sp_r[i] - radius);
  534. if (current <= delta) {
  535. /* if current distance is smaller than smallest distance so far */
  536. delta = current;
  537. best_id = i; /* remember index */
  538. }
  539. }
  540. return best_id;
  541. }
  542. static int compensate_volume(AVFilterContext *ctx)
  543. {
  544. struct SOFAlizerContext *s = ctx->priv;
  545. float compensate;
  546. float energy = 0;
  547. float *ir;
  548. int m, j;
  549. if (s->sofa.ncid) {
  550. /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
  551. struct NCSofa *sofa = &s->sofa;
  552. m = find_m(s, 0, 0, 1);
  553. /* get energy of that IR and compensate volume */
  554. ir = sofa->data_ir + 2 * m * sofa->n_samples;
  555. for (j = 0; j < sofa->n_samples; j++) {
  556. energy += *(ir + j) * *(ir + j);
  557. }
  558. compensate = 256 / (sofa->n_samples * sqrt(energy));
  559. av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
  560. ir = sofa->data_ir;
  561. for (j = 0; j < sofa->n_samples * sofa->m_dim * 2; j++) {
  562. ir[j] *= compensate; /* apply volume compensation to IRs */
  563. }
  564. }
  565. return 0;
  566. }
  567. typedef struct ThreadData {
  568. AVFrame *in, *out;
  569. int *write;
  570. int **delay;
  571. float **ir;
  572. int *n_clippings;
  573. float **ringbuffer;
  574. float **temp_src;
  575. } ThreadData;
  576. static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
  577. {
  578. SOFAlizerContext *s = ctx->priv;
  579. ThreadData *td = arg;
  580. AVFrame *in = td->in, *out = td->out;
  581. int offset = jobnr;
  582. int *write = &td->write[jobnr];
  583. const int *const delay = td->delay[jobnr];
  584. const float *const ir = td->ir[jobnr];
  585. int *n_clippings = &td->n_clippings[jobnr];
  586. float *ringbuffer = td->ringbuffer[jobnr];
  587. float *temp_src = td->temp_src[jobnr];
  588. const int n_samples = s->sofa.n_samples; /* length of one IR */
  589. const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
  590. float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
  591. int in_channels = in->channels; /* number of input channels */
  592. /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
  593. int buffer_length = s->buffer_length;
  594. /* -1 for AND instead of MODULO (applied to powers of 2): */
  595. uint32_t modulo = (uint32_t)buffer_length - 1;
  596. float *buffer[10]; /* holds ringbuffer for each input channel */
  597. int wr = *write;
  598. int read;
  599. int i, j, l;
  600. dst += offset;
  601. for (l = 0; l < in_channels; l++) {
  602. /* get starting address of ringbuffer for each input channel */
  603. buffer[l] = ringbuffer + l * buffer_length;
  604. }
  605. for (i = 0; i < in->nb_samples; i++) {
  606. const float *temp_ir = ir; /* using same set of IRs for each sample */
  607. *dst = 0;
  608. for (l = 0; l < in_channels; l++) {
  609. /* write current input sample to ringbuffer (for each channel) */
  610. *(buffer[l] + wr) = src[s->reorder[l]];
  611. }
  612. /* loop goes through all channels to be convolved (excl. LFE): */
  613. for (l = 0; l < s->n_conv; l++) {
  614. const float *const bptr = buffer[l];
  615. /* current read position in ringbuffer: input sample write position
  616. * - delay for l-th ch. + diff. betw. IR length and buffer length
  617. * (mod buffer length) */
  618. read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
  619. for (j = 0; j < n_samples; j++)
  620. temp_src[j] = bptr[(read + j) & modulo];
  621. /* multiply signal and IR, and add up the results */
  622. dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
  623. temp_ir += n_samples;
  624. }
  625. if (s->lfe) { /* LFE */
  626. /* apply gain to LFE signal and add to output buffer */
  627. *dst += *(buffer[s->n_conv] + wr) * s->gain_lfe;
  628. }
  629. /* clippings counter */
  630. if (fabs(*dst) > 1)
  631. *n_clippings += 1;
  632. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  633. dst += 2;
  634. src += in_channels;
  635. wr = (wr + 1) & modulo; /* update ringbuffer write position */
  636. }
  637. *write = wr; /* remember write position in ringbuffer for next call */
  638. return 0;
  639. }
  640. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  641. {
  642. AVFilterContext *ctx = inlink->dst;
  643. SOFAlizerContext *s = ctx->priv;
  644. AVFilterLink *outlink = ctx->outputs[0];
  645. int n_clippings[2] = { 0 };
  646. ThreadData td;
  647. AVFrame *out;
  648. out = ff_get_audio_buffer(outlink, in->nb_samples);
  649. if (!out) {
  650. av_frame_free(&in);
  651. return AVERROR(ENOMEM);
  652. }
  653. av_frame_copy_props(out, in);
  654. td.in = in; td.out = out; td.write = s->write;
  655. td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
  656. td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
  657. ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
  658. emms_c();
  659. /* display error message if clipping occured */
  660. if (n_clippings[0] + n_clippings[1] > 0) {
  661. av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
  662. n_clippings[0] + n_clippings[1], out->nb_samples * 2);
  663. }
  664. av_frame_free(&in);
  665. return ff_filter_frame(outlink, out);
  666. }
  667. static int query_formats(AVFilterContext *ctx)
  668. {
  669. struct SOFAlizerContext *s = ctx->priv;
  670. AVFilterFormats *formats = NULL;
  671. AVFilterChannelLayouts *layouts = NULL;
  672. int ret, sample_rates[] = { 48000, -1 };
  673. static const uint64_t channel_layouts[] = { AV_CH_LAYOUT_MONO,
  674. AV_CH_LAYOUT_STEREO,
  675. AV_CH_LAYOUT_2POINT1,
  676. AV_CH_LAYOUT_SURROUND,
  677. AV_CH_LAYOUT_2_1,
  678. AV_CH_LAYOUT_4POINT0,
  679. AV_CH_LAYOUT_QUAD,
  680. AV_CH_LAYOUT_2_2,
  681. AV_CH_LAYOUT_3POINT1,
  682. AV_CH_LAYOUT_5POINT0_BACK,
  683. AV_CH_LAYOUT_5POINT0,
  684. AV_CH_LAYOUT_4POINT1,
  685. AV_CH_LAYOUT_5POINT1_BACK,
  686. AV_CH_LAYOUT_5POINT1,
  687. AV_CH_LAYOUT_6POINT0,
  688. AV_CH_LAYOUT_HEXAGONAL,
  689. AV_CH_LAYOUT_6POINT1,
  690. AV_CH_LAYOUT_6POINT1_BACK,
  691. AV_CH_LAYOUT_7POINT0,
  692. AV_CH_LAYOUT_7POINT1,
  693. AV_CH_LAYOUT_OCTAGONAL,
  694. 0, };
  695. ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  696. if (ret)
  697. return ret;
  698. ret = ff_set_common_formats(ctx, formats);
  699. if (ret)
  700. return ret;
  701. layouts = ff_make_formatu64_list(channel_layouts);
  702. if (!layouts)
  703. return AVERROR(ENOMEM);
  704. ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
  705. if (ret)
  706. return ret;
  707. layouts = NULL;
  708. ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
  709. if (ret)
  710. return ret;
  711. ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
  712. if (ret)
  713. return ret;
  714. sample_rates[0] = s->sample_rate;
  715. formats = ff_make_format_list(sample_rates);
  716. if (!formats)
  717. return AVERROR(ENOMEM);
  718. return ff_set_common_samplerates(ctx, formats);
  719. }
  720. static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
  721. {
  722. struct SOFAlizerContext *s = ctx->priv;
  723. const int n_samples = s->sofa.n_samples;
  724. int n_conv = s->n_conv; /* no. channels to convolve (excl. LFE) */
  725. int delay_l[10]; /* broadband delay for each IR */
  726. int delay_r[10];
  727. int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
  728. float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
  729. float *data_ir_l = NULL;
  730. float *data_ir_r = NULL;
  731. int offset = 0; /* used for faster pointer arithmetics in for-loop */
  732. int m[s->n_conv]; /* measurement index m of IR closest to required source positions */
  733. int i, j, azim_orig = azim;
  734. if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
  735. av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
  736. return AVERROR_INVALIDDATA;
  737. }
  738. /* get temporary IR for L and R channel */
  739. data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
  740. data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
  741. if (!data_ir_r || !data_ir_l) {
  742. av_free(data_ir_l);
  743. av_free(data_ir_r);
  744. return AVERROR(ENOMEM);
  745. }
  746. for (i = 0; i < s->n_conv; i++) {
  747. /* load and store IRs and corresponding delays */
  748. azim = (int)(s->speaker_pos[i] + azim_orig) % 360;
  749. /* get id of IR closest to desired position */
  750. m[i] = find_m(s, azim, elev, radius);
  751. /* load the delays associated with the current IRs */
  752. delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
  753. delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
  754. offset = i * n_samples; /* no. samples already written */
  755. for (j = 0; j < n_samples; j++) {
  756. /* load reversed IRs of the specified source position
  757. * sample-by-sample for left and right ear; and apply gain */
  758. *(data_ir_l + offset + j) = /* left channel */
  759. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
  760. *(data_ir_r + offset + j) = /* right channel */
  761. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
  762. }
  763. av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
  764. m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
  765. }
  766. /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
  767. memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
  768. memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);
  769. av_free(data_ir_l); /* free temporary IR memory */
  770. av_free(data_ir_r);
  771. memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
  772. memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
  773. return 0;
  774. }
  775. static av_cold int init(AVFilterContext *ctx)
  776. {
  777. SOFAlizerContext *s = ctx->priv;
  778. int ret;
  779. /* load SOFA file, */
  780. /* initialize file IDs to 0 before attempting to load SOFA files,
  781. * this assures that in case of error, only the memory of already
  782. * loaded files is free'd */
  783. s->sofa.ncid = 0;
  784. ret = load_sofa(ctx, s->filename, &s->sample_rate);
  785. if (ret) {
  786. /* file loading error */
  787. av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
  788. } else { /* no file loading error, resampling not required */
  789. av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
  790. }
  791. if (ret) {
  792. av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
  793. return ret;
  794. }
  795. s->fdsp = avpriv_float_dsp_alloc(0);
  796. if (!s->fdsp)
  797. return AVERROR(ENOMEM);
  798. return 0;
  799. }
  800. static inline unsigned clz(unsigned x)
  801. {
  802. unsigned i = sizeof(x) * 8;
  803. while (x) {
  804. x >>= 1;
  805. i--;
  806. }
  807. return i;
  808. }
  809. static int config_input(AVFilterLink *inlink)
  810. {
  811. AVFilterContext *ctx = inlink->dst;
  812. SOFAlizerContext *s = ctx->priv;
  813. int nb_input_channels = inlink->channels; /* no. input channels */
  814. int n_max_ir = 0;
  815. int n_current;
  816. int n_max = 0;
  817. int ret;
  818. /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
  819. s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
  820. s->lfe = !!(inlink->channel_layout & AV_CH_LOW_FREQUENCY);
  821. /* LFE is an input channel but requires no convolution */
  822. s->n_conv = nb_input_channels - s->lfe;
  823. /* get size of ringbuffer (longest IR plus max. delay) */
  824. /* then choose next power of 2 for performance optimization */
  825. n_current = s->sofa.n_samples + max_delay(&s->sofa);
  826. if (n_current > n_max) {
  827. /* length of longest IR plus max. delay (in all SOFA files) */
  828. n_max = n_current;
  829. /* length of longest IR (without delay, in all SOFA files) */
  830. n_max_ir = s->sofa.n_samples;
  831. }
  832. /* buffer length is longest IR plus max. delay -> next power of 2
  833. (32 - count leading zeros gives required exponent) */
  834. s->buffer_length = exp2(32 - clz((uint32_t)n_max));
  835. /* Allocate memory for the impulse responses, delays and the ringbuffers */
  836. /* size: (longest IR) * (number of channels to convolute), without LFE */
  837. s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
  838. s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
  839. /* length: number of channels to convolute */
  840. s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
  841. s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
  842. /* length: (buffer length) * (number of input channels),
  843. * OR: buffer length (if frequency domain processing)
  844. * calloc zero-initializes the buffer */
  845. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  846. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  847. /* length: number of channels to convolute */
  848. s->speaker_pos = av_malloc_array(s->n_conv, sizeof(*s->speaker_pos));
  849. /* memory allocation failed: */
  850. if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
  851. !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
  852. !s->speaker_pos)
  853. return AVERROR(ENOMEM);
  854. compensate_volume(ctx);
  855. /* get speaker positions */
  856. if ((ret = get_speaker_pos(ctx, s->speaker_pos)) < 0) {
  857. av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
  858. return ret;
  859. }
  860. /* load IRs to data_ir[0] and data_ir[1] for required directions */
  861. /* only load IRs if time-domain convolution is used. */
  862. if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
  863. return ret;
  864. av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
  865. inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
  866. return 0;
  867. }
  868. static av_cold void uninit(AVFilterContext *ctx)
  869. {
  870. SOFAlizerContext *s = ctx->priv;
  871. if (s->sofa.ncid) {
  872. av_freep(&s->sofa.sp_a);
  873. av_freep(&s->sofa.sp_e);
  874. av_freep(&s->sofa.sp_r);
  875. av_freep(&s->sofa.data_delay);
  876. av_freep(&s->sofa.data_ir);
  877. }
  878. av_freep(&s->delay[0]);
  879. av_freep(&s->delay[1]);
  880. av_freep(&s->data_ir[0]);
  881. av_freep(&s->data_ir[1]);
  882. av_freep(&s->ringbuffer[0]);
  883. av_freep(&s->ringbuffer[1]);
  884. av_freep(&s->speaker_pos);
  885. av_freep(&s->temp_src[0]);
  886. av_freep(&s->temp_src[1]);
  887. av_freep(&s->fdsp);
  888. }
  889. #define OFFSET(x) offsetof(SOFAlizerContext, x)
  890. #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  891. static const AVOption sofalizer_options[] = {
  892. { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
  893. { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
  894. { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
  895. { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
  896. { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
  897. { NULL }
  898. };
  899. AVFILTER_DEFINE_CLASS(sofalizer);
  900. static const AVFilterPad inputs[] = {
  901. {
  902. .name = "default",
  903. .type = AVMEDIA_TYPE_AUDIO,
  904. .config_props = config_input,
  905. .filter_frame = filter_frame,
  906. },
  907. { NULL }
  908. };
  909. static const AVFilterPad outputs[] = {
  910. {
  911. .name = "default",
  912. .type = AVMEDIA_TYPE_AUDIO,
  913. },
  914. { NULL }
  915. };
  916. AVFilter ff_af_sofalizer = {
  917. .name = "sofalizer",
  918. .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
  919. .priv_size = sizeof(SOFAlizerContext),
  920. .priv_class = &sofalizer_class,
  921. .init = init,
  922. .uninit = uninit,
  923. .query_formats = query_formats,
  924. .inputs = inputs,
  925. .outputs = outputs,
  926. .flags = AVFILTER_FLAG_SLICE_THREADS,
  927. };