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