]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_sofalizer.c
avfilter/af_sofalizer: use fabsf() instead of fabs()
[ffmpeg] / libavfilter / af_sofalizer.c
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
6  *
7  * Authors: Andreas Fuchs <andi.fuchs.mail@gmail.com>
8  *          Wolfgang Hrauda <wolfgang.hrauda@gmx.at>
9  *
10  * SOFAlizer project coordinator at ARI, main developer of SOFA:
11  *          Piotr Majdak <piotr@majdak.at>
12  *
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.
17  *
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.
22  *
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  *****************************************************************************/
27
28 #include <math.h>
29 #include <mysofa.h>
30
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"
37 #include "avfilter.h"
38 #include "internal.h"
39 #include "audio.h"
40
41 #define TIME_DOMAIN      0
42 #define FREQUENCY_DOMAIN 1
43
44 typedef struct MySofa {  /* contains data of one SOFA file */
45     struct MYSOFA_EASY *easy;
46     int n_samples;       /* length of one impulse response (IR) */
47     float *lir, *rir;    /* IRs (time-domain) */
48     int max_delay;
49 } MySofa;
50
51 typedef struct VirtualSpeaker {
52     uint8_t set;
53     float azim;
54     float elev;
55 } VirtualSpeaker;
56
57 typedef struct SOFAlizerContext {
58     const AVClass *class;
59
60     char *filename;             /* name of SOFA file */
61     MySofa sofa;                /* contains data of the SOFA file */
62
63     int sample_rate;            /* sample rate from SOFA file */
64     float *speaker_azim;        /* azimuth of the virtual loudspeakers */
65     float *speaker_elev;        /* elevation of the virtual loudspeakers */
66     char *speakers_pos;         /* custom positions of the virtual loudspeakers */
67     float lfe_gain;             /* initial gain for the LFE channel */
68     float gain_lfe;             /* gain applied to LFE channel */
69     int lfe_channel;            /* LFE channel position in channel layout */
70
71     int n_conv;                 /* number of channels to convolute */
72
73                                 /* buffer variables (for convolution) */
74     float *ringbuffer[2];       /* buffers input samples, length of one buffer: */
75                                 /* no. input ch. (incl. LFE) x buffer_length */
76     int write[2];               /* current write position to ringbuffer */
77     int buffer_length;          /* is: longest IR plus max. delay in all SOFA files */
78                                 /* then choose next power of 2 */
79     int n_fft;                  /* number of samples in one FFT block */
80
81                                 /* netCDF variables */
82     int *delay[2];              /* broadband delay for each channel/IR to be convolved */
83
84     float *data_ir[2];          /* IRs for all channels to be convolved */
85                                 /* (this excludes the LFE) */
86     float *temp_src[2];
87     FFTComplex *temp_fft[2];
88
89                          /* control variables */
90     float gain;          /* filter gain (in dB) */
91     float rotation;      /* rotation of virtual loudspeakers (in degrees)  */
92     float elevation;     /* elevation of virtual loudspeakers (in deg.) */
93     float radius;        /* distance virtual loudspeakers to listener (in metres) */
94     int type;            /* processing type */
95     int framesize;       /* size of buffer */
96
97     VirtualSpeaker vspkrpos[64];
98
99     FFTContext *fft[2], *ifft[2];
100     FFTComplex *data_hrtf[2];
101
102     AVFloatDSPContext *fdsp;
103 } SOFAlizerContext;
104
105 static int close_sofa(struct MySofa *sofa)
106 {
107     mysofa_close(sofa->easy);
108     sofa->easy = NULL;
109
110     return 0;
111 }
112
113 static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
114 {
115     struct SOFAlizerContext *s = ctx->priv;
116     struct MYSOFA_HRTF *mysofa;
117     char *license;
118     int ret;
119
120     mysofa = mysofa_load(filename, &ret);
121     if (ret || !mysofa) {
122         av_log(ctx, AV_LOG_ERROR, "Can't find SOFA-file '%s'\n", filename);
123         return AVERROR(EINVAL);
124     }
125
126     if (mysofa->DataSamplingRate.elements != 1)
127         return AVERROR(EINVAL);
128     *samplingrate = mysofa->DataSamplingRate.values[0];
129     s->sofa.n_samples = mysofa->N;
130     license = mysofa_getAttribute(mysofa->attributes, (char *)"License");
131     if (license)
132         av_log(ctx, AV_LOG_INFO, "SOFA license: %s\n", license);
133     mysofa_free(mysofa);
134
135     return 0;
136 }
137
138 static int parse_channel_name(char **arg, int *rchannel, char *buf)
139 {
140     int len, i, channel_id = 0;
141     int64_t layout, layout0;
142
143     /* try to parse a channel name, e.g. "FL" */
144     if (av_sscanf(*arg, "%7[A-Z]%n", buf, &len)) {
145         layout0 = layout = av_get_channel_layout(buf);
146         /* channel_id <- first set bit in layout */
147         for (i = 32; i > 0; i >>= 1) {
148             if (layout >= 1LL << i) {
149                 channel_id += i;
150                 layout >>= i;
151             }
152         }
153         /* reject layouts that are not a single channel */
154         if (channel_id >= 64 || layout0 != 1LL << channel_id)
155             return AVERROR(EINVAL);
156         *rchannel = channel_id;
157         *arg += len;
158         return 0;
159     }
160     return AVERROR(EINVAL);
161 }
162
163 static void parse_speaker_pos(AVFilterContext *ctx, int64_t in_channel_layout)
164 {
165     SOFAlizerContext *s = ctx->priv;
166     char *arg, *tokenizer, *p, *args = av_strdup(s->speakers_pos);
167
168     if (!args)
169         return;
170     p = args;
171
172     while ((arg = av_strtok(p, "|", &tokenizer))) {
173         char buf[8];
174         float azim, elev;
175         int out_ch_id;
176
177         p = NULL;
178         if (parse_channel_name(&arg, &out_ch_id, buf)) {
179             av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", buf);
180             continue;
181         }
182         if (av_sscanf(arg, "%f %f", &azim, &elev) == 2) {
183             s->vspkrpos[out_ch_id].set = 1;
184             s->vspkrpos[out_ch_id].azim = azim;
185             s->vspkrpos[out_ch_id].elev = elev;
186         } else if (av_sscanf(arg, "%f", &azim) == 1) {
187             s->vspkrpos[out_ch_id].set = 1;
188             s->vspkrpos[out_ch_id].azim = azim;
189             s->vspkrpos[out_ch_id].elev = 0;
190         }
191     }
192
193     av_free(args);
194 }
195
196 static int get_speaker_pos(AVFilterContext *ctx,
197                            float *speaker_azim, float *speaker_elev)
198 {
199     struct SOFAlizerContext *s = ctx->priv;
200     uint64_t channels_layout = ctx->inputs[0]->channel_layout;
201     float azim[16] = { 0 };
202     float elev[16] = { 0 };
203     int m, ch, n_conv = ctx->inputs[0]->channels; /* get no. input channels */
204
205     if (n_conv > 16)
206         return AVERROR(EINVAL);
207
208     s->lfe_channel = -1;
209
210     if (s->speakers_pos)
211         parse_speaker_pos(ctx, channels_layout);
212
213     /* set speaker positions according to input channel configuration: */
214     for (m = 0, ch = 0; ch < n_conv && m < 64; m++) {
215         uint64_t mask = channels_layout & (1ULL << m);
216
217         switch (mask) {
218         case AV_CH_FRONT_LEFT:            azim[ch] =  30;      break;
219         case AV_CH_FRONT_RIGHT:           azim[ch] = 330;      break;
220         case AV_CH_FRONT_CENTER:          azim[ch] =   0;      break;
221         case AV_CH_LOW_FREQUENCY:
222         case AV_CH_LOW_FREQUENCY_2:       s->lfe_channel = ch; break;
223         case AV_CH_BACK_LEFT:             azim[ch] = 150;      break;
224         case AV_CH_BACK_RIGHT:            azim[ch] = 210;      break;
225         case AV_CH_BACK_CENTER:           azim[ch] = 180;      break;
226         case AV_CH_SIDE_LEFT:             azim[ch] =  90;      break;
227         case AV_CH_SIDE_RIGHT:            azim[ch] = 270;      break;
228         case AV_CH_FRONT_LEFT_OF_CENTER:  azim[ch] =  15;      break;
229         case AV_CH_FRONT_RIGHT_OF_CENTER: azim[ch] = 345;      break;
230         case AV_CH_TOP_CENTER:            azim[ch] =   0;
231                                           elev[ch] =  90;      break;
232         case AV_CH_TOP_FRONT_LEFT:        azim[ch] =  30;
233                                           elev[ch] =  45;      break;
234         case AV_CH_TOP_FRONT_CENTER:      azim[ch] =   0;
235                                           elev[ch] =  45;      break;
236         case AV_CH_TOP_FRONT_RIGHT:       azim[ch] = 330;
237                                           elev[ch] =  45;      break;
238         case AV_CH_TOP_BACK_LEFT:         azim[ch] = 150;
239                                           elev[ch] =  45;      break;
240         case AV_CH_TOP_BACK_RIGHT:        azim[ch] = 210;
241                                           elev[ch] =  45;      break;
242         case AV_CH_TOP_BACK_CENTER:       azim[ch] = 180;
243                                           elev[ch] =  45;      break;
244         case AV_CH_WIDE_LEFT:             azim[ch] =  90;      break;
245         case AV_CH_WIDE_RIGHT:            azim[ch] = 270;      break;
246         case AV_CH_SURROUND_DIRECT_LEFT:  azim[ch] =  90;      break;
247         case AV_CH_SURROUND_DIRECT_RIGHT: azim[ch] = 270;      break;
248         case AV_CH_STEREO_LEFT:           azim[ch] =  90;      break;
249         case AV_CH_STEREO_RIGHT:          azim[ch] = 270;      break;
250         case 0:                                                break;
251         default:
252             return AVERROR(EINVAL);
253         }
254
255         if (s->vspkrpos[m].set) {
256             azim[ch] = s->vspkrpos[m].azim;
257             elev[ch] = s->vspkrpos[m].elev;
258         }
259
260         if (mask)
261             ch++;
262     }
263
264     memcpy(speaker_azim, azim, n_conv * sizeof(float));
265     memcpy(speaker_elev, elev, n_conv * sizeof(float));
266
267     return 0;
268
269 }
270
271 typedef struct ThreadData {
272     AVFrame *in, *out;
273     int *write;
274     int **delay;
275     float **ir;
276     int *n_clippings;
277     float **ringbuffer;
278     float **temp_src;
279     FFTComplex **temp_fft;
280 } ThreadData;
281
282 static int sofalizer_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
283 {
284     SOFAlizerContext *s = ctx->priv;
285     ThreadData *td = arg;
286     AVFrame *in = td->in, *out = td->out;
287     int offset = jobnr;
288     int *write = &td->write[jobnr];
289     const int *const delay = td->delay[jobnr];
290     const float *const ir = td->ir[jobnr];
291     int *n_clippings = &td->n_clippings[jobnr];
292     float *ringbuffer = td->ringbuffer[jobnr];
293     float *temp_src = td->temp_src[jobnr];
294     const int n_samples = s->sofa.n_samples; /* length of one IR */
295     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
296     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
297     const int in_channels = s->n_conv; /* number of input channels */
298     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
299     const int buffer_length = s->buffer_length;
300     /* -1 for AND instead of MODULO (applied to powers of 2): */
301     const uint32_t modulo = (uint32_t)buffer_length - 1;
302     float *buffer[16]; /* holds ringbuffer for each input channel */
303     int wr = *write;
304     int read;
305     int i, l;
306
307     dst += offset;
308     for (l = 0; l < in_channels; l++) {
309         /* get starting address of ringbuffer for each input channel */
310         buffer[l] = ringbuffer + l * buffer_length;
311     }
312
313     for (i = 0; i < in->nb_samples; i++) {
314         const float *temp_ir = ir; /* using same set of IRs for each sample */
315
316         dst[0] = 0;
317         for (l = 0; l < in_channels; l++) {
318             /* write current input sample to ringbuffer (for each channel) */
319             buffer[l][wr] = src[l];
320         }
321
322         /* loop goes through all channels to be convolved */
323         for (l = 0; l < in_channels; l++) {
324             const float *const bptr = buffer[l];
325
326             if (l == s->lfe_channel) {
327                 /* LFE is an input channel but requires no convolution */
328                 /* apply gain to LFE signal and add to output buffer */
329                 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
330                 temp_ir += FFALIGN(n_samples, 32);
331                 continue;
332             }
333
334             /* current read position in ringbuffer: input sample write position
335              * - delay for l-th ch. + diff. betw. IR length and buffer length
336              * (mod buffer length) */
337             read = (wr - delay[l] - (n_samples - 1) + buffer_length) & modulo;
338
339             if (read + n_samples < buffer_length) {
340                 memmove(temp_src, bptr + read, n_samples * sizeof(*temp_src));
341             } else {
342                 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
343
344                 memmove(temp_src, bptr + read, len * sizeof(*temp_src));
345                 memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
346             }
347
348             /* multiply signal and IR, and add up the results */
349             dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, n_samples);
350             temp_ir += FFALIGN(n_samples, 32);
351         }
352
353         /* clippings counter */
354         if (fabsf(dst[0]) > 1)
355             n_clippings[0]++;
356
357         /* move output buffer pointer by +2 to get to next sample of processed channel: */
358         dst += 2;
359         src += in_channels;
360         wr   = (wr + 1) & modulo; /* update ringbuffer write position */
361     }
362
363     *write = wr; /* remember write position in ringbuffer for next call */
364
365     return 0;
366 }
367
368 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
369 {
370     SOFAlizerContext *s = ctx->priv;
371     ThreadData *td = arg;
372     AVFrame *in = td->in, *out = td->out;
373     int offset = jobnr;
374     int *write = &td->write[jobnr];
375     FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
376     int *n_clippings = &td->n_clippings[jobnr];
377     float *ringbuffer = td->ringbuffer[jobnr];
378     const int n_samples = s->sofa.n_samples; /* length of one IR */
379     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
380     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
381     const int in_channels = s->n_conv; /* number of input channels */
382     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
383     const int buffer_length = s->buffer_length;
384     /* -1 for AND instead of MODULO (applied to powers of 2): */
385     const uint32_t modulo = (uint32_t)buffer_length - 1;
386     FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
387     FFTContext *ifft = s->ifft[jobnr];
388     FFTContext *fft = s->fft[jobnr];
389     const int n_conv = s->n_conv;
390     const int n_fft = s->n_fft;
391     const float fft_scale = 1.0f / s->n_fft;
392     FFTComplex *hrtf_offset;
393     int wr = *write;
394     int n_read;
395     int i, j;
396
397     dst += offset;
398
399     /* find minimum between number of samples and output buffer length:
400      * (important, if one IR is longer than the output buffer) */
401     n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
402     for (j = 0; j < n_read; j++) {
403         /* initialize output buf with saved signal from overflow buf */
404         dst[2 * j]     = ringbuffer[wr];
405         ringbuffer[wr] = 0.0; /* re-set read samples to zero */
406         /* update ringbuffer read/write position */
407         wr  = (wr + 1) & modulo;
408     }
409
410     /* initialize rest of output buffer with 0 */
411     for (j = n_read; j < in->nb_samples; j++) {
412         dst[2 * j] = 0;
413     }
414
415     for (i = 0; i < n_conv; i++) {
416         if (i == s->lfe_channel) { /* LFE */
417             for (j = 0; j < in->nb_samples; j++) {
418                 /* apply gain to LFE signal and add to output buffer */
419                 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
420             }
421             continue;
422         }
423
424         /* outer loop: go through all input channels to be convolved */
425         offset = i * n_fft; /* no. samples already processed */
426         hrtf_offset = hrtf + offset;
427
428         /* fill FFT input with 0 (we want to zero-pad) */
429         memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
430
431         for (j = 0; j < in->nb_samples; j++) {
432             /* prepare input for FFT */
433             /* write all samples of current input channel to FFT input array */
434             fft_in[j].re = src[j * in_channels + i];
435         }
436
437         /* transform input signal of current channel to frequency domain */
438         av_fft_permute(fft, fft_in);
439         av_fft_calc(fft, fft_in);
440         for (j = 0; j < n_fft; j++) {
441             const FFTComplex *hcomplex = hrtf_offset + j;
442             const float re = fft_in[j].re;
443             const float im = fft_in[j].im;
444
445             /* complex multiplication of input signal and HRTFs */
446             /* output channel (real): */
447             fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
448             /* output channel (imag): */
449             fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
450         }
451
452         /* transform output signal of current channel back to time domain */
453         av_fft_permute(ifft, fft_in);
454         av_fft_calc(ifft, fft_in);
455
456         for (j = 0; j < in->nb_samples; j++) {
457             /* write output signal of current channel to output buffer */
458             dst[2 * j] += fft_in[j].re * fft_scale;
459         }
460
461         for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
462             /* write the rest of output signal to overflow buffer */
463             int write_pos = (wr + j) & modulo;
464
465             *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
466         }
467     }
468
469     /* go through all samples of current output buffer: count clippings */
470     for (i = 0; i < out->nb_samples; i++) {
471         /* clippings counter */
472         if (fabsf(dst[0]) > 1) { /* if current output sample > 1 */
473             n_clippings[0]++;
474         }
475
476         /* move output buffer pointer by +2 to get to next sample of processed channel: */
477         dst += 2;
478     }
479
480     /* remember read/write position in ringbuffer for next call */
481     *write = wr;
482
483     return 0;
484 }
485
486 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
487 {
488     AVFilterContext *ctx = inlink->dst;
489     SOFAlizerContext *s = ctx->priv;
490     AVFilterLink *outlink = ctx->outputs[0];
491     int n_clippings[2] = { 0 };
492     ThreadData td;
493     AVFrame *out;
494
495     out = ff_get_audio_buffer(outlink, in->nb_samples);
496     if (!out) {
497         av_frame_free(&in);
498         return AVERROR(ENOMEM);
499     }
500     av_frame_copy_props(out, in);
501
502     td.in = in; td.out = out; td.write = s->write;
503     td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
504     td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
505     td.temp_fft = s->temp_fft;
506
507     if (s->type == TIME_DOMAIN) {
508         ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
509     } else {
510         ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
511     }
512     emms_c();
513
514     /* display error message if clipping occurred */
515     if (n_clippings[0] + n_clippings[1] > 0) {
516         av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
517                n_clippings[0] + n_clippings[1], out->nb_samples * 2);
518     }
519
520     av_frame_free(&in);
521     return ff_filter_frame(outlink, out);
522 }
523
524 static int query_formats(AVFilterContext *ctx)
525 {
526     struct SOFAlizerContext *s = ctx->priv;
527     AVFilterFormats *formats = NULL;
528     AVFilterChannelLayouts *layouts = NULL;
529     int ret, sample_rates[] = { 48000, -1 };
530
531     ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
532     if (ret)
533         return ret;
534     ret = ff_set_common_formats(ctx, formats);
535     if (ret)
536         return ret;
537
538     layouts = ff_all_channel_layouts();
539     if (!layouts)
540         return AVERROR(ENOMEM);
541
542     ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
543     if (ret)
544         return ret;
545
546     layouts = NULL;
547     ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
548     if (ret)
549         return ret;
550
551     ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
552     if (ret)
553         return ret;
554
555     sample_rates[0] = s->sample_rate;
556     formats = ff_make_format_list(sample_rates);
557     if (!formats)
558         return AVERROR(ENOMEM);
559     return ff_set_common_samplerates(ctx, formats);
560 }
561
562 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
563 {
564     struct SOFAlizerContext *s = ctx->priv;
565     int n_samples;
566     int n_conv = s->n_conv; /* no. channels to convolve */
567     int n_fft;
568     float delay_l; /* broadband delay for each IR */
569     float delay_r;
570     int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
571     float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
572     FFTComplex *data_hrtf_l = NULL;
573     FFTComplex *data_hrtf_r = NULL;
574     FFTComplex *fft_in_l = NULL;
575     FFTComplex *fft_in_r = NULL;
576     float *data_ir_l = NULL;
577     float *data_ir_r = NULL;
578     int offset = 0; /* used for faster pointer arithmetics in for-loop */
579     int i, j, azim_orig = azim, elev_orig = elev;
580     int filter_length, ret = 0;
581     int n_current;
582     int n_max = 0;
583
584     s->sofa.easy = mysofa_open(s->filename, sample_rate, &filter_length, &ret);
585     if (!s->sofa.easy || ret) { /* if an invalid SOFA file has been selected */
586         av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
587         return AVERROR_INVALIDDATA;
588     }
589
590     n_samples = s->sofa.n_samples;
591
592     s->data_ir[0] = av_calloc(FFALIGN(n_samples, 32), sizeof(float) * s->n_conv);
593     s->data_ir[1] = av_calloc(FFALIGN(n_samples, 32), sizeof(float) * s->n_conv);
594     s->delay[0] = av_calloc(s->n_conv, sizeof(int));
595     s->delay[1] = av_calloc(s->n_conv, sizeof(int));
596
597     if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
598         ret = AVERROR(ENOMEM);
599         goto fail;
600     }
601
602     /* get temporary IR for L and R channel */
603     data_ir_l = av_calloc(n_conv * FFALIGN(n_samples, 32), sizeof(*data_ir_l));
604     data_ir_r = av_calloc(n_conv * FFALIGN(n_samples, 32), sizeof(*data_ir_r));
605     if (!data_ir_r || !data_ir_l) {
606         ret = AVERROR(ENOMEM);
607         goto fail;
608     }
609
610     if (s->type == TIME_DOMAIN) {
611         s->temp_src[0] = av_calloc(FFALIGN(n_samples, 32), sizeof(float));
612         s->temp_src[1] = av_calloc(FFALIGN(n_samples, 32), sizeof(float));
613         if (!s->temp_src[0] || !s->temp_src[1]) {
614             ret = AVERROR(ENOMEM);
615             goto fail;
616         }
617     }
618
619     s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
620     s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
621     if (!s->speaker_azim || !s->speaker_elev) {
622         ret = AVERROR(ENOMEM);
623         goto fail;
624     }
625
626     /* get speaker positions */
627     if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
628         av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
629         goto fail;
630     }
631
632     for (i = 0; i < s->n_conv; i++) {
633         float coordinates[3];
634
635         /* load and store IRs and corresponding delays */
636         azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
637         elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
638
639         coordinates[0] = azim;
640         coordinates[1] = elev;
641         coordinates[2] = radius;
642
643         mysofa_s2c(coordinates);
644
645         /* get id of IR closest to desired position */
646         mysofa_getfilter_float(s->sofa.easy, coordinates[0], coordinates[1], coordinates[2],
647                                data_ir_l + FFALIGN(n_samples, 32) * i,
648                                data_ir_r + FFALIGN(n_samples, 32) * i,
649                                &delay_l, &delay_r);
650
651         s->delay[0][i] = delay_l * sample_rate;
652         s->delay[1][i] = delay_r * sample_rate;
653
654         s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
655     }
656
657     /* get size of ringbuffer (longest IR plus max. delay) */
658     /* then choose next power of 2 for performance optimization */
659     n_current = s->sofa.n_samples + s->sofa.max_delay;
660     /* length of longest IR plus max. delay */
661     n_max = FFMAX(n_max, n_current);
662
663     /* buffer length is longest IR plus max. delay -> next power of 2
664        (32 - count leading zeros gives required exponent)  */
665     s->buffer_length = 1 << (32 - ff_clz(n_max));
666     s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
667
668     if (s->type == FREQUENCY_DOMAIN) {
669         av_fft_end(s->fft[0]);
670         av_fft_end(s->fft[1]);
671         s->fft[0] = av_fft_init(log2(s->n_fft), 0);
672         s->fft[1] = av_fft_init(log2(s->n_fft), 0);
673         av_fft_end(s->ifft[0]);
674         av_fft_end(s->ifft[1]);
675         s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
676         s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
677
678         if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
679             av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
680             ret = AVERROR(ENOMEM);
681             goto fail;
682         }
683     }
684
685     if (s->type == TIME_DOMAIN) {
686         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
687         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
688     } else {
689         /* get temporary HRTF memory for L and R channel */
690         data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
691         data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
692         if (!data_hrtf_r || !data_hrtf_l) {
693             ret = AVERROR(ENOMEM);
694             goto fail;
695         }
696
697         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
698         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
699         s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
700         s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
701         if (!s->temp_fft[0] || !s->temp_fft[1]) {
702             ret = AVERROR(ENOMEM);
703             goto fail;
704         }
705     }
706
707     if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
708         ret = AVERROR(ENOMEM);
709         goto fail;
710     }
711
712     if (s->type == FREQUENCY_DOMAIN) {
713         fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
714         fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
715         if (!fft_in_l || !fft_in_r) {
716             ret = AVERROR(ENOMEM);
717             goto fail;
718         }
719     }
720
721     for (i = 0; i < s->n_conv; i++) {
722         float *lir, *rir;
723
724         offset = i * FFALIGN(n_samples, 32); /* no. samples already written */
725
726         lir = data_ir_l + offset;
727         rir = data_ir_r + offset;
728
729         if (s->type == TIME_DOMAIN) {
730             for (j = 0; j < n_samples; j++) {
731                 /* load reversed IRs of the specified source position
732                  * sample-by-sample for left and right ear; and apply gain */
733                 s->data_ir[0][offset + j] = lir[n_samples - 1 - j] * gain_lin;
734                 s->data_ir[1][offset + j] = rir[n_samples - 1 - j] * gain_lin;
735             }
736         } else {
737             memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
738             memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
739
740             offset = i * n_fft; /* no. samples already written */
741             for (j = 0; j < n_samples; j++) {
742                 /* load non-reversed IRs of the specified source position
743                  * sample-by-sample and apply gain,
744                  * L channel is loaded to real part, R channel to imag part,
745                  * IRs ared shifted by L and R delay */
746                 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
747                 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
748             }
749
750             /* actually transform to frequency domain (IRs -> HRTFs) */
751             av_fft_permute(s->fft[0], fft_in_l);
752             av_fft_calc(s->fft[0], fft_in_l);
753             memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
754             av_fft_permute(s->fft[0], fft_in_r);
755             av_fft_calc(s->fft[0], fft_in_r);
756             memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
757         }
758     }
759
760     if (s->type == FREQUENCY_DOMAIN) {
761         s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
762         s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
763         if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
764             ret = AVERROR(ENOMEM);
765             goto fail;
766         }
767
768         memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
769             sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
770         memcpy(s->data_hrtf[1], data_hrtf_r,
771             sizeof(FFTComplex) * n_conv * n_fft);
772     }
773
774 fail:
775     av_freep(&data_hrtf_l); /* free temporary HRTF memory */
776     av_freep(&data_hrtf_r);
777
778     av_freep(&data_ir_l); /* free temprary IR memory */
779     av_freep(&data_ir_r);
780
781     av_freep(&fft_in_l); /* free temporary FFT memory */
782     av_freep(&fft_in_r);
783
784     return ret;
785 }
786
787 static av_cold int init(AVFilterContext *ctx)
788 {
789     SOFAlizerContext *s = ctx->priv;
790     int ret;
791
792     if (!s->filename) {
793         av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
794         return AVERROR(EINVAL);
795     }
796
797     /* preload SOFA file, */
798     ret = preload_sofa(ctx, s->filename, &s->sample_rate);
799     if (ret) {
800         /* file loading error */
801         av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
802     } else { /* no file loading error, resampling not required */
803         av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
804     }
805
806     if (ret) {
807         av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
808         return ret;
809     }
810
811     s->fdsp = avpriv_float_dsp_alloc(0);
812     if (!s->fdsp)
813         return AVERROR(ENOMEM);
814
815     return 0;
816 }
817
818 static int config_input(AVFilterLink *inlink)
819 {
820     AVFilterContext *ctx = inlink->dst;
821     SOFAlizerContext *s = ctx->priv;
822     int ret;
823
824     if (s->type == FREQUENCY_DOMAIN) {
825         inlink->partial_buf_size =
826         inlink->min_samples =
827         inlink->max_samples = s->framesize;
828     }
829
830     /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
831     s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
832
833     s->n_conv = inlink->channels;
834
835     /* load IRs to data_ir[0] and data_ir[1] for required directions */
836     if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
837         return ret;
838
839     av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
840         inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
841
842     return 0;
843 }
844
845 static av_cold void uninit(AVFilterContext *ctx)
846 {
847     SOFAlizerContext *s = ctx->priv;
848
849     close_sofa(&s->sofa);
850     av_fft_end(s->ifft[0]);
851     av_fft_end(s->ifft[1]);
852     av_fft_end(s->fft[0]);
853     av_fft_end(s->fft[1]);
854     av_freep(&s->delay[0]);
855     av_freep(&s->delay[1]);
856     av_freep(&s->data_ir[0]);
857     av_freep(&s->data_ir[1]);
858     av_freep(&s->ringbuffer[0]);
859     av_freep(&s->ringbuffer[1]);
860     av_freep(&s->speaker_azim);
861     av_freep(&s->speaker_elev);
862     av_freep(&s->temp_src[0]);
863     av_freep(&s->temp_src[1]);
864     av_freep(&s->temp_fft[0]);
865     av_freep(&s->temp_fft[1]);
866     av_freep(&s->data_hrtf[0]);
867     av_freep(&s->data_hrtf[1]);
868     av_freep(&s->fdsp);
869 }
870
871 #define OFFSET(x) offsetof(SOFAlizerContext, x)
872 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
873
874 static const AVOption sofalizer_options[] = {
875     { "sofa",      "sofa filename",  OFFSET(filename),  AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
876     { "gain",      "set gain in dB", OFFSET(gain),      AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
877     { "rotation",  "set rotation"  , OFFSET(rotation),  AV_OPT_TYPE_FLOAT,  {.dbl=0},    -360, 360, .flags = FLAGS },
878     { "elevation", "set elevation",  OFFSET(elevation), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -90,  90, .flags = FLAGS },
879     { "radius",    "set radius",     OFFSET(radius),    AV_OPT_TYPE_FLOAT,  {.dbl=1},       0,   5, .flags = FLAGS },
880     { "type",      "set processing", OFFSET(type),      AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
881     { "time",      "time domain",      0,               AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
882     { "freq",      "frequency domain", 0,               AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
883     { "speakers",  "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING,  {.str=0},    0, 0, .flags = FLAGS },
884     { "lfegain",   "set lfe gain",                 OFFSET(lfe_gain),     AV_OPT_TYPE_FLOAT,   {.dbl=0},   -9, 9, .flags = FLAGS },
885     { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT,    {.i64=1024},1024,96000, .flags = FLAGS },
886     { NULL }
887 };
888
889 AVFILTER_DEFINE_CLASS(sofalizer);
890
891 static const AVFilterPad inputs[] = {
892     {
893         .name         = "default",
894         .type         = AVMEDIA_TYPE_AUDIO,
895         .config_props = config_input,
896         .filter_frame = filter_frame,
897     },
898     { NULL }
899 };
900
901 static const AVFilterPad outputs[] = {
902     {
903         .name = "default",
904         .type = AVMEDIA_TYPE_AUDIO,
905     },
906     { NULL }
907 };
908
909 AVFilter ff_af_sofalizer = {
910     .name          = "sofalizer",
911     .description   = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
912     .priv_size     = sizeof(SOFAlizerContext),
913     .priv_class    = &sofalizer_class,
914     .init          = init,
915     .uninit        = uninit,
916     .query_formats = query_formats,
917     .inputs        = inputs,
918     .outputs       = outputs,
919     .flags         = AVFILTER_FLAG_SLICE_THREADS,
920 };