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.

1235 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 & (1ULL << 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. const float fft_scale = 1.0f / s->n_fft;
  617. FFTComplex *hrtf_offset;
  618. int wr = *write;
  619. int n_read;
  620. int i, j;
  621. dst += offset;
  622. /* find minimum between number of samples and output buffer length:
  623. * (important, if one IR is longer than the output buffer) */
  624. n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
  625. for (j = 0; j < n_read; j++) {
  626. /* initialize output buf with saved signal from overflow buf */
  627. dst[2 * j] = ringbuffer[wr];
  628. ringbuffer[wr] = 0.0; /* re-set read samples to zero */
  629. /* update ringbuffer read/write position */
  630. wr = (wr + 1) & modulo;
  631. }
  632. /* initialize rest of output buffer with 0 */
  633. for (j = n_read; j < in->nb_samples; j++) {
  634. dst[2 * j] = 0;
  635. }
  636. for (i = 0; i < n_conv; i++) {
  637. if (i == s->lfe_channel) { /* LFE */
  638. for (j = 0; j < in->nb_samples; j++) {
  639. /* apply gain to LFE signal and add to output buffer */
  640. dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
  641. }
  642. continue;
  643. }
  644. /* outer loop: go through all input channels to be convolved */
  645. offset = i * n_fft; /* no. samples already processed */
  646. hrtf_offset = hrtf + offset;
  647. /* fill FFT input with 0 (we want to zero-pad) */
  648. memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
  649. for (j = 0; j < in->nb_samples; j++) {
  650. /* prepare input for FFT */
  651. /* write all samples of current input channel to FFT input array */
  652. fft_in[j].re = src[j * in_channels + i];
  653. }
  654. /* transform input signal of current channel to frequency domain */
  655. av_fft_permute(fft, fft_in);
  656. av_fft_calc(fft, fft_in);
  657. for (j = 0; j < n_fft; j++) {
  658. const FFTComplex *hcomplex = hrtf_offset + j;
  659. const float re = fft_in[j].re;
  660. const float im = fft_in[j].im;
  661. /* complex multiplication of input signal and HRTFs */
  662. /* output channel (real): */
  663. fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
  664. /* output channel (imag): */
  665. fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
  666. }
  667. /* transform output signal of current channel back to time domain */
  668. av_fft_permute(ifft, fft_in);
  669. av_fft_calc(ifft, fft_in);
  670. for (j = 0; j < in->nb_samples; j++) {
  671. /* write output signal of current channel to output buffer */
  672. dst[2 * j] += fft_in[j].re * fft_scale;
  673. }
  674. for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
  675. /* write the rest of output signal to overflow buffer */
  676. int write_pos = (wr + j) & modulo;
  677. *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
  678. }
  679. }
  680. /* go through all samples of current output buffer: count clippings */
  681. for (i = 0; i < out->nb_samples; i++) {
  682. /* clippings counter */
  683. if (fabs(*dst) > 1) { /* if current output sample > 1 */
  684. n_clippings[0]++;
  685. }
  686. /* move output buffer pointer by +2 to get to next sample of processed channel: */
  687. dst += 2;
  688. }
  689. /* remember read/write position in ringbuffer for next call */
  690. *write = wr;
  691. return 0;
  692. }
  693. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  694. {
  695. AVFilterContext *ctx = inlink->dst;
  696. SOFAlizerContext *s = ctx->priv;
  697. AVFilterLink *outlink = ctx->outputs[0];
  698. int n_clippings[2] = { 0 };
  699. ThreadData td;
  700. AVFrame *out;
  701. out = ff_get_audio_buffer(outlink, in->nb_samples);
  702. if (!out) {
  703. av_frame_free(&in);
  704. return AVERROR(ENOMEM);
  705. }
  706. av_frame_copy_props(out, in);
  707. td.in = in; td.out = out; td.write = s->write;
  708. td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
  709. td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
  710. td.temp_fft = s->temp_fft;
  711. if (s->type == TIME_DOMAIN) {
  712. ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
  713. } else {
  714. ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
  715. }
  716. emms_c();
  717. /* display error message if clipping occurred */
  718. if (n_clippings[0] + n_clippings[1] > 0) {
  719. av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
  720. n_clippings[0] + n_clippings[1], out->nb_samples * 2);
  721. }
  722. av_frame_free(&in);
  723. return ff_filter_frame(outlink, out);
  724. }
  725. static int query_formats(AVFilterContext *ctx)
  726. {
  727. struct SOFAlizerContext *s = ctx->priv;
  728. AVFilterFormats *formats = NULL;
  729. AVFilterChannelLayouts *layouts = NULL;
  730. int ret, sample_rates[] = { 48000, -1 };
  731. ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
  732. if (ret)
  733. return ret;
  734. ret = ff_set_common_formats(ctx, formats);
  735. if (ret)
  736. return ret;
  737. layouts = ff_all_channel_layouts();
  738. if (!layouts)
  739. return AVERROR(ENOMEM);
  740. ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
  741. if (ret)
  742. return ret;
  743. layouts = NULL;
  744. ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
  745. if (ret)
  746. return ret;
  747. ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
  748. if (ret)
  749. return ret;
  750. sample_rates[0] = s->sample_rate;
  751. formats = ff_make_format_list(sample_rates);
  752. if (!formats)
  753. return AVERROR(ENOMEM);
  754. return ff_set_common_samplerates(ctx, formats);
  755. }
  756. static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
  757. {
  758. struct SOFAlizerContext *s = ctx->priv;
  759. const int n_samples = s->sofa.n_samples;
  760. int n_conv = s->n_conv; /* no. channels to convolve */
  761. int n_fft = s->n_fft;
  762. int delay_l[16]; /* broadband delay for each IR */
  763. int delay_r[16];
  764. int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
  765. float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
  766. FFTComplex *data_hrtf_l = NULL;
  767. FFTComplex *data_hrtf_r = NULL;
  768. FFTComplex *fft_in_l = NULL;
  769. FFTComplex *fft_in_r = NULL;
  770. float *data_ir_l = NULL;
  771. float *data_ir_r = NULL;
  772. int offset = 0; /* used for faster pointer arithmetics in for-loop */
  773. int m[16]; /* measurement index m of IR closest to required source positions */
  774. int i, j, azim_orig = azim, elev_orig = elev;
  775. if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
  776. av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
  777. return AVERROR_INVALIDDATA;
  778. }
  779. if (s->type == TIME_DOMAIN) {
  780. s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
  781. s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
  782. /* get temporary IR for L and R channel */
  783. data_ir_l = av_calloc(n_conv * FFALIGN(n_samples, 16), sizeof(*data_ir_l));
  784. data_ir_r = av_calloc(n_conv * FFALIGN(n_samples, 16), sizeof(*data_ir_r));
  785. if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
  786. av_free(data_ir_l);
  787. av_free(data_ir_r);
  788. return AVERROR(ENOMEM);
  789. }
  790. } else {
  791. /* get temporary HRTF memory for L and R channel */
  792. data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
  793. data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
  794. if (!data_hrtf_r || !data_hrtf_l) {
  795. av_free(data_hrtf_l);
  796. av_free(data_hrtf_r);
  797. return AVERROR(ENOMEM);
  798. }
  799. }
  800. for (i = 0; i < s->n_conv; i++) {
  801. /* load and store IRs and corresponding delays */
  802. azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
  803. elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
  804. /* get id of IR closest to desired position */
  805. m[i] = find_m(s, azim, elev, radius);
  806. /* load the delays associated with the current IRs */
  807. delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
  808. delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
  809. if (s->type == TIME_DOMAIN) {
  810. offset = i * FFALIGN(n_samples, 16); /* no. samples already written */
  811. for (j = 0; j < n_samples; j++) {
  812. /* load reversed IRs of the specified source position
  813. * sample-by-sample for left and right ear; and apply gain */
  814. *(data_ir_l + offset + j) = /* left channel */
  815. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
  816. *(data_ir_r + offset + j) = /* right channel */
  817. *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
  818. }
  819. } else {
  820. fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
  821. fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
  822. if (!fft_in_l || !fft_in_r) {
  823. av_free(data_hrtf_l);
  824. av_free(data_hrtf_r);
  825. av_free(fft_in_l);
  826. av_free(fft_in_r);
  827. return AVERROR(ENOMEM);
  828. }
  829. offset = i * n_fft; /* no. samples already written */
  830. for (j = 0; j < n_samples; j++) {
  831. /* load non-reversed IRs of the specified source position
  832. * sample-by-sample and apply gain,
  833. * L channel is loaded to real part, R channel to imag part,
  834. * IRs ared shifted by L and R delay */
  835. fft_in_l[delay_l[i] + j].re = /* left channel */
  836. *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
  837. fft_in_r[delay_r[i] + j].re = /* right channel */
  838. *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
  839. }
  840. /* actually transform to frequency domain (IRs -> HRTFs) */
  841. av_fft_permute(s->fft[0], fft_in_l);
  842. av_fft_calc(s->fft[0], fft_in_l);
  843. memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
  844. av_fft_permute(s->fft[0], fft_in_r);
  845. av_fft_calc(s->fft[0], fft_in_r);
  846. memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
  847. }
  848. av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
  849. m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
  850. }
  851. if (s->type == TIME_DOMAIN) {
  852. /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
  853. memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * FFALIGN(n_samples, 16));
  854. memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * FFALIGN(n_samples, 16));
  855. av_freep(&data_ir_l); /* free temporary IR memory */
  856. av_freep(&data_ir_r);
  857. } else {
  858. s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  859. s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
  860. if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
  861. av_freep(&data_hrtf_l);
  862. av_freep(&data_hrtf_r);
  863. av_freep(&fft_in_l);
  864. av_freep(&fft_in_r);
  865. return AVERROR(ENOMEM); /* memory allocation failed */
  866. }
  867. memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
  868. sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
  869. memcpy(s->data_hrtf[1], data_hrtf_r,
  870. sizeof(FFTComplex) * n_conv * n_fft);
  871. av_freep(&data_hrtf_l); /* free temporary HRTF memory */
  872. av_freep(&data_hrtf_r);
  873. av_freep(&fft_in_l); /* free temporary FFT memory */
  874. av_freep(&fft_in_r);
  875. }
  876. memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
  877. memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
  878. return 0;
  879. }
  880. static av_cold int init(AVFilterContext *ctx)
  881. {
  882. SOFAlizerContext *s = ctx->priv;
  883. int ret;
  884. if (!s->filename) {
  885. av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
  886. return AVERROR(EINVAL);
  887. }
  888. /* load SOFA file, */
  889. /* initialize file IDs to 0 before attempting to load SOFA files,
  890. * this assures that in case of error, only the memory of already
  891. * loaded files is free'd */
  892. s->sofa.ncid = 0;
  893. ret = load_sofa(ctx, s->filename, &s->sample_rate);
  894. if (ret) {
  895. /* file loading error */
  896. av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
  897. } else { /* no file loading error, resampling not required */
  898. av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
  899. }
  900. if (ret) {
  901. av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
  902. return ret;
  903. }
  904. s->fdsp = avpriv_float_dsp_alloc(0);
  905. if (!s->fdsp)
  906. return AVERROR(ENOMEM);
  907. return 0;
  908. }
  909. static int config_input(AVFilterLink *inlink)
  910. {
  911. AVFilterContext *ctx = inlink->dst;
  912. SOFAlizerContext *s = ctx->priv;
  913. int nb_input_channels = inlink->channels; /* no. input channels */
  914. int n_max_ir = 0;
  915. int n_current;
  916. int n_max = 0;
  917. int ret;
  918. if (s->type == FREQUENCY_DOMAIN) {
  919. inlink->partial_buf_size =
  920. inlink->min_samples =
  921. inlink->max_samples = inlink->sample_rate;
  922. }
  923. /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
  924. s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
  925. s->n_conv = nb_input_channels;
  926. /* get size of ringbuffer (longest IR plus max. delay) */
  927. /* then choose next power of 2 for performance optimization */
  928. n_current = s->sofa.n_samples + max_delay(&s->sofa);
  929. if (n_current > n_max) {
  930. /* length of longest IR plus max. delay (in all SOFA files) */
  931. n_max = n_current;
  932. /* length of longest IR (without delay, in all SOFA files) */
  933. n_max_ir = s->sofa.n_samples;
  934. }
  935. /* buffer length is longest IR plus max. delay -> next power of 2
  936. (32 - count leading zeros gives required exponent) */
  937. s->buffer_length = 1 << (32 - ff_clz(n_max));
  938. s->n_fft = 1 << (32 - ff_clz(n_max + inlink->sample_rate));
  939. if (s->type == FREQUENCY_DOMAIN) {
  940. av_fft_end(s->fft[0]);
  941. av_fft_end(s->fft[1]);
  942. s->fft[0] = av_fft_init(log2(s->n_fft), 0);
  943. s->fft[1] = av_fft_init(log2(s->n_fft), 0);
  944. av_fft_end(s->ifft[0]);
  945. av_fft_end(s->ifft[1]);
  946. s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
  947. s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
  948. if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
  949. av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
  950. return AVERROR(ENOMEM);
  951. }
  952. }
  953. /* Allocate memory for the impulse responses, delays and the ringbuffers */
  954. /* size: (longest IR) * (number of channels to convolute) */
  955. s->data_ir[0] = av_calloc(FFALIGN(n_max_ir, 16), sizeof(float) * s->n_conv);
  956. s->data_ir[1] = av_calloc(FFALIGN(n_max_ir, 16), sizeof(float) * s->n_conv);
  957. /* length: number of channels to convolute */
  958. s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
  959. s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
  960. /* length: (buffer length) * (number of input channels),
  961. * OR: buffer length (if frequency domain processing)
  962. * calloc zero-initializes the buffer */
  963. if (s->type == TIME_DOMAIN) {
  964. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  965. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
  966. } else {
  967. s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
  968. s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
  969. s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  970. s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
  971. if (!s->temp_fft[0] || !s->temp_fft[1])
  972. return AVERROR(ENOMEM);
  973. }
  974. /* length: number of channels to convolute */
  975. s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
  976. s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
  977. /* memory allocation failed: */
  978. if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
  979. !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
  980. !s->speaker_azim || !s->speaker_elev)
  981. return AVERROR(ENOMEM);
  982. compensate_volume(ctx);
  983. /* get speaker positions */
  984. if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
  985. av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
  986. return ret;
  987. }
  988. /* load IRs to data_ir[0] and data_ir[1] for required directions */
  989. if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
  990. return ret;
  991. av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
  992. inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
  993. return 0;
  994. }
  995. static av_cold void uninit(AVFilterContext *ctx)
  996. {
  997. SOFAlizerContext *s = ctx->priv;
  998. if (s->sofa.ncid) {
  999. av_freep(&s->sofa.sp_a);
  1000. av_freep(&s->sofa.sp_e);
  1001. av_freep(&s->sofa.sp_r);
  1002. av_freep(&s->sofa.data_delay);
  1003. av_freep(&s->sofa.data_ir);
  1004. }
  1005. av_fft_end(s->ifft[0]);
  1006. av_fft_end(s->ifft[1]);
  1007. av_fft_end(s->fft[0]);
  1008. av_fft_end(s->fft[1]);
  1009. av_freep(&s->delay[0]);
  1010. av_freep(&s->delay[1]);
  1011. av_freep(&s->data_ir[0]);
  1012. av_freep(&s->data_ir[1]);
  1013. av_freep(&s->ringbuffer[0]);
  1014. av_freep(&s->ringbuffer[1]);
  1015. av_freep(&s->speaker_azim);
  1016. av_freep(&s->speaker_elev);
  1017. av_freep(&s->temp_src[0]);
  1018. av_freep(&s->temp_src[1]);
  1019. av_freep(&s->temp_fft[0]);
  1020. av_freep(&s->temp_fft[1]);
  1021. av_freep(&s->data_hrtf[0]);
  1022. av_freep(&s->data_hrtf[1]);
  1023. av_freep(&s->fdsp);
  1024. }
  1025. #define OFFSET(x) offsetof(SOFAlizerContext, x)
  1026. #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  1027. static const AVOption sofalizer_options[] = {
  1028. { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
  1029. { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
  1030. { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
  1031. { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
  1032. { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
  1033. { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
  1034. { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
  1035. { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
  1036. { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
  1037. { NULL }
  1038. };
  1039. AVFILTER_DEFINE_CLASS(sofalizer);
  1040. static const AVFilterPad inputs[] = {
  1041. {
  1042. .name = "default",
  1043. .type = AVMEDIA_TYPE_AUDIO,
  1044. .config_props = config_input,
  1045. .filter_frame = filter_frame,
  1046. },
  1047. { NULL }
  1048. };
  1049. static const AVFilterPad outputs[] = {
  1050. {
  1051. .name = "default",
  1052. .type = AVMEDIA_TYPE_AUDIO,
  1053. },
  1054. { NULL }
  1055. };
  1056. AVFilter ff_af_sofalizer = {
  1057. .name = "sofalizer",
  1058. .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
  1059. .priv_size = sizeof(SOFAlizerContext),
  1060. .priv_class = &sofalizer_class,
  1061. .init = init,
  1062. .uninit = uninit,
  1063. .query_formats = query_formats,
  1064. .inputs = inputs,
  1065. .outputs = outputs,
  1066. .flags = AVFILTER_FLAG_SLICE_THREADS,
  1067. };