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/avstring.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/float_dsp.h"
35 #include "libavutil/intmath.h"
36 #include "libavutil/opt.h"
42 #define FREQUENCY_DOMAIN 1
44 typedef struct NCSofa { /* contains data of one SOFA file */
45 int ncid; /* netCDF ID of the opened SOFA file */
46 int n_samples; /* length of one impulse response (IR) */
47 int m_dim; /* number of measurement positions */
48 int *data_delay; /* broadband delay of each IR */
49 /* all measurement positions for each receiver (i.e. ear): */
50 float *sp_a; /* azimuth angles */
51 float *sp_e; /* elevation angles */
52 float *sp_r; /* radii */
53 /* data at each measurement position for each receiver: */
54 float *data_ir; /* IRs (time-domain) */
57 typedef struct VirtualSpeaker {
63 typedef struct SOFAlizerContext {
66 char *filename; /* name of SOFA file */
67 NCSofa sofa; /* contains data of the SOFA file */
69 int sample_rate; /* sample rate from SOFA file */
70 float *speaker_azim; /* azimuth of the virtual loudspeakers */
71 float *speaker_elev; /* elevation of the virtual loudspeakers */
72 char *speakers_pos; /* custom positions of the virtual loudspeakers */
73 float lfe_gain; /* initial gain for the LFE channel */
74 float gain_lfe; /* gain applied to LFE channel */
75 int lfe_channel; /* LFE channel position in channel layout */
77 int n_conv; /* number of channels to convolute */
79 /* buffer variables (for convolution) */
80 float *ringbuffer[2]; /* buffers input samples, length of one buffer: */
81 /* no. input ch. (incl. LFE) x buffer_length */
82 int write[2]; /* current write position to ringbuffer */
83 int buffer_length; /* is: longest IR plus max. delay in all SOFA files */
84 /* then choose next power of 2 */
85 int n_fft; /* number of samples in one FFT block */
87 /* netCDF variables */
88 int *delay[2]; /* broadband delay for each channel/IR to be convolved */
90 float *data_ir[2]; /* IRs for all channels to be convolved */
91 /* (this excludes the LFE) */
93 FFTComplex *temp_fft[2];
95 /* control variables */
96 float gain; /* filter gain (in dB) */
97 float rotation; /* rotation of virtual loudspeakers (in degrees) */
98 float elevation; /* elevation of virtual loudspeakers (in deg.) */
99 float radius; /* distance virtual loudspeakers to listener (in metres) */
100 int type; /* processing type */
102 VirtualSpeaker vspkrpos[64];
104 FFTContext *fft[2], *ifft[2];
105 FFTComplex *data_hrtf[2];
107 AVFloatDSPContext *fdsp;
110 static int close_sofa(struct NCSofa *sofa)
112 av_freep(&sofa->data_delay);
113 av_freep(&sofa->sp_a);
114 av_freep(&sofa->sp_e);
115 av_freep(&sofa->sp_r);
116 av_freep(&sofa->data_ir);
117 nc_close(sofa->ncid);
123 static int load_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
125 struct SOFAlizerContext *s = ctx->priv;
126 /* variables associated with content of SOFA file: */
127 int ncid, n_dims, n_vars, n_gatts, n_unlim_dim_id, status;
128 char data_delay_dim_name[NC_MAX_NAME];
129 float *sp_a, *sp_e, *sp_r, *data_ir;
130 char *sofa_conventions;
131 char dim_name[NC_MAX_NAME]; /* names of netCDF dimensions */
132 size_t *dim_length; /* lengths of netCDF dimensions */
134 unsigned int sample_rate;
135 int data_delay_dim_id[2];
149 status = nc_open(filename, NC_NOWRITE, &ncid); /* open SOFA file read-only */
150 if (status != NC_NOERR) {
151 av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
152 return AVERROR(EINVAL);
155 /* get number of dimensions, vars, global attributes and Id of unlimited dimensions: */
156 nc_inq(ncid, &n_dims, &n_vars, &n_gatts, &n_unlim_dim_id);
158 /* -- get number of measurements ("M") and length of one IR ("N") -- */
159 dim_length = av_malloc_array(n_dims, sizeof(*dim_length));
162 return AVERROR(ENOMEM);
165 for (i = 0; i < n_dims; i++) { /* go through all dimensions of file */
166 nc_inq_dim(ncid, i, (char *)&dim_name, &dim_length[i]); /* get dimensions */
167 if (!strncmp("M", (const char *)&dim_name, 1)) /* get ID of dimension "M" */
169 if (!strncmp("N", (const char *)&dim_name, 1)) /* get ID of dimension "N" */
173 if ((m_dim_id == -1) || (n_dim_id == -1)) { /* dimension "M" or "N" couldn't be found */
174 av_log(ctx, AV_LOG_ERROR, "Can't find required dimensions in SOFA file.\n");
175 av_freep(&dim_length);
177 return AVERROR(EINVAL);
180 n_samples = dim_length[n_dim_id]; /* get length of one IR */
181 m_dim = dim_length[m_dim_id]; /* get number of measurements */
183 av_freep(&dim_length);
185 /* -- check file type -- */
186 /* get length of attritube "Conventions" */
187 status = nc_inq_attlen(ncid, NC_GLOBAL, "Conventions", &att_len);
188 if (status != NC_NOERR) {
189 av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"Conventions\".\n");
191 return AVERROR_INVALIDDATA;
194 /* check whether file is SOFA file */
195 text = av_malloc(att_len + 1);
198 return AVERROR(ENOMEM);
201 nc_get_att_text(ncid, NC_GLOBAL, "Conventions", text);
202 *(text + att_len) = 0;
203 if (strncmp("SOFA", text, 4)) {
204 av_log(ctx, AV_LOG_ERROR, "Not a SOFA file!\n");
207 return AVERROR(EINVAL);
211 status = nc_inq_attlen(ncid, NC_GLOBAL, "License", &att_len);
212 if (status == NC_NOERR) {
213 text = av_malloc(att_len + 1);
215 nc_get_att_text(ncid, NC_GLOBAL, "License", text);
216 *(text + att_len) = 0;
217 av_log(ctx, AV_LOG_INFO, "SOFA file License: %s\n", text);
222 status = nc_inq_attlen(ncid, NC_GLOBAL, "SourceDescription", &att_len);
223 if (status == NC_NOERR) {
224 text = av_malloc(att_len + 1);
226 nc_get_att_text(ncid, NC_GLOBAL, "SourceDescription", text);
227 *(text + att_len) = 0;
228 av_log(ctx, AV_LOG_INFO, "SOFA file SourceDescription: %s\n", text);
233 status = nc_inq_attlen(ncid, NC_GLOBAL, "Comment", &att_len);
234 if (status == NC_NOERR) {
235 text = av_malloc(att_len + 1);
237 nc_get_att_text(ncid, NC_GLOBAL, "Comment", text);
238 *(text + att_len) = 0;
239 av_log(ctx, AV_LOG_INFO, "SOFA file Comment: %s\n", text);
244 status = nc_inq_attlen(ncid, NC_GLOBAL, "SOFAConventions", &att_len);
245 if (status != NC_NOERR) {
246 av_log(ctx, AV_LOG_ERROR, "Can't get length of attribute \"SOFAConventions\".\n");
248 return AVERROR_INVALIDDATA;
251 sofa_conventions = av_malloc(att_len + 1);
252 if (!sofa_conventions) {
254 return AVERROR(ENOMEM);
257 nc_get_att_text(ncid, NC_GLOBAL, "SOFAConventions", sofa_conventions);
258 *(sofa_conventions + att_len) = 0;
259 if (strncmp("SimpleFreeFieldHRIR", sofa_conventions, att_len)) {
260 av_log(ctx, AV_LOG_ERROR, "Not a SimpleFreeFieldHRIR file!\n");
261 av_freep(&sofa_conventions);
263 return AVERROR(EINVAL);
265 av_freep(&sofa_conventions);
267 /* -- get sampling rate of HRTFs -- */
268 /* read ID, then value */
269 status = nc_inq_varid(ncid, "Data.SamplingRate", &samplingrate_id);
270 status += nc_get_var_uint(ncid, samplingrate_id, &sample_rate);
271 if (status != NC_NOERR) {
272 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.SamplingRate.\n");
274 return AVERROR(EINVAL);
276 *samplingrate = sample_rate; /* remember sampling rate */
278 /* -- allocate memory for one value for each measurement position: -- */
279 sp_a = s->sofa.sp_a = av_malloc_array(m_dim, sizeof(float));
280 sp_e = s->sofa.sp_e = av_malloc_array(m_dim, sizeof(float));
281 sp_r = s->sofa.sp_r = av_malloc_array(m_dim, sizeof(float));
282 /* delay and IR values required for each ear and measurement position: */
283 data_delay = s->sofa.data_delay = av_calloc(m_dim, 2 * sizeof(int));
284 data_ir = s->sofa.data_ir = av_calloc(m_dim * FFALIGN(n_samples, 16), sizeof(float) * 2);
286 if (!data_delay || !sp_a || !sp_e || !sp_r || !data_ir) {
287 /* if memory could not be allocated */
288 close_sofa(&s->sofa);
289 return AVERROR(ENOMEM);
292 /* get impulse responses (HRTFs): */
293 /* get corresponding ID */
294 status = nc_inq_varid(ncid, "Data.IR", &data_ir_id);
295 status += nc_get_var_float(ncid, data_ir_id, data_ir); /* read and store IRs */
296 if (status != NC_NOERR) {
297 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.IR!\n");
298 ret = AVERROR(EINVAL);
302 /* get source positions of the HRTFs in the SOFA file: */
303 status = nc_inq_varid(ncid, "SourcePosition", &sp_id); /* get corresponding ID */
304 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 0 } ,
305 (size_t[2]){ m_dim, 1}, sp_a); /* read & store azimuth angles */
306 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 1 } ,
307 (size_t[2]){ m_dim, 1}, sp_e); /* read & store elevation angles */
308 status += nc_get_vara_float(ncid, sp_id, (size_t[2]){ 0, 2 } ,
309 (size_t[2]){ m_dim, 1}, sp_r); /* read & store radii */
310 if (status != NC_NOERR) { /* if any source position variable coudn't be read */
311 av_log(ctx, AV_LOG_ERROR, "Couldn't read SourcePosition.\n");
312 ret = AVERROR(EINVAL);
316 /* read Data.Delay, check for errors and fit it to data_delay */
317 status = nc_inq_varid(ncid, "Data.Delay", &data_delay_id);
318 status += nc_inq_vardimid(ncid, data_delay_id, &data_delay_dim_id[0]);
319 status += nc_inq_dimname(ncid, data_delay_dim_id[0], data_delay_dim_name);
320 if (status != NC_NOERR) {
321 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay.\n");
322 ret = AVERROR(EINVAL);
326 /* Data.Delay dimension check */
327 /* dimension of Data.Delay is [I R]: */
328 if (!strncmp(data_delay_dim_name, "I", 2)) {
329 /* check 2 characters to assure string is 0-terminated after "I" */
330 int delay[2]; /* delays get from SOFA file: */
333 av_log(ctx, AV_LOG_DEBUG, "Data.Delay has dimension [I R]\n");
334 status = nc_get_var_int(ncid, data_delay_id, &delay[0]);
335 if (status != NC_NOERR) {
336 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
337 ret = AVERROR(EINVAL);
340 data_delay_r = data_delay + m_dim;
341 for (i = 0; i < m_dim; i++) { /* extend given dimension [I R] to [M R] */
342 /* assign constant delay value for all measurements to data_delay fields */
343 data_delay[i] = delay[0];
344 data_delay_r[i] = delay[1];
346 /* dimension of Data.Delay is [M R] */
347 } else if (!strncmp(data_delay_dim_name, "M", 2)) {
348 av_log(ctx, AV_LOG_ERROR, "Data.Delay in dimension [M R]\n");
349 /* get delays from SOFA file: */
350 status = nc_get_var_int(ncid, data_delay_id, data_delay);
351 if (status != NC_NOERR) {
352 av_log(ctx, AV_LOG_ERROR, "Couldn't read Data.Delay\n");
353 ret = AVERROR(EINVAL);
356 } else { /* dimension of Data.Delay is neither [I R] nor [M R] */
357 av_log(ctx, AV_LOG_ERROR, "Data.Delay does not have the required dimensions [I R] or [M R].\n");
358 ret = AVERROR(EINVAL);
362 /* save information in SOFA struct: */
363 s->sofa.m_dim = m_dim; /* no. measurement positions */
364 s->sofa.n_samples = n_samples; /* length on one IR */
365 s->sofa.ncid = ncid; /* netCDF ID of SOFA file */
366 nc_close(ncid); /* close SOFA file */
368 av_log(ctx, AV_LOG_DEBUG, "m_dim: %d n_samples %d\n", m_dim, n_samples);
373 close_sofa(&s->sofa);
377 static int parse_channel_name(char **arg, int *rchannel, char *buf)
379 int len, i, channel_id = 0;
380 int64_t layout, layout0;
382 /* try to parse a channel name, e.g. "FL" */
383 if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
384 layout0 = layout = av_get_channel_layout(buf);
385 /* channel_id <- first set bit in layout */
386 for (i = 32; i > 0; i >>= 1) {
387 if (layout >= 1LL << i) {
392 /* reject layouts that are not a single channel */
393 if (channel_id >= 64 || layout0 != 1LL << channel_id)
394 return AVERROR(EINVAL);
395 *rchannel = channel_id;
399 return AVERROR(EINVAL);
402 static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
404 SOFAlizerContext *s = ctx->priv;
405 char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
411 while ((arg = av_strtok(p, "|", &tokenizer))) {
417 if (parse_channel_name(&arg, &out_ch_id, buf)) {
418 av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
421 if (sscanf(arg, "%f %f", &azim, &elev) == 2) {
422 s->vspkrpos[out_ch_id].set = 1;
423 s->vspkrpos[out_ch_id].azim = azim;
424 s->vspkrpos[out_ch_id].elev = elev;
425 } else if (sscanf(arg, "%f", &azim) == 1) {
426 s->vspkrpos[out_ch_id].set = 1;
427 s->vspkrpos[out_ch_id].azim = azim;
428 s->vspkrpos[out_ch_id].elev = 0;
435 static int get_speaker_pos(AVFilterContext *ctx,
436 float *speaker_azim, float *speaker_elev)
438 struct SOFAlizerContext *s = ctx->priv;
439 uint64_t channels_layout = ctx->inputs[0]->channel_layout;
440 float azim[16] = { 0 };
441 float elev[16] = { 0 };
442 int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
445 return AVERROR(EINVAL);
450 parse_speaker_pos(ctx, channels_layout);
452 /* set speaker positions according to input channel configuration: */
453 for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
454 uint64_t mask = channels_layout & (1ULL << m);
457 case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
458 case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
459 case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
460 case AV_CH_LOW_FREQUENCY:
461 case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
462 case AV_CH_BACK_LEFT: azim[ch] = 150; break;
463 case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
464 case AV_CH_BACK_CENTER: azim[ch] = 180; break;
465 case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
466 case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
467 case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
468 case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
469 case AV_CH_TOP_CENTER: azim[ch] = 0;
470 elev[ch] = 90; break;
471 case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
472 elev[ch] = 45; break;
473 case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
474 elev[ch] = 45; break;
475 case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
476 elev[ch] = 45; break;
477 case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
478 elev[ch] = 45; break;
479 case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
480 elev[ch] = 45; break;
481 case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
482 elev[ch] = 45; break;
483 case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
484 case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
485 case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
486 case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
487 case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
488 case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
491 return AVERROR(EINVAL);
494 if (s->vspkrpos[m].set) {
495 azim[ch] = s->vspkrpos[m].azim;
496 elev[ch] = s->vspkrpos[m].elev;
503 memcpy(speaker_azim, azim, n_conv * sizeof(float));
504 memcpy(speaker_elev, elev, n_conv * sizeof(float));
510 static int max_delay(struct NCSofa *sofa)
514 for (i = 0; i < sofa->m_dim * 2; i++) {
515 /* search maximum delay in given SOFA file */
516 max = FFMAX(max, sofa->data_delay[i]);
522 static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
524 /* get source positions and M of currently selected SOFA file */
525 float *sp_a = s->sofa.sp_a; /* azimuth angle */
526 float *sp_e = s->sofa.sp_e; /* elevation angle */
527 float *sp_r = s->sofa.sp_r; /* radius */
528 int m_dim = s->sofa.m_dim; /* no. measurements */
529 int best_id = 0; /* index m currently closest to desired source pos. */
530 float delta = 1000; /* offset between desired and currently best pos. */
534 for (i = 0; i < m_dim; i++) {
535 /* search through all measurements in currently selected SOFA file */
536 /* distance of current to desired source position: */
537 current = fabs(sp_a[i] - azim) +
538 fabs(sp_e[i] - elev) +
539 fabs(sp_r[i] - radius);
540 if (current <= delta) {
541 /* if current distance is smaller than smallest distance so far */
543 best_id = i; /* remember index */
550 static int compensate_volume(AVFilterContext *ctx)
552 struct SOFAlizerContext *s = ctx->priv;
559 /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
560 struct NCSofa *sofa = &s->sofa;
561 m = find_m(s, 0, 0, 1);
562 /* get energy of that IR and compensate volume */
563 ir = sofa->data_ir + 2 * m * sofa->n_samples;
564 if (sofa->n_samples & 31) {
565 energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
567 energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
569 compensate = 256 / (sofa->n_samples * sqrt(energy));
570 av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
572 /* apply volume compensation to IRs */
573 if (sofa->n_samples & 31) {
575 for (i = 0; i < sofa->n_samples * sofa->m_dim * 2; i++) {
576 ir[i] = ir[i] * compensate;
579 s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
587 typedef struct ThreadData {
595 FFTComplex **temp_fft;
598 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
600 SOFAlizerContext *s = ctx->priv;
601 ThreadData *td = arg;
602 AVFrame *in = td->in, *out = td->out;
604 int *write = &td->write[jobnr];
605 const int *const delay = td->delay[jobnr];
606 const float *const ir = td->ir[jobnr];
607 int *n_clippings = &td->n_clippings[jobnr];
608 float *ringbuffer = td->ringbuffer[jobnr];
609 float *temp_src = td->temp_src[jobnr];
610 const int n_samples = s->sofa.n_samples; /* length of one IR */
611 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
612 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
613 const int in_channels = s->n_conv; /* number of input channels */
614 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
615 const int buffer_length = s->buffer_length;
616 /* -1 for AND instead of MODULO (applied to powers of 2): */
617 const uint32_t modulo = (uint32_t)buffer_length - 1;
618 float *buffer[16]; /* holds ringbuffer for each input channel */
624 for (l = 0; l < in_channels; l++) {
625 /* get starting address of ringbuffer for each input channel */
626 buffer[l] = ringbuffer + l * buffer_length;
629 for (i = 0; i < in->nb_samples; i++) {
630 const float *temp_ir = ir; /* using same set of IRs for each sample */
633 for (l = 0; l < in_channels; l++) {
634 /* write current input sample to ringbuffer (for each channel) */
635 *(buffer[l] + wr) = src[l];
638 /* loop goes through all channels to be convolved */
639 for (l = 0; l < in_channels; l++) {
640 const float *const bptr = buffer[l];
642 if (l == s->lfe_channel) {
643 /* LFE is an input channel but requires no convolution */
644 /* apply gain to LFE signal and add to output buffer */
645 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
646 temp_ir += FFALIGN(n_samples, 16);
650 /* current read position in ringbuffer: input sample write position
651 * - delay for l-th ch. + diff. betw. IR length and buffer length
652 * (mod buffer length) */
653 read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
655 if (read + n_samples < buffer_length) {
656 memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
658 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
660 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
661 memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
664 /* multiply signal and IR, and add up the results */
665 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
666 temp_ir += FFALIGN(n_samples, 16);
669 /* clippings counter */
673 /* move output buffer pointer by +2 to get to next sample of processed channel: */
676 wr = (wr + 1) & modulo; /* update ringbuffer write position */
679 *write = wr; /* remember write position in ringbuffer for next call */
684 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
686 SOFAlizerContext *s = ctx->priv;
687 ThreadData *td = arg;
688 AVFrame *in = td->in, *out = td->out;
690 int *write = &td->write[jobnr];
691 FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
692 int *n_clippings = &td->n_clippings[jobnr];
693 float *ringbuffer = td->ringbuffer[jobnr];
694 const int n_samples = s->sofa.n_samples; /* length of one IR */
695 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
696 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
697 const int in_channels = s->n_conv; /* number of input channels */
698 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
699 const int buffer_length = s->buffer_length;
700 /* -1 for AND instead of MODULO (applied to powers of 2): */
701 const uint32_t modulo = (uint32_t)buffer_length - 1;
702 FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
703 FFTContext *ifft = s->ifft[jobnr];
704 FFTContext *fft = s->fft[jobnr];
705 const int n_conv = s->n_conv;
706 const int n_fft = s->n_fft;
707 const float fft_scale = 1.0f / s->n_fft;
708 FFTComplex *hrtf_offset;
715 /* find minimum between number of samples and output buffer length:
716 * (important, if one IR is longer than the output buffer) */
717 n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
718 for (j = 0; j < n_read; j++) {
719 /* initialize output buf with saved signal from overflow buf */
720 dst[2 * j] = ringbuffer[wr];
721 ringbuffer[wr] = 0.0; /* re-set read samples to zero */
722 /* update ringbuffer read/write position */
723 wr = (wr + 1) & modulo;
726 /* initialize rest of output buffer with 0 */
727 for (j = n_read; j < in->nb_samples; j++) {
731 for (i = 0; i < n_conv; i++) {
732 if (i == s->lfe_channel) { /* LFE */
733 for (j = 0; j < in->nb_samples; j++) {
734 /* apply gain to LFE signal and add to output buffer */
735 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
740 /* outer loop: go through all input channels to be convolved */
741 offset = i * n_fft; /* no. samples already processed */
742 hrtf_offset = hrtf + offset;
744 /* fill FFT input with 0 (we want to zero-pad) */
745 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
747 for (j = 0; j < in->nb_samples; j++) {
748 /* prepare input for FFT */
749 /* write all samples of current input channel to FFT input array */
750 fft_in[j].re = src[j * in_channels + i];
753 /* transform input signal of current channel to frequency domain */
754 av_fft_permute(fft, fft_in);
755 av_fft_calc(fft, fft_in);
756 for (j = 0; j < n_fft; j++) {
757 const FFTComplex *hcomplex = hrtf_offset + j;
758 const float re = fft_in[j].re;
759 const float im = fft_in[j].im;
761 /* complex multiplication of input signal and HRTFs */
762 /* output channel (real): */
763 fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
764 /* output channel (imag): */
765 fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
768 /* transform output signal of current channel back to time domain */
769 av_fft_permute(ifft, fft_in);
770 av_fft_calc(ifft, fft_in);
772 for (j = 0; j < in->nb_samples; j++) {
773 /* write output signal of current channel to output buffer */
774 dst[2 * j] += fft_in[j].re * fft_scale;
777 for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
778 /* write the rest of output signal to overflow buffer */
779 int write_pos = (wr + j) & modulo;
781 *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
785 /* go through all samples of current output buffer: count clippings */
786 for (i = 0; i < out->nb_samples; i++) {
787 /* clippings counter */
788 if (fabs(*dst) > 1) { /* if current output sample > 1 */
792 /* move output buffer pointer by +2 to get to next sample of processed channel: */
796 /* remember read/write position in ringbuffer for next call */
802 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
804 AVFilterContext *ctx = inlink->dst;
805 SOFAlizerContext *s = ctx->priv;
806 AVFilterLink *outlink = ctx->outputs[0];
807 int n_clippings[2] = { 0 };
811 out = ff_get_audio_buffer(outlink, in->nb_samples);
814 return AVERROR(ENOMEM);
816 av_frame_copy_props(out, in);
818 td.in = in; td.out = out; td.write = s->write;
819 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
820 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
821 td.temp_fft = s->temp_fft;
823 if (s->type == TIME_DOMAIN) {
824 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
826 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
830 /* display error message if clipping occurred */
831 if (n_clippings[0] + n_clippings[1] > 0) {
832 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
833 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
837 return ff_filter_frame(outlink, out);
840 static int query_formats(AVFilterContext *ctx)
842 struct SOFAlizerContext *s = ctx->priv;
843 AVFilterFormats *formats = NULL;
844 AVFilterChannelLayouts *layouts = NULL;
845 int ret, sample_rates[] = { 48000, -1 };
847 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
850 ret = ff_set_common_formats(ctx, formats);
854 layouts = ff_all_channel_layouts();
856 return AVERROR(ENOMEM);
858 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
863 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
867 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
871 sample_rates[0] = s->sample_rate;
872 formats = ff_make_format_list(sample_rates);
874 return AVERROR(ENOMEM);
875 return ff_set_common_samplerates(ctx, formats);
878 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
880 struct SOFAlizerContext *s = ctx->priv;
881 const int n_samples = s->sofa.n_samples;
882 int n_conv = s->n_conv; /* no. channels to convolve */
883 int n_fft = s->n_fft;
884 int delay_l[16]; /* broadband delay for each IR */
886 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
887 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
888 FFTComplex *data_hrtf_l = NULL;
889 FFTComplex *data_hrtf_r = NULL;
890 FFTComplex *fft_in_l = NULL;
891 FFTComplex *fft_in_r = NULL;
892 float *data_ir_l = NULL;
893 float *data_ir_r = NULL;
894 int offset = 0; /* used for faster pointer arithmetics in for-loop */
895 int m[16]; /* measurement index m of IR closest to required source positions */
896 int i, j, azim_orig = azim, elev_orig = elev;
898 if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
899 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
900 return AVERROR_INVALIDDATA;
903 if (s->type == TIME_DOMAIN) {
904 s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
905 s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
907 /* get temporary IR for L and R channel */
908 data_ir_l = av_calloc(n_conv * FFALIGN(n_samples, 16), sizeof(*data_ir_l));
909 data_ir_r = av_calloc(n_conv * FFALIGN(n_samples, 16), sizeof(*data_ir_r));
910 if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
913 return AVERROR(ENOMEM);
916 /* get temporary HRTF memory for L and R channel */
917 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
918 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
919 if (!data_hrtf_r || !data_hrtf_l) {
920 av_free(data_hrtf_l);
921 av_free(data_hrtf_r);
922 return AVERROR(ENOMEM);
926 for (i = 0; i < s->n_conv; i++) {
927 /* load and store IRs and corresponding delays */
928 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
929 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
930 /* get id of IR closest to desired position */
931 m[i] = find_m(s, azim, elev, radius);
933 /* load the delays associated with the current IRs */
934 delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
935 delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
937 if (s->type == TIME_DOMAIN) {
938 offset = i * FFALIGN(n_samples, 16); /* no. samples already written */
939 for (j = 0; j < n_samples; j++) {
940 /* load reversed IRs of the specified source position
941 * sample-by-sample for left and right ear; and apply gain */
942 *(data_ir_l + offset + j) = /* left channel */
943 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
944 *(data_ir_r + offset + j) = /* right channel */
945 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
948 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
949 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
950 if (!fft_in_l || !fft_in_r) {
951 av_free(data_hrtf_l);
952 av_free(data_hrtf_r);
955 return AVERROR(ENOMEM);
958 offset = i * n_fft; /* no. samples already written */
959 for (j = 0; j < n_samples; j++) {
960 /* load non-reversed IRs of the specified source position
961 * sample-by-sample and apply gain,
962 * L channel is loaded to real part, R channel to imag part,
963 * IRs ared shifted by L and R delay */
964 fft_in_l[delay_l[i] + j].re = /* left channel */
965 *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
966 fft_in_r[delay_r[i] + j].re = /* right channel */
967 *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
970 /* actually transform to frequency domain (IRs -> HRTFs) */
971 av_fft_permute(s->fft[0], fft_in_l);
972 av_fft_calc(s->fft[0], fft_in_l);
973 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
974 av_fft_permute(s->fft[0], fft_in_r);
975 av_fft_calc(s->fft[0], fft_in_r);
976 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
979 av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
980 m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
983 if (s->type == TIME_DOMAIN) {
984 /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
985 memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * FFALIGN(n_samples, 16));
986 memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * FFALIGN(n_samples, 16));
988 av_freep(&data_ir_l); /* free temporary IR memory */
989 av_freep(&data_ir_r);
991 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
992 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
993 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
994 av_freep(&data_hrtf_l);
995 av_freep(&data_hrtf_r);
998 return AVERROR(ENOMEM); /* memory allocation failed */
1001 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
1002 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
1003 memcpy(s->data_hrtf[1], data_hrtf_r,
1004 sizeof(FFTComplex) * n_conv * n_fft);
1006 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
1007 av_freep(&data_hrtf_r);
1009 av_freep(&fft_in_l); /* free temporary FFT memory */
1010 av_freep(&fft_in_r);
1013 memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
1014 memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
1019 static av_cold int init(AVFilterContext *ctx)
1021 SOFAlizerContext *s = ctx->priv;
1025 av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
1026 return AVERROR(EINVAL);
1029 /* load SOFA file, */
1030 /* initialize file IDs to 0 before attempting to load SOFA files,
1031 * this assures that in case of error, only the memory of already
1032 * loaded files is free'd */
1034 ret = load_sofa(ctx, s->filename, &s->sample_rate);
1036 /* file loading error */
1037 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
1038 } else { /* no file loading error, resampling not required */
1039 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
1043 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
1047 s->fdsp = avpriv_float_dsp_alloc(0);
1049 return AVERROR(ENOMEM);
1054 static int config_input(AVFilterLink *inlink)
1056 AVFilterContext *ctx = inlink->dst;
1057 SOFAlizerContext *s = ctx->priv;
1058 int nb_input_channels = inlink->channels; /* no. input channels */
1064 if (s->type == FREQUENCY_DOMAIN) {
1065 inlink->partial_buf_size =
1066 inlink->min_samples =
1067 inlink->max_samples = inlink->sample_rate;
1070 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
1071 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
1073 s->n_conv = nb_input_channels;
1075 /* get size of ringbuffer (longest IR plus max. delay) */
1076 /* then choose next power of 2 for performance optimization */
1077 n_current = s->sofa.n_samples + max_delay(&s->sofa);
1078 if (n_current > n_max) {
1079 /* length of longest IR plus max. delay (in all SOFA files) */
1081 /* length of longest IR (without delay, in all SOFA files) */
1082 n_max_ir = s->sofa.n_samples;
1084 /* buffer length is longest IR plus max. delay -> next power of 2
1085 (32 - count leading zeros gives required exponent) */
1086 s->buffer_length = 1 << (32 - ff_clz(n_max));
1087 s->n_fft = 1 << (32 - ff_clz(n_max + inlink->sample_rate));
1089 if (s->type == FREQUENCY_DOMAIN) {
1090 av_fft_end(s->fft[0]);
1091 av_fft_end(s->fft[1]);
1092 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
1093 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
1094 av_fft_end(s->ifft[0]);
1095 av_fft_end(s->ifft[1]);
1096 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
1097 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
1099 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
1100 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
1101 return AVERROR(ENOMEM);
1105 /* Allocate memory for the impulse responses, delays and the ringbuffers */
1106 /* size: (longest IR) * (number of channels to convolute) */
1107 s->data_ir[0] = av_calloc(FFALIGN(n_max_ir, 16), sizeof(float) * s->n_conv);
1108 s->data_ir[1] = av_calloc(FFALIGN(n_max_ir, 16), sizeof(float) * s->n_conv);
1109 /* length: number of channels to convolute */
1110 s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
1111 s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
1112 /* length: (buffer length) * (number of input channels),
1113 * OR: buffer length (if frequency domain processing)
1114 * calloc zero-initializes the buffer */
1116 if (s->type == TIME_DOMAIN) {
1117 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1118 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1120 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
1121 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
1122 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1123 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1124 if (!s->temp_fft[0] || !s->temp_fft[1])
1125 return AVERROR(ENOMEM);
1128 /* length: number of channels to convolute */
1129 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
1130 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
1132 /* memory allocation failed: */
1133 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
1134 !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
1135 !s->speaker_azim || !s->speaker_elev)
1136 return AVERROR(ENOMEM);
1138 compensate_volume(ctx);
1140 /* get speaker positions */
1141 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
1142 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
1146 /* load IRs to data_ir[0] and data_ir[1] for required directions */
1147 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
1150 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
1151 inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
1156 static av_cold void uninit(AVFilterContext *ctx)
1158 SOFAlizerContext *s = ctx->priv;
1161 av_freep(&s->sofa.sp_a);
1162 av_freep(&s->sofa.sp_e);
1163 av_freep(&s->sofa.sp_r);
1164 av_freep(&s->sofa.data_delay);
1165 av_freep(&s->sofa.data_ir);
1167 av_fft_end(s->ifft[0]);
1168 av_fft_end(s->ifft[1]);
1169 av_fft_end(s->fft[0]);
1170 av_fft_end(s->fft[1]);
1171 av_freep(&s->delay[0]);
1172 av_freep(&s->delay[1]);
1173 av_freep(&s->data_ir[0]);
1174 av_freep(&s->data_ir[1]);
1175 av_freep(&s->ringbuffer[0]);
1176 av_freep(&s->ringbuffer[1]);
1177 av_freep(&s->speaker_azim);
1178 av_freep(&s->speaker_elev);
1179 av_freep(&s->temp_src[0]);
1180 av_freep(&s->temp_src[1]);
1181 av_freep(&s->temp_fft[0]);
1182 av_freep(&s->temp_fft[1]);
1183 av_freep(&s->data_hrtf[0]);
1184 av_freep(&s->data_hrtf[1]);
1188 #define OFFSET(x) offsetof(SOFAlizerContext, x)
1189 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1191 static const AVOption sofalizer_options[] = {
1192 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1193 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
1194 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
1195 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
1196 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
1197 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
1198 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
1199 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
1200 { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
1201 { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -9, 9, .flags = FLAGS },
1205 AVFILTER_DEFINE_CLASS(sofalizer);
1207 static const AVFilterPad inputs[] = {
1210 .type = AVMEDIA_TYPE_AUDIO,
1211 .config_props = config_input,
1212 .filter_frame = filter_frame,
1217 static const AVFilterPad outputs[] = {
1220 .type = AVMEDIA_TYPE_AUDIO,
1225 AVFilter ff_af_sofalizer = {
1226 .name = "sofalizer",
1227 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1228 .priv_size = sizeof(SOFAlizerContext),
1229 .priv_class = &sofalizer_class,
1232 .query_formats = query_formats,
1235 .flags = AVFILTER_FLAG_SLICE_THREADS,