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]; /* Array to hold FFT values */
92 FFTComplex *temp_afft[2]; /* Array to accumulate FFT values prior to IFFT */
94 /* control variables */
95 float gain; /* filter gain (in dB) */
96 float rotation; /* rotation of virtual loudspeakers (in degrees) */
97 float elevation; /* elevation of virtual loudspeakers (in deg.) */
98 float radius; /* distance virtual loudspeakers to listener (in metres) */
99 int type; /* processing type */
100 int framesize; /* size of buffer */
101 int normalize; /* should all IRs be normalized upon import ? */
102 int interpolate; /* should wanted IRs be interpolated from neighbors ? */
103 int minphase; /* should all IRs be minphased upon import ? */
104 float anglestep; /* neighbor search angle step, in agles */
105 float radstep; /* neighbor search radius step, in meters */
107 VirtualSpeaker vspkrpos[64];
109 FFTContext *fft[2], *ifft[2];
110 FFTComplex *data_hrtf[2];
112 AVFloatDSPContext *fdsp;
115 static int close_sofa(struct MySofa *sofa)
117 if (sofa->neighborhood)
118 mysofa_neighborhood_free(sofa->neighborhood);
119 sofa->neighborhood = NULL;
121 mysofa_lookup_free(sofa->lookup);
124 mysofa_free(sofa->hrtf);
126 av_freep(&sofa->fir);
131 static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
133 struct SOFAlizerContext *s = ctx->priv;
134 struct MYSOFA_HRTF *mysofa;
138 mysofa = mysofa_load(filename, &ret);
139 s->sofa.hrtf = mysofa;
140 if (ret || !mysofa) {
141 av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
142 return AVERROR(EINVAL);
145 ret = mysofa_check(mysofa);
146 if (ret != MYSOFA_OK) {
147 av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
152 mysofa_loudness(s->sofa.hrtf);
155 mysofa_minphase(s->sofa.hrtf, 0.01f);
157 mysofa_tocartesian(s->sofa.hrtf);
159 s->sofa.lookup = mysofa_lookup_init(s->sofa.hrtf);
160 if (s->sofa.lookup == NULL)
161 return AVERROR(EINVAL);
164 s->sofa.neighborhood = mysofa_neighborhood_init_withstepdefine(s->sofa.hrtf,
169 s->sofa.fir = av_calloc(s->sofa.hrtf->N * s->sofa.hrtf->R, sizeof(*s->sofa.fir));
171 return AVERROR(ENOMEM);
173 if (mysofa->DataSamplingRate.elements != 1)
174 return AVERROR(EINVAL);
175 av_log(ctx, AV_LOG_DEBUG, "Original IR length: %d.\n", mysofa->N);
176 *samplingrate = mysofa->DataSamplingRate.values[0];
177 license = mysofa_getAttribute(mysofa->attributes, (char *)"License");
179 av_log(ctx, AV_LOG_INFO, "SOFA license: %s\n", license);
184 static int parse_channel_name(char **arg, int *rchannel, char *buf)
186 int len, i, channel_id = 0;
187 int64_t layout, layout0;
189 /* try to parse a channel name, e.g. "FL" */
190 if (av_sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
191 layout0 = layout = av_get_channel_layout(buf);
192 /* channel_id <- first set bit in layout */
193 for (i = 32; i > 0; i >>= 1) {
194 if (layout >= 1LL << i) {
199 /* reject layouts that are not a single channel */
200 if (channel_id >= 64 || layout0 != 1LL << channel_id)
201 return AVERROR(EINVAL);
202 *rchannel = channel_id;
206 return AVERROR(EINVAL);
209 static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
211 SOFAlizerContext *s = ctx->priv;
212 char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
218 while ((arg = av_strtok(p, "|", &tokenizer))) {
224 if (parse_channel_name(&arg, &out_ch_id, buf)) {
225 av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
228 if (av_sscanf(arg, "%f %f", &azim, &elev) == 2) {
229 s->vspkrpos[out_ch_id].set = 1;
230 s->vspkrpos[out_ch_id].azim = azim;
231 s->vspkrpos[out_ch_id].elev = elev;
232 } else if (av_sscanf(arg, "%f", &azim) == 1) {
233 s->vspkrpos[out_ch_id].set = 1;
234 s->vspkrpos[out_ch_id].azim = azim;
235 s->vspkrpos[out_ch_id].elev = 0;
242 static int get_speaker_pos(AVFilterContext *ctx,
243 float *speaker_azim, float *speaker_elev)
245 struct SOFAlizerContext *s = ctx->priv;
246 uint64_t channels_layout = ctx->inputs[0]->channel_layout;
247 float azim[16] = { 0 };
248 float elev[16] = { 0 };
249 int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
252 return AVERROR(EINVAL);
257 parse_speaker_pos(ctx, channels_layout);
259 /* set speaker positions according to input channel configuration: */
260 for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
261 uint64_t mask = channels_layout & (1ULL << m);
264 case AV_CH_FRONT_LEFT: azim[ch] = 30; break;
265 case AV_CH_FRONT_RIGHT: azim[ch] = 330; break;
266 case AV_CH_FRONT_CENTER: azim[ch] = 0; break;
267 case AV_CH_LOW_FREQUENCY:
268 case AV_CH_LOW_FREQUENCY_2: s->lfe_channel = ch; break;
269 case AV_CH_BACK_LEFT: azim[ch] = 150; break;
270 case AV_CH_BACK_RIGHT: azim[ch] = 210; break;
271 case AV_CH_BACK_CENTER: azim[ch] = 180; break;
272 case AV_CH_SIDE_LEFT: azim[ch] = 90; break;
273 case AV_CH_SIDE_RIGHT: azim[ch] = 270; break;
274 case AV_CH_FRONT_LEFT_OF_CENTER: azim[ch] = 15; break;
275 case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345; break;
276 case AV_CH_TOP_CENTER: azim[ch] = 0;
277 elev[ch] = 90; break;
278 case AV_CH_TOP_FRONT_LEFT: azim[ch] = 30;
279 elev[ch] = 45; break;
280 case AV_CH_TOP_FRONT_CENTER: azim[ch] = 0;
281 elev[ch] = 45; break;
282 case AV_CH_TOP_FRONT_RIGHT: azim[ch] = 330;
283 elev[ch] = 45; break;
284 case AV_CH_TOP_BACK_LEFT: azim[ch] = 150;
285 elev[ch] = 45; break;
286 case AV_CH_TOP_BACK_RIGHT: azim[ch] = 210;
287 elev[ch] = 45; break;
288 case AV_CH_TOP_BACK_CENTER: azim[ch] = 180;
289 elev[ch] = 45; break;
290 case AV_CH_WIDE_LEFT: azim[ch] = 90; break;
291 case AV_CH_WIDE_RIGHT: azim[ch] = 270; break;
292 case AV_CH_SURROUND_DIRECT_LEFT: azim[ch] = 90; break;
293 case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270; break;
294 case AV_CH_STEREO_LEFT: azim[ch] = 90; break;
295 case AV_CH_STEREO_RIGHT: azim[ch] = 270; break;
298 return AVERROR(EINVAL);
301 if (s->vspkrpos[m].set) {
302 azim[ch] = s->vspkrpos[m].azim;
303 elev[ch] = s->vspkrpos[m].elev;
310 memcpy(speaker_azim, azim, n_conv * sizeof(float));
311 memcpy(speaker_elev, elev, n_conv * sizeof(float));
317 typedef struct ThreadData {
325 FFTComplex **temp_fft;
326 FFTComplex **temp_afft;
329 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
331 SOFAlizerContext *s = ctx->priv;
332 ThreadData *td = arg;
333 AVFrame *in = td->in, *out = td->out;
335 int *write = &td->write[jobnr];
336 const int *const delay = td->delay[jobnr];
337 const float *const ir = td->ir[jobnr];
338 int *n_clippings = &td->n_clippings[jobnr];
339 float *ringbuffer = td->ringbuffer[jobnr];
340 float *temp_src = td->temp_src[jobnr];
341 const int ir_samples = s->sofa.ir_samples; /* length of one IR */
342 const int n_samples = s->sofa.n_samples;
343 const int planar = in->format == AV_SAMPLE_FMT_FLTP;
344 const int mult = 1 + !planar;
345 const float *src = (const float *)in->extended_data[0]; /* get pointer to audio input buffer */
346 float *dst = (float *)out->extended_data[jobnr * planar]; /* get pointer to audio output buffer */
347 const int in_channels = s->n_conv; /* number of input channels */
348 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
349 const int buffer_length = s->buffer_length;
350 /* -1 for AND instead of MODULO (applied to powers of 2): */
351 const uint32_t modulo = (uint32_t)buffer_length - 1;
352 float *buffer[16]; /* holds ringbuffer for each input channel */
360 for (l = 0; l < in_channels; l++) {
361 /* get starting address of ringbuffer for each input channel */
362 buffer[l] = ringbuffer + l * buffer_length;
365 for (i = 0; i < in->nb_samples; i++) {
366 const float *temp_ir = ir; /* using same set of IRs for each sample */
370 for (l = 0; l < in_channels; l++) {
371 const float *srcp = (const float *)in->extended_data[l];
373 /* write current input sample to ringbuffer (for each channel) */
374 buffer[l][wr] = srcp[i];
377 for (l = 0; l < in_channels; l++) {
378 /* write current input sample to ringbuffer (for each channel) */
379 buffer[l][wr] = src[l];
383 /* loop goes through all channels to be convolved */
384 for (l = 0; l < in_channels; l++) {
385 const float *const bptr = buffer[l];
387 if (l == s->lfe_channel) {
388 /* LFE is an input channel but requires no convolution */
389 /* apply gain to LFE signal and add to output buffer */
390 dst[0] += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
391 temp_ir += n_samples;
395 /* current read position in ringbuffer: input sample write position
396 * - delay for l-th ch. + diff. betw. IR length and buffer length
397 * (mod buffer length) */
398 read = (wr - delay[l] - (ir_samples - 1) + buffer_length) & modulo;
400 if (read + ir_samples < buffer_length) {
401 memmove(temp_src, bptr + read, ir_samples * sizeof(*temp_src));
403 int len = FFMIN(n_samples - (read % ir_samples), buffer_length - read);
405 memmove(temp_src, bptr + read, len * sizeof(*temp_src));
406 memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
409 /* multiply signal and IR, and add up the results */
410 dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, FFALIGN(ir_samples, 32));
411 temp_ir += n_samples;
414 /* clippings counter */
415 if (fabsf(dst[0]) > 1)
418 /* move output buffer pointer by +2 to get to next sample of processed channel: */
421 wr = (wr + 1) & modulo; /* update ringbuffer write position */
424 *write = wr; /* remember write position in ringbuffer for next call */
429 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
431 SOFAlizerContext *s = ctx->priv;
432 ThreadData *td = arg;
433 AVFrame *in = td->in, *out = td->out;
435 int *write = &td->write[jobnr];
436 FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
437 int *n_clippings = &td->n_clippings[jobnr];
438 float *ringbuffer = td->ringbuffer[jobnr];
439 const int ir_samples = s->sofa.ir_samples; /* length of one IR */
440 const int planar = in->format == AV_SAMPLE_FMT_FLTP;
441 const int mult = 1 + !planar;
442 float *dst = (float *)out->extended_data[jobnr * planar]; /* get pointer to audio output buffer */
443 const int in_channels = s->n_conv; /* number of input channels */
444 /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
445 const int buffer_length = s->buffer_length;
446 /* -1 for AND instead of MODULO (applied to powers of 2): */
447 const uint32_t modulo = (uint32_t)buffer_length - 1;
448 FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
449 FFTComplex *fft_acc = s->temp_afft[jobnr];
450 FFTContext *ifft = s->ifft[jobnr];
451 FFTContext *fft = s->fft[jobnr];
452 const int n_conv = s->n_conv;
453 const int n_fft = s->n_fft;
454 const float fft_scale = 1.0f / s->n_fft;
455 FFTComplex *hrtf_offset;
463 /* find minimum between number of samples and output buffer length:
464 * (important, if one IR is longer than the output buffer) */
465 n_read = FFMIN(ir_samples, in->nb_samples);
466 for (j = 0; j < n_read; j++) {
467 /* initialize output buf with saved signal from overflow buf */
468 dst[mult * j] = ringbuffer[wr];
469 ringbuffer[wr] = 0.0f; /* re-set read samples to zero */
470 /* update ringbuffer read/write position */
471 wr = (wr + 1) & modulo;
474 /* initialize rest of output buffer with 0 */
475 for (j = n_read; j < in->nb_samples; j++) {
479 /* fill FFT accumulation with 0 */
480 memset(fft_acc, 0, sizeof(FFTComplex) * n_fft);
482 for (i = 0; i < n_conv; i++) {
483 const float *src = (const float *)in->extended_data[i * planar]; /* get pointer to audio input buffer */
485 if (i == s->lfe_channel) { /* LFE */
486 if (in->format == AV_SAMPLE_FMT_FLT) {
487 for (j = 0; j < in->nb_samples; j++) {
488 /* apply gain to LFE signal and add to output buffer */
489 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
492 for (j = 0; j < in->nb_samples; j++) {
493 /* apply gain to LFE signal and add to output buffer */
494 dst[j] += src[j] * s->gain_lfe;
500 /* outer loop: go through all input channels to be convolved */
501 offset = i * n_fft; /* no. samples already processed */
502 hrtf_offset = hrtf + offset;
504 /* fill FFT input with 0 (we want to zero-pad) */
505 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
507 if (in->format == AV_SAMPLE_FMT_FLT) {
508 for (j = 0; j < in->nb_samples; j++) {
509 /* prepare input for FFT */
510 /* write all samples of current input channel to FFT input array */
511 fft_in[j].re = src[j * in_channels + i];
514 for (j = 0; j < in->nb_samples; j++) {
515 /* prepare input for FFT */
516 /* write all samples of current input channel to FFT input array */
517 fft_in[j].re = src[j];
521 /* transform input signal of current channel to frequency domain */
522 av_fft_permute(fft, fft_in);
523 av_fft_calc(fft, fft_in);
524 for (j = 0; j < n_fft; j++) {
525 const FFTComplex *hcomplex = hrtf_offset + j;
526 const float re = fft_in[j].re;
527 const float im = fft_in[j].im;
529 /* complex multiplication of input signal and HRTFs */
530 /* output channel (real): */
531 fft_acc[j].re += re * hcomplex->re - im * hcomplex->im;
532 /* output channel (imag): */
533 fft_acc[j].im += re * hcomplex->im + im * hcomplex->re;
537 /* transform output signal of current channel back to time domain */
538 av_fft_permute(ifft, fft_acc);
539 av_fft_calc(ifft, fft_acc);
541 for (j = 0; j < in->nb_samples; j++) {
542 /* write output signal of current channel to output buffer */
543 dst[mult * j] += fft_acc[j].re * fft_scale;
546 for (j = 0; j < ir_samples - 1; j++) { /* overflow length is IR length - 1 */
547 /* write the rest of output signal to overflow buffer */
548 int write_pos = (wr + j) & modulo;
550 *(ringbuffer + write_pos) += fft_acc[in->nb_samples + j].re * fft_scale;
553 /* go through all samples of current output buffer: count clippings */
554 for (i = 0; i < out->nb_samples; i++) {
555 /* clippings counter */
556 if (fabsf(dst[i * mult]) > 1) { /* if current output sample > 1 */
561 /* remember read/write position in ringbuffer for next call */
567 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
569 AVFilterContext *ctx = inlink->dst;
570 SOFAlizerContext *s = ctx->priv;
571 AVFilterLink *outlink = ctx->outputs[0];
572 int n_clippings[2] = { 0 };
576 out = ff_get_audio_buffer(outlink, in->nb_samples);
579 return AVERROR(ENOMEM);
581 av_frame_copy_props(out, in);
583 td.in = in; td.out = out; td.write = s->write;
584 td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
585 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
586 td.temp_fft = s->temp_fft;
587 td.temp_afft = s->temp_afft;
589 if (s->type == TIME_DOMAIN) {
590 ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
592 ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
596 /* display error message if clipping occurred */
597 if (n_clippings[0] + n_clippings[1] > 0) {
598 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
599 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
603 return ff_filter_frame(outlink, out);
606 static int query_formats(AVFilterContext *ctx)
608 struct SOFAlizerContext *s = ctx->priv;
609 AVFilterFormats *formats = NULL;
610 AVFilterChannelLayouts *layouts = NULL;
611 int ret, sample_rates[] = { 48000, -1 };
612 static const enum AVSampleFormat sample_fmts[] = {
613 AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLTP,
617 formats = ff_make_format_list(sample_fmts);
619 return AVERROR(ENOMEM);
620 ret = ff_set_common_formats(ctx, formats);
624 layouts = ff_all_channel_layouts();
626 return AVERROR(ENOMEM);
628 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
633 ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
637 ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
641 sample_rates[0] = s->sample_rate;
642 formats = ff_make_format_list(sample_rates);
644 return AVERROR(ENOMEM);
645 return ff_set_common_samplerates(ctx, formats);
648 static int getfilter_float(AVFilterContext *ctx, float x, float y, float z,
649 float *left, float *right,
650 float *delay_left, float *delay_right)
652 struct SOFAlizerContext *s = ctx->priv;
653 float c[3], delays[2];
659 c[0] = x, c[1] = y, c[2] = z;
660 nearest = mysofa_lookup(s->sofa.lookup, c);
662 return AVERROR(EINVAL);
664 if (s->interpolate) {
665 neighbors = mysofa_neighborhood(s->sofa.neighborhood, nearest);
666 res = mysofa_interpolate(s->sofa.hrtf, c,
668 s->sofa.fir, delays);
670 if (s->sofa.hrtf->DataDelay.elements > s->sofa.hrtf->R) {
671 delays[0] = s->sofa.hrtf->DataDelay.values[nearest * s->sofa.hrtf->R];
672 delays[1] = s->sofa.hrtf->DataDelay.values[nearest * s->sofa.hrtf->R + 1];
674 delays[0] = s->sofa.hrtf->DataDelay.values[0];
675 delays[1] = s->sofa.hrtf->DataDelay.values[1];
677 res = s->sofa.hrtf->DataIR.values + nearest * s->sofa.hrtf->N * s->sofa.hrtf->R;
680 *delay_left = delays[0];
681 *delay_right = delays[1];
684 fr = res + s->sofa.hrtf->N;
686 memcpy(left, fl, sizeof(float) * s->sofa.hrtf->N);
687 memcpy(right, fr, sizeof(float) * s->sofa.hrtf->N);
692 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
694 struct SOFAlizerContext *s = ctx->priv;
697 int n_conv = s->n_conv; /* no. channels to convolve */
699 float delay_l; /* broadband delay for each IR */
701 int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
702 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
703 FFTComplex *data_hrtf_l = NULL;
704 FFTComplex *data_hrtf_r = NULL;
705 FFTComplex *fft_in_l = NULL;
706 FFTComplex *fft_in_r = NULL;
707 float *data_ir_l = NULL;
708 float *data_ir_r = NULL;
709 int offset = 0; /* used for faster pointer arithmetics in for-loop */
710 int i, j, azim_orig = azim, elev_orig = elev;
715 av_log(ctx, AV_LOG_DEBUG, "IR length: %d.\n", s->sofa.hrtf->N);
716 s->sofa.ir_samples = s->sofa.hrtf->N;
717 s->sofa.n_samples = 1 << (32 - ff_clz(s->sofa.ir_samples));
719 n_samples = s->sofa.n_samples;
720 ir_samples = s->sofa.ir_samples;
722 s->data_ir[0] = av_calloc(n_samples, sizeof(float) * s->n_conv);
723 s->data_ir[1] = av_calloc(n_samples, sizeof(float) * s->n_conv);
724 s->delay[0] = av_calloc(s->n_conv, sizeof(int));
725 s->delay[1] = av_calloc(s->n_conv, sizeof(int));
727 if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
728 ret = AVERROR(ENOMEM);
732 /* get temporary IR for L and R channel */
733 data_ir_l = av_calloc(n_conv * n_samples, sizeof(*data_ir_l));
734 data_ir_r = av_calloc(n_conv * n_samples, sizeof(*data_ir_r));
735 if (!data_ir_r || !data_ir_l) {
736 ret = AVERROR(ENOMEM);
740 if (s->type == TIME_DOMAIN) {
741 s->temp_src[0] = av_calloc(n_samples, sizeof(float));
742 s->temp_src[1] = av_calloc(n_samples, sizeof(float));
743 if (!s->temp_src[0] || !s->temp_src[1]) {
744 ret = AVERROR(ENOMEM);
749 s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
750 s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
751 if (!s->speaker_azim || !s->speaker_elev) {
752 ret = AVERROR(ENOMEM);
756 /* get speaker positions */
757 if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
758 av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
762 for (i = 0; i < s->n_conv; i++) {
763 float coordinates[3];
765 /* load and store IRs and corresponding delays */
766 azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
767 elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
769 coordinates[0] = azim;
770 coordinates[1] = elev;
771 coordinates[2] = radius;
773 mysofa_s2c(coordinates);
775 /* get id of IR closest to desired position */
776 ret = getfilter_float(ctx, coordinates[0], coordinates[1], coordinates[2],
777 data_ir_l + n_samples * i,
778 data_ir_r + n_samples * i,
783 s->delay[0][i] = delay_l * sample_rate;
784 s->delay[1][i] = delay_r * sample_rate;
786 s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
789 /* get size of ringbuffer (longest IR plus max. delay) */
790 /* then choose next power of 2 for performance optimization */
791 n_current = n_samples + s->sofa.max_delay;
792 /* length of longest IR plus max. delay */
793 n_max = FFMAX(n_max, n_current);
795 /* buffer length is longest IR plus max. delay -> next power of 2
796 (32 - count leading zeros gives required exponent) */
797 s->buffer_length = 1 << (32 - ff_clz(n_max));
798 s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
800 if (s->type == FREQUENCY_DOMAIN) {
801 av_fft_end(s->fft[0]);
802 av_fft_end(s->fft[1]);
803 s->fft[0] = av_fft_init(log2(s->n_fft), 0);
804 s->fft[1] = av_fft_init(log2(s->n_fft), 0);
805 av_fft_end(s->ifft[0]);
806 av_fft_end(s->ifft[1]);
807 s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
808 s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
810 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
811 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
812 ret = AVERROR(ENOMEM);
817 if (s->type == TIME_DOMAIN) {
818 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
819 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
821 /* get temporary HRTF memory for L and R channel */
822 data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
823 data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
824 if (!data_hrtf_r || !data_hrtf_l) {
825 ret = AVERROR(ENOMEM);
829 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
830 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
831 s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
832 s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
833 s->temp_afft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
834 s->temp_afft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
835 if (!s->temp_fft[0] || !s->temp_fft[1] ||
836 !s->temp_afft[0] || !s->temp_afft[1]) {
837 ret = AVERROR(ENOMEM);
842 if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
843 ret = AVERROR(ENOMEM);
847 if (s->type == FREQUENCY_DOMAIN) {
848 fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
849 fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
850 if (!fft_in_l || !fft_in_r) {
851 ret = AVERROR(ENOMEM);
856 for (i = 0; i < s->n_conv; i++) {
859 offset = i * n_samples; /* no. samples already written */
861 lir = data_ir_l + offset;
862 rir = data_ir_r + offset;
864 if (s->type == TIME_DOMAIN) {
865 for (j = 0; j < ir_samples; j++) {
866 /* load reversed IRs of the specified source position
867 * sample-by-sample for left and right ear; and apply gain */
868 s->data_ir[0][offset + j] = lir[ir_samples - 1 - j] * gain_lin;
869 s->data_ir[1][offset + j] = rir[ir_samples - 1 - j] * gain_lin;
872 memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
873 memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
875 offset = i * n_fft; /* no. samples already written */
876 for (j = 0; j < ir_samples; j++) {
877 /* load non-reversed IRs of the specified source position
878 * sample-by-sample and apply gain,
879 * L channel is loaded to real part, R channel to imag part,
880 * IRs are shifted by L and R delay */
881 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
882 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
885 /* actually transform to frequency domain (IRs -> HRTFs) */
886 av_fft_permute(s->fft[0], fft_in_l);
887 av_fft_calc(s->fft[0], fft_in_l);
888 memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
889 av_fft_permute(s->fft[0], fft_in_r);
890 av_fft_calc(s->fft[0], fft_in_r);
891 memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
895 if (s->type == FREQUENCY_DOMAIN) {
896 s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
897 s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
898 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
899 ret = AVERROR(ENOMEM);
903 memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
904 sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
905 memcpy(s->data_hrtf[1], data_hrtf_r,
906 sizeof(FFTComplex) * n_conv * n_fft);
910 av_freep(&data_hrtf_l); /* free temporary HRTF memory */
911 av_freep(&data_hrtf_r);
913 av_freep(&data_ir_l); /* free temprary IR memory */
914 av_freep(&data_ir_r);
916 av_freep(&fft_in_l); /* free temporary FFT memory */
922 static av_cold int init(AVFilterContext *ctx)
924 SOFAlizerContext *s = ctx->priv;
928 av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
929 return AVERROR(EINVAL);
932 /* preload SOFA file, */
933 ret = preload_sofa(ctx, s->filename, &s->sample_rate);
935 /* file loading error */
936 av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
937 } else { /* no file loading error, resampling not required */
938 av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
942 av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
946 s->fdsp = avpriv_float_dsp_alloc(0);
948 return AVERROR(ENOMEM);
953 static int config_input(AVFilterLink *inlink)
955 AVFilterContext *ctx = inlink->dst;
956 SOFAlizerContext *s = ctx->priv;
959 if (s->type == FREQUENCY_DOMAIN) {
960 inlink->partial_buf_size =
961 inlink->min_samples =
962 inlink->max_samples = s->framesize;
965 /* gain -3 dB per channel */
966 s->gain_lfe = expf((s->gain - 3 * inlink->channels + s->lfe_gain) / 20 * M_LN10);
968 s->n_conv = inlink->channels;
970 /* load IRs to data_ir[0] and data_ir[1] for required directions */
971 if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
974 av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
975 inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
980 static av_cold void uninit(AVFilterContext *ctx)
982 SOFAlizerContext *s = ctx->priv;
984 close_sofa(&s->sofa);
985 av_fft_end(s->ifft[0]);
986 av_fft_end(s->ifft[1]);
987 av_fft_end(s->fft[0]);
988 av_fft_end(s->fft[1]);
993 av_freep(&s->delay[0]);
994 av_freep(&s->delay[1]);
995 av_freep(&s->data_ir[0]);
996 av_freep(&s->data_ir[1]);
997 av_freep(&s->ringbuffer[0]);
998 av_freep(&s->ringbuffer[1]);
999 av_freep(&s->speaker_azim);
1000 av_freep(&s->speaker_elev);
1001 av_freep(&s->temp_src[0]);
1002 av_freep(&s->temp_src[1]);
1003 av_freep(&s->temp_afft[0]);
1004 av_freep(&s->temp_afft[1]);
1005 av_freep(&s->temp_fft[0]);
1006 av_freep(&s->temp_fft[1]);
1007 av_freep(&s->data_hrtf[0]);
1008 av_freep(&s->data_hrtf[1]);
1012 #define OFFSET(x) offsetof(SOFAlizerContext, x)
1013 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1015 static const AVOption sofalizer_options[] = {
1016 { "sofa", "sofa filename", OFFSET(filename), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1017 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
1018 { "rotation", "set rotation" , OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -360, 360, .flags = FLAGS },
1019 { "elevation", "set elevation", OFFSET(elevation), AV_OPT_TYPE_FLOAT, {.dbl=0}, -90, 90, .flags = FLAGS },
1020 { "radius", "set radius", OFFSET(radius), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 5, .flags = FLAGS },
1021 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
1022 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
1023 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
1024 { "speakers", "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING, {.str=0}, 0, 0, .flags = FLAGS },
1025 { "lfegain", "set lfe gain", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20,40, .flags = FLAGS },
1026 { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT, {.i64=1024},1024,96000, .flags = FLAGS },
1027 { "normalize", "normalize IRs", OFFSET(normalize), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, .flags = FLAGS },
1028 { "interpolate","interpolate IRs from neighbors", OFFSET(interpolate),AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
1029 { "minphase", "minphase IRs", OFFSET(minphase), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, .flags = FLAGS },
1030 { "anglestep", "set neighbor search angle step", OFFSET(anglestep), AV_OPT_TYPE_FLOAT, {.dbl=.5}, 0.01, 10, .flags = FLAGS },
1031 { "radstep", "set neighbor search radius step", OFFSET(radstep), AV_OPT_TYPE_FLOAT, {.dbl=.01}, 0.01, 1, .flags = FLAGS },
1035 AVFILTER_DEFINE_CLASS(sofalizer);
1037 static const AVFilterPad inputs[] = {
1040 .type = AVMEDIA_TYPE_AUDIO,
1041 .config_props = config_input,
1042 .filter_frame = filter_frame,
1047 static const AVFilterPad outputs[] = {
1050 .type = AVMEDIA_TYPE_AUDIO,
1055 AVFilter ff_af_sofalizer = {
1056 .name = "sofalizer",
1057 .description = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
1058 .priv_size = sizeof(SOFAlizerContext),
1059 .priv_class = &sofalizer_class,
1062 .query_formats = query_formats,
1065 .flags = AVFILTER_FLAG_SLICE_THREADS,