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
7 * Authors: Andreas Fuchs <andi.fuchs.mail@gmail.com>
8 * Wolfgang Hrauda <wolfgang.hrauda@gmx.at>
10 * SOFAlizer project coordinator at ARI, main developer of SOFA:
11 * Piotr Majdak <piotr@majdak.at>
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.
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.
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 *****************************************************************************/
31 #include "libavcodec/avfft.h"
32 #include "libavutil/float_dsp.h"
33 #include "libavutil/opt.h"
39 #define FREQUENCY_DOMAIN 1
41 typedef struct NCSofa { /* contains data of one SOFA file */
42 int ncid; /* netCDF ID of the opened SOFA file */
43 int n_samples; /* length of one impulse response (IR) */
44 int m_dim; /* number of measurement positions */
45 int *data_delay; /* broadband delay of each IR */
46 /* all measurement positions for each receiver (i.e. ear): */
47 float *sp_a; /* azimuth angles */
48 float *sp_e; /* elevation angles */
49 float *sp_r; /* radii */
50 /* data at each measurement position for each receiver: */
51 float *data_ir; /* IRs (time-domain) */
54 typedef struct SOFAlizerContext {
57 char *filename; /* name of SOFA file */
58 NCSofa sofa; /* contains data of the SOFA file */
60 int sample_rate; /* sample rate from SOFA file */
61 float *speaker_azim; /* azimuth of the virtual loudspeakers */
62 float *speaker_elev; /* elevation of the virtual loudspeakers */
63 float gain_lfe; /* gain applied to LFE channel */
64 int lfe_channel; /* LFE channel position in channel layout */
66 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 */
76 /* netCDF variables */
77 int *delay[2]; /* broadband delay for each channel/IR to be convolved */
79 float *data_ir[2]; /* IRs for all channels to be convolved */
80 /* (this excludes the LFE) */
82 FFTComplex *temp_fft[2];
84 /* control variables */
85 float gain; /* filter gain (in dB) */
86 float rotation; /* rotation of virtual loudspeakers (in degrees) */
87 float elevation; /* elevation of virtual loudspeakers (in deg.) */
88 float radius; /* distance virtual loudspeakers to listener (in metres) */
89 int type; /* processing type */
91 FFTContext *fft[2], *ifft[2];
92 FFTComplex *data_hrtf[2];
94 AVFloatDSPContext *fdsp;
97 static int close_sofa(struct NCSofa *sofa)
99 av_freep(&sofa->data_delay);
100 av_freep(&sofa->sp_a);
101 av_freep(&sofa->sp_e);
102 av_freep(&sofa->sp_r);
103 av_freep(&sofa->data_ir);
104 nc_close(sofa->ncid);
110 static int load_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
112 struct SOFAlizerContext *s = ctx->priv;
113 /* variables associated with content of SOFA file: */
114 int ncid, n_dims, n_vars, n_gatts, n_unlim_dim_id, status;
115 char data_delay_dim_name[NC_MAX_NAME];
116 float *sp_a, *sp_e, *sp_r, *data_ir;
117 char *sofa_conventions;
118 char dim_name[NC_MAX_NAME]; /* names of netCDF dimensions */
119 size_t *dim_length; /* lengths of netCDF dimensions */
121 unsigned int sample_rate;
122 int data_delay_dim_id[2];
136 status = nc_open(filename, NC_NOWRITE, &ncid); /* open SOFA file read-only */
137 if (status != NC_NOERR) {
138 av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
139 return AVERROR(EINVAL);
142 /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
143 nc_inq(ncid, &n_dims, &n_vars, &n_gatts, &n_unlim_dim_id);
145 /* -- get number of measurements ("M") and length of one IR ("N") -- */
146 dim_length = av_malloc_array(n_dims, sizeof(*dim_length));
149 return AVERROR(ENOMEM);
152 for (i = 0; i < n_dims; i++) { /* go through all dimensions of file */
153 nc_inq_dim(ncid, i, (char *)&dim_name, &dim_length[i]); /* get dimensions */
154 if (!strncmp("M", (const char *)&dim_name, 1)) /* get ID of dimension "M" */
156 if (!strncmp("N", (const char *)&dim_name, 1)) /* get ID of dimension "N" */
160 if ((m_dim_id == -1) || (n_dim_id == -1)) { /* dimension "M" or "N" couldn't be found */
161 av_log(ctx, AV_LOG_ERROR, "Can't find required dimensions in SOFA file.\n");
162 av_freep(&dim_length);
164 return AVERROR(EINVAL);
167 n_samples = dim_length[n_dim_id]; /* get length of one IR */
168 m_dim = dim_length[m_dim_id]; /* get number of measurements */
170 av_freep(&dim_length);
172 /* -- check file type -- */
173 /* get length of attritube "Conventions" */
174 status = nc_inq_attlen(ncid, NC_GLOBAL, "Conventions", &att_len);
175 if (status != NC_NOERR) {
176 av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
178 return AVERROR_INVALIDDATA;
181 /* check whether file is SOFA file */
182 text = av_malloc(att_len + 1);
185 return AVERROR(ENOMEM);
188 nc_get_att_text(ncid, NC_GLOBAL, "Conventions", text);
189 *(text + att_len) = 0;
190 if (strncmp("SOFA", text, 4)) {
191 av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
194 return AVERROR(EINVAL);
198 status = nc_inq_attlen(ncid, NC_GLOBAL, "License", &att_len);
199 if (status == NC_NOERR) {
200 text = av_malloc(att_len + 1);
202 nc_get_att_text(ncid, NC_GLOBAL, "License", text);
203 *(text + att_len) = 0;
204 av_log(ctx, AV_LOG_INFO, "SOFA file License: %s\n", text);
209 status = nc_inq_attlen(ncid, NC_GLOBAL, "SourceDescription", &att_len);
210 if (status == NC_NOERR) {
211 text = av_malloc(att_len + 1);
213 nc_get_att_text(ncid, NC_GLOBAL, "SourceDescription", text);
214 *(text + att_len) = 0;
215 av_log(ctx, AV_LOG_INFO, "SOFA file SourceDescription: %s\n", text);
220 status = nc_inq_attlen(ncid, NC_GLOBAL, "Comment", &att_len);
221 if (status == NC_NOERR) {
222 text = av_malloc(att_len + 1);
224 nc_get_att_text(ncid, NC_GLOBAL, "Comment", text);
225 *(text + att_len) = 0;
226 av_log(ctx, AV_LOG_INFO, "SOFA file Comment: %s\n", text);
231 status = nc_inq_attlen(ncid, NC_GLOBAL, "SOFAConventions", &att_len);
232 if (status != NC_NOERR) {
233 av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"SOFAConventions\".\n");
235 return AVERROR_INVALIDDATA;
238 sofa_conventions = av_malloc(att_len + 1);
239 if (!sofa_conventions) {
241 return AVERROR(ENOMEM);
244 nc_get_att_text(ncid, NC_GLOBAL, "SOFAConventions", sofa_conventions);
245 *(sofa_conventions + att_len) = 0;
246 if (strncmp("SimpleFreeFieldHRIR", sofa_conventions, att_len)) {
247 av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
248 av_freep(&sofa_conventions);
250 return AVERROR(EINVAL);
252 av_freep(&sofa_conventions);
254 /* -- get sampling rate of HRTFs -- */
255 /* read ID, then value */
256 status = nc_inq_varid(ncid, "Data.SamplingRate", &samplingrate_id);
257 status += nc_get_var_uint(ncid, samplingrate_id, &sample_rate);
258 if (status != NC_NOERR) {
259 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
261 return AVERROR(EINVAL);
263 *samplingrate = sample_rate; /* remember sampling rate */
265 /* -- allocate memory for one value for each measurement position: -- */
266 sp_a = s->sofa.sp_a = av_malloc_array(m_dim, sizeof(float));
267 sp_e = s->sofa.sp_e = av_malloc_array(m_dim, sizeof(float));
268 sp_r = s->sofa.sp_r = av_malloc_array(m_dim, sizeof(float));
269 /* delay and IR values required for each ear and measurement position: */
270 data_delay = s->sofa.data_delay = av_calloc(m_dim, 2 * sizeof(int));
271 data_ir = s->sofa.data_ir = av_malloc_array(m_dim * n_samples, sizeof(float) * 2);
273 if (!data_delay || !sp_a || !sp_e || !sp_r || !data_ir) {
274 /* if memory could not be allocated */
275 close_sofa(&s->sofa);
276 return AVERROR(ENOMEM);
279 /* get impulse responses (HRTFs): */
280 /* get corresponding ID */
281 status = nc_inq_varid(ncid, "Data.IR", &data_ir_id);
282 status += nc_get_var_float(ncid, data_ir_id, data_ir); /* read and store IRs */
283 if (status != NC_NOERR) {
284 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.IR!\n");
285 ret = AVERROR(EINVAL);
289 /* get source positions of the HRTFs in the SOFA file: */
290 status = nc_inq_varid(ncid, "SourcePosition", &sp_id); /* get corresponding ID */
291 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 0 } ,
292 (size_t[2]){ m_dim, 1}, sp_a); /* read & store azimuth angles */
293 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 1 } ,
294 (size_t[2]){ m_dim, 1}, sp_e); /* read & store elevation angles */
295 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 2 } ,
296 (size_t[2]){ m_dim, 1}, sp_r); /* read & store radii */
297 if (status != NC_NOERR) { /* if any source position variable coudn't be read */
298 av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
299 ret = AVERROR(EINVAL);
303 /* read Data.Delay, check for errors and fit it to data_delay */
304 status = nc_inq_varid(ncid, "Data.Delay", &data_delay_id);
305 status += nc_inq_vardimid(ncid, data_delay_id, &data_delay_dim_id[0]);
306 status += nc_inq_dimname(ncid, data_delay_dim_id[0], data_delay_dim_name);
307 if (status != NC_NOERR) {
308 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
309 ret = AVERROR(EINVAL);
313 /* Data.Delay dimension check */
314 /* dimension of Data.Delay is [I R]: */
315 if (!strncmp(data_delay_dim_name, "I", 2)) {
316 /* check 2 characters to assure string is 0-terminated after "I" */
317 int delay[2]; /* delays get from SOFA file: */
319 av_log(ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n");
320 status = nc_get_var_int(ncid, data_delay_id, &delay[0]);
321 if (status != NC_NOERR) {
322 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
323 ret = AVERROR(EINVAL);
326 int *data_delay_r = data_delay + m_dim;
327 for (i = 0; i < m_dim; i++) { /* extend given dimension [I R] to [M R] */
328 /* assign constant delay value for all measurements to data_delay fields */
329 data_delay[i] = delay[0];
330 data_delay_r[i] = delay[1];
332 /* dimension of Data.Delay is [M R] */
333 } else if (!strncmp(data_delay_dim_name, "M", 2)) {
334 av_log(ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
335 /* get delays from SOFA file: */
336 status = nc_get_var_int(ncid, data_delay_id, data_delay);
337 if (status != NC_NOERR) {
338 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
339 ret = AVERROR(EINVAL);
342 } else { /* dimension of Data.Delay is neither [I R] nor [M R] */
343 av_log(ctx, AV_LOG_ERROR, "Data.Delay does not have the required dimensions [I R] or [M R].\n");
344 ret = AVERROR(EINVAL);
348 /* save information in SOFA struct: */
349 s->sofa.m_dim = m_dim; /* no. measurement positions */
350 s->sofa.n_samples = n_samples; /* length on one IR */
351 s->sofa.ncid = ncid; /* netCDF ID of SOFA file */
352 nc_close(ncid); /* close SOFA file */
357 close_sofa(&s->sofa);
361 static int get_speaker_pos(AVFilterContext *ctx,
362 float *speaker_azim, float *speaker_elev)
364 struct SOFAlizerContext *s = ctx->priv;
365 uint64_t channels_layout = ctx->inputs[0]->channel_layout;
366 float azim[16] = { 0 };
367 float elev[16] = { 0 };
368 int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
371 return AVERROR(EINVAL);
375 /* set speaker positions according to input channel configuration: */
376 for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
377 uint64_t mask = channels_layout & (1 << m);
380 case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
381 case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
382 case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
383 case AV_CH_LOW_FREQUENCY:
384 case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
385 case AV_CH_BACK_LEFT: azim[ch] = 150; break;
386 case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
387 case AV_CH_BACK_CENTER: azim[ch] = 180; break;
388 case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
389 case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
390 case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
391 case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
392 case AV_CH_TOP_CENTER: azim[ch] = 0;
393 elev[ch] = 90; break;
394 case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
395 elev[ch] = 45; break;
396 case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
397 elev[ch] = 45; break;
398 case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
399 elev[ch] = 45; break;
400 case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
401 elev[ch] = 45; break;
402 case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
403 elev[ch] = 45; break;
404 case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
405 elev[ch] = 45; break;
406 case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
407 case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
408 case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
409 case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
410 case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
411 case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
414 return AVERROR(EINVAL);
420 memcpy(speaker_azim, azim, n_conv * sizeof(float));
421 memcpy(speaker_elev, elev, n_conv * sizeof(float));
427 static int max_delay(struct NCSofa *sofa)
431 for (i = 0; i < sofa->m_dim * 2; i++) {
432 /* search maximum delay in given SOFA file */
433 max = FFMAX(max, sofa->data_delay[i]);
439 static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
441 /* get source positions and M of currently selected SOFA file */
442 float *sp_a = s->sofa.sp_a; /* azimuth angle */
443 float *sp_e = s->sofa.sp_e; /* elevation angle */
444 float *sp_r = s->sofa.sp_r; /* radius */
445 int m_dim = s->sofa.m_dim; /* no. measurements */
446 int best_id = 0; /* index m currently closest to desired source pos. */
447 float delta = 1000; /* offset between desired and currently best pos. */
451 for (i = 0; i < m_dim; i++) {
452 /* search through all measurements in currently selected SOFA file */
453 /* distance of current to desired source position: */
454 current = fabs(sp_a[i] - azim) +
455 fabs(sp_e[i] - elev) +
456 fabs(sp_r[i] - radius);
457 if (current <= delta) {
458 /* if current distance is smaller than smallest distance so far */
460 best_id = i; /* remember index */
467 static int compensate_volume(AVFilterContext *ctx)
469 struct SOFAlizerContext *s = ctx->priv;
476 /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
477 struct NCSofa *sofa = &s->sofa;
478 m = find_m(s, 0, 0, 1);
479 /* get energy of that IR and compensate volume */
480 ir = sofa->data_ir + 2 * m * sofa->n_samples;
481 if (sofa->n_samples & 31) {
482 energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
484 energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
486 compensate = 256 / (sofa->n_samples * sqrt(energy));
487 av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
489 /* apply volume compensation to IRs */
490 s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
497 typedef struct ThreadData {
505 FFTComplex **temp_fft;
508 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
510 SOFAlizerContext *s = ctx->priv;
511 ThreadData *td = arg;
512 AVFrame *in = td->in, *out = td->out;
514 int *write = &td->write[jobnr];
515 const int *const delay = td->delay[jobnr];
516 const float *const ir = td->ir[jobnr];
517 int *n_clippings = &td->n_clippings[jobnr];
518 float *ringbuffer = td->ringbuffer[jobnr];
519 float *temp_src = td->temp_src[jobnr];
520 const int n_samples = s->sofa.n_samples; /* length of one IR */
521 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
522 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
523 const int in_channels = s->n_conv; /* number of input channels */
524 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
525 const int buffer_length = s->buffer_length;
526 /* -1 for AND instead of MODULO (applied to powers of 2): */
527 const uint32_t modulo = (uint32_t)buffer_length - 1;
528 float *buffer[16]; /* holds ringbuffer for each input channel */
534 for (l = 0; l < in_channels; l++) {
535 /* get starting address of ringbuffer for each input channel */
536 buffer[l] = ringbuffer + l * buffer_length;
539 for (i = 0; i < in->nb_samples; i++) {
540 const float *temp_ir = ir; /* using same set of IRs for each sample */
543 for (l = 0; l < in_channels; l++) {
544 /* write current input sample to ringbuffer (for each channel) */
545 *(buffer[l] + wr) = src[l];
548 /* loop goes through all channels to be convolved */
549 for (l = 0; l < in_channels; l++) {
550 const float *const bptr = buffer[l];
552 if (l == s->lfe_channel) {
553 /* LFE is an input channel but requires no convolution */
554 /* apply gain to LFE signal and add to output buffer */
555 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
556 temp_ir += n_samples;
560 /* current read position in ringbuffer: input sample write position
561 * - delay for l-th ch. + diff. betw. IR length and buffer length
562 * (mod buffer length) */
563 read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
565 if (read + n_samples < buffer_length) {
566 memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
568 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
570 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
571 memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
574 /* multiply signal and IR, and add up the results */
575 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
576 temp_ir += n_samples;
579 /* clippings counter */
583 /* move output buffer pointer by +2 to get to next sample of processed channel: */
586 wr = (wr + 1) & modulo; /* update ringbuffer write position */
589 *write = wr; /* remember write position in ringbuffer for next call */
594 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
596 SOFAlizerContext *s = ctx->priv;
597 ThreadData *td = arg;
598 AVFrame *in = td->in, *out = td->out;
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;
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;
634 /* initialize rest of output buffer with 0 */
635 for (j = n_read; j < in->nb_samples; j++) {
639 for (i = 0; i < n_conv; i++) {
640 if (i == s->lfe_channel) { /* LFE */
641 for (j = 0; j < in->nb_samples; j++) {
642 /* apply gain to LFE signal and add to output buffer */
643 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
648 /* outer loop: go through all input channels to be convolved */
649 offset = i * n_fft; /* no. samples already processed */
651 /* fill FFT input with 0 (we want to zero-pad) */
652 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
654 for (j = 0; j < in->nb_samples; j++) {
655 /* prepare input for FFT */
656 /* write all samples of current input channel to FFT input array */
657 fft_in[j].re = src[j * in_channels + i];
660 /* transform input signal of current channel to frequency domain */
661 av_fft_permute(fft, fft_in);
662 av_fft_calc(fft, fft_in);
663 for (j = 0; j < n_fft; j++) {
664 const float re = fft_in[j].re;
665 const float im = fft_in[j].im;
667 /* complex multiplication of input signal and HRTFs */
668 /* output channel (real): */
669 fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
670 /* output channel (imag): */
671 fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
674 /* transform output signal of current channel back to time domain */
675 av_fft_permute(ifft, fft_in);
676 av_fft_calc(ifft, fft_in);
678 for (j = 0; j < in->nb_samples; j++) {
679 /* write output signal of current channel to output buffer */
680 dst[2 * j] += fft_in[j].re / (float)n_fft;
683 for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
684 /* write the rest of output signal to overflow buffer */
685 int write_pos = (wr + j) & modulo;
687 *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
691 /* go through all samples of current output buffer: count clippings */
692 for (i = 0; i < out->nb_samples; i++) {
693 /* clippings counter */
694 if (fabs(*dst) > 1) { /* if current output sample > 1 */
695 *n_clippings = *n_clippings + 1;
698 /* move output buffer pointer by +2 to get to next sample of processed channel: */
702 /* remember read/write position in ringbuffer for next call */
708 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
710 AVFilterContext *ctx = inlink->dst;
711 SOFAlizerContext *s = ctx->priv;
712 AVFilterLink *outlink = ctx->outputs[0];
713 int n_clippings[2] = { 0 };
717 out = ff_get_audio_buffer(outlink, in->nb_samples);
720 return AVERROR(ENOMEM);
722 av_frame_copy_props(out, in);
724 td.in = in; td.out = out; td.write = s->write;
725 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
726 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
727 td.temp_fft = s->temp_fft;
729 if (s->type == TIME_DOMAIN) {
730 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
732 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
736 /* display error message if clipping occurred */
737 if (n_clippings[0] + n_clippings[1] > 0) {
738 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
739 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
743 return ff_filter_frame(outlink, out);
746 static int query_formats(AVFilterContext *ctx)
748 struct SOFAlizerContext *s = ctx->priv;
749 AVFilterFormats *formats = NULL;
750 AVFilterChannelLayouts *layouts = NULL;
751 int ret, sample_rates[] = { 48000, -1 };
753 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
756 ret = ff_set_common_formats(ctx, formats);
760 layouts = ff_all_channel_layouts();
762 return AVERROR(ENOMEM);
764 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
769 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
773 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
777 sample_rates[0] = s->sample_rate;
778 formats = ff_make_format_list(sample_rates);
780 return AVERROR(ENOMEM);
781 return ff_set_common_samplerates(ctx, formats);
784 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
786 struct SOFAlizerContext *s = ctx->priv;
787 const int n_samples = s->sofa.n_samples;
788 int n_conv = s->n_conv; /* no. channels to convolve */
789 int n_fft = s->n_fft;
790 int delay_l[16]; /* broadband delay for each IR */
792 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
793 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
794 FFTComplex *data_hrtf_l = NULL;
795 FFTComplex *data_hrtf_r = NULL;
796 FFTComplex *fft_in_l = NULL;
797 FFTComplex *fft_in_r = NULL;
798 float *data_ir_l = NULL;
799 float *data_ir_r = NULL;
800 int offset = 0; /* used for faster pointer arithmetics in for-loop */
801 int m[16]; /* measurement index m of IR closest to required source positions */
802 int i, j, azim_orig = azim, elev_orig = elev;
804 if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
805 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
806 return AVERROR_INVALIDDATA;
809 if (s->type == TIME_DOMAIN) {
810 s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
811 s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
813 /* get temporary IR for L and R channel */
814 data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
815 data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
816 if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
819 return AVERROR(ENOMEM);
822 /* get temporary HRTF memory for L and R channel */
823 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
824 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
825 if (!data_hrtf_r || !data_hrtf_l) {
826 av_free(data_hrtf_l);
827 av_free(data_hrtf_r);
828 return AVERROR(ENOMEM);
832 for (i = 0; i < s->n_conv; i++) {
833 /* load and store IRs and corresponding delays */
834 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
835 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
836 /* get id of IR closest to desired position */
837 m[i] = find_m(s, azim, elev, radius);
839 /* load the delays associated with the current IRs */
840 delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
841 delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
843 if (s->type == TIME_DOMAIN) {
844 offset = i * n_samples; /* no. samples already written */
845 for (j = 0; j < n_samples; j++) {
846 /* load reversed IRs of the specified source position
847 * sample-by-sample for left and right ear; and apply gain */
848 *(data_ir_l + offset + j) = /* left channel */
849 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
850 *(data_ir_r + offset + j) = /* right channel */
851 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
854 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
855 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
856 if (!fft_in_l || !fft_in_r) {
857 av_free(data_hrtf_l);
858 av_free(data_hrtf_r);
861 return AVERROR(ENOMEM);
864 offset = i * n_fft; /* no. samples already written */
865 for (j = 0; j < n_samples; j++) {
866 /* load non-reversed IRs of the specified source position
867 * sample-by-sample and apply gain,
868 * L channel is loaded to real part, R channel to imag part,
869 * IRs ared shifted by L and R delay */
870 fft_in_l[delay_l[i] + j].re = /* left channel */
871 *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
872 fft_in_r[delay_r[i] + j].re = /* right channel */
873 *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
876 /* actually transform to frequency domain (IRs -> HRTFs) */
877 av_fft_permute(s->fft[0], fft_in_l);
878 av_fft_calc(s->fft[0], fft_in_l);
879 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
880 av_fft_permute(s->fft[0], fft_in_r);
881 av_fft_calc(s->fft[0], fft_in_r);
882 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
885 av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
886 m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
889 if (s->type == TIME_DOMAIN) {
890 /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
891 memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
892 memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);
894 av_freep(&data_ir_l); /* free temporary IR memory */
895 av_freep(&data_ir_r);
897 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
898 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
899 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
900 av_freep(&data_hrtf_l);
901 av_freep(&data_hrtf_r);
904 return AVERROR(ENOMEM); /* memory allocation failed */
907 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
908 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
909 memcpy(s->data_hrtf[1], data_hrtf_r,
910 sizeof(FFTComplex) * n_conv * n_fft);
912 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
913 av_freep(&data_hrtf_r);
915 av_freep(&fft_in_l); /* free temporary FFT memory */
919 memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
920 memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
925 static av_cold int init(AVFilterContext *ctx)
927 SOFAlizerContext *s = ctx->priv;
930 /* load SOFA file, */
931 /* initialize file IDs to 0 before attempting to load SOFA files,
932 * this assures that in case of error, only the memory of already
933 * loaded files is free'd */
935 ret = load_sofa(ctx, s->filename, &s->sample_rate);
937 /* file loading error */
938 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
939 } else { /* no file loading error, resampling not required */
940 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
944 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
948 s->fdsp = avpriv_float_dsp_alloc(0);
950 return AVERROR(ENOMEM);
955 static inline unsigned clz(unsigned x)
957 unsigned i = sizeof(x) * 8;
967 static int config_input(AVFilterLink *inlink)
969 AVFilterContext *ctx = inlink->dst;
970 SOFAlizerContext *s = ctx->priv;
971 int nb_input_channels = inlink->channels; /* no. input channels */
977 if (s->type == FREQUENCY_DOMAIN) {
978 inlink->partial_buf_size =
979 inlink->min_samples =
980 inlink->max_samples = inlink->sample_rate;
983 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
984 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
986 s->n_conv = nb_input_channels;
988 /* get size of ringbuffer (longest IR plus max. delay) */
989 /* then choose next power of 2 for performance optimization */
990 n_current = s->sofa.n_samples + max_delay(&s->sofa);
991 if (n_current > n_max) {
992 /* length of longest IR plus max. delay (in all SOFA files) */
994 /* length of longest IR (without delay, in all SOFA files) */
995 n_max_ir = s->sofa.n_samples;
997 /* buffer length is longest IR plus max. delay -> next power of 2
998 (32 - count leading zeros gives required exponent) */
999 s->buffer_length = exp2(32 - clz((uint32_t)n_max));
1000 s->n_fft = exp2(32 - clz((uint32_t)(n_max + inlink->sample_rate)));
1002 if (s->type == FREQUENCY_DOMAIN) {
1003 av_fft_end(s->fft[0]);
1004 av_fft_end(s->fft[1]);
1005 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
1006 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
1007 av_fft_end(s->ifft[0]);
1008 av_fft_end(s->ifft[1]);
1009 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
1010 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
1012 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
1013 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts.\n");
1014 return AVERROR(ENOMEM);
1018 /* Allocate memory for the impulse responses, delays and the ringbuffers */
1019 /* size: (longest IR) * (number of channels to convolute) */
1020 s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
1021 s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
1022 /* length: number of channels to convolute */
1023 s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
1024 s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
1025 /* length: (buffer length) * (number of input channels),
1026 * OR: buffer length (if frequency domain processing)
1027 * calloc zero-initializes the buffer */
1029 if (s->type == TIME_DOMAIN) {
1030 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1031 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1033 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
1034 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
1035 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1036 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1037 if (!s->temp_fft[0] || !s->temp_fft[1])
1038 return AVERROR(ENOMEM);
1041 /* length: number of channels to convolute */
1042 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
1043 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
1045 /* memory allocation failed: */
1046 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
1047 !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
1048 !s->speaker_azim || !s->speaker_elev)
1049 return AVERROR(ENOMEM);
1051 compensate_volume(ctx);
1053 /* get speaker positions */
1054 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
1055 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
1059 /* load IRs to data_ir[0] and data_ir[1] for required directions */
1060 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
1063 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
1064 inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
1069 static av_cold void uninit(AVFilterContext *ctx)
1071 SOFAlizerContext *s = ctx->priv;
1074 av_freep(&s->sofa.sp_a);
1075 av_freep(&s->sofa.sp_e);
1076 av_freep(&s->sofa.sp_r);
1077 av_freep(&s->sofa.data_delay);
1078 av_freep(&s->sofa.data_ir);
1080 av_fft_end(s->ifft[0]);
1081 av_fft_end(s->ifft[1]);
1082 av_fft_end(s->fft[0]);
1083 av_fft_end(s->fft[1]);
1084 av_freep(&s->delay[0]);
1085 av_freep(&s->delay[1]);
1086 av_freep(&s->data_ir[0]);
1087 av_freep(&s->data_ir[1]);
1088 av_freep(&s->ringbuffer[0]);
1089 av_freep(&s->ringbuffer[1]);
1090 av_freep(&s->speaker_azim);
1091 av_freep(&s->speaker_elev);
1092 av_freep(&s->temp_src[0]);
1093 av_freep(&s->temp_src[1]);
1094 av_freep(&s->temp_fft[0]);
1095 av_freep(&s->temp_fft[1]);
1096 av_freep(&s->data_hrtf[0]);
1097 av_freep(&s->data_hrtf[1]);
1101 #define OFFSET(x) offsetof(SOFAlizerContext, x)
1102 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1104 static const AVOption sofalizer_options[] = {
1105 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1106 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
1107 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
1108 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
1109 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
1110 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
1111 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
1112 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
1116 AVFILTER_DEFINE_CLASS(sofalizer);
1118 static const AVFilterPad inputs[] = {
1121 .type = AVMEDIA_TYPE_AUDIO,
1122 .config_props = config_input,
1123 .filter_frame = filter_frame,
1128 static const AVFilterPad outputs[] = {
1131 .type = AVMEDIA_TYPE_AUDIO,
1136 AVFilter ff_af_sofalizer = {
1137 .name = "sofalizer",
1138 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1139 .priv_size = sizeof(SOFAlizerContext),
1140 .priv_class = &sofalizer_class,
1143 .query_formats = query_formats,
1146 .flags = AVFILTER_FLAG_SLICE_THREADS,