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.

1231 lines
46KB

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