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[10] = { 0 };
367 float elev[10] = { 0 };
368 int n_conv = ctx->inputs[0]->channels; /* get no. input channels */
372 /* set speaker positions according to input channel configuration: */
373 switch (channels_layout) {
374 case AV_CH_LAYOUT_MONO:
377 case AV_CH_LAYOUT_2POINT1:
379 case AV_CH_LAYOUT_STEREO:
383 case AV_CH_LAYOUT_3POINT1:
385 case AV_CH_LAYOUT_SURROUND:
390 case AV_CH_LAYOUT_2_1:
395 case AV_CH_LAYOUT_2_2:
401 case AV_CH_LAYOUT_QUAD:
407 case AV_CH_LAYOUT_4POINT1:
414 case AV_CH_LAYOUT_4POINT0:
420 case AV_CH_LAYOUT_5POINT1:
428 case AV_CH_LAYOUT_5POINT0:
435 case AV_CH_LAYOUT_5POINT1_BACK:
443 case AV_CH_LAYOUT_5POINT0_BACK:
450 case AV_CH_LAYOUT_6POINT1:
459 case AV_CH_LAYOUT_6POINT0:
467 case AV_CH_LAYOUT_6POINT1_BACK:
476 case AV_CH_LAYOUT_HEXAGONAL:
484 case AV_CH_LAYOUT_7POINT1:
494 case AV_CH_LAYOUT_7POINT0:
503 case AV_CH_LAYOUT_OCTAGONAL:
517 memcpy(speaker_azim, azim, n_conv * sizeof(float));
518 memcpy(speaker_elev, elev, n_conv * sizeof(float));
524 static int max_delay(struct NCSofa *sofa)
528 for (i = 0; i < sofa->m_dim * 2; i++) {
529 /* search maximum delay in given SOFA file */
530 max = FFMAX(max, sofa->data_delay[i]);
536 static int find_m(SOFAlizerContext *s, int azim, int elev, float radius)
538 /* get source positions and M of currently selected SOFA file */
539 float *sp_a = s->sofa.sp_a; /* azimuth angle */
540 float *sp_e = s->sofa.sp_e; /* elevation angle */
541 float *sp_r = s->sofa.sp_r; /* radius */
542 int m_dim = s->sofa.m_dim; /* no. measurements */
543 int best_id = 0; /* index m currently closest to desired source pos. */
544 float delta = 1000; /* offset between desired and currently best pos. */
548 for (i = 0; i < m_dim; i++) {
549 /* search through all measurements in currently selected SOFA file */
550 /* distance of current to desired source position: */
551 current = fabs(sp_a[i] - azim) +
552 fabs(sp_e[i] - elev) +
553 fabs(sp_r[i] - radius);
554 if (current <= delta) {
555 /* if current distance is smaller than smallest distance so far */
557 best_id = i; /* remember index */
564 static int compensate_volume(AVFilterContext *ctx)
566 struct SOFAlizerContext *s = ctx->priv;
573 /* find IR at front center position in the SOFA file (IR closest to 0°,0°,1m) */
574 struct NCSofa *sofa = &s->sofa;
575 m = find_m(s, 0, 0, 1);
576 /* get energy of that IR and compensate volume */
577 ir = sofa->data_ir + 2 * m * sofa->n_samples;
578 if (sofa->n_samples & 31) {
579 energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
581 energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
583 compensate = 256 / (sofa->n_samples * sqrt(energy));
584 av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
586 /* apply volume compensation to IRs */
587 s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
594 typedef struct ThreadData {
602 FFTComplex **temp_fft;
605 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
607 SOFAlizerContext *s = ctx->priv;
608 ThreadData *td = arg;
609 AVFrame *in = td->in, *out = td->out;
611 int *write = &td->write[jobnr];
612 const int *const delay = td->delay[jobnr];
613 const float *const ir = td->ir[jobnr];
614 int *n_clippings = &td->n_clippings[jobnr];
615 float *ringbuffer = td->ringbuffer[jobnr];
616 float *temp_src = td->temp_src[jobnr];
617 const int n_samples = s->sofa.n_samples; /* length of one IR */
618 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
619 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
620 const int in_channels = s->n_conv; /* number of input channels */
621 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
622 const int buffer_length = s->buffer_length;
623 /* -1 for AND instead of MODULO (applied to powers of 2): */
624 const uint32_t modulo = (uint32_t)buffer_length - 1;
625 float *buffer[10]; /* holds ringbuffer for each input channel */
631 for (l = 0; l < in_channels; l++) {
632 /* get starting address of ringbuffer for each input channel */
633 buffer[l] = ringbuffer + l * buffer_length;
636 for (i = 0; i < in->nb_samples; i++) {
637 const float *temp_ir = ir; /* using same set of IRs for each sample */
640 for (l = 0; l < in_channels; l++) {
641 /* write current input sample to ringbuffer (for each channel) */
642 *(buffer[l] + wr) = src[l];
645 /* loop goes through all channels to be convolved */
646 for (l = 0; l < in_channels; l++) {
647 const float *const bptr = buffer[l];
649 if (l == s->lfe_channel) {
650 /* LFE is an input channel but requires no convolution */
651 /* apply gain to LFE signal and add to output buffer */
652 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
653 temp_ir += n_samples;
657 /* current read position in ringbuffer: input sample write position
658 * - delay for l-th ch. + diff. betw. IR length and buffer length
659 * (mod buffer length) */
660 read = (wr - *(delay + l) - (n_samples - 1) + buffer_length) & modulo;
662 if (read + n_samples < buffer_length) {
663 memcpy(temp_src, bptr + read, n_samples * sizeof(*temp_src));
665 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
667 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
668 memcpy(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
671 /* multiply signal and IR, and add up the results */
672 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
673 temp_ir += n_samples;
676 /* clippings counter */
680 /* move output buffer pointer by +2 to get to next sample of processed channel: */
683 wr = (wr + 1) & modulo; /* update ringbuffer write position */
686 *write = wr; /* remember write position in ringbuffer for next call */
691 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
693 SOFAlizerContext *s = ctx->priv;
694 ThreadData *td = arg;
695 AVFrame *in = td->in, *out = td->out;
697 int *write = &td->write[jobnr];
698 FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
699 int *n_clippings = &td->n_clippings[jobnr];
700 float *ringbuffer = td->ringbuffer[jobnr];
701 const int n_samples = s->sofa.n_samples; /* length of one IR */
702 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
703 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
704 const int in_channels = s->n_conv; /* number of input channels */
705 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
706 const int buffer_length = s->buffer_length;
707 /* -1 for AND instead of MODULO (applied to powers of 2): */
708 const uint32_t modulo = (uint32_t)buffer_length - 1;
709 FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
710 FFTContext *ifft = s->ifft[jobnr];
711 FFTContext *fft = s->fft[jobnr];
712 const int n_conv = s->n_conv;
713 const int n_fft = s->n_fft;
720 /* find minimum between number of samples and output buffer length:
721 * (important, if one IR is longer than the output buffer) */
722 n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
723 for (j = 0; j < n_read; j++) {
724 /* initialize output buf with saved signal from overflow buf */
725 dst[2 * j] = ringbuffer[wr];
726 ringbuffer[wr] = 0.0; /* re-set read samples to zero */
727 /* update ringbuffer read/write position */
728 wr = (wr + 1) & modulo;
731 /* initialize rest of output buffer with 0 */
732 for (j = n_read; j < in->nb_samples; j++) {
736 for (i = 0; i < n_conv; i++) {
737 if (i == s->lfe_channel) { /* LFE */
738 for (j = 0; j < in->nb_samples; j++) {
739 /* apply gain to LFE signal and add to output buffer */
740 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
745 /* outer loop: go through all input channels to be convolved */
746 offset = i * n_fft; /* no. samples already processed */
748 /* fill FFT input with 0 (we want to zero-pad) */
749 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
751 for (j = 0; j < in->nb_samples; j++) {
752 /* prepare input for FFT */
753 /* write all samples of current input channel to FFT input array */
754 fft_in[j].re = src[j * in_channels + i];
757 /* transform input signal of current channel to frequency domain */
758 av_fft_permute(fft, fft_in);
759 av_fft_calc(fft, fft_in);
760 for (j = 0; j < n_fft; j++) {
761 const float re = fft_in[j].re;
762 const float im = fft_in[j].im;
764 /* complex multiplication of input signal and HRTFs */
765 /* output channel (real): */
766 fft_in[j].re = re * (hrtf + offset + j)->re - im * (hrtf + offset + j)->im;
767 /* output channel (imag): */
768 fft_in[j].im = re * (hrtf + offset + j)->im + im * (hrtf + offset + j)->re;
771 /* transform output signal of current channel back to time domain */
772 av_fft_permute(ifft, fft_in);
773 av_fft_calc(ifft, fft_in);
775 for (j = 0; j < in->nb_samples; j++) {
776 /* write output signal of current channel to output buffer */
777 dst[2 * j] += fft_in[j].re / (float)n_fft;
780 for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
781 /* write the rest of output signal to overflow buffer */
782 int write_pos = (wr + j) & modulo;
784 *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re / (float)n_fft;
788 /* go through all samples of current output buffer: count clippings */
789 for (i = 0; i < out->nb_samples; i++) {
790 /* clippings counter */
791 if (fabs(*dst) > 1) { /* if current output sample > 1 */
792 *n_clippings = *n_clippings + 1;
795 /* move output buffer pointer by +2 to get to next sample of processed channel: */
799 /* remember read/write position in ringbuffer for next call */
805 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
807 AVFilterContext *ctx = inlink->dst;
808 SOFAlizerContext *s = ctx->priv;
809 AVFilterLink *outlink = ctx->outputs[0];
810 int n_clippings[2] = { 0 };
814 out = ff_get_audio_buffer(outlink, in->nb_samples);
817 return AVERROR(ENOMEM);
819 av_frame_copy_props(out, in);
821 td.in = in; td.out = out; td.write = s->write;
822 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
823 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
824 td.temp_fft = s->temp_fft;
826 if (s->type == TIME_DOMAIN) {
827 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
829 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
833 /* display error message if clipping occured */
834 if (n_clippings[0] + n_clippings[1] > 0) {
835 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
836 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
840 return ff_filter_frame(outlink, out);
843 static int query_formats(AVFilterContext *ctx)
845 struct SOFAlizerContext *s = ctx->priv;
846 AVFilterFormats *formats = NULL;
847 AVFilterChannelLayouts *layouts = NULL;
848 int ret, sample_rates[] = { 48000, -1 };
849 static const uint64_t channel_layouts[] = { AV_CH_LAYOUT_MONO,
851 AV_CH_LAYOUT_2POINT1,
852 AV_CH_LAYOUT_SURROUND,
854 AV_CH_LAYOUT_4POINT0,
857 AV_CH_LAYOUT_3POINT1,
858 AV_CH_LAYOUT_5POINT0_BACK,
859 AV_CH_LAYOUT_5POINT0,
860 AV_CH_LAYOUT_4POINT1,
861 AV_CH_LAYOUT_5POINT1_BACK,
862 AV_CH_LAYOUT_5POINT1,
863 AV_CH_LAYOUT_6POINT0,
864 AV_CH_LAYOUT_HEXAGONAL,
865 AV_CH_LAYOUT_6POINT1,
866 AV_CH_LAYOUT_6POINT1_BACK,
867 AV_CH_LAYOUT_7POINT0,
868 AV_CH_LAYOUT_7POINT1,
869 AV_CH_LAYOUT_OCTAGONAL,
872 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
875 ret = ff_set_common_formats(ctx, formats);
879 layouts = ff_make_formatu64_list(channel_layouts);
881 return AVERROR(ENOMEM);
883 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
888 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
892 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
896 sample_rates[0] = s->sample_rate;
897 formats = ff_make_format_list(sample_rates);
899 return AVERROR(ENOMEM);
900 return ff_set_common_samplerates(ctx, formats);
903 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)
905 struct SOFAlizerContext *s = ctx->priv;
906 const int n_samples = s->sofa.n_samples;
907 int n_conv = s->n_conv; /* no. channels to convolve */
908 int n_fft = s->n_fft;
909 int delay_l[10]; /* broadband delay for each IR */
911 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
912 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
913 FFTComplex *data_hrtf_l = NULL;
914 FFTComplex *data_hrtf_r = NULL;
915 FFTComplex *fft_in_l = NULL;
916 FFTComplex *fft_in_r = NULL;
917 float *data_ir_l = NULL;
918 float *data_ir_r = NULL;
919 int offset = 0; /* used for faster pointer arithmetics in for-loop */
920 int m[10]; /* measurement index m of IR closest to required source positions */
921 int i, j, azim_orig = azim, elev_orig = elev;
923 if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */
924 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
925 return AVERROR_INVALIDDATA;
928 if (s->type == TIME_DOMAIN) {
929 s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
930 s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));
932 /* get temporary IR for L and R channel */
933 data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));
934 data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));
935 if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {
938 return AVERROR(ENOMEM);
941 /* get temporary HRTF memory for L and R channel */
942 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
943 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
944 if (!data_hrtf_r || !data_hrtf_l) {
945 av_free(data_hrtf_l);
946 av_free(data_hrtf_r);
947 return AVERROR(ENOMEM);
951 for (i = 0; i < s->n_conv; i++) {
952 /* load and store IRs and corresponding delays */
953 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
954 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
955 /* get id of IR closest to desired position */
956 m[i] = find_m(s, azim, elev, radius);
958 /* load the delays associated with the current IRs */
959 delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);
960 delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);
962 if (s->type == TIME_DOMAIN) {
963 offset = i * n_samples; /* no. samples already written */
964 for (j = 0; j < n_samples; j++) {
965 /* load reversed IRs of the specified source position
966 * sample-by-sample for left and right ear; and apply gain */
967 *(data_ir_l + offset + j) = /* left channel */
968 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;
969 *(data_ir_r + offset + j) = /* right channel */
970 *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j + n_samples) * gain_lin;
973 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
974 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
975 if (!fft_in_l || !fft_in_r) {
976 av_free(data_hrtf_l);
977 av_free(data_hrtf_r);
980 return AVERROR(ENOMEM);
983 offset = i * n_fft; /* no. samples already written */
984 for (j = 0; j < n_samples; j++) {
985 /* load non-reversed IRs of the specified source position
986 * sample-by-sample and apply gain,
987 * L channel is loaded to real part, R channel to imag part,
988 * IRs ared shifted by L and R delay */
989 fft_in_l[delay_l[i] + j].re = /* left channel */
990 *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;
991 fft_in_r[delay_r[i] + j].re = /* right channel */
992 *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;
995 /* actually transform to frequency domain (IRs -> HRTFs) */
996 av_fft_permute(s->fft[0], fft_in_l);
997 av_fft_calc(s->fft[0], fft_in_l);
998 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
999 av_fft_permute(s->fft[0], fft_in_r);
1000 av_fft_calc(s->fft[0], fft_in_r);
1001 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
1004 av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",
1005 m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));
1008 if (s->type == TIME_DOMAIN) {
1009 /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */
1010 memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);
1011 memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);
1013 av_freep(&data_ir_l); /* free temporary IR memory */
1014 av_freep(&data_ir_r);
1016 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
1017 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
1018 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
1019 av_freep(&data_hrtf_l);
1020 av_freep(&data_hrtf_r);
1021 av_freep(&fft_in_l);
1022 av_freep(&fft_in_r);
1023 return AVERROR(ENOMEM); /* memory allocation failed */
1026 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
1027 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
1028 memcpy(s->data_hrtf[1], data_hrtf_r,
1029 sizeof(FFTComplex) * n_conv * n_fft);
1031 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
1032 av_freep(&data_hrtf_r);
1034 av_freep(&fft_in_l); /* free temporary FFT memory */
1035 av_freep(&fft_in_r);
1038 memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);
1039 memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);
1044 static av_cold int init(AVFilterContext *ctx)
1046 SOFAlizerContext *s = ctx->priv;
1049 /* load SOFA file, */
1050 /* initialize file IDs to 0 before attempting to load SOFA files,
1051 * this assures that in case of error, only the memory of already
1052 * loaded files is free'd */
1054 ret = load_sofa(ctx, s->filename, &s->sample_rate);
1056 /* file loading error */
1057 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
1058 } else { /* no file loading error, resampling not required */
1059 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
1063 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
1067 s->fdsp = avpriv_float_dsp_alloc(0);
1069 return AVERROR(ENOMEM);
1074 static inline unsigned clz(unsigned x)
1076 unsigned i = sizeof(x) * 8;
1086 static int config_input(AVFilterLink *inlink)
1088 AVFilterContext *ctx = inlink->dst;
1089 SOFAlizerContext *s = ctx->priv;
1090 int nb_input_channels = inlink->channels; /* no. input channels */
1096 if (s->type == FREQUENCY_DOMAIN) {
1097 inlink->partial_buf_size =
1098 inlink->min_samples =
1099 inlink->max_samples = inlink->sample_rate;
1102 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
1103 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6) / 20 * M_LN10);
1105 s->n_conv = nb_input_channels;
1107 /* get size of ringbuffer (longest IR plus max. delay) */
1108 /* then choose next power of 2 for performance optimization */
1109 n_current = s->sofa.n_samples + max_delay(&s->sofa);
1110 if (n_current > n_max) {
1111 /* length of longest IR plus max. delay (in all SOFA files) */
1113 /* length of longest IR (without delay, in all SOFA files) */
1114 n_max_ir = s->sofa.n_samples;
1116 /* buffer length is longest IR plus max. delay -> next power of 2
1117 (32 - count leading zeros gives required exponent) */
1118 s->buffer_length = exp2(32 - clz((uint32_t)n_max));
1119 s->n_fft = exp2(32 - clz((uint32_t)(n_max + inlink->sample_rate)));
1121 if (s->type == FREQUENCY_DOMAIN) {
1122 av_fft_end(s->fft[0]);
1123 av_fft_end(s->fft[1]);
1124 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
1125 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
1126 av_fft_end(s->ifft[0]);
1127 av_fft_end(s->ifft[1]);
1128 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
1129 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
1131 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
1132 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts.\n");
1133 return AVERROR(ENOMEM);
1137 /* Allocate memory for the impulse responses, delays and the ringbuffers */
1138 /* size: (longest IR) * (number of channels to convolute) */
1139 s->data_ir[0] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
1140 s->data_ir[1] = av_malloc_array(n_max_ir, sizeof(float) * s->n_conv);
1141 /* length: number of channels to convolute */
1142 s->delay[0] = av_malloc_array(s->n_conv, sizeof(float));
1143 s->delay[1] = av_malloc_array(s->n_conv, sizeof(float));
1144 /* length: (buffer length) * (number of input channels),
1145 * OR: buffer length (if frequency domain processing)
1146 * calloc zero-initializes the buffer */
1148 if (s->type == TIME_DOMAIN) {
1149 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1150 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
1152 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
1153 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
1154 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1155 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
1156 if (!s->temp_fft[0] || !s->temp_fft[1])
1157 return AVERROR(ENOMEM);
1160 /* length: number of channels to convolute */
1161 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
1162 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
1164 /* memory allocation failed: */
1165 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[1] ||
1166 !s->delay[0] || !s->ringbuffer[0] || !s->ringbuffer[1] ||
1167 !s->speaker_azim || !s->speaker_elev)
1168 return AVERROR(ENOMEM);
1170 compensate_volume(ctx);
1172 /* get speaker positions */
1173 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
1174 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
1178 /* load IRs to data_ir[0] and data_ir[1] for required directions */
1179 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius)) < 0)
1182 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
1183 inlink->sample_rate, s->n_conv, nb_input_channels, s->buffer_length);
1188 static av_cold void uninit(AVFilterContext *ctx)
1190 SOFAlizerContext *s = ctx->priv;
1193 av_freep(&s->sofa.sp_a);
1194 av_freep(&s->sofa.sp_e);
1195 av_freep(&s->sofa.sp_r);
1196 av_freep(&s->sofa.data_delay);
1197 av_freep(&s->sofa.data_ir);
1199 av_fft_end(s->ifft[0]);
1200 av_fft_end(s->ifft[1]);
1201 av_fft_end(s->fft[0]);
1202 av_fft_end(s->fft[1]);
1203 av_freep(&s->delay[0]);
1204 av_freep(&s->delay[1]);
1205 av_freep(&s->data_ir[0]);
1206 av_freep(&s->data_ir[1]);
1207 av_freep(&s->ringbuffer[0]);
1208 av_freep(&s->ringbuffer[1]);
1209 av_freep(&s->speaker_azim);
1210 av_freep(&s->speaker_elev);
1211 av_freep(&s->temp_src[0]);
1212 av_freep(&s->temp_src[1]);
1213 av_freep(&s->temp_fft[0]);
1214 av_freep(&s->temp_fft[1]);
1215 av_freep(&s->data_hrtf[0]);
1216 av_freep(&s->data_hrtf[1]);
1220 #define OFFSET(x) offsetof(SOFAlizerContext, x)
1221 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1223 static const AVOption sofalizer_options[] = {
1224 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1225 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
1226 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
1227 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
1228 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
1229 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
1230 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
1231 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
1235 AVFILTER_DEFINE_CLASS(sofalizer);
1237 static const AVFilterPad inputs[] = {
1240 .type = AVMEDIA_TYPE_AUDIO,
1241 .config_props = config_input,
1242 .filter_frame = filter_frame,
1247 static const AVFilterPad outputs[] = {
1250 .type = AVMEDIA_TYPE_AUDIO,
1255 AVFilter ff_af_sofalizer = {
1256 .name = "sofalizer",
1257 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1258 .priv_size = sizeof(SOFAlizerContext),
1259 .priv_class = &sofalizer_class,
1262 .query_formats = query_formats,
1265 .flags = AVFILTER_FLAG_SLICE_THREADS,