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/intmath.h"
34 #include "libavutil/opt.h"
40 #define FREQUENCY_DOMAIN 1
42 typedef struct NCSofa { /* contains data of one SOFA file */
43 int ncid; /* netCDF ID of the opened SOFA file */
44 int n_samples; /* length of one impulse response (IR) */
45 int m_dim; /* number of measurement positions */
46 int *data_delay; /* broadband delay of each IR */
47 /* all measurement positions for each receiver (i.e. ear): */
48 float *sp_a; /* azimuth angles */
49 float *sp_e; /* elevation angles */
50 float *sp_r; /* radii */
51 /* data at each measurement position for each receiver: */
52 float *data_ir; /* IRs (time-domain) */
55 typedef struct SOFAlizerContext {
58 char *filename; /* name of SOFA file */
59 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 float gain_lfe; /* gain applied to LFE channel */
65 int lfe_channel; /* LFE channel position in channel layout */
67 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 */
77 /* netCDF variables */
78 int *delay[2]; /* broadband delay for each channel/IR to be convolved */
80 float *data_ir[2]; /* IRs for all channels to be convolved */
81 /* (this excludes the LFE) */
83 FFTComplex *temp_fft[2];
85 /* control variables */
86 float gain; /* filter gain (in dB) */
87 float rotation; /* rotation of virtual loudspeakers (in degrees) */
88 float elevation; /* elevation of virtual loudspeakers (in deg.) */
89 float radius; /* distance virtual loudspeakers to listener (in metres) */
90 int type; /* processing type */
92 FFTContext *fft[2], *ifft[2];
93 FFTComplex *data_hrtf[2];
95 AVFloatDSPContext *fdsp;
98 static int close_sofa(struct NCSofa *sofa)
100 av_freep(&sofa->data_delay);
101 av_freep(&sofa->sp_a);
102 av_freep(&sofa->sp_e);
103 av_freep(&sofa->sp_r);
104 av_freep(&sofa->data_ir);
105 nc_close(sofa->ncid);
111 static int load_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
113 struct SOFAlizerContext *s = ctx->priv;
114 /* variables associated with content of SOFA file: */
115 int ncid, n_dims, n_vars, n_gatts, n_unlim_dim_id, status;
116 char data_delay_dim_name[NC_MAX_NAME];
117 float *sp_a, *sp_e, *sp_r, *data_ir;
118 char *sofa_conventions;
119 char dim_name[NC_MAX_NAME]; /* names of netCDF dimensions */
120 size_t *dim_length; /* lengths of netCDF dimensions */
122 unsigned int sample_rate;
123 int data_delay_dim_id[2];
137 status = nc_open(filename, NC_NOWRITE, &ncid); /* open SOFA file read-only */
138 if (status != NC_NOERR) {
139 av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
140 return AVERROR(EINVAL);
143 /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
144 nc_inq(ncid, &n_dims, &n_vars, &n_gatts, &n_unlim_dim_id);
146 /* -- get number of measurements ("M") and length of one IR ("N") -- */
147 dim_length = av_malloc_array(n_dims, sizeof(*dim_length));
150 return AVERROR(ENOMEM);
153 for (i = 0; i < n_dims; i++) { /* go through all dimensions of file */
154 nc_inq_dim(ncid, i, (char *)&dim_name, &dim_length[i]); /* get dimensions */
155 if (!strncmp("M", (const char *)&dim_name, 1)) /* get ID of dimension "M" */
157 if (!strncmp("N", (const char *)&dim_name, 1)) /* get ID of dimension "N" */
161 if ((m_dim_id == -1) || (n_dim_id == -1)) { /* dimension "M" or "N" couldn't be found */
162 av_log(ctx, AV_LOG_ERROR, "Can't find required dimensions in SOFA file.\n");
163 av_freep(&dim_length);
165 return AVERROR(EINVAL);
168 n_samples = dim_length[n_dim_id]; /* get length of one IR */
169 m_dim = dim_length[m_dim_id]; /* get number of measurements */
171 av_freep(&dim_length);
173 /* -- check file type -- */
174 /* get length of attritube "Conventions" */
175 status = nc_inq_attlen(ncid, NC_GLOBAL, "Conventions", &att_len);
176 if (status != NC_NOERR) {
177 av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
179 return AVERROR_INVALIDDATA;
182 /* check whether file is SOFA file */
183 text = av_malloc(att_len + 1);
186 return AVERROR(ENOMEM);
189 nc_get_att_text(ncid, NC_GLOBAL, "Conventions", text);
190 *(text + att_len) = 0;
191 if (strncmp("SOFA", text, 4)) {
192 av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
195 return AVERROR(EINVAL);
199 status = nc_inq_attlen(ncid, NC_GLOBAL, "License", &att_len);
200 if (status == NC_NOERR) {
201 text = av_malloc(att_len + 1);
203 nc_get_att_text(ncid, NC_GLOBAL, "License", text);
204 *(text + att_len) = 0;
205 av_log(ctx, AV_LOG_INFO, "SOFA file License: %s\n", text);
210 status = nc_inq_attlen(ncid, NC_GLOBAL, "SourceDescription", &att_len);
211 if (status == NC_NOERR) {
212 text = av_malloc(att_len + 1);
214 nc_get_att_text(ncid, NC_GLOBAL, "SourceDescription", text);
215 *(text + att_len) = 0;
216 av_log(ctx, AV_LOG_INFO, "SOFA file SourceDescription: %s\n", text);
221 status = nc_inq_attlen(ncid, NC_GLOBAL, "Comment", &att_len);
222 if (status == NC_NOERR) {
223 text = av_malloc(att_len + 1);
225 nc_get_att_text(ncid, NC_GLOBAL, "Comment", text);
226 *(text + att_len) = 0;
227 av_log(ctx, AV_LOG_INFO, "SOFA file Comment: %s\n", text);
232 status = nc_inq_attlen(ncid, NC_GLOBAL, "SOFAConventions", &att_len);
233 if (status != NC_NOERR) {
234 av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"SOFAConventions\".\n");
236 return AVERROR_INVALIDDATA;
239 sofa_conventions = av_malloc(att_len + 1);
240 if (!sofa_conventions) {
242 return AVERROR(ENOMEM);
245 nc_get_att_text(ncid, NC_GLOBAL, "SOFAConventions", sofa_conventions);
246 *(sofa_conventions + att_len) = 0;
247 if (strncmp("SimpleFreeFieldHRIR", sofa_conventions, att_len)) {
248 av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
249 av_freep(&sofa_conventions);
251 return AVERROR(EINVAL);
253 av_freep(&sofa_conventions);
255 /* -- get sampling rate of HRTFs -- */
256 /* read ID, then value */
257 status = nc_inq_varid(ncid, "Data.SamplingRate", &samplingrate_id);
258 status += nc_get_var_uint(ncid, samplingrate_id, &sample_rate);
259 if (status != NC_NOERR) {
260 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
262 return AVERROR(EINVAL);
264 *samplingrate = sample_rate; /* remember sampling rate */
266 /* -- allocate memory for one value for each measurement position: -- */
267 sp_a = s->sofa.sp_a = av_malloc_array(m_dim, sizeof(float));
268 sp_e = s->sofa.sp_e = av_malloc_array(m_dim, sizeof(float));
269 sp_r = s->sofa.sp_r = av_malloc_array(m_dim, sizeof(float));
270 /* delay and IR values required for each ear and measurement position: */
271 data_delay = s->sofa.data_delay = av_calloc(m_dim, 2 * sizeof(int));
272 data_ir = s->sofa.data_ir = av_calloc(m_dim * FFALIGN(n_samples, 16), sizeof(float) * 2);
274 if (!data_delay || !sp_a || !sp_e || !sp_r || !data_ir) {
275 /* if memory could not be allocated */
276 close_sofa(&s->sofa);
277 return AVERROR(ENOMEM);
280 /* get impulse responses (HRTFs): */
281 /* get corresponding ID */
282 status = nc_inq_varid(ncid, "Data.IR", &data_ir_id);
283 status += nc_get_var_float(ncid, data_ir_id, data_ir); /* read and store IRs */
284 if (status != NC_NOERR) {
285 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.IR!\n");
286 ret = AVERROR(EINVAL);
290 /* get source positions of the HRTFs in the SOFA file: */
291 status = nc_inq_varid(ncid, "SourcePosition", &sp_id); /* get corresponding ID */
292 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 0 } ,
293 (size_t[2]){ m_dim, 1}, sp_a); /* read & store azimuth angles */
294 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 1 } ,
295 (size_t[2]){ m_dim, 1}, sp_e); /* read & store elevation angles */
296 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 2 } ,
297 (size_t[2]){ m_dim, 1}, sp_r); /* read & store radii */
298 if (status != NC_NOERR) { /* if any source position variable coudn't be read */
299 av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
300 ret = AVERROR(EINVAL);
304 /* read Data.Delay, check for errors and fit it to data_delay */
305 status = nc_inq_varid(ncid, "Data.Delay", &data_delay_id);
306 status += nc_inq_vardimid(ncid, data_delay_id, &data_delay_dim_id[0]);
307 status += nc_inq_dimname(ncid, data_delay_dim_id[0], data_delay_dim_name);
308 if (status != NC_NOERR) {
309 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
310 ret = AVERROR(EINVAL);
314 /* Data.Delay dimension check */
315 /* dimension of Data.Delay is [I R]: */
316 if (!strncmp(data_delay_dim_name, "I", 2)) {
317 /* check 2 characters to assure string is 0-terminated after "I" */
318 int delay[2]; /* delays get from SOFA file: */
320 av_log(ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n");
321 status = nc_get_var_int(ncid, data_delay_id, &delay[0]);
322 if (status != NC_NOERR) {
323 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
324 ret = AVERROR(EINVAL);
327 int *data_delay_r = data_delay + m_dim;
328 for (i = 0; i < m_dim; i++) { /* extend given dimension [I R] to [M R] */
329 /* assign constant delay value for all measurements to data_delay fields */
330 data_delay[i] = delay[0];
331 data_delay_r[i] = delay[1];
333 /* dimension of Data.Delay is [M R] */
334 } else if (!strncmp(data_delay_dim_name, "M", 2)) {
335 av_log(ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
336 /* get delays from SOFA file: */
337 status = nc_get_var_int(ncid, data_delay_id, data_delay);
338 if (status != NC_NOERR) {
339 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
340 ret = AVERROR(EINVAL);
343 } else { /* dimension of Data.Delay is neither [I R] nor [M R] */
344 av_log(ctx, AV_LOG_ERROR, "Data.Delay does not have the required dimensions [I R] or [M R].\n");
345 ret = AVERROR(EINVAL);
349 /* save information in SOFA struct: */
350 s->sofa.m_dim = m_dim; /* no. measurement positions */
351 s->sofa.n_samples = n_samples; /* length on one IR */
352 s->sofa.ncid = ncid; /* netCDF ID of SOFA file */
353 nc_close(ncid); /* close SOFA file */
355 av_log(ctx, AV_LOG_DEBUG, "m_dim: %d n_samples %d\n", m_dim, n_samples);
360 close_sofa(&s->sofa);
364 static int get_speaker_pos(AVFilterContext *ctx,
365 float *speaker_azim, float *speaker_elev)
367 struct SOFAlizerContext *s = ctx->priv;
368 uint64_t channels_layout = ctx->inputs[0]->channel_layout;
369 float azim[16] = { 0 };
370 float elev[16] = { 0 };
371 int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
374 return AVERROR(EINVAL);
378 /* set speaker positions according to input channel configuration: */
379 for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
380 uint64_t mask = channels_layout & (1 << m);
383 case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
384 case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
385 case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
386 case AV_CH_LOW_FREQUENCY:
387 case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
388 case AV_CH_BACK_LEFT: azim[ch] = 150; break;
389 case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
390 case AV_CH_BACK_CENTER: azim[ch] = 180; break;
391 case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
392 case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
393 case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
394 case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
395 case AV_CH_TOP_CENTER: azim[ch] = 0;
396 elev[ch] = 90; break;
397 case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
398 elev[ch] = 45; break;
399 case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
400 elev[ch] = 45; break;
401 case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
402 elev[ch] = 45; break;
403 case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
404 elev[ch] = 45; break;
405 case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
406 elev[ch] = 45; break;
407 case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
408 elev[ch] = 45; break;
409 case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
410 case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
411 case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
412 case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
413 case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
414 case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
417 return AVERROR(EINVAL);
423 memcpy(speaker_azim, azim, n_conv * sizeof(float));
424 memcpy(speaker_elev, elev, n_conv * sizeof(float));
430 static int max_delay(struct NCSofa *sofa)
434 for (i = 0; i < sofa->m_dim * 2; i++) {
435 /* search maximum delay in given SOFA file */
436 max = FFMAX(max, sofa->data_delay[i]);
442 static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
444 /* get source positions and M of currently selected SOFA file */
445 float *sp_a = s->sofa.sp_a; /* azimuth angle */
446 float *sp_e = s->sofa.sp_e; /* elevation angle */
447 float *sp_r = s->sofa.sp_r; /* radius */
448 int m_dim = s->sofa.m_dim; /* no. measurements */
449 int best_id = 0; /* index m currently closest to desired source pos. */
450 float delta = 1000; /* offset between desired and currently best pos. */
454 for (i = 0; i < m_dim; i++) {
455 /* search through all measurements in currently selected SOFA file */
456 /* distance of current to desired source position: */
457 current = fabs(sp_a[i] - azim) +
458 fabs(sp_e[i] - elev) +
459 fabs(sp_r[i] - radius);
460 if (current <= delta) {
461 /* if current distance is smaller than smallest distance so far */
463 best_id = i; /* remember index */
470 static int compensate_volume(AVFilterContext *ctx)
472 struct SOFAlizerContext *s = ctx->priv;
479 /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
480 struct NCSofa *sofa = &s->sofa;
481 m = find_m(s, 0, 0, 1);
482 /* get energy of that IR and compensate volume */
483 ir = sofa->data_ir + 2 * m * sofa->n_samples;
484 if (sofa->n_samples & 31) {
485 energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
487 energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
489 compensate = 256 / (sofa->n_samples * sqrt(energy));
490 av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
492 /* apply volume compensation to IRs */
493 if (sofa->n_samples & 31) {
495 for (i = 0; i < sofa->n_samples * sofa->m_dim * 2; i++) {
496 ir[i] = ir[i] * compensate;
499 s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
507 typedef struct ThreadData {
515 FFTComplex **temp_fft;
518 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
520 SOFAlizerContext *s = ctx->priv;
521 ThreadData *td = arg;
522 AVFrame *in = td->in, *out = td->out;
524 int *write = &td->write[jobnr];
525 const int *const delay = td->delay[jobnr];
526 const float *const ir = td->ir[jobnr];
527 int *n_clippings = &td->n_clippings[jobnr];
528 float *ringbuffer = td->ringbuffer[jobnr];
529 float *temp_src = td->temp_src[jobnr];
530 const int n_samples = s->sofa.n_samples; /* length of one IR */
531 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
532 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
533 const int in_channels = s->n_conv; /* number of input channels */
534 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
535 const int buffer_length = s->buffer_length;
536 /* -1 for AND instead of MODULO (applied to powers of 2): */
537 const uint32_t modulo = (uint32_t)buffer_length - 1;
538 float *buffer[16]; /* holds ringbuffer for each input channel */
544 for (l = 0; l < in_channels; l++) {
545 /* get starting address of ringbuffer for each input channel */
546 buffer[l] = ringbuffer + l * buffer_length;
549 for (i = 0; i < in->nb_samples; i++) {
550 const float *temp_ir = ir; /* using same set of IRs for each sample */
553 for (l = 0; l < in_channels; l++) {
554 /* write current input sample to ringbuffer (for each channel) */
555 *(buffer[l] + wr) = src[l];
558 /* loop goes through all channels to be convolved */
559 for (l = 0; l < in_channels; l++) {
560 const float *const bptr = buffer[l];
562 if (l == s->lfe_channel) {
563 /* LFE is an input channel but requires no convolution */
564 /* apply gain to LFE signal and add to output buffer */
565 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
566 temp_ir += FFALIGN(n_samples, 16);
570 /* current read position in ringbuffer: input sample write position
571 * - delay for l-th ch. + diff. betw. IR length and buffer length
572 * (mod buffer length) */
573 read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
575 if (read + n_samples < buffer_length) {
576 memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
578 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
580 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
581 memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
584 /* multiply signal and IR, and add up the results */
585 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
586 temp_ir += FFALIGN(n_samples, 16);
589 /* clippings counter */
593 /* move output buffer pointer by +2 to get to next sample of processed channel: */
596 wr = (wr + 1) & modulo; /* update ringbuffer write position */
599 *write = wr; /* remember write position in ringbuffer for next call */
604 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
606 SOFAlizerContext *s = ctx->priv;
607 ThreadData *td = arg;
608 AVFrame *in = td->in, *out = td->out;
610 int *write = &td->write[jobnr];
611 FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
612 int *n_clippings = &td->n_clippings[jobnr];
613 float *ringbuffer = td->ringbuffer[jobnr];
614 const int n_samples = s->sofa.n_samples; /* length of one IR */
615 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
616 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
617 const int in_channels = s->n_conv; /* number of input channels */
618 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
619 const int buffer_length = s->buffer_length;
620 /* -1 for AND instead of MODULO (applied to powers of 2): */
621 const uint32_t modulo = (uint32_t)buffer_length - 1;
622 FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
623 FFTContext *ifft = s->ifft[jobnr];
624 FFTContext *fft = s->fft[jobnr];
625 const int n_conv = s->n_conv;
626 const int n_fft = s->n_fft;
633 /* find minimum between number of samples and output buffer length:
634 * (important, if one IR is longer than the output buffer) */
635 n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
636 for (j = 0; j < n_read; j++) {
637 /* initialize output buf with saved signal from overflow buf */
638 dst[2 * j] = ringbuffer[wr];
639 ringbuffer[wr] = 0.0; /* re-set read samples to zero */
640 /* update ringbuffer read/write position */
641 wr = (wr + 1) & modulo;
644 /* initialize rest of output buffer with 0 */
645 for (j = n_read; j < in->nb_samples; j++) {
649 for (i = 0; i < n_conv; i++) {
650 if (i == s->lfe_channel) { /* LFE */
651 for (j = 0; j < in->nb_samples; j++) {
652 /* apply gain to LFE signal and add to output buffer */
653 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
658 /* outer loop: go through all input channels to be convolved */
659 offset = i * n_fft; /* no. samples already processed */
661 /* fill FFT input with 0 (we want to zero-pad) */
662 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
664 for (j = 0; j < in->nb_samples; j++) {
665 /* prepare input for FFT */
666 /* write all samples of current input channel to FFT input array */
667 fft_in[j].re = src[j * in_channels + i];
670 /* transform input signal of current channel to frequency domain */
671 av_fft_permute(fft, fft_in);
672 av_fft_calc(fft, fft_in);
673 for (j = 0; j < n_fft; j++) {
674 const float re = fft_in[j].re;
675 const float im = fft_in[j].im;
677 /* complex multiplication of input signal and HRTFs */
678 /* output channel (real): */
679 fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
680 /* output channel (imag): */
681 fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
684 /* transform output signal of current channel back to time domain */
685 av_fft_permute(ifft, fft_in);
686 av_fft_calc(ifft, fft_in);
688 for (j = 0; j < in->nb_samples; j++) {
689 /* write output signal of current channel to output buffer */
690 dst[2 * j] += fft_in[j].re / (float)n_fft;
693 for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
694 /* write the rest of output signal to overflow buffer */
695 int write_pos = (wr + j) & modulo;
697 *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
701 /* go through all samples of current output buffer: count clippings */
702 for (i = 0; i < out->nb_samples; i++) {
703 /* clippings counter */
704 if (fabs(*dst) > 1) { /* if current output sample > 1 */
705 *n_clippings = *n_clippings + 1;
708 /* move output buffer pointer by +2 to get to next sample of processed channel: */
712 /* remember read/write position in ringbuffer for next call */
718 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
720 AVFilterContext *ctx = inlink->dst;
721 SOFAlizerContext *s = ctx->priv;
722 AVFilterLink *outlink = ctx->outputs[0];
723 int n_clippings[2] = { 0 };
727 out = ff_get_audio_buffer(outlink, in->nb_samples);
730 return AVERROR(ENOMEM);
732 av_frame_copy_props(out, in);
734 td.in = in; td.out = out; td.write = s->write;
735 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
736 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
737 td.temp_fft = s->temp_fft;
739 if (s->type == TIME_DOMAIN) {
740 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
742 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
746 /* display error message if clipping occurred */
747 if (n_clippings[0] + n_clippings[1] > 0) {
748 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
749 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
753 return ff_filter_frame(outlink, out);
756 static int query_formats(AVFilterContext *ctx)
758 struct SOFAlizerContext *s = ctx->priv;
759 AVFilterFormats *formats = NULL;
760 AVFilterChannelLayouts *layouts = NULL;
761 int ret, sample_rates[] = { 48000, -1 };
763 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
766 ret = ff_set_common_formats(ctx, formats);
770 layouts = ff_all_channel_layouts();
772 return AVERROR(ENOMEM);
774 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
779 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
783 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
787 sample_rates[0] = s->sample_rate;
788 formats = ff_make_format_list(sample_rates);
790 return AVERROR(ENOMEM);
791 return ff_set_common_samplerates(ctx, formats);
794 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
796 struct SOFAlizerContext *s = ctx->priv;
797 const int n_samples = s->sofa.n_samples;
798 int n_conv = s->n_conv; /* no. channels to convolve */
799 int n_fft = s->n_fft;
800 int delay_l[16]; /* broadband delay for each IR */
802 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
803 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
804 FFTComplex *data_hrtf_l = NULL;
805 FFTComplex *data_hrtf_r = NULL;
806 FFTComplex *fft_in_l = NULL;
807 FFTComplex *fft_in_r = NULL;
808 float *data_ir_l = NULL;
809 float *data_ir_r = NULL;
810 int offset = 0; /* used for faster pointer arithmetics in for-loop */
811 int m[16]; /* measurement index m of IR closest to required source positions */
812 int i, j, azim_orig = azim, elev_orig = elev;
814 if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
815 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
816 return AVERROR_INVALIDDATA;
819 if (s->type == TIME_DOMAIN) {
820 s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
821 s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
823 /* get temporary IR for L and R channel */
824 data_ir_l = av_calloc(n_conv * FFALIGN(n_samples, 16), sizeof(*data_ir_l));
825 data_ir_r = av_calloc(n_conv * FFALIGN(n_samples, 16), sizeof(*data_ir_r));
826 if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
829 return AVERROR(ENOMEM);
832 /* get temporary HRTF memory for L and R channel */
833 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
834 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
835 if (!data_hrtf_r || !data_hrtf_l) {
836 av_free(data_hrtf_l);
837 av_free(data_hrtf_r);
838 return AVERROR(ENOMEM);
842 for (i = 0; i < s->n_conv; i++) {
843 /* load and store IRs and corresponding delays */
844 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
845 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
846 /* get id of IR closest to desired position */
847 m[i] = find_m(s, azim, elev, radius);
849 /* load the delays associated with the current IRs */
850 delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
851 delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
853 if (s->type == TIME_DOMAIN) {
854 offset = i * FFALIGN(n_samples, 16); /* no. samples already written */
855 for (j = 0; j < n_samples; j++) {
856 /* load reversed IRs of the specified source position
857 * sample-by-sample for left and right ear; and apply gain */
858 *(data_ir_l + offset + j) = /* left channel */
859 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
860 *(data_ir_r + offset + j) = /* right channel */
861 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
864 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
865 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
866 if (!fft_in_l || !fft_in_r) {
867 av_free(data_hrtf_l);
868 av_free(data_hrtf_r);
871 return AVERROR(ENOMEM);
874 offset = i * n_fft; /* no. samples already written */
875 for (j = 0; j < n_samples; j++) {
876 /* load non-reversed IRs of the specified source position
877 * sample-by-sample and apply gain,
878 * L channel is loaded to real part, R channel to imag part,
879 * IRs ared shifted by L and R delay */
880 fft_in_l[delay_l[i] + j].re = /* left channel */
881 *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
882 fft_in_r[delay_r[i] + j].re = /* right channel */
883 *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
886 /* actually transform to frequency domain (IRs -> HRTFs) */
887 av_fft_permute(s->fft[0], fft_in_l);
888 av_fft_calc(s->fft[0], fft_in_l);
889 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
890 av_fft_permute(s->fft[0], fft_in_r);
891 av_fft_calc(s->fft[0], fft_in_r);
892 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
895 av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
896 m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
899 if (s->type == TIME_DOMAIN) {
900 /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
901 memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * FFALIGN(n_samples, 16));
902 memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * FFALIGN(n_samples, 16));
904 av_freep(&data_ir_l); /* free temporary IR memory */
905 av_freep(&data_ir_r);
907 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
908 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
909 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
910 av_freep(&data_hrtf_l);
911 av_freep(&data_hrtf_r);
914 return AVERROR(ENOMEM); /* memory allocation failed */
917 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
918 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
919 memcpy(s->data_hrtf[1], data_hrtf_r,
920 sizeof(FFTComplex) * n_conv * n_fft);
922 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
923 av_freep(&data_hrtf_r);
925 av_freep(&fft_in_l); /* free temporary FFT memory */
929 memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
930 memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
935 static av_cold int init(AVFilterContext *ctx)
937 SOFAlizerContext *s = ctx->priv;
940 /* load SOFA file, */
941 /* initialize file IDs to 0 before attempting to load SOFA files,
942 * this assures that in case of error, only the memory of already
943 * loaded files is free'd */
945 ret = load_sofa(ctx, s->filename, &s->sample_rate);
947 /* file loading error */
948 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
949 } else { /* no file loading error, resampling not required */
950 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
954 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
958 s->fdsp = avpriv_float_dsp_alloc(0);
960 return AVERROR(ENOMEM);
965 static int config_input(AVFilterLink *inlink)
967 AVFilterContext *ctx = inlink->dst;
968 SOFAlizerContext *s = ctx->priv;
969 int nb_input_channels = inlink->channels; /* no. input channels */
975 if (s->type == FREQUENCY_DOMAIN) {
976 inlink->partial_buf_size =
977 inlink->min_samples =
978 inlink->max_samples = inlink->sample_rate;
981 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
982 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
984 s->n_conv = nb_input_channels;
986 /* get size of ringbuffer (longest IR plus max. delay) */
987 /* then choose next power of 2 for performance optimization */
988 n_current = s->sofa.n_samples + max_delay(&s->sofa);
989 if (n_current > n_max) {
990 /* length of longest IR plus max. delay (in all SOFA files) */
992 /* length of longest IR (without delay, in all SOFA files) */
993 n_max_ir = s->sofa.n_samples;
995 /* buffer length is longest IR plus max. delay -> next power of 2
996 (32 - count leading zeros gives required exponent) */
997 s->buffer_length = 1 << (32 - ff_clz(n_max));
998 s->n_fft = 1 << (32 - ff_clz(n_max + inlink->sample_rate));
1000 if (s->type == FREQUENCY_DOMAIN) {
1001 av_fft_end(s->fft[0]);
1002 av_fft_end(s->fft[1]);
1003 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
1004 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
1005 av_fft_end(s->ifft[0]);
1006 av_fft_end(s->ifft[1]);
1007 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
1008 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
1010 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
1011 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
1012 return AVERROR(ENOMEM);
1016 /* Allocate memory for the impulse responses, delays and the ringbuffers */
1017 /* size: (longest IR) * (number of channels to convolute) */
1018 s->data_ir[0] = av_calloc(FFALIGN(n_max_ir, 16), sizeof(float) * s->n_conv);
1019 s->data_ir[1] = av_calloc(FFALIGN(n_max_ir, 16), sizeof(float) * s->n_conv);
1020 /* length: number of channels to convolute */
1021 s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
1022 s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
1023 /* length: (buffer length) * (number of input channels),
1024 * OR: buffer length (if frequency domain processing)
1025 * calloc zero-initializes the buffer */
1027 if (s->type == TIME_DOMAIN) {
1028 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1029 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1031 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
1032 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
1033 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1034 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1035 if (!s->temp_fft[0] || !s->temp_fft[1])
1036 return AVERROR(ENOMEM);
1039 /* length: number of channels to convolute */
1040 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
1041 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
1043 /* memory allocation failed: */
1044 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
1045 !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
1046 !s->speaker_azim || !s->speaker_elev)
1047 return AVERROR(ENOMEM);
1049 compensate_volume(ctx);
1051 /* get speaker positions */
1052 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
1053 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
1057 /* load IRs to data_ir[0] and data_ir[1] for required directions */
1058 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
1061 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
1062 inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
1067 static av_cold void uninit(AVFilterContext *ctx)
1069 SOFAlizerContext *s = ctx->priv;
1072 av_freep(&s->sofa.sp_a);
1073 av_freep(&s->sofa.sp_e);
1074 av_freep(&s->sofa.sp_r);
1075 av_freep(&s->sofa.data_delay);
1076 av_freep(&s->sofa.data_ir);
1078 av_fft_end(s->ifft[0]);
1079 av_fft_end(s->ifft[1]);
1080 av_fft_end(s->fft[0]);
1081 av_fft_end(s->fft[1]);
1082 av_freep(&s->delay[0]);
1083 av_freep(&s->delay[1]);
1084 av_freep(&s->data_ir[0]);
1085 av_freep(&s->data_ir[1]);
1086 av_freep(&s->ringbuffer[0]);
1087 av_freep(&s->ringbuffer[1]);
1088 av_freep(&s->speaker_azim);
1089 av_freep(&s->speaker_elev);
1090 av_freep(&s->temp_src[0]);
1091 av_freep(&s->temp_src[1]);
1092 av_freep(&s->temp_fft[0]);
1093 av_freep(&s->temp_fft[1]);
1094 av_freep(&s->data_hrtf[0]);
1095 av_freep(&s->data_hrtf[1]);
1099 #define OFFSET(x) offsetof(SOFAlizerContext, x)
1100 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1102 static const AVOption sofalizer_options[] = {
1103 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1104 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
1105 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
1106 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
1107 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
1108 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
1109 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
1110 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
1114 AVFILTER_DEFINE_CLASS(sofalizer);
1116 static const AVFilterPad inputs[] = {
1119 .type = AVMEDIA_TYPE_AUDIO,
1120 .config_props = config_input,
1121 .filter_frame = filter_frame,
1126 static const AVFilterPad outputs[] = {
1129 .type = AVMEDIA_TYPE_AUDIO,
1134 AVFilter ff_af_sofalizer = {
1135 .name = "sofalizer",
1136 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1137 .priv_size = sizeof(SOFAlizerContext),
1138 .priv_class = &sofalizer_class,
1141 .query_formats = query_formats,
1144 .flags = AVFILTER_FLAG_SLICE_THREADS,