]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_sofalizer.c
avfilter/af_sofalizer: reset FFT pointers back to NULL
[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 ir_samples;      /* length of one impulse response (IR) */
47     int n_samples;       /* ir_samples to next power of 2 */
48     float *lir, *rir;    /* IRs (time-domain) */
49     int max_delay;
50 } MySofa;
51
52 typedef struct VirtualSpeaker {
53     uint8_t set;
54     float azim;
55     float elev;
56 } VirtualSpeaker;
57
58 typedef struct SOFAlizerContext {
59     const AVClass *class;
60
61     char *filename;             /* name of SOFA file */
62     MySofa sofa;                /* contains data of the SOFA file */
63
64     int sample_rate;            /* sample rate from SOFA file */
65     float *speaker_azim;        /* azimuth of the virtual loudspeakers */
66     float *speaker_elev;        /* elevation of the virtual loudspeakers */
67     char *speakers_pos;         /* custom positions of the virtual loudspeakers */
68     float lfe_gain;             /* initial gain for the LFE channel */
69     float gain_lfe;             /* gain applied to LFE channel */
70     int lfe_channel;            /* LFE channel position in channel layout */
71
72     int n_conv;                 /* number of channels to convolute */
73
74                                 /* buffer variables (for convolution) */
75     float *ringbuffer[2];       /* buffers input samples, length of one buffer: */
76                                 /* no. input ch. (incl. LFE) x buffer_length */
77     int write[2];               /* current write position to ringbuffer */
78     int buffer_length;          /* is: longest IR plus max. delay in all SOFA files */
79                                 /* then choose next power of 2 */
80     int n_fft;                  /* number of samples in one FFT block */
81
82                                 /* netCDF variables */
83     int *delay[2];              /* broadband delay for each channel/IR to be convolved */
84
85     float *data_ir[2];          /* IRs for all channels to be convolved */
86                                 /* (this excludes the LFE) */
87     float *temp_src[2];
88     FFTComplex *temp_fft[2];
89
90                          /* control variables */
91     float gain;          /* filter gain (in dB) */
92     float rotation;      /* rotation of virtual loudspeakers (in degrees)  */
93     float elevation;     /* elevation of virtual loudspeakers (in deg.) */
94     float radius;        /* distance virtual loudspeakers to listener (in metres) */
95     int type;            /* processing type */
96     int framesize;       /* size of buffer */
97
98     VirtualSpeaker vspkrpos[64];
99
100     FFTContext *fft[2], *ifft[2];
101     FFTComplex *data_hrtf[2];
102
103     AVFloatDSPContext *fdsp;
104 } SOFAlizerContext;
105
106 static int close_sofa(struct MySofa *sofa)
107 {
108     mysofa_close(sofa->easy);
109     sofa->easy = NULL;
110
111     return 0;
112 }
113
114 static int preload_sofa(AVFilterContext *ctx, char *filename, int *samplingrate)
115 {
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     av_log(ctx, AV_LOG_DEBUG, "Original IR length: %d.\n", mysofa->N);
129     *samplingrate = mysofa->DataSamplingRate.values[0];
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 ir_samples = s->sofa.ir_samples; /* length of one IR */
295     const int n_samples = s->sofa.n_samples;
296     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
297     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
298     const int in_channels = s->n_conv; /* number of input channels */
299     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
300     const int buffer_length = s->buffer_length;
301     /* -1 for AND instead of MODULO (applied to powers of 2): */
302     const uint32_t modulo = (uint32_t)buffer_length - 1;
303     float *buffer[16]; /* holds ringbuffer for each input channel */
304     int wr = *write;
305     int read;
306     int i, l;
307
308     dst += offset;
309     for (l = 0; l < in_channels; l++) {
310         /* get starting address of ringbuffer for each input channel */
311         buffer[l] = ringbuffer + l * buffer_length;
312     }
313
314     for (i = 0; i < in->nb_samples; i++) {
315         const float *temp_ir = ir; /* using same set of IRs for each sample */
316
317         dst[0] = 0;
318         for (l = 0; l < in_channels; l++) {
319             /* write current input sample to ringbuffer (for each channel) */
320             buffer[l][wr] = src[l];
321         }
322
323         /* loop goes through all channels to be convolved */
324         for (l = 0; l < in_channels; l++) {
325             const float *const bptr = buffer[l];
326
327             if (l == s->lfe_channel) {
328                 /* LFE is an input channel but requires no convolution */
329                 /* apply gain to LFE signal and add to output buffer */
330                 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
331                 temp_ir += n_samples;
332                 continue;
333             }
334
335             /* current read position in ringbuffer: input sample write position
336              * - delay for l-th ch. + diff. betw. IR length and buffer length
337              * (mod buffer length) */
338             read = (wr - delay[l] - (n_samples - 1) + buffer_length) & modulo;
339
340             if (read + n_samples < buffer_length) {
341                 memmove(temp_src, bptr + read, n_samples * sizeof(*temp_src));
342             } else {
343                 int len = FFMIN(n_samples - (read % n_samples), buffer_length - read);
344
345                 memmove(temp_src, bptr + read, len * sizeof(*temp_src));
346                 memmove(temp_src + len, bptr, (n_samples - len) * sizeof(*temp_src));
347             }
348
349             /* multiply signal and IR, and add up the results */
350             dst[0] += s->fdsp->scalarproduct_float(temp_ir, temp_src, FFALIGN(ir_samples, 32));
351             temp_ir += n_samples;
352         }
353
354         /* clippings counter */
355         if (fabsf(dst[0]) > 1)
356             n_clippings[0]++;
357
358         /* move output buffer pointer by +2 to get to next sample of processed channel: */
359         dst += 2;
360         src += in_channels;
361         wr   = (wr + 1) & modulo; /* update ringbuffer write position */
362     }
363
364     *write = wr; /* remember write position in ringbuffer for next call */
365
366     return 0;
367 }
368
369 static int sofalizer_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
370 {
371     SOFAlizerContext *s = ctx->priv;
372     ThreadData *td = arg;
373     AVFrame *in = td->in, *out = td->out;
374     int offset = jobnr;
375     int *write = &td->write[jobnr];
376     FFTComplex *hrtf = s->data_hrtf[jobnr]; /* get pointers to current HRTF data */
377     int *n_clippings = &td->n_clippings[jobnr];
378     float *ringbuffer = td->ringbuffer[jobnr];
379     const int n_samples = s->sofa.n_samples; /* length of one IR */
380     const float *src = (const float *)in->data[0]; /* get pointer to audio input buffer */
381     float *dst = (float *)out->data[0]; /* get pointer to audio output buffer */
382     const int in_channels = s->n_conv; /* number of input channels */
383     /* ring buffer length is: longest IR plus max. delay -> next power of 2 */
384     const int buffer_length = s->buffer_length;
385     /* -1 for AND instead of MODULO (applied to powers of 2): */
386     const uint32_t modulo = (uint32_t)buffer_length - 1;
387     FFTComplex *fft_in = s->temp_fft[jobnr]; /* temporary array for FFT input/output data */
388     FFTContext *ifft = s->ifft[jobnr];
389     FFTContext *fft = s->fft[jobnr];
390     const int n_conv = s->n_conv;
391     const int n_fft = s->n_fft;
392     const float fft_scale = 1.0f / s->n_fft;
393     FFTComplex *hrtf_offset;
394     int wr = *write;
395     int n_read;
396     int i, j;
397
398     dst += offset;
399
400     /* find minimum between number of samples and output buffer length:
401      * (important, if one IR is longer than the output buffer) */
402     n_read = FFMIN(s->sofa.n_samples, in->nb_samples);
403     for (j = 0; j < n_read; j++) {
404         /* initialize output buf with saved signal from overflow buf */
405         dst[2 * j]     = ringbuffer[wr];
406         ringbuffer[wr] = 0.0; /* re-set read samples to zero */
407         /* update ringbuffer read/write position */
408         wr  = (wr + 1) & modulo;
409     }
410
411     /* initialize rest of output buffer with 0 */
412     for (j = n_read; j < in->nb_samples; j++) {
413         dst[2 * j] = 0;
414     }
415
416     for (i = 0; i < n_conv; i++) {
417         if (i == s->lfe_channel) { /* LFE */
418             for (j = 0; j < in->nb_samples; j++) {
419                 /* apply gain to LFE signal and add to output buffer */
420                 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
421             }
422             continue;
423         }
424
425         /* outer loop: go through all input channels to be convolved */
426         offset = i * n_fft; /* no. samples already processed */
427         hrtf_offset = hrtf + offset;
428
429         /* fill FFT input with 0 (we want to zero-pad) */
430         memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
431
432         for (j = 0; j < in->nb_samples; j++) {
433             /* prepare input for FFT */
434             /* write all samples of current input channel to FFT input array */
435             fft_in[j].re = src[j * in_channels + i];
436         }
437
438         /* transform input signal of current channel to frequency domain */
439         av_fft_permute(fft, fft_in);
440         av_fft_calc(fft, fft_in);
441         for (j = 0; j < n_fft; j++) {
442             const FFTComplex *hcomplex = hrtf_offset + j;
443             const float re = fft_in[j].re;
444             const float im = fft_in[j].im;
445
446             /* complex multiplication of input signal and HRTFs */
447             /* output channel (real): */
448             fft_in[j].re = re * hcomplex->re - im * hcomplex->im;
449             /* output channel (imag): */
450             fft_in[j].im = re * hcomplex->im + im * hcomplex->re;
451         }
452
453         /* transform output signal of current channel back to time domain */
454         av_fft_permute(ifft, fft_in);
455         av_fft_calc(ifft, fft_in);
456
457         for (j = 0; j < in->nb_samples; j++) {
458             /* write output signal of current channel to output buffer */
459             dst[2 * j] += fft_in[j].re * fft_scale;
460         }
461
462         for (j = 0; j < n_samples - 1; j++) { /* overflow length is IR length - 1 */
463             /* write the rest of output signal to overflow buffer */
464             int write_pos = (wr + j) & modulo;
465
466             *(ringbuffer + write_pos) += fft_in[in->nb_samples + j].re * fft_scale;
467         }
468     }
469
470     /* go through all samples of current output buffer: count clippings */
471     for (i = 0; i < out->nb_samples; i++) {
472         /* clippings counter */
473         if (fabsf(dst[0]) > 1) { /* if current output sample > 1 */
474             n_clippings[0]++;
475         }
476
477         /* move output buffer pointer by +2 to get to next sample of processed channel: */
478         dst += 2;
479     }
480
481     /* remember read/write position in ringbuffer for next call */
482     *write = wr;
483
484     return 0;
485 }
486
487 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
488 {
489     AVFilterContext *ctx = inlink->dst;
490     SOFAlizerContext *s = ctx->priv;
491     AVFilterLink *outlink = ctx->outputs[0];
492     int n_clippings[2] = { 0 };
493     ThreadData td;
494     AVFrame *out;
495
496     out = ff_get_audio_buffer(outlink, in->nb_samples);
497     if (!out) {
498         av_frame_free(&in);
499         return AVERROR(ENOMEM);
500     }
501     av_frame_copy_props(out, in);
502
503     td.in = in; td.out = out; td.write = s->write;
504     td.delay = s->delay; td.ir = s->data_ir; td.n_clippings = n_clippings;
505     td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
506     td.temp_fft = s->temp_fft;
507
508     if (s->type == TIME_DOMAIN) {
509         ctx->internal->execute(ctx, sofalizer_convolute, &td, NULL, 2);
510     } else {
511         ctx->internal->execute(ctx, sofalizer_fast_convolute, &td, NULL, 2);
512     }
513     emms_c();
514
515     /* display error message if clipping occurred */
516     if (n_clippings[0] + n_clippings[1] > 0) {
517         av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
518                n_clippings[0] + n_clippings[1], out->nb_samples * 2);
519     }
520
521     av_frame_free(&in);
522     return ff_filter_frame(outlink, out);
523 }
524
525 static int query_formats(AVFilterContext *ctx)
526 {
527     struct SOFAlizerContext *s = ctx->priv;
528     AVFilterFormats *formats = NULL;
529     AVFilterChannelLayouts *layouts = NULL;
530     int ret, sample_rates[] = { 48000, -1 };
531
532     ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
533     if (ret)
534         return ret;
535     ret = ff_set_common_formats(ctx, formats);
536     if (ret)
537         return ret;
538
539     layouts = ff_all_channel_layouts();
540     if (!layouts)
541         return AVERROR(ENOMEM);
542
543     ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts);
544     if (ret)
545         return ret;
546
547     layouts = NULL;
548     ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
549     if (ret)
550         return ret;
551
552     ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts);
553     if (ret)
554         return ret;
555
556     sample_rates[0] = s->sample_rate;
557     formats = ff_make_format_list(sample_rates);
558     if (!formats)
559         return AVERROR(ENOMEM);
560     return ff_set_common_samplerates(ctx, formats);
561 }
562
563 static int load_data(AVFilterContext *ctx, int azim, int elev, float radius, int sample_rate)
564 {
565     struct SOFAlizerContext *s = ctx->priv;
566     int n_samples;
567     int ir_samples;
568     int n_conv = s->n_conv; /* no. channels to convolve */
569     int n_fft;
570     float delay_l; /* broadband delay for each IR */
571     float delay_r;
572     int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */
573     float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */
574     FFTComplex *data_hrtf_l = NULL;
575     FFTComplex *data_hrtf_r = NULL;
576     FFTComplex *fft_in_l = NULL;
577     FFTComplex *fft_in_r = NULL;
578     float *data_ir_l = NULL;
579     float *data_ir_r = NULL;
580     int offset = 0; /* used for faster pointer arithmetics in for-loop */
581     int i, j, azim_orig = azim, elev_orig = elev;
582     int filter_length, ret = 0;
583     int n_current;
584     int n_max = 0;
585
586     s->sofa.easy = mysofa_open(s->filename, sample_rate, &filter_length, &ret);
587     if (!s->sofa.easy || ret) { /* if an invalid SOFA file has been selected */
588         av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");
589         return AVERROR_INVALIDDATA;
590     }
591
592     av_log(ctx, AV_LOG_DEBUG, "IR length: %d.\n", s->sofa.easy->hrtf->N);
593     s->sofa.ir_samples = s->sofa.easy->hrtf->N;
594     s->sofa.n_samples = 1 << (32 - ff_clz(s->sofa.ir_samples));
595
596     n_samples = s->sofa.n_samples;
597     ir_samples = s->sofa.ir_samples;
598
599     s->data_ir[0] = av_calloc(n_samples, sizeof(float) * s->n_conv);
600     s->data_ir[1] = av_calloc(n_samples, sizeof(float) * s->n_conv);
601     s->delay[0] = av_calloc(s->n_conv, sizeof(int));
602     s->delay[1] = av_calloc(s->n_conv, sizeof(int));
603
604     if (!s->data_ir[0] || !s->data_ir[1] || !s->delay[0] || !s->delay[1]) {
605         ret = AVERROR(ENOMEM);
606         goto fail;
607     }
608
609     /* get temporary IR for L and R channel */
610     data_ir_l = av_calloc(n_conv * n_samples, sizeof(*data_ir_l));
611     data_ir_r = av_calloc(n_conv * n_samples, sizeof(*data_ir_r));
612     if (!data_ir_r || !data_ir_l) {
613         ret = AVERROR(ENOMEM);
614         goto fail;
615     }
616
617     if (s->type == TIME_DOMAIN) {
618         s->temp_src[0] = av_calloc(n_samples, sizeof(float));
619         s->temp_src[1] = av_calloc(n_samples, sizeof(float));
620         if (!s->temp_src[0] || !s->temp_src[1]) {
621             ret = AVERROR(ENOMEM);
622             goto fail;
623         }
624     }
625
626     s->speaker_azim = av_calloc(s->n_conv, sizeof(*s->speaker_azim));
627     s->speaker_elev = av_calloc(s->n_conv, sizeof(*s->speaker_elev));
628     if (!s->speaker_azim || !s->speaker_elev) {
629         ret = AVERROR(ENOMEM);
630         goto fail;
631     }
632
633     /* get speaker positions */
634     if ((ret = get_speaker_pos(ctx, s->speaker_azim, s->speaker_elev)) < 0) {
635         av_log(ctx, AV_LOG_ERROR, "Couldn't get speaker positions. Input channel configuration not supported.\n");
636         goto fail;
637     }
638
639     for (i = 0; i < s->n_conv; i++) {
640         float coordinates[3];
641
642         /* load and store IRs and corresponding delays */
643         azim = (int)(s->speaker_azim[i] + azim_orig) % 360;
644         elev = (int)(s->speaker_elev[i] + elev_orig) % 90;
645
646         coordinates[0] = azim;
647         coordinates[1] = elev;
648         coordinates[2] = radius;
649
650         mysofa_s2c(coordinates);
651
652         /* get id of IR closest to desired position */
653         mysofa_getfilter_float(s->sofa.easy, coordinates[0], coordinates[1], coordinates[2],
654                                data_ir_l + n_samples * i,
655                                data_ir_r + n_samples * i,
656                                &delay_l, &delay_r);
657
658         s->delay[0][i] = delay_l * sample_rate;
659         s->delay[1][i] = delay_r * sample_rate;
660
661         s->sofa.max_delay = FFMAX3(s->sofa.max_delay, s->delay[0][i], s->delay[1][i]);
662     }
663
664     /* get size of ringbuffer (longest IR plus max. delay) */
665     /* then choose next power of 2 for performance optimization */
666     n_current = n_samples + s->sofa.max_delay;
667     /* length of longest IR plus max. delay */
668     n_max = FFMAX(n_max, n_current);
669
670     /* buffer length is longest IR plus max. delay -> next power of 2
671        (32 - count leading zeros gives required exponent)  */
672     s->buffer_length = 1 << (32 - ff_clz(n_max));
673     s->n_fft = n_fft = 1 << (32 - ff_clz(n_max + s->framesize));
674
675     if (s->type == FREQUENCY_DOMAIN) {
676         av_fft_end(s->fft[0]);
677         av_fft_end(s->fft[1]);
678         s->fft[0] = av_fft_init(log2(s->n_fft), 0);
679         s->fft[1] = av_fft_init(log2(s->n_fft), 0);
680         av_fft_end(s->ifft[0]);
681         av_fft_end(s->ifft[1]);
682         s->ifft[0] = av_fft_init(log2(s->n_fft), 1);
683         s->ifft[1] = av_fft_init(log2(s->n_fft), 1);
684
685         if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
686             av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
687             ret = AVERROR(ENOMEM);
688             goto fail;
689         }
690     }
691
692     if (s->type == TIME_DOMAIN) {
693         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
694         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
695     } else {
696         /* get temporary HRTF memory for L and R channel */
697         data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);
698         data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);
699         if (!data_hrtf_r || !data_hrtf_l) {
700             ret = AVERROR(ENOMEM);
701             goto fail;
702         }
703
704         s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
705         s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
706         s->temp_fft[0] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
707         s->temp_fft[1] = av_malloc_array(s->n_fft, sizeof(FFTComplex));
708         if (!s->temp_fft[0] || !s->temp_fft[1]) {
709             ret = AVERROR(ENOMEM);
710             goto fail;
711         }
712     }
713
714     if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
715         ret = AVERROR(ENOMEM);
716         goto fail;
717     }
718
719     if (s->type == FREQUENCY_DOMAIN) {
720         fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));
721         fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));
722         if (!fft_in_l || !fft_in_r) {
723             ret = AVERROR(ENOMEM);
724             goto fail;
725         }
726     }
727
728     for (i = 0; i < s->n_conv; i++) {
729         float *lir, *rir;
730
731         offset = i * n_samples; /* no. samples already written */
732
733         lir = data_ir_l + offset;
734         rir = data_ir_r + offset;
735
736         if (s->type == TIME_DOMAIN) {
737             for (j = 0; j < ir_samples; j++) {
738                 /* load reversed IRs of the specified source position
739                  * sample-by-sample for left and right ear; and apply gain */
740                 s->data_ir[0][offset + j] = lir[ir_samples - 1 - j] * gain_lin;
741                 s->data_ir[1][offset + j] = rir[ir_samples - 1 - j] * gain_lin;
742             }
743         } else {
744             memset(fft_in_l, 0, n_fft * sizeof(*fft_in_l));
745             memset(fft_in_r, 0, n_fft * sizeof(*fft_in_r));
746
747             offset = i * n_fft; /* no. samples already written */
748             for (j = 0; j < ir_samples; j++) {
749                 /* load non-reversed IRs of the specified source position
750                  * sample-by-sample and apply gain,
751                  * L channel is loaded to real part, R channel to imag part,
752                  * IRs ared shifted by L and R delay */
753                 fft_in_l[s->delay[0][i] + j].re = lir[j] * gain_lin;
754                 fft_in_r[s->delay[1][i] + j].re = rir[j] * gain_lin;
755             }
756
757             /* actually transform to frequency domain (IRs -> HRTFs) */
758             av_fft_permute(s->fft[0], fft_in_l);
759             av_fft_calc(s->fft[0], fft_in_l);
760             memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));
761             av_fft_permute(s->fft[0], fft_in_r);
762             av_fft_calc(s->fft[0], fft_in_r);
763             memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));
764         }
765     }
766
767     if (s->type == FREQUENCY_DOMAIN) {
768         s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
769         s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));
770         if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
771             ret = AVERROR(ENOMEM);
772             goto fail;
773         }
774
775         memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */
776             sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */
777         memcpy(s->data_hrtf[1], data_hrtf_r,
778             sizeof(FFTComplex) * n_conv * n_fft);
779     }
780
781 fail:
782     av_freep(&data_hrtf_l); /* free temporary HRTF memory */
783     av_freep(&data_hrtf_r);
784
785     av_freep(&data_ir_l); /* free temprary IR memory */
786     av_freep(&data_ir_r);
787
788     av_freep(&fft_in_l); /* free temporary FFT memory */
789     av_freep(&fft_in_r);
790
791     return ret;
792 }
793
794 static av_cold int init(AVFilterContext *ctx)
795 {
796     SOFAlizerContext *s = ctx->priv;
797     int ret;
798
799     if (!s->filename) {
800         av_log(ctx, AV_LOG_ERROR, "Valid SOFA filename must be set.\n");
801         return AVERROR(EINVAL);
802     }
803
804     /* preload SOFA file, */
805     ret = preload_sofa(ctx, s->filename, &s->sample_rate);
806     if (ret) {
807         /* file loading error */
808         av_log(ctx, AV_LOG_ERROR, "Error while loading SOFA file: '%s'\n", s->filename);
809     } else { /* no file loading error, resampling not required */
810         av_log(ctx, AV_LOG_DEBUG, "File '%s' loaded.\n", s->filename);
811     }
812
813     if (ret) {
814         av_log(ctx, AV_LOG_ERROR, "No valid SOFA file could be loaded. Please specify valid SOFA file.\n");
815         return ret;
816     }
817
818     s->fdsp = avpriv_float_dsp_alloc(0);
819     if (!s->fdsp)
820         return AVERROR(ENOMEM);
821
822     return 0;
823 }
824
825 static int config_input(AVFilterLink *inlink)
826 {
827     AVFilterContext *ctx = inlink->dst;
828     SOFAlizerContext *s = ctx->priv;
829     int ret;
830
831     if (s->type == FREQUENCY_DOMAIN) {
832         inlink->partial_buf_size =
833         inlink->min_samples =
834         inlink->max_samples = s->framesize;
835     }
836
837     /* gain -3 dB per channel, -6 dB to get LFE on a similar level */
838     s->gain_lfe = expf((s->gain - 3 * inlink->channels - 6 + s->lfe_gain) / 20 * M_LN10);
839
840     s->n_conv = inlink->channels;
841
842     /* load IRs to data_ir[0] and data_ir[1] for required directions */
843     if ((ret = load_data(ctx, s->rotation, s->elevation, s->radius, inlink->sample_rate)) < 0)
844         return ret;
845
846     av_log(ctx, AV_LOG_DEBUG, "Samplerate: %d Channels to convolute: %d, Length of ringbuffer: %d x %d\n",
847         inlink->sample_rate, s->n_conv, inlink->channels, s->buffer_length);
848
849     return 0;
850 }
851
852 static av_cold void uninit(AVFilterContext *ctx)
853 {
854     SOFAlizerContext *s = ctx->priv;
855
856     close_sofa(&s->sofa);
857     av_fft_end(s->ifft[0]);
858     av_fft_end(s->ifft[1]);
859     av_fft_end(s->fft[0]);
860     av_fft_end(s->fft[1]);
861     s->ifft[0] = NULL;
862     s->ifft[1] = NULL;
863     s->fft[0] = NULL;
864     s->fft[1] = NULL;
865     av_freep(&s->delay[0]);
866     av_freep(&s->delay[1]);
867     av_freep(&s->data_ir[0]);
868     av_freep(&s->data_ir[1]);
869     av_freep(&s->ringbuffer[0]);
870     av_freep(&s->ringbuffer[1]);
871     av_freep(&s->speaker_azim);
872     av_freep(&s->speaker_elev);
873     av_freep(&s->temp_src[0]);
874     av_freep(&s->temp_src[1]);
875     av_freep(&s->temp_fft[0]);
876     av_freep(&s->temp_fft[1]);
877     av_freep(&s->data_hrtf[0]);
878     av_freep(&s->data_hrtf[1]);
879     av_freep(&s->fdsp);
880 }
881
882 #define OFFSET(x) offsetof(SOFAlizerContext, x)
883 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
884
885 static const AVOption sofalizer_options[] = {
886     { "sofa",      "sofa filename",  OFFSET(filename),  AV_OPT_TYPE_STRING, {.str=NULL},            .flags = FLAGS },
887     { "gain",      "set gain in dB", OFFSET(gain),      AV_OPT_TYPE_FLOAT,  {.dbl=0},     -20,  40, .flags = FLAGS },
888     { "rotation",  "set rotation"  , OFFSET(rotation),  AV_OPT_TYPE_FLOAT,  {.dbl=0},    -360, 360, .flags = FLAGS },
889     { "elevation", "set elevation",  OFFSET(elevation), AV_OPT_TYPE_FLOAT,  {.dbl=0},     -90,  90, .flags = FLAGS },
890     { "radius",    "set radius",     OFFSET(radius),    AV_OPT_TYPE_FLOAT,  {.dbl=1},       0,   5, .flags = FLAGS },
891     { "type",      "set processing", OFFSET(type),      AV_OPT_TYPE_INT,    {.i64=1},       0,   1, .flags = FLAGS, "type" },
892     { "time",      "time domain",      0,               AV_OPT_TYPE_CONST,  {.i64=0},       0,   0, .flags = FLAGS, "type" },
893     { "freq",      "frequency domain", 0,               AV_OPT_TYPE_CONST,  {.i64=1},       0,   0, .flags = FLAGS, "type" },
894     { "speakers",  "set speaker custom positions", OFFSET(speakers_pos), AV_OPT_TYPE_STRING,  {.str=0},    0, 0, .flags = FLAGS },
895     { "lfegain",   "set lfe gain",                 OFFSET(lfe_gain),     AV_OPT_TYPE_FLOAT,   {.dbl=0},  -20,40, .flags = FLAGS },
896     { "framesize", "set frame size", OFFSET(framesize), AV_OPT_TYPE_INT,    {.i64=1024},1024,96000, .flags = FLAGS },
897     { NULL }
898 };
899
900 AVFILTER_DEFINE_CLASS(sofalizer);
901
902 static const AVFilterPad inputs[] = {
903     {
904         .name         = "default",
905         .type         = AVMEDIA_TYPE_AUDIO,
906         .config_props = config_input,
907         .filter_frame = filter_frame,
908     },
909     { NULL }
910 };
911
912 static const AVFilterPad outputs[] = {
913     {
914         .name = "default",
915         .type = AVMEDIA_TYPE_AUDIO,
916     },
917     { NULL }
918 };
919
920 AVFilter ff_af_sofalizer = {
921     .name          = "sofalizer",
922     .description   = NULL_IF_CONFIG_SMALL("SOFAlizer (Spatially Oriented Format for Acoustics)."),
923     .priv_size     = sizeof(SOFAlizerContext),
924     .priv_class    = &sofalizer_class,
925     .init          = init,
926     .uninit        = uninit,
927     .query_formats = query_formats,
928     .inputs        = inputs,
929     .outputs       = outputs,
930     .flags         = AVFILTER_FLAG_SLICE_THREADS,
931 };