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_HRTF *hrtf;
46 struct MYSOFA_LOOKUP *lookup;
47 struct MYSOFA_NEIGHBORHOOD *neighborhood;
48 int ir_samples; /* length of one impulse response (IR) */
49 int n_samples; /* ir_samples to next power of 2 */
50 float *lir, *rir; /* IRs (time-domain) */
55 typedef struct VirtualSpeaker {
61 typedef struct SOFAlizerContext {
64 char *filename; /* name of SOFA file */
65 MySofa sofa; /* contains data of the SOFA file */
67 int sample_rate; /* sample rate from SOFA file */
68 float *speaker_azim; /* azimuth of the virtual loudspeakers */
69 float *speaker_elev; /* elevation of the virtual loudspeakers */
70 char *speakers_pos; /* custom positions of the virtual loudspeakers */
71 float lfe_gain; /* initial gain for the LFE channel */
72 float gain_lfe; /* gain applied to LFE channel */
73 int lfe_channel; /* LFE channel position in channel layout */
75 int n_conv; /* number of channels to convolute */
77 /* buffer variables (for convolution) */
78 float *ringbuffer[2]; /* buffers input samples, length of one buffer: */
79 /* no. input ch. (incl. LFE) x buffer_length */
80 int write[2]; /* current write position to ringbuffer */
81 int buffer_length; /* is: longest IR plus max. delay in all SOFA files */
82 /* then choose next power of 2 */
83 int n_fft; /* number of samples in one FFT block */
85 /* netCDF variables */
86 int *delay[2]; /* broadband delay for each channel/IR to be convolved */
88 float *data_ir[2]; /* IRs for all channels to be convolved */
89 /* (this excludes the LFE) */
91 FFTComplex *temp_fft[2];
93 /* control variables */
94 float gain; /* filter gain (in dB) */
95 float rotation; /* rotation of virtual loudspeakers (in degrees) */
96 float elevation; /* elevation of virtual loudspeakers (in deg.) */
97 float radius; /* distance virtual loudspeakers to listener (in metres) */
98 int type; /* processing type */
99 int framesize; /* size of buffer */
100 int normalize; /* should all IRs be normalized upon import ? */
101 int interpolate; /* should wanted IRs be interpolated from neighbors ? */
102 int minphase; /* should all IRs be minphased upon import ? */
103 float anglestep; /* neighbor search angle step, in agles */
104 float radstep; /* neighbor search radius step, in meters */
106 VirtualSpeaker vspkrpos[64];
108 FFTContext *fft[2], *ifft[2];
109 FFTComplex *data_hrtf[2];
111 AVFloatDSPContext *fdsp;
114 static int close_sofa(struct MySofa *sofa)
116 if (sofa->neighborhood)
117 mysofa_neighborhood_free(sofa->neighborhood);
118 sofa->neighborhood = NULL;
120 mysofa_lookup_free(sofa->lookup);
123 mysofa_free(sofa->hrtf);
125 av_freep(&sofa->fir);
130 static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
132 struct SOFAlizerContext *s = ctx->priv;
133 struct MYSOFA_HRTF *mysofa;
137 mysofa = mysofa_load(filename, &ret);
138 s->sofa.hrtf = mysofa;
139 if (ret || !mysofa) {
140 av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
141 return AVERROR(EINVAL);
144 ret = mysofa_check(mysofa);
145 if (ret != MYSOFA_OK) {
146 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
151 mysofa_loudness(s->sofa.hrtf);
154 mysofa_minphase(s->sofa.hrtf, 0.01);
156 mysofa_tocartesian(s->sofa.hrtf);
158 s->sofa.lookup = mysofa_lookup_init(s->sofa.hrtf);
159 if (s->sofa.lookup == NULL)
160 return AVERROR(EINVAL);
163 s->sofa.neighborhood = mysofa_neighborhood_init_withstepdefine(s->sofa.hrtf,
168 s->sofa.fir = av_calloc(s->sofa.hrtf->N * s->sofa.hrtf->R, sizeof(*s->sofa.fir));
170 return AVERROR(ENOMEM);
172 if (mysofa->DataSamplingRate.elements != 1)
173 return AVERROR(EINVAL);
174 av_log(ctx, AV_LOG_DEBUG, "Original IR length: %d.\n", mysofa->N);
175 *samplingrate = mysofa->DataSamplingRate.values[0];
176 license = mysofa_getAttribute(mysofa->attributes, (char *)"License");
178 av_log(ctx, AV_LOG_INFO, "SOFA license: %s\n", license);
183 static int parse_channel_name(char **arg, int *rchannel, char *buf)
185 int len, i, channel_id = 0;
186 int64_t layout, layout0;
188 /* try to parse a channel name, e.g. "FL" */
189 if (av_sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
190 layout0 = layout = av_get_channel_layout(buf);
191 /* channel_id <- first set bit in layout */
192 for (i = 32; i > 0; i >>= 1) {
193 if (layout >= 1LL << i) {
198 /* reject layouts that are not a single channel */
199 if (channel_id >= 64 || layout0 != 1LL << channel_id)
200 return AVERROR(EINVAL);
201 *rchannel = channel_id;
205 return AVERROR(EINVAL);
208 static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
210 SOFAlizerContext *s = ctx->priv;
211 char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
217 while ((arg = av_strtok(p, "|", &tokenizer))) {
223 if (parse_channel_name(&arg, &out_ch_id, buf)) {
224 av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
227 if (av_sscanf(arg, "%f %f", &azim, &elev) == 2) {
228 s->vspkrpos[out_ch_id].set = 1;
229 s->vspkrpos[out_ch_id].azim = azim;
230 s->vspkrpos[out_ch_id].elev = elev;
231 } else if (av_sscanf(arg, "%f", &azim) == 1) {
232 s->vspkrpos[out_ch_id].set = 1;
233 s->vspkrpos[out_ch_id].azim = azim;
234 s->vspkrpos[out_ch_id].elev = 0;
241 static int get_speaker_pos(AVFilterContext *ctx,
242 float *speaker_azim, float *speaker_elev)
244 struct SOFAlizerContext *s = ctx->priv;
245 uint64_t channels_layout = ctx->inputs[0]->channel_layout;
246 float azim[16] = { 0 };
247 float elev[16] = { 0 };
248 int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
251 return AVERROR(EINVAL);
256 parse_speaker_pos(ctx, channels_layout);
258 /* set speaker positions according to input channel configuration: */
259 for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
260 uint64_t mask = channels_layout & (1ULL << m);
263 case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
264 case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
265 case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
266 case AV_CH_LOW_FREQUENCY:
267 case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
268 case AV_CH_BACK_LEFT: azim[ch] = 150; break;
269 case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
270 case AV_CH_BACK_CENTER: azim[ch] = 180; break;
271 case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
272 case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
273 case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
274 case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
275 case AV_CH_TOP_CENTER: azim[ch] = 0;
276 elev[ch] = 90; break;
277 case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
278 elev[ch] = 45; break;
279 case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
280 elev[ch] = 45; break;
281 case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
282 elev[ch] = 45; break;
283 case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
284 elev[ch] = 45; break;
285 case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
286 elev[ch] = 45; break;
287 case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
288 elev[ch] = 45; break;
289 case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
290 case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
291 case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
292 case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
293 case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
294 case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
297 return AVERROR(EINVAL);
300 if (s->vspkrpos[m].set) {
301 azim[ch] = s->vspkrpos[m].azim;
302 elev[ch] = s->vspkrpos[m].elev;
309 memcpy(speaker_azim, azim, n_conv * sizeof(float));
310 memcpy(speaker_elev, elev, n_conv * sizeof(float));
316 typedef struct ThreadData {
324 FFTComplex **temp_fft;
327 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
329 SOFAlizerContext *s = ctx->priv;
330 ThreadData *td = arg;
331 AVFrame *in = td->in, *out = td->out;
333 int *write = &td->write[jobnr];
334 const int *const delay = td->delay[jobnr];
335 const float *const ir = td->ir[jobnr];
336 int *n_clippings = &td->n_clippings[jobnr];
337 float *ringbuffer = td->ringbuffer[jobnr];
338 float *temp_src = td->temp_src[jobnr];
339 const int ir_samples = s->sofa.ir_samples; /* length of one IR */
340 const int n_samples = s->sofa.n_samples;
341 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
342 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
343 const int in_channels = s->n_conv; /* number of input channels */
344 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
345 const int buffer_length = s->buffer_length;
346 /* -1 for AND instead of MODULO (applied to powers of 2): */
347 const uint32_t modulo = (uint32_t)buffer_length - 1;
348 float *buffer[16]; /* holds ringbuffer for each input channel */
354 for (l = 0; l < in_channels; l++) {
355 /* get starting address of ringbuffer for each input channel */
356 buffer[l] = ringbuffer + l * buffer_length;
359 for (i = 0; i < in->nb_samples; i++) {
360 const float *temp_ir = ir; /* using same set of IRs for each sample */
363 for (l = 0; l < in_channels; l++) {
364 /* write current input sample to ringbuffer (for each channel) */
365 buffer[l][wr] = src[l];
368 /* loop goes through all channels to be convolved */
369 for (l = 0; l < in_channels; l++) {
370 const float *const bptr = buffer[l];
372 if (l == s->lfe_channel) {
373 /* LFE is an input channel but requires no convolution */
374 /* apply gain to LFE signal and add to output buffer */
375 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
376 temp_ir += n_samples;
380 /* current read position in ringbuffer: input sample write position
381 * - delay for l-th ch. + diff. betw. IR length and buffer length
382 * (mod buffer length) */
383 read = (wr - delay[l] - (n_samples - 1) + buffer_length) & modulo;
385 if (read + n_samples < buffer_length) {
386 memmove(temp_src, bptr + read, n_samples * sizeof(*temp_src));
388 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
390 memmove(temp_src, bptr + read, len * sizeof(*temp_src));
391 memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
394 /* multiply signal and IR, and add up the results */
395 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, FFALIGN(ir_samples, 32));
396 temp_ir += n_samples;
399 /* clippings counter */
400 if (fabsf(dst[0]) > 1)
403 /* move output buffer pointer by +2 to get to next sample of processed channel: */
406 wr = (wr + 1) & modulo; /* update ringbuffer write position */
409 *write = wr; /* remember write position in ringbuffer for next call */
414 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
416 SOFAlizerContext *s = ctx->priv;
417 ThreadData *td = arg;
418 AVFrame *in = td->in, *out = td->out;
420 int *write = &td->write[jobnr];
421 FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
422 int *n_clippings = &td->n_clippings[jobnr];
423 float *ringbuffer = td->ringbuffer[jobnr];
424 const int n_samples = s->sofa.n_samples; /* length of one IR */
425 const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
426 float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
427 const int in_channels = s->n_conv; /* number of input channels */
428 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
429 const int buffer_length = s->buffer_length;
430 /* -1 for AND instead of MODULO (applied to powers of 2): */
431 const uint32_t modulo = (uint32_t)buffer_length - 1;
432 FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
433 FFTContext *ifft = s->ifft[jobnr];
434 FFTContext *fft = s->fft[jobnr];
435 const int n_conv = s->n_conv;
436 const int n_fft = s->n_fft;
437 const float fft_scale = 1.0f / s->n_fft;
438 FFTComplex *hrtf_offset;
445 /* find minimum between number of samples and output buffer length:
446 * (important, if one IR is longer than the output buffer) */
447 n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
448 for (j = 0; j < n_read; j++) {
449 /* initialize output buf with saved signal from overflow buf */
450 dst[2 * j] = ringbuffer[wr];
451 ringbuffer[wr] = 0.0; /* re-set read samples to zero */
452 /* update ringbuffer read/write position */
453 wr = (wr + 1) & modulo;
456 /* initialize rest of output buffer with 0 */
457 for (j = n_read; j < in->nb_samples; j++) {
461 for (i = 0; i < n_conv; i++) {
462 if (i == s->lfe_channel) { /* LFE */
463 for (j = 0; j < in->nb_samples; j++) {
464 /* apply gain to LFE signal and add to output buffer */
465 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
470 /* outer loop: go through all input channels to be convolved */
471 offset = i * n_fft; /* no. samples already processed */
472 hrtf_offset = hrtf + offset;
474 /* fill FFT input with 0 (we want to zero-pad) */
475 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
477 for (j = 0; j < in->nb_samples; j++) {
478 /* prepare input for FFT */
479 /* write all samples of current input channel to FFT input array */
480 fft_in[j].re = src[j * in_channels + i];
483 /* transform input signal of current channel to frequency domain */
484 av_fft_permute(fft, fft_in);
485 av_fft_calc(fft, fft_in);
486 for (j = 0; j < n_fft; j++) {
487 const FFTComplex *hcomplex = hrtf_offset + j;
488 const float re = fft_in[j].re;
489 const float im = fft_in[j].im;
491 /* complex multiplication of input signal and HRTFs */
492 /* output channel (real): */
493 fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
494 /* output channel (imag): */
495 fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
498 /* transform output signal of current channel back to time domain */
499 av_fft_permute(ifft, fft_in);
500 av_fft_calc(ifft, fft_in);
502 for (j = 0; j < in->nb_samples; j++) {
503 /* write output signal of current channel to output buffer */
504 dst[2 * j] += fft_in[j].re * fft_scale;
507 for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
508 /* write the rest of output signal to overflow buffer */
509 int write_pos = (wr + j) & modulo;
511 *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
515 /* go through all samples of current output buffer: count clippings */
516 for (i = 0; i < out->nb_samples; i++) {
517 /* clippings counter */
518 if (fabsf(dst[0]) > 1) { /* if current output sample > 1 */
522 /* move output buffer pointer by +2 to get to next sample of processed channel: */
526 /* remember read/write position in ringbuffer for next call */
532 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
534 AVFilterContext *ctx = inlink->dst;
535 SOFAlizerContext *s = ctx->priv;
536 AVFilterLink *outlink = ctx->outputs[0];
537 int n_clippings[2] = { 0 };
541 out = ff_get_audio_buffer(outlink, in->nb_samples);
544 return AVERROR(ENOMEM);
546 av_frame_copy_props(out, in);
548 td.in = in; td.out = out; td.write = s->write;
549 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
550 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
551 td.temp_fft = s->temp_fft;
553 if (s->type == TIME_DOMAIN) {
554 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
556 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
560 /* display error message if clipping occurred */
561 if (n_clippings[0] + n_clippings[1] > 0) {
562 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
563 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
567 return ff_filter_frame(outlink, out);
570 static int query_formats(AVFilterContext *ctx)
572 struct SOFAlizerContext *s = ctx->priv;
573 AVFilterFormats *formats = NULL;
574 AVFilterChannelLayouts *layouts = NULL;
575 int ret, sample_rates[] = { 48000, -1 };
577 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
580 ret = ff_set_common_formats(ctx, formats);
584 layouts = ff_all_channel_layouts();
586 return AVERROR(ENOMEM);
588 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
593 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
597 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
601 sample_rates[0] = s->sample_rate;
602 formats = ff_make_format_list(sample_rates);
604 return AVERROR(ENOMEM);
605 return ff_set_common_samplerates(ctx, formats);
608 static int getfilter_float(AVFilterContext *ctx, float x, float y, float z,
609 float *left, float *right,
610 float *delay_left, float *delay_right)
612 struct SOFAlizerContext *s = ctx->priv;
613 float c[3], delays[2];
619 c[0] = x, c[1] = y, c[2] = z;
620 nearest = mysofa_lookup(s->sofa.lookup, c);
622 return AVERROR(EINVAL);
624 if (s->interpolate) {
625 neighbors = mysofa_neighborhood(s->sofa.neighborhood, nearest);
626 res = mysofa_interpolate(s->sofa.hrtf, c,
628 s->sofa.fir, delays);
630 res = s->sofa.hrtf->DataIR.values + nearest * s->sofa.hrtf->N * s->sofa.hrtf->R;
633 *delay_left = delays[0];
634 *delay_right = delays[1];
637 fr = res + s->sofa.hrtf->N;
639 memcpy(left, fl, sizeof(float) * s->sofa.hrtf->N);
640 memcpy(right, fr, sizeof(float) * s->sofa.hrtf->N);
645 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
647 struct SOFAlizerContext *s = ctx->priv;
650 int n_conv = s->n_conv; /* no. channels to convolve */
652 float delay_l; /* broadband delay for each IR */
654 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
655 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
656 FFTComplex *data_hrtf_l = NULL;
657 FFTComplex *data_hrtf_r = NULL;
658 FFTComplex *fft_in_l = NULL;
659 FFTComplex *fft_in_r = NULL;
660 float *data_ir_l = NULL;
661 float *data_ir_r = NULL;
662 int offset = 0; /* used for faster pointer arithmetics in for-loop */
663 int i, j, azim_orig = azim, elev_orig = elev;
668 av_log(ctx, AV_LOG_DEBUG, "IR length: %d.\n", s->sofa.hrtf->N);
669 s->sofa.ir_samples = s->sofa.hrtf->N;
670 s->sofa.n_samples = 1 << (32 - ff_clz(s->sofa.ir_samples));
672 n_samples = s->sofa.n_samples;
673 ir_samples = s->sofa.ir_samples;
675 s->data_ir[0] = av_calloc(n_samples, sizeof(float) * s->n_conv);
676 s->data_ir[1] = av_calloc(n_samples, sizeof(float) * s->n_conv);
677 s->delay[0] = av_calloc(s->n_conv, sizeof(int));
678 s->delay[1] = av_calloc(s->n_conv, sizeof(int));
680 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
681 ret = AVERROR(ENOMEM);
685 /* get temporary IR for L and R channel */
686 data_ir_l = av_calloc(n_conv * n_samples, sizeof(*data_ir_l));
687 data_ir_r = av_calloc(n_conv * n_samples, sizeof(*data_ir_r));
688 if (!data_ir_r || !data_ir_l) {
689 ret = AVERROR(ENOMEM);
693 if (s->type == TIME_DOMAIN) {
694 s->temp_src[0] = av_calloc(n_samples, sizeof(float));
695 s->temp_src[1] = av_calloc(n_samples, sizeof(float));
696 if (!s->temp_src[0] || !s->temp_src[1]) {
697 ret = AVERROR(ENOMEM);
702 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
703 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
704 if (!s->speaker_azim || !s->speaker_elev) {
705 ret = AVERROR(ENOMEM);
709 /* get speaker positions */
710 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
711 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
715 for (i = 0; i < s->n_conv; i++) {
716 float coordinates[3];
718 /* load and store IRs and corresponding delays */
719 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
720 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
722 coordinates[0] = azim;
723 coordinates[1] = elev;
724 coordinates[2] = radius;
726 mysofa_s2c(coordinates);
728 /* get id of IR closest to desired position */
729 ret = getfilter_float(ctx, coordinates[0], coordinates[1], coordinates[2],
730 data_ir_l + n_samples * i,
731 data_ir_r + n_samples * i,
736 s->delay[0][i] = delay_l * sample_rate;
737 s->delay[1][i] = delay_r * sample_rate;
739 s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
742 /* get size of ringbuffer (longest IR plus max. delay) */
743 /* then choose next power of 2 for performance optimization */
744 n_current = n_samples + s->sofa.max_delay;
745 /* length of longest IR plus max. delay */
746 n_max = FFMAX(n_max, n_current);
748 /* buffer length is longest IR plus max. delay -> next power of 2
749 (32 - count leading zeros gives required exponent) */
750 s->buffer_length = 1 << (32 - ff_clz(n_max));
751 s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
753 if (s->type == FREQUENCY_DOMAIN) {
754 av_fft_end(s->fft[0]);
755 av_fft_end(s->fft[1]);
756 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
757 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
758 av_fft_end(s->ifft[0]);
759 av_fft_end(s->ifft[1]);
760 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
761 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
763 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
764 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
765 ret = AVERROR(ENOMEM);
770 if (s->type == TIME_DOMAIN) {
771 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
772 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
774 /* get temporary HRTF memory for L and R channel */
775 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
776 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
777 if (!data_hrtf_r || !data_hrtf_l) {
778 ret = AVERROR(ENOMEM);
782 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
783 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
784 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
785 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
786 if (!s->temp_fft[0] || !s->temp_fft[1]) {
787 ret = AVERROR(ENOMEM);
792 if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
793 ret = AVERROR(ENOMEM);
797 if (s->type == FREQUENCY_DOMAIN) {
798 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
799 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
800 if (!fft_in_l || !fft_in_r) {
801 ret = AVERROR(ENOMEM);
806 for (i = 0; i < s->n_conv; i++) {
809 offset = i * n_samples; /* no. samples already written */
811 lir = data_ir_l + offset;
812 rir = data_ir_r + offset;
814 if (s->type == TIME_DOMAIN) {
815 for (j = 0; j < ir_samples; j++) {
816 /* load reversed IRs of the specified source position
817 * sample-by-sample for left and right ear; and apply gain */
818 s->data_ir[0][offset + j] = lir[ir_samples - 1 - j] * gain_lin;
819 s->data_ir[1][offset + j] = rir[ir_samples - 1 - j] * gain_lin;
822 memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
823 memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
825 offset = i * n_fft; /* no. samples already written */
826 for (j = 0; j < ir_samples; j++) {
827 /* load non-reversed IRs of the specified source position
828 * sample-by-sample and apply gain,
829 * L channel is loaded to real part, R channel to imag part,
830 * IRs ared shifted by L and R delay */
831 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
832 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
835 /* actually transform to frequency domain (IRs -> HRTFs) */
836 av_fft_permute(s->fft[0], fft_in_l);
837 av_fft_calc(s->fft[0], fft_in_l);
838 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
839 av_fft_permute(s->fft[0], fft_in_r);
840 av_fft_calc(s->fft[0], fft_in_r);
841 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
845 if (s->type == FREQUENCY_DOMAIN) {
846 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
847 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
848 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
849 ret = AVERROR(ENOMEM);
853 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
854 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
855 memcpy(s->data_hrtf[1], data_hrtf_r,
856 sizeof(FFTComplex) * n_conv * n_fft);
860 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
861 av_freep(&data_hrtf_r);
863 av_freep(&data_ir_l); /* free temprary IR memory */
864 av_freep(&data_ir_r);
866 av_freep(&fft_in_l); /* free temporary FFT memory */
872 static av_cold int init(AVFilterContext *ctx)
874 SOFAlizerContext *s = ctx->priv;
878 av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
879 return AVERROR(EINVAL);
882 /* preload SOFA file, */
883 ret = preload_sofa(ctx, s->filename, &s->sample_rate);
885 /* file loading error */
886 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
887 } else { /* no file loading error, resampling not required */
888 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
892 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
896 s->fdsp = avpriv_float_dsp_alloc(0);
898 return AVERROR(ENOMEM);
903 static int config_input(AVFilterLink *inlink)
905 AVFilterContext *ctx = inlink->dst;
906 SOFAlizerContext *s = ctx->priv;
909 if (s->type == FREQUENCY_DOMAIN) {
910 inlink->partial_buf_size =
911 inlink->min_samples =
912 inlink->max_samples = s->framesize;
915 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
916 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
918 s->n_conv = inlink->channels;
920 /* load IRs to data_ir[0] and data_ir[1] for required directions */
921 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
924 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
925 inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
930 static av_cold void uninit(AVFilterContext *ctx)
932 SOFAlizerContext *s = ctx->priv;
934 close_sofa(&s->sofa);
935 av_fft_end(s->ifft[0]);
936 av_fft_end(s->ifft[1]);
937 av_fft_end(s->fft[0]);
938 av_fft_end(s->fft[1]);
943 av_freep(&s->delay[0]);
944 av_freep(&s->delay[1]);
945 av_freep(&s->data_ir[0]);
946 av_freep(&s->data_ir[1]);
947 av_freep(&s->ringbuffer[0]);
948 av_freep(&s->ringbuffer[1]);
949 av_freep(&s->speaker_azim);
950 av_freep(&s->speaker_elev);
951 av_freep(&s->temp_src[0]);
952 av_freep(&s->temp_src[1]);
953 av_freep(&s->temp_fft[0]);
954 av_freep(&s->temp_fft[1]);
955 av_freep(&s->data_hrtf[0]);
956 av_freep(&s->data_hrtf[1]);
960 #define OFFSET(x) offsetof(SOFAlizerContext, x)
961 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
963 static const AVOption sofalizer_options[] = {
964 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
965 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
966 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
967 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
968 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 5, .flags = FLAGS },
969 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
970 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
971 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
972 { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
973 { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20,40, .flags = FLAGS },
974 { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT, {.i64=1024},1024,96000, .flags = FLAGS },
975 { "normalize", "normalize IRs", OFFSET(normalize), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, .flags = FLAGS },
976 { "interpolate","interpolate IRs from neighbors", OFFSET(interpolate),AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
977 { "minphase", "minphase IRs", OFFSET(minphase), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
978 { "anglestep", "set neighbor search angle step", OFFSET(anglestep), AV_OPT_TYPE_FLOAT, {.dbl=.5}, 0.01, 10, .flags = FLAGS },
979 { "radstep", "set neighbor search radius step", OFFSET(radstep), AV_OPT_TYPE_FLOAT, {.dbl=.01}, 0.01, 1, .flags = FLAGS },
983 AVFILTER_DEFINE_CLASS(sofalizer);
985 static const AVFilterPad inputs[] = {
988 .type = AVMEDIA_TYPE_AUDIO,
989 .config_props = config_input,
990 .filter_frame = filter_frame,
995 static const AVFilterPad outputs[] = {
998 .type = AVMEDIA_TYPE_AUDIO,
1003 AVFilter ff_af_sofalizer = {
1004 .name = "sofalizer",
1005 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1006 .priv_size = sizeof(SOFAlizerContext),
1007 .priv_class = &sofalizer_class,
1010 .query_formats = query_formats,
1013 .flags = AVFILTER_FLAG_SLICE_THREADS,