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.

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