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