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 if (s->sofa.hrtf->DataDelay.elements > s->sofa.hrtf->R) {
631 delays[0] = s->sofa.hrtf->DataDelay.values[nearest * s->sofa.hrtf->R];
632 delays[1] = s->sofa.hrtf->DataDelay.values[nearest * s->sofa.hrtf->R + 1];
634 delays[0] = s->sofa.hrtf->DataDelay.values[0];
635 delays[1] = s->sofa.hrtf->DataDelay.values[1];
637 res = s->sofa.hrtf->DataIR.values + nearest * s->sofa.hrtf->N * s->sofa.hrtf->R;
640 *delay_left = delays[0];
641 *delay_right = delays[1];
644 fr = res + s->sofa.hrtf->N;
646 memcpy(left, fl, sizeof(float) * s->sofa.hrtf->N);
647 memcpy(right, fr, sizeof(float) * s->sofa.hrtf->N);
652 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
654 struct SOFAlizerContext *s = ctx->priv;
657 int n_conv = s->n_conv; /* no. channels to convolve */
659 float delay_l; /* broadband delay for each IR */
661 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
662 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
663 FFTComplex *data_hrtf_l = NULL;
664 FFTComplex *data_hrtf_r = NULL;
665 FFTComplex *fft_in_l = NULL;
666 FFTComplex *fft_in_r = NULL;
667 float *data_ir_l = NULL;
668 float *data_ir_r = NULL;
669 int offset = 0; /* used for faster pointer arithmetics in for-loop */
670 int i, j, azim_orig = azim, elev_orig = elev;
675 av_log(ctx, AV_LOG_DEBUG, "IR length: %d.\n", s->sofa.hrtf->N);
676 s->sofa.ir_samples = s->sofa.hrtf->N;
677 s->sofa.n_samples = 1 << (32 - ff_clz(s->sofa.ir_samples));
679 n_samples = s->sofa.n_samples;
680 ir_samples = s->sofa.ir_samples;
682 s->data_ir[0] = av_calloc(n_samples, sizeof(float) * s->n_conv);
683 s->data_ir[1] = av_calloc(n_samples, sizeof(float) * s->n_conv);
684 s->delay[0] = av_calloc(s->n_conv, sizeof(int));
685 s->delay[1] = av_calloc(s->n_conv, sizeof(int));
687 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
688 ret = AVERROR(ENOMEM);
692 /* get temporary IR for L and R channel */
693 data_ir_l = av_calloc(n_conv * n_samples, sizeof(*data_ir_l));
694 data_ir_r = av_calloc(n_conv * n_samples, sizeof(*data_ir_r));
695 if (!data_ir_r || !data_ir_l) {
696 ret = AVERROR(ENOMEM);
700 if (s->type == TIME_DOMAIN) {
701 s->temp_src[0] = av_calloc(n_samples, sizeof(float));
702 s->temp_src[1] = av_calloc(n_samples, sizeof(float));
703 if (!s->temp_src[0] || !s->temp_src[1]) {
704 ret = AVERROR(ENOMEM);
709 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
710 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
711 if (!s->speaker_azim || !s->speaker_elev) {
712 ret = AVERROR(ENOMEM);
716 /* get speaker positions */
717 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
718 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
722 for (i = 0; i < s->n_conv; i++) {
723 float coordinates[3];
725 /* load and store IRs and corresponding delays */
726 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
727 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
729 coordinates[0] = azim;
730 coordinates[1] = elev;
731 coordinates[2] = radius;
733 mysofa_s2c(coordinates);
735 /* get id of IR closest to desired position */
736 ret = getfilter_float(ctx, coordinates[0], coordinates[1], coordinates[2],
737 data_ir_l + n_samples * i,
738 data_ir_r + n_samples * i,
743 s->delay[0][i] = delay_l * sample_rate;
744 s->delay[1][i] = delay_r * sample_rate;
746 s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
749 /* get size of ringbuffer (longest IR plus max. delay) */
750 /* then choose next power of 2 for performance optimization */
751 n_current = n_samples + s->sofa.max_delay;
752 /* length of longest IR plus max. delay */
753 n_max = FFMAX(n_max, n_current);
755 /* buffer length is longest IR plus max. delay -> next power of 2
756 (32 - count leading zeros gives required exponent) */
757 s->buffer_length = 1 << (32 - ff_clz(n_max));
758 s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
760 if (s->type == FREQUENCY_DOMAIN) {
761 av_fft_end(s->fft[0]);
762 av_fft_end(s->fft[1]);
763 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
764 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
765 av_fft_end(s->ifft[0]);
766 av_fft_end(s->ifft[1]);
767 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
768 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
770 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
771 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
772 ret = AVERROR(ENOMEM);
777 if (s->type == TIME_DOMAIN) {
778 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
779 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
781 /* get temporary HRTF memory for L and R channel */
782 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
783 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
784 if (!data_hrtf_r || !data_hrtf_l) {
785 ret = AVERROR(ENOMEM);
789 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
790 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
791 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
792 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
793 if (!s->temp_fft[0] || !s->temp_fft[1]) {
794 ret = AVERROR(ENOMEM);
799 if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
800 ret = AVERROR(ENOMEM);
804 if (s->type == FREQUENCY_DOMAIN) {
805 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
806 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
807 if (!fft_in_l || !fft_in_r) {
808 ret = AVERROR(ENOMEM);
813 for (i = 0; i < s->n_conv; i++) {
816 offset = i * n_samples; /* no. samples already written */
818 lir = data_ir_l + offset;
819 rir = data_ir_r + offset;
821 if (s->type == TIME_DOMAIN) {
822 for (j = 0; j < ir_samples; j++) {
823 /* load reversed IRs of the specified source position
824 * sample-by-sample for left and right ear; and apply gain */
825 s->data_ir[0][offset + j] = lir[ir_samples - 1 - j] * gain_lin;
826 s->data_ir[1][offset + j] = rir[ir_samples - 1 - j] * gain_lin;
829 memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
830 memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
832 offset = i * n_fft; /* no. samples already written */
833 for (j = 0; j < ir_samples; j++) {
834 /* load non-reversed IRs of the specified source position
835 * sample-by-sample and apply gain,
836 * L channel is loaded to real part, R channel to imag part,
837 * IRs ared shifted by L and R delay */
838 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
839 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
842 /* actually transform to frequency domain (IRs -> HRTFs) */
843 av_fft_permute(s->fft[0], fft_in_l);
844 av_fft_calc(s->fft[0], fft_in_l);
845 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
846 av_fft_permute(s->fft[0], fft_in_r);
847 av_fft_calc(s->fft[0], fft_in_r);
848 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
852 if (s->type == FREQUENCY_DOMAIN) {
853 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
854 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
855 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
856 ret = AVERROR(ENOMEM);
860 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
861 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
862 memcpy(s->data_hrtf[1], data_hrtf_r,
863 sizeof(FFTComplex) * n_conv * n_fft);
867 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
868 av_freep(&data_hrtf_r);
870 av_freep(&data_ir_l); /* free temprary IR memory */
871 av_freep(&data_ir_r);
873 av_freep(&fft_in_l); /* free temporary FFT memory */
879 static av_cold int init(AVFilterContext *ctx)
881 SOFAlizerContext *s = ctx->priv;
885 av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
886 return AVERROR(EINVAL);
889 /* preload SOFA file, */
890 ret = preload_sofa(ctx, s->filename, &s->sample_rate);
892 /* file loading error */
893 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
894 } else { /* no file loading error, resampling not required */
895 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
899 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
903 s->fdsp = avpriv_float_dsp_alloc(0);
905 return AVERROR(ENOMEM);
910 static int config_input(AVFilterLink *inlink)
912 AVFilterContext *ctx = inlink->dst;
913 SOFAlizerContext *s = ctx->priv;
916 if (s->type == FREQUENCY_DOMAIN) {
917 inlink->partial_buf_size =
918 inlink->min_samples =
919 inlink->max_samples = s->framesize;
922 /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
923 s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
925 s->n_conv = inlink->channels;
927 /* load IRs to data_ir[0] and data_ir[1] for required directions */
928 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
931 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
932 inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
937 static av_cold void uninit(AVFilterContext *ctx)
939 SOFAlizerContext *s = ctx->priv;
941 close_sofa(&s->sofa);
942 av_fft_end(s->ifft[0]);
943 av_fft_end(s->ifft[1]);
944 av_fft_end(s->fft[0]);
945 av_fft_end(s->fft[1]);
950 av_freep(&s->delay[0]);
951 av_freep(&s->delay[1]);
952 av_freep(&s->data_ir[0]);
953 av_freep(&s->data_ir[1]);
954 av_freep(&s->ringbuffer[0]);
955 av_freep(&s->ringbuffer[1]);
956 av_freep(&s->speaker_azim);
957 av_freep(&s->speaker_elev);
958 av_freep(&s->temp_src[0]);
959 av_freep(&s->temp_src[1]);
960 av_freep(&s->temp_fft[0]);
961 av_freep(&s->temp_fft[1]);
962 av_freep(&s->data_hrtf[0]);
963 av_freep(&s->data_hrtf[1]);
967 #define OFFSET(x) offsetof(SOFAlizerContext, x)
968 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
970 static const AVOption sofalizer_options[] = {
971 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
972 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
973 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
974 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
975 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 5, .flags = FLAGS },
976 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
977 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
978 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
979 { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
980 { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20,40, .flags = FLAGS },
981 { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT, {.i64=1024},1024,96000, .flags = FLAGS },
982 { "normalize", "normalize IRs", OFFSET(normalize), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, .flags = FLAGS },
983 { "interpolate","interpolate IRs from neighbors", OFFSET(interpolate),AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
984 { "minphase", "minphase IRs", OFFSET(minphase), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
985 { "anglestep", "set neighbor search angle step", OFFSET(anglestep), AV_OPT_TYPE_FLOAT, {.dbl=.5}, 0.01, 10, .flags = FLAGS },
986 { "radstep", "set neighbor search radius step", OFFSET(radstep), AV_OPT_TYPE_FLOAT, {.dbl=.01}, 0.01, 1, .flags = FLAGS },
990 AVFILTER_DEFINE_CLASS(sofalizer);
992 static const AVFilterPad inputs[] = {
995 .type = AVMEDIA_TYPE_AUDIO,
996 .config_props = config_input,
997 .filter_frame = filter_frame,
1002 static const AVFilterPad outputs[] = {
1005 .type = AVMEDIA_TYPE_AUDIO,
1010 AVFilter ff_af_sofalizer = {
1011 .name = "sofalizer",
1012 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1013 .priv_size = sizeof(SOFAlizerContext),
1014 .priv_class = &sofalizer_class,
1017 .query_formats = query_formats,
1020 .flags = AVFILTER_FLAG_SLICE_THREADS,