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