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 MySofa { /* contains data of one SOFA file */
45 struct MYSOFA_EASY *easy;
46 int n_samples; /* length of one impulse response (IR) */
47 float *lir, *rir; /* IRs (time-domain) */
51 typedef struct VirtualSpeaker {
57 typedef struct SOFAlizerContext {
60 char *filename; /* name of SOFA file */
61 MySofa sofa; /* contains data of the SOFA file */
63 int sample_rate; /* sample rate from SOFA file */
64 float *speaker_azim; /* azimuth of the virtual loudspeakers */
65 float *speaker_elev; /* elevation of the virtual loudspeakers */
66 char *speakers_pos; /* custom positions of the virtual loudspeakers */
67 float lfe_gain; /* initial gain for the LFE channel */
68 float gain_lfe; /* gain applied to LFE channel */
69 int lfe_channel; /* LFE channel position in channel layout */
71 int n_conv; /* number of channels to convolute */
73 /* buffer variables (for convolution) */
74 float *ringbuffer[2]; /* buffers input samples, length of one buffer: */
75 /* no. input ch. (incl. LFE) x buffer_length */
76 int write[2]; /* current write position to ringbuffer */
77 int buffer_length; /* is: longest IR plus max. delay in all SOFA files */
78 /* then choose next power of 2 */
79 int n_fft; /* number of samples in one FFT block */
81 /* netCDF variables */
82 int *delay[2]; /* broadband delay for each channel/IR to be convolved */
84 float *data_ir[2]; /* IRs for all channels to be convolved */
85 /* (this excludes the LFE) */
87 FFTComplex *temp_fft[2];
89 /* control variables */
90 float gain; /* filter gain (in dB) */
91 float rotation; /* rotation of virtual loudspeakers (in degrees) */
92 float elevation; /* elevation of virtual loudspeakers (in deg.) */
93 float radius; /* distance virtual loudspeakers to listener (in metres) */
94 int type; /* processing type */
96 VirtualSpeaker vspkrpos[64];
98 FFTContext *fft[2], *ifft[2];
99 FFTComplex *data_hrtf[2];
101 AVFloatDSPContext *fdsp;
104 static int close_sofa(struct MySofa *sofa)
106 mysofa_close(sofa->easy);
112 static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
114 struct SOFAlizerContext *s = ctx->priv;
115 struct MYSOFA_HRTF *mysofa;
118 mysofa = mysofa_load(filename, &ret);
119 if (ret || !mysofa) {
120 av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
121 return AVERROR(EINVAL);
124 if (mysofa->DataSamplingRate.elements != 1)
125 return AVERROR(EINVAL);
126 *samplingrate = mysofa->DataSamplingRate.values[0];
127 s->sofa.n_samples = mysofa->N;
133 static int parse_channel_name(char **arg, int *rchannel, char *buf)
135 int len, i, channel_id = 0;
136 int64_t layout, layout0;
138 /* try to parse a channel name, e.g. "FL" */
139 if (sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
140 layout0 = layout = av_get_channel_layout(buf);
141 /* channel_id <- first set bit in layout */
142 for (i = 32; i > 0; i >>= 1) {
143 if (layout >= 1LL << i) {
148 /* reject layouts that are not a single channel */
149 if (channel_id >= 64 || layout0 != 1LL << channel_id)
150 return AVERROR(EINVAL);
151 *rchannel = channel_id;
155 return AVERROR(EINVAL);
158 static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
160 SOFAlizerContext *s = ctx->priv;
161 char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
167 while ((arg = av_strtok(p, "|", &tokenizer))) {
173 if (parse_channel_name(&arg, &out_ch_id, buf)) {
174 av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
177 if (sscanf(arg, "%f %f", &azim, &elev) == 2) {
178 s->vspkrpos[out_ch_id].set = 1;
179 s->vspkrpos[out_ch_id].azim = azim;
180 s->vspkrpos[out_ch_id].elev = elev;
181 } else if (sscanf(arg, "%f", &azim) == 1) {
182 s->vspkrpos[out_ch_id].set = 1;
183 s->vspkrpos[out_ch_id].azim = azim;
184 s->vspkrpos[out_ch_id].elev = 0;
191 static int get_speaker_pos(AVFilterContext *ctx,
192 float *speaker_azim, float *speaker_elev)
194 struct SOFAlizerContext *s = ctx->priv;
195 uint64_t channels_layout = ctx->inputs[0]->channel_layout;
196 float azim[16] = { 0 };
197 float elev[16] = { 0 };
198 int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
201 return AVERROR(EINVAL);
206 parse_speaker_pos(ctx, channels_layout);
208 /* set speaker positions according to input channel configuration: */
209 for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
210 uint64_t mask = channels_layout & (1ULL << m);
213 case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
214 case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
215 case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
216 case AV_CH_LOW_FREQUENCY:
217 case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
218 case AV_CH_BACK_LEFT: azim[ch] = 150; break;
219 case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
220 case AV_CH_BACK_CENTER: azim[ch] = 180; break;
221 case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
222 case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
223 case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
224 case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
225 case AV_CH_TOP_CENTER: azim[ch] = 0;
226 elev[ch] = 90; break;
227 case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
228 elev[ch] = 45; break;
229 case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
230 elev[ch] = 45; break;
231 case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
232 elev[ch] = 45; break;
233 case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
234 elev[ch] = 45; break;
235 case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
236 elev[ch] = 45; break;
237 case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
238 elev[ch] = 45; break;
239 case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
240 case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
241 case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
242 case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
243 case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
244 case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
247 return AVERROR(EINVAL);
250 if (s->vspkrpos[m].set) {
251 azim[ch] = s->vspkrpos[m].azim;
252 elev[ch] = s->vspkrpos[m].elev;
259 memcpy(speaker_azim, azim, n_conv * sizeof(float));
260 memcpy(speaker_elev, elev, n_conv * sizeof(float));
266 typedef struct ThreadData {
274 FFTComplex **temp_fft;
277 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
279 SOFAlizerContext *s = ctx->priv;
280 ThreadData *td = arg;
281 AVFrame *in = td->in, *out = td->out;
283 int *write = &td->write[jobnr];
284 const int *const delay = td->delay[jobnr];
285 const float *const ir = td->ir[jobnr];
286 int *n_clippings = &td->n_clippings[jobnr];
287 float *ringbuffer = td->ringbuffer[jobnr];
288 float *temp_src = td->temp_src[jobnr];
289 const int n_samples = s->sofa.n_samples; /* length of one IR */
290 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
291 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
292 const int in_channels = s->n_conv; /* number of input channels */
293 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
294 const int buffer_length = s->buffer_length;
295 /* -1 for AND instead of MODULO (applied to powers of 2): */
296 const uint32_t modulo = (uint32_t)buffer_length - 1;
297 float *buffer[16]; /* holds ringbuffer for each input channel */
303 for (l = 0; l < in_channels; l++) {
304 /* get starting address of ringbuffer for each input channel */
305 buffer[l] = ringbuffer + l * buffer_length;
308 for (i = 0; i < in->nb_samples; i++) {
309 const float *temp_ir = ir; /* using same set of IRs for each sample */
312 for (l = 0; l < in_channels; l++) {
313 /* write current input sample to ringbuffer (for each channel) */
314 buffer[l][wr] = src[l];
317 /* loop goes through all channels to be convolved */
318 for (l = 0; l < in_channels; l++) {
319 const float *const bptr = buffer[l];
321 if (l == s->lfe_channel) {
322 /* LFE is an input channel but requires no convolution */
323 /* apply gain to LFE signal and add to output buffer */
324 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
325 temp_ir += FFALIGN(n_samples, 32);
329 /* current read position in ringbuffer: input sample write position
330 * - delay for l-th ch. + diff. betw. IR length and buffer length
331 * (mod buffer length) */
332 read = (wr - delay[l] - (n_samples - 1) + buffer_length) & modulo;
334 if (read + n_samples < buffer_length) {
335 memmove(temp_src, bptr + read, n_samples * sizeof(*temp_src));
337 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
339 memmove(temp_src, bptr + read, len * sizeof(*temp_src));
340 memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
343 /* multiply signal and IR, and add up the results */
344 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
345 temp_ir += FFALIGN(n_samples, 32);
348 /* clippings counter */
349 if (fabs(dst[0]) > 1)
352 /* move output buffer pointer by +2 to get to next sample of processed channel: */
355 wr = (wr + 1) & modulo; /* update ringbuffer write position */
358 *write = wr; /* remember write position in ringbuffer for next call */
363 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
365 SOFAlizerContext *s = ctx->priv;
366 ThreadData *td = arg;
367 AVFrame *in = td->in, *out = td->out;
369 int *write = &td->write[jobnr];
370 FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
371 int *n_clippings = &td->n_clippings[jobnr];
372 float *ringbuffer = td->ringbuffer[jobnr];
373 const int n_samples = s->sofa.n_samples; /* length of one IR */
374 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
375 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
376 const int in_channels = s->n_conv; /* number of input channels */
377 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
378 const int buffer_length = s->buffer_length;
379 /* -1 for AND instead of MODULO (applied to powers of 2): */
380 const uint32_t modulo = (uint32_t)buffer_length - 1;
381 FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
382 FFTContext *ifft = s->ifft[jobnr];
383 FFTContext *fft = s->fft[jobnr];
384 const int n_conv = s->n_conv;
385 const int n_fft = s->n_fft;
386 const float fft_scale = 1.0f / s->n_fft;
387 FFTComplex *hrtf_offset;
394 /* find minimum between number of samples and output buffer length:
395 * (important, if one IR is longer than the output buffer) */
396 n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
397 for (j = 0; j < n_read; j++) {
398 /* initialize output buf with saved signal from overflow buf */
399 dst[2 * j] = ringbuffer[wr];
400 ringbuffer[wr] = 0.0; /* re-set read samples to zero */
401 /* update ringbuffer read/write position */
402 wr = (wr + 1) & modulo;
405 /* initialize rest of output buffer with 0 */
406 for (j = n_read; j < in->nb_samples; j++) {
410 for (i = 0; i < n_conv; i++) {
411 if (i == s->lfe_channel) { /* LFE */
412 for (j = 0; j < in->nb_samples; j++) {
413 /* apply gain to LFE signal and add to output buffer */
414 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
419 /* outer loop: go through all input channels to be convolved */
420 offset = i * n_fft; /* no. samples already processed */
421 hrtf_offset = hrtf + offset;
423 /* fill FFT input with 0 (we want to zero-pad) */
424 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
426 for (j = 0; j < in->nb_samples; j++) {
427 /* prepare input for FFT */
428 /* write all samples of current input channel to FFT input array */
429 fft_in[j].re = src[j * in_channels + i];
432 /* transform input signal of current channel to frequency domain */
433 av_fft_permute(fft, fft_in);
434 av_fft_calc(fft, fft_in);
435 for (j = 0; j < n_fft; j++) {
436 const FFTComplex *hcomplex = hrtf_offset + j;
437 const float re = fft_in[j].re;
438 const float im = fft_in[j].im;
440 /* complex multiplication of input signal and HRTFs */
441 /* output channel (real): */
442 fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
443 /* output channel (imag): */
444 fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
447 /* transform output signal of current channel back to time domain */
448 av_fft_permute(ifft, fft_in);
449 av_fft_calc(ifft, fft_in);
451 for (j = 0; j < in->nb_samples; j++) {
452 /* write output signal of current channel to output buffer */
453 dst[2 * j] += fft_in[j].re * fft_scale;
456 for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
457 /* write the rest of output signal to overflow buffer */
458 int write_pos = (wr + j) & modulo;
460 *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
464 /* go through all samples of current output buffer: count clippings */
465 for (i = 0; i < out->nb_samples; i++) {
466 /* clippings counter */
467 if (fabs(*dst) > 1) { /* if current output sample > 1 */
471 /* move output buffer pointer by +2 to get to next sample of processed channel: */
475 /* remember read/write position in ringbuffer for next call */
481 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
483 AVFilterContext *ctx = inlink->dst;
484 SOFAlizerContext *s = ctx->priv;
485 AVFilterLink *outlink = ctx->outputs[0];
486 int n_clippings[2] = { 0 };
490 out = ff_get_audio_buffer(outlink, in->nb_samples);
493 return AVERROR(ENOMEM);
495 av_frame_copy_props(out, in);
497 td.in = in; td.out = out; td.write = s->write;
498 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
499 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
500 td.temp_fft = s->temp_fft;
502 if (s->type == TIME_DOMAIN) {
503 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
505 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
509 /* display error message if clipping occurred */
510 if (n_clippings[0] + n_clippings[1] > 0) {
511 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
512 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
516 return ff_filter_frame(outlink, out);
519 static int query_formats(AVFilterContext *ctx)
521 struct SOFAlizerContext *s = ctx->priv;
522 AVFilterFormats *formats = NULL;
523 AVFilterChannelLayouts *layouts = NULL;
524 int ret, sample_rates[] = { 48000, -1 };
526 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
529 ret = ff_set_common_formats(ctx, formats);
533 layouts = ff_all_channel_layouts();
535 return AVERROR(ENOMEM);
537 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
542 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
546 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
550 sample_rates[0] = s->sample_rate;
551 formats = ff_make_format_list(sample_rates);
553 return AVERROR(ENOMEM);
554 return ff_set_common_samplerates(ctx, formats);
557 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
559 struct SOFAlizerContext *s = ctx->priv;
561 int n_conv = s->n_conv; /* no. channels to convolve */
563 float delay_l; /* broadband delay for each IR */
565 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
566 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
567 FFTComplex *data_hrtf_l = NULL;
568 FFTComplex *data_hrtf_r = NULL;
569 FFTComplex *fft_in_l = NULL;
570 FFTComplex *fft_in_r = NULL;
571 float *data_ir_l = NULL;
572 float *data_ir_r = NULL;
573 int offset = 0; /* used for faster pointer arithmetics in for-loop */
574 int i, j, azim_orig = azim, elev_orig = elev;
575 int filter_length, ret = 0;
579 s->sofa.easy = mysofa_open(s->filename, sample_rate, &filter_length, &ret);
580 if (!s->sofa.easy || ret) { /* if an invalid SOFA file has been selected */
581 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
582 return AVERROR_INVALIDDATA;
585 n_samples = s->sofa.n_samples;
587 s->data_ir[0] = av_calloc(FFALIGN(n_samples, 32), sizeof(float) * s->n_conv);
588 s->data_ir[1] = av_calloc(FFALIGN(n_samples, 32), sizeof(float) * s->n_conv);
589 s->delay[0] = av_calloc(s->n_conv, sizeof(int));
590 s->delay[1] = av_calloc(s->n_conv, sizeof(int));
592 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
593 ret = AVERROR(ENOMEM);
597 /* get temporary IR for L and R channel */
598 data_ir_l = av_calloc(n_conv * FFALIGN(n_samples, 32), sizeof(*data_ir_l));
599 data_ir_r = av_calloc(n_conv * FFALIGN(n_samples, 32), sizeof(*data_ir_r));
600 if (!data_ir_r || !data_ir_l) {
601 ret = AVERROR(ENOMEM);
605 if (s->type == TIME_DOMAIN) {
606 s->temp_src[0] = av_calloc(FFALIGN(n_samples, 32), sizeof(float));
607 s->temp_src[1] = av_calloc(FFALIGN(n_samples, 32), sizeof(float));
608 if (!s->temp_src[0] || !s->temp_src[1]) {
609 ret = AVERROR(ENOMEM);
614 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
615 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
616 if (!s->speaker_azim || !s->speaker_elev) {
617 ret = AVERROR(ENOMEM);
621 /* get speaker positions */
622 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
623 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
627 for (i = 0; i < s->n_conv; i++) {
628 float coordinates[3];
630 /* load and store IRs and corresponding delays */
631 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
632 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
634 coordinates[0] = azim;
635 coordinates[1] = elev;
636 coordinates[2] = radius;
638 mysofa_s2c(coordinates);
640 /* get id of IR closest to desired position */
641 mysofa_getfilter_float(s->sofa.easy, coordinates[0], coordinates[1], coordinates[2],
642 data_ir_l + FFALIGN(n_samples, 32) * i,
643 data_ir_r + FFALIGN(n_samples, 32) * i,
646 s->delay[0][i] = delay_l * sample_rate;
647 s->delay[1][i] = delay_r * sample_rate;
649 s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
652 /* get size of ringbuffer (longest IR plus max. delay) */
653 /* then choose next power of 2 for performance optimization */
654 n_current = s->sofa.n_samples + s->sofa.max_delay;
655 /* length of longest IR plus max. delay */
656 n_max = FFMAX(n_max, n_current);
658 /* buffer length is longest IR plus max. delay -> next power of 2
659 (32 - count leading zeros gives required exponent) */
660 s->buffer_length = 1 << (32 - ff_clz(n_max));
661 s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + sample_rate));
663 if (s->type == FREQUENCY_DOMAIN) {
664 av_fft_end(s->fft[0]);
665 av_fft_end(s->fft[1]);
666 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
667 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
668 av_fft_end(s->ifft[0]);
669 av_fft_end(s->ifft[1]);
670 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
671 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
673 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
674 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
675 ret = AVERROR(ENOMEM);
680 if (s->type == TIME_DOMAIN) {
681 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
682 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
684 /* get temporary HRTF memory for L and R channel */
685 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
686 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
687 if (!data_hrtf_r || !data_hrtf_l) {
688 ret = AVERROR(ENOMEM);
692 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
693 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
694 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
695 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
696 if (!s->temp_fft[0] || !s->temp_fft[1]) {
697 ret = AVERROR(ENOMEM);
702 if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
703 ret = AVERROR(ENOMEM);
707 if (s->type == FREQUENCY_DOMAIN) {
708 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
709 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
710 if (!fft_in_l || !fft_in_r) {
711 ret = AVERROR(ENOMEM);
716 for (i = 0; i < s->n_conv; i++) {
719 offset = i * FFALIGN(n_samples, 32); /* no. samples already written */
721 lir = data_ir_l + offset;
722 rir = data_ir_r + offset;
724 if (s->type == TIME_DOMAIN) {
725 for (j = 0; j < n_samples; j++) {
726 /* load reversed IRs of the specified source position
727 * sample-by-sample for left and right ear; and apply gain */
728 s->data_ir[0][offset + j] = lir[n_samples - 1 - j] * gain_lin;
729 s->data_ir[1][offset + j] = rir[n_samples - 1 - j] * gain_lin;
732 memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
733 memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
735 offset = i * n_fft; /* no. samples already written */
736 for (j = 0; j < n_samples; j++) {
737 /* load non-reversed IRs of the specified source position
738 * sample-by-sample and apply gain,
739 * L channel is loaded to real part, R channel to imag part,
740 * IRs ared shifted by L and R delay */
741 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
742 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
745 /* actually transform to frequency domain (IRs -> HRTFs) */
746 av_fft_permute(s->fft[0], fft_in_l);
747 av_fft_calc(s->fft[0], fft_in_l);
748 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
749 av_fft_permute(s->fft[0], fft_in_r);
750 av_fft_calc(s->fft[0], fft_in_r);
751 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
755 if (s->type == FREQUENCY_DOMAIN) {
756 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
757 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
758 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
759 ret = AVERROR(ENOMEM);
763 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
764 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
765 memcpy(s->data_hrtf[1], data_hrtf_r,
766 sizeof(FFTComplex) * n_conv * n_fft);
770 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
771 av_freep(&data_hrtf_r);
773 av_freep(&data_ir_l); /* free temprary IR memory */
774 av_freep(&data_ir_r);
776 av_freep(&fft_in_l); /* free temporary FFT memory */
782 static av_cold int init(AVFilterContext *ctx)
784 SOFAlizerContext *s = ctx->priv;
788 av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
789 return AVERROR(EINVAL);
792 /* preload SOFA file, */
793 ret = preload_sofa(ctx, s->filename, &s->sample_rate);
795 /* file loading error */
796 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
797 } else { /* no file loading error, resampling not required */
798 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
802 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
806 s->fdsp = avpriv_float_dsp_alloc(0);
808 return AVERROR(ENOMEM);
813 static int config_input(AVFilterLink *inlink)
815 AVFilterContext *ctx = inlink->dst;
816 SOFAlizerContext *s = ctx->priv;
819 if (s->type == FREQUENCY_DOMAIN) {
820 inlink->partial_buf_size =
821 inlink->min_samples =
822 inlink->max_samples = inlink->sample_rate;
825 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
826 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
828 s->n_conv = inlink->channels;
830 /* load IRs to data_ir[0] and data_ir[1] for required directions */
831 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
834 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
835 inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
840 static av_cold void uninit(AVFilterContext *ctx)
842 SOFAlizerContext *s = ctx->priv;
844 close_sofa(&s->sofa);
845 av_fft_end(s->ifft[0]);
846 av_fft_end(s->ifft[1]);
847 av_fft_end(s->fft[0]);
848 av_fft_end(s->fft[1]);
849 av_freep(&s->delay[0]);
850 av_freep(&s->delay[1]);
851 av_freep(&s->data_ir[0]);
852 av_freep(&s->data_ir[1]);
853 av_freep(&s->ringbuffer[0]);
854 av_freep(&s->ringbuffer[1]);
855 av_freep(&s->speaker_azim);
856 av_freep(&s->speaker_elev);
857 av_freep(&s->temp_src[0]);
858 av_freep(&s->temp_src[1]);
859 av_freep(&s->temp_fft[0]);
860 av_freep(&s->temp_fft[1]);
861 av_freep(&s->data_hrtf[0]);
862 av_freep(&s->data_hrtf[1]);
866 #define OFFSET(x) offsetof(SOFAlizerContext, x)
867 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
869 static const AVOption sofalizer_options[] = {
870 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
871 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
872 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
873 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
874 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 3, .flags = FLAGS },
875 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
876 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
877 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
878 { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
879 { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -9, 9, .flags = FLAGS },
883 AVFILTER_DEFINE_CLASS(sofalizer);
885 static const AVFilterPad inputs[] = {
888 .type = AVMEDIA_TYPE_AUDIO,
889 .config_props = config_input,
890 .filter_frame = filter_frame,
895 static const AVFilterPad outputs[] = {
898 .type = AVMEDIA_TYPE_AUDIO,
903 AVFilter ff_af_sofalizer = {
905 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
906 .priv_size = sizeof(SOFAlizerContext),
907 .priv_class = &sofalizer_class,
910 .query_formats = query_formats,
913 .flags = AVFILTER_FLAG_SLICE_THREADS,