2 * Copyright (C) 2017 Paul B Mahol
3 * Copyright (C) 2013-2015 Andreas Fuchs, Wolfgang Hrauda
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavutil/avstring.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/float_dsp.h"
26 #include "libavutil/intmath.h"
27 #include "libavutil/opt.h"
28 #include "libavcodec/avfft.h"
36 #define FREQUENCY_DOMAIN 1
41 typedef struct HeadphoneContext {
60 float lfe_gain, gain_lfe;
72 FFTComplex *temp_fft[2];
73 FFTComplex *temp_afft[2];
75 FFTContext *fft[2], *ifft[2];
76 FFTComplex *data_hrtf[2];
78 float (*scalarproduct_float)(const float *v1, const float *v2, int len);
86 static int parse_channel_name(const char *arg, uint64_t *rchannel)
88 uint64_t layout = av_get_channel_layout(arg);
90 if (av_get_channel_layout_nb_channels(layout) != 1)
91 return AVERROR(EINVAL);
96 static void parse_map(AVFilterContext *ctx)
98 HeadphoneContext *s = ctx->priv;
99 char *arg, *tokenizer, *p;
100 uint64_t used_channels = 0;
103 while ((arg = av_strtok(p, "|", &tokenizer))) {
104 uint64_t out_channel;
107 if (parse_channel_name(arg, &out_channel)) {
108 av_log(ctx, AV_LOG_WARNING, "Failed to parse \'%s\' as channel name.\n", arg);
111 if (used_channels & out_channel) {
112 av_log(ctx, AV_LOG_WARNING, "Ignoring duplicate channel '%s'.\n", arg);
115 used_channels |= out_channel;
116 s->mapping[s->nb_irs] = out_channel;
120 if (s->hrir_fmt == HRIR_MULTI)
121 s->nb_hrir_inputs = 1;
123 s->nb_hrir_inputs = s->nb_irs;
126 typedef struct ThreadData {
133 FFTComplex **temp_fft;
134 FFTComplex **temp_afft;
137 static int headphone_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
139 HeadphoneContext *s = ctx->priv;
140 ThreadData *td = arg;
141 AVFrame *in = td->in, *out = td->out;
143 int *write = &td->write[jobnr];
144 const float *const ir = td->ir[jobnr];
145 int *n_clippings = &td->n_clippings[jobnr];
146 float *ringbuffer = td->ringbuffer[jobnr];
147 float *temp_src = td->temp_src[jobnr];
148 const int ir_len = s->ir_len;
149 const int air_len = s->air_len;
150 const float *src = (const float *)in->data[0];
151 float *dst = (float *)out->data[0];
152 const int in_channels = in->channels;
153 const int buffer_length = s->buffer_length;
154 const uint32_t modulo = (uint32_t)buffer_length - 1;
161 for (l = 0; l < in_channels; l++) {
162 buffer[l] = ringbuffer + l * buffer_length;
165 for (i = 0; i < in->nb_samples; i++) {
166 const float *cur_ir = ir;
169 for (l = 0; l < in_channels; l++) {
170 *(buffer[l] + wr) = src[l];
173 for (l = 0; l < in_channels; cur_ir += air_len, l++) {
174 const float *const bptr = buffer[l];
176 if (l == s->lfe_channel) {
177 *dst += *(buffer[s->lfe_channel] + wr) * s->gain_lfe;
181 read = (wr - (ir_len - 1)) & modulo;
183 if (read + ir_len < buffer_length) {
184 memcpy(temp_src, bptr + read, ir_len * sizeof(*temp_src));
186 int len = FFMIN(air_len - (read % ir_len), buffer_length - read);
188 memcpy(temp_src, bptr + read, len * sizeof(*temp_src));
189 memcpy(temp_src + len, bptr, (air_len - len) * sizeof(*temp_src));
192 dst[0] += s->scalarproduct_float(cur_ir, temp_src, FFALIGN(ir_len, 32));
195 if (fabsf(dst[0]) > 1)
200 wr = (wr + 1) & modulo;
208 static int headphone_fast_convolute(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
210 HeadphoneContext *s = ctx->priv;
211 ThreadData *td = arg;
212 AVFrame *in = td->in, *out = td->out;
214 int *write = &td->write[jobnr];
215 FFTComplex *hrtf = s->data_hrtf[jobnr];
216 int *n_clippings = &td->n_clippings[jobnr];
217 float *ringbuffer = td->ringbuffer[jobnr];
218 const int ir_len = s->ir_len;
219 const float *src = (const float *)in->data[0];
220 float *dst = (float *)out->data[0];
221 const int in_channels = in->channels;
222 const int buffer_length = s->buffer_length;
223 const uint32_t modulo = (uint32_t)buffer_length - 1;
224 FFTComplex *fft_in = s->temp_fft[jobnr];
225 FFTComplex *fft_acc = s->temp_afft[jobnr];
226 FFTContext *ifft = s->ifft[jobnr];
227 FFTContext *fft = s->fft[jobnr];
228 const int n_fft = s->n_fft;
229 const float fft_scale = 1.0f / s->n_fft;
230 FFTComplex *hrtf_offset;
237 n_read = FFMIN(ir_len, in->nb_samples);
238 for (j = 0; j < n_read; j++) {
239 dst[2 * j] = ringbuffer[wr];
240 ringbuffer[wr] = 0.0;
241 wr = (wr + 1) & modulo;
244 for (j = n_read; j < in->nb_samples; j++) {
248 memset(fft_acc, 0, sizeof(FFTComplex) * n_fft);
250 for (i = 0; i < in_channels; i++) {
251 if (i == s->lfe_channel) {
252 for (j = 0; j < in->nb_samples; j++) {
253 dst[2 * j] += src[i + j * in_channels] * s->gain_lfe;
259 hrtf_offset = hrtf + offset;
261 memset(fft_in, 0, sizeof(FFTComplex) * n_fft);
263 for (j = 0; j < in->nb_samples; j++) {
264 fft_in[j].re = src[j * in_channels + i];
267 av_fft_permute(fft, fft_in);
268 av_fft_calc(fft, fft_in);
269 for (j = 0; j < n_fft; j++) {
270 const FFTComplex *hcomplex = hrtf_offset + j;
271 const float re = fft_in[j].re;
272 const float im = fft_in[j].im;
274 fft_acc[j].re += re * hcomplex->re - im * hcomplex->im;
275 fft_acc[j].im += re * hcomplex->im + im * hcomplex->re;
279 av_fft_permute(ifft, fft_acc);
280 av_fft_calc(ifft, fft_acc);
282 for (j = 0; j < in->nb_samples; j++) {
283 dst[2 * j] += fft_acc[j].re * fft_scale;
284 if (fabsf(dst[2 * j]) > 1)
288 for (j = 0; j < ir_len - 1; j++) {
289 int write_pos = (wr + j) & modulo;
291 *(ringbuffer + write_pos) += fft_acc[in->nb_samples + j].re * fft_scale;
299 static int check_ir(AVFilterLink *inlink, int input_number)
301 AVFilterContext *ctx = inlink->dst;
302 HeadphoneContext *s = ctx->priv;
303 int ir_len, max_ir_len;
305 ir_len = ff_inlink_queued_samples(inlink);
307 if (ir_len > max_ir_len) {
308 av_log(ctx, AV_LOG_ERROR, "Too big length of IRs: %d > %d.\n", ir_len, max_ir_len);
309 return AVERROR(EINVAL);
311 s->hrir_in[input_number].ir_len = ir_len;
312 s->ir_len = FFMAX(ir_len, s->ir_len);
317 static int headphone_frame(HeadphoneContext *s, AVFrame *in, AVFilterLink *outlink)
319 AVFilterContext *ctx = outlink->src;
320 int n_clippings[2] = { 0 };
324 out = ff_get_audio_buffer(outlink, in->nb_samples);
327 return AVERROR(ENOMEM);
331 td.in = in; td.out = out; td.write = s->write;
332 td.ir = s->data_ir; td.n_clippings = n_clippings;
333 td.ringbuffer = s->ringbuffer; td.temp_src = s->temp_src;
334 td.temp_fft = s->temp_fft;
335 td.temp_afft = s->temp_afft;
337 if (s->type == TIME_DOMAIN) {
338 ctx->internal->execute(ctx, headphone_convolute, &td, NULL, 2);
340 ctx->internal->execute(ctx, headphone_fast_convolute, &td, NULL, 2);
344 if (n_clippings[0] + n_clippings[1] > 0) {
345 av_log(ctx, AV_LOG_WARNING, "%d of %d samples clipped. Please reduce gain.\n",
346 n_clippings[0] + n_clippings[1], out->nb_samples * 2);
350 return ff_filter_frame(outlink, out);
353 static int convert_coeffs(AVFilterContext *ctx, AVFilterLink *inlink)
355 struct HeadphoneContext *s = ctx->priv;
356 const int ir_len = s->ir_len;
357 int nb_input_channels = ctx->inputs[0]->channels;
358 float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10);
364 s->air_len = 1 << (32 - ff_clz(ir_len));
365 if (s->type == TIME_DOMAIN) {
366 s->air_len = FFALIGN(s->air_len, 32);
368 s->buffer_length = 1 << (32 - ff_clz(s->air_len));
369 s->n_fft = n_fft = 1 << (32 - ff_clz(ir_len + s->size));
371 if (s->type == FREQUENCY_DOMAIN) {
372 s->fft[0] = av_fft_init(av_log2(s->n_fft), 0);
373 s->fft[1] = av_fft_init(av_log2(s->n_fft), 0);
374 s->ifft[0] = av_fft_init(av_log2(s->n_fft), 1);
375 s->ifft[1] = av_fft_init(av_log2(s->n_fft), 1);
377 if (!s->fft[0] || !s->fft[1] || !s->ifft[0] || !s->ifft[1]) {
378 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT contexts of size %d.\n", s->n_fft);
379 ret = AVERROR(ENOMEM);
384 if (s->type == TIME_DOMAIN) {
385 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
386 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float) * nb_input_channels);
388 s->ringbuffer[0] = av_calloc(s->buffer_length, sizeof(float));
389 s->ringbuffer[1] = av_calloc(s->buffer_length, sizeof(float));
390 s->temp_fft[0] = av_calloc(s->n_fft, sizeof(FFTComplex));
391 s->temp_fft[1] = av_calloc(s->n_fft, sizeof(FFTComplex));
392 s->temp_afft[0] = av_calloc(s->n_fft, sizeof(FFTComplex));
393 s->temp_afft[1] = av_calloc(s->n_fft, sizeof(FFTComplex));
394 if (!s->temp_fft[0] || !s->temp_fft[1] ||
395 !s->temp_afft[0] || !s->temp_afft[1]) {
396 ret = AVERROR(ENOMEM);
401 if (!s->ringbuffer[0] || !s->ringbuffer[1]) {
402 ret = AVERROR(ENOMEM);
406 if (s->type == TIME_DOMAIN) {
407 s->temp_src[0] = av_calloc(s->air_len, sizeof(float));
408 s->temp_src[1] = av_calloc(s->air_len, sizeof(float));
410 s->data_ir[0] = av_calloc(nb_input_channels * s->air_len, sizeof(*s->data_ir[0]));
411 s->data_ir[1] = av_calloc(nb_input_channels * s->air_len, sizeof(*s->data_ir[1]));
412 if (!s->data_ir[0] || !s->data_ir[1] || !s->temp_src[0] || !s->temp_src[1]) {
413 ret = AVERROR(ENOMEM);
417 s->data_hrtf[0] = av_calloc(n_fft, sizeof(*s->data_hrtf[0]) * nb_input_channels);
418 s->data_hrtf[1] = av_calloc(n_fft, sizeof(*s->data_hrtf[1]) * nb_input_channels);
419 if (!s->data_hrtf[0] || !s->data_hrtf[1]) {
420 ret = AVERROR(ENOMEM);
425 for (i = 0; i < s->nb_hrir_inputs; av_frame_free(&frame), i++) {
426 int len = s->hrir_in[i].ir_len;
429 ret = ff_inlink_consume_samples(ctx->inputs[i + 1], len, len, &frame);
432 ptr = (float *)frame->extended_data[0];
434 if (s->hrir_fmt == HRIR_STEREO) {
435 int idx = av_get_channel_layout_channel_index(inlink->channel_layout,
439 if (s->type == TIME_DOMAIN) {
440 float *data_ir_l = s->data_ir[0] + idx * s->air_len;
441 float *data_ir_r = s->data_ir[1] + idx * s->air_len;
443 for (j = 0; j < len; j++) {
444 data_ir_l[j] = ptr[len * 2 - j * 2 - 2] * gain_lin;
445 data_ir_r[j] = ptr[len * 2 - j * 2 - 1] * gain_lin;
448 FFTComplex *fft_in_l = s->data_hrtf[0] + idx * n_fft;
449 FFTComplex *fft_in_r = s->data_hrtf[1] + idx * n_fft;
451 for (j = 0; j < len; j++) {
452 fft_in_l[j].re = ptr[j * 2 ] * gain_lin;
453 fft_in_r[j].re = ptr[j * 2 + 1] * gain_lin;
456 av_fft_permute(s->fft[0], fft_in_l);
457 av_fft_calc(s->fft[0], fft_in_l);
458 av_fft_permute(s->fft[0], fft_in_r);
459 av_fft_calc(s->fft[0], fft_in_r);
462 int I, N = ctx->inputs[1]->channels;
464 for (k = 0; k < N / 2; k++) {
465 int idx = av_get_channel_layout_channel_index(inlink->channel_layout,
471 if (s->type == TIME_DOMAIN) {
472 float *data_ir_l = s->data_ir[0] + idx * s->air_len;
473 float *data_ir_r = s->data_ir[1] + idx * s->air_len;
475 for (j = 0; j < len; j++) {
476 data_ir_l[j] = ptr[len * N - j * N - N + I ] * gain_lin;
477 data_ir_r[j] = ptr[len * N - j * N - N + I + 1] * gain_lin;
480 FFTComplex *fft_in_l = s->data_hrtf[0] + idx * n_fft;
481 FFTComplex *fft_in_r = s->data_hrtf[1] + idx * n_fft;
483 for (j = 0; j < len; j++) {
484 fft_in_l[j].re = ptr[j * N + I ] * gain_lin;
485 fft_in_r[j].re = ptr[j * N + I + 1] * gain_lin;
488 av_fft_permute(s->fft[0], fft_in_l);
489 av_fft_calc(s->fft[0], fft_in_l);
490 av_fft_permute(s->fft[0], fft_in_r);
491 av_fft_calc(s->fft[0], fft_in_r);
503 static int activate(AVFilterContext *ctx)
505 HeadphoneContext *s = ctx->priv;
506 AVFilterLink *inlink = ctx->inputs[0];
507 AVFilterLink *outlink = ctx->outputs[0];
511 FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[0], ctx);
514 for (i = 0; i < s->nb_hrir_inputs; i++) {
515 AVFilterLink *input = ctx->inputs[i + 1];
517 if (s->hrir_in[i].eof)
520 if ((ret = check_ir(input, i)) < 0)
523 if (ff_outlink_get_status(input) == AVERROR_EOF) {
524 if (!ff_inlink_queued_samples(input)) {
525 av_log(ctx, AV_LOG_ERROR, "No samples provided for "
526 "HRIR stream %d.\n", i);
527 return AVERROR_INVALIDDATA;
529 s->hrir_in[i].eof = 1;
531 if (ff_outlink_frame_wanted(ctx->outputs[0]))
532 ff_inlink_request_frame(input);
540 ret = convert_coeffs(ctx, inlink);
543 } else if (!s->have_hrirs)
546 if ((ret = ff_inlink_consume_samples(ctx->inputs[0], s->size, s->size, &in)) > 0) {
547 ret = headphone_frame(s, in, outlink);
555 FF_FILTER_FORWARD_STATUS(ctx->inputs[0], ctx->outputs[0]);
556 if (ff_outlink_frame_wanted(ctx->outputs[0]))
557 ff_inlink_request_frame(ctx->inputs[0]);
562 static int query_formats(AVFilterContext *ctx)
564 struct HeadphoneContext *s = ctx->priv;
565 AVFilterFormats *formats = NULL;
566 AVFilterChannelLayouts *layouts = NULL;
567 AVFilterChannelLayouts *stereo_layout = NULL;
568 AVFilterChannelLayouts *hrir_layouts = NULL;
571 ret = ff_add_format(&formats, AV_SAMPLE_FMT_FLT);
574 ret = ff_set_common_formats(ctx, formats);
578 layouts = ff_all_channel_layouts();
580 return AVERROR(ENOMEM);
582 ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->outcfg.channel_layouts);
586 ret = ff_add_channel_layout(&stereo_layout, AV_CH_LAYOUT_STEREO);
589 ret = ff_channel_layouts_ref(stereo_layout, &ctx->outputs[0]->incfg.channel_layouts);
593 if (s->hrir_fmt == HRIR_MULTI) {
594 hrir_layouts = ff_all_channel_counts();
596 return AVERROR(ENOMEM);
597 ret = ff_channel_layouts_ref(hrir_layouts, &ctx->inputs[1]->outcfg.channel_layouts);
601 for (i = 1; i <= s->nb_hrir_inputs; i++) {
602 ret = ff_channel_layouts_ref(stereo_layout, &ctx->inputs[i]->outcfg.channel_layouts);
608 formats = ff_all_samplerates();
610 return AVERROR(ENOMEM);
611 return ff_set_common_samplerates(ctx, formats);
614 static int config_input(AVFilterLink *inlink)
616 AVFilterContext *ctx = inlink->dst;
617 HeadphoneContext *s = ctx->priv;
619 if (s->nb_irs < inlink->channels) {
620 av_log(ctx, AV_LOG_ERROR, "Number of HRIRs must be >= %d.\n", inlink->channels);
621 return AVERROR(EINVAL);
624 s->lfe_channel = av_get_channel_layout_channel_index(inlink->channel_layout,
625 AV_CH_LOW_FREQUENCY);
629 static av_cold int init(AVFilterContext *ctx)
631 HeadphoneContext *s = ctx->priv;
636 .type = AVMEDIA_TYPE_AUDIO,
637 .config_props = config_input,
639 if ((ret = ff_insert_inpad(ctx, 0, &pad)) < 0)
643 av_log(ctx, AV_LOG_ERROR, "Valid mapping must be set.\n");
644 return AVERROR(EINVAL);
649 for (i = 0; i < s->nb_hrir_inputs; i++) {
650 char *name = av_asprintf("hrir%d", i);
653 .type = AVMEDIA_TYPE_AUDIO,
656 return AVERROR(ENOMEM);
657 if ((ret = ff_insert_inpad(ctx, i + 1, &pad)) < 0) {
663 if (s->type == TIME_DOMAIN) {
664 AVFloatDSPContext *fdsp = avpriv_float_dsp_alloc(0);
666 return AVERROR(ENOMEM);
667 s->scalarproduct_float = fdsp->scalarproduct_float;
674 static int config_output(AVFilterLink *outlink)
676 AVFilterContext *ctx = outlink->src;
677 HeadphoneContext *s = ctx->priv;
678 AVFilterLink *inlink = ctx->inputs[0];
680 if (s->hrir_fmt == HRIR_MULTI) {
681 AVFilterLink *hrir_link = ctx->inputs[1];
683 if (hrir_link->channels < inlink->channels * 2) {
684 av_log(ctx, AV_LOG_ERROR, "Number of channels in HRIR stream must be >= %d.\n", inlink->channels * 2);
685 return AVERROR(EINVAL);
689 s->gain_lfe = expf((s->gain - 3 * inlink->channels + s->lfe_gain) / 20 * M_LN10);
694 static av_cold void uninit(AVFilterContext *ctx)
696 HeadphoneContext *s = ctx->priv;
698 av_fft_end(s->ifft[0]);
699 av_fft_end(s->ifft[1]);
700 av_fft_end(s->fft[0]);
701 av_fft_end(s->fft[1]);
702 av_freep(&s->data_ir[0]);
703 av_freep(&s->data_ir[1]);
704 av_freep(&s->ringbuffer[0]);
705 av_freep(&s->ringbuffer[1]);
706 av_freep(&s->temp_src[0]);
707 av_freep(&s->temp_src[1]);
708 av_freep(&s->temp_fft[0]);
709 av_freep(&s->temp_fft[1]);
710 av_freep(&s->temp_afft[0]);
711 av_freep(&s->temp_afft[1]);
712 av_freep(&s->data_hrtf[0]);
713 av_freep(&s->data_hrtf[1]);
715 for (unsigned i = 1; i < ctx->nb_inputs; i++)
716 av_freep(&ctx->input_pads[i].name);
719 #define OFFSET(x) offsetof(HeadphoneContext, x)
720 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
722 static const AVOption headphone_options[] = {
723 { "map", "set channels convolution mappings", OFFSET(map), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
724 { "gain", "set gain in dB", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
725 { "lfe", "set lfe gain in dB", OFFSET(lfe_gain), AV_OPT_TYPE_FLOAT, {.dbl=0}, -20, 40, .flags = FLAGS },
726 { "type", "set processing", OFFSET(type), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags = FLAGS, "type" },
727 { "time", "time domain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, .flags = FLAGS, "type" },
728 { "freq", "frequency domain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, .flags = FLAGS, "type" },
729 { "size", "set frame size", OFFSET(size), AV_OPT_TYPE_INT, {.i64=1024},1024,96000, .flags = FLAGS },
730 { "hrir", "set hrir format", OFFSET(hrir_fmt), AV_OPT_TYPE_INT, {.i64=HRIR_STEREO}, 0, 1, .flags = FLAGS, "hrir" },
731 { "stereo", "hrir files have exactly 2 channels", 0, AV_OPT_TYPE_CONST, {.i64=HRIR_STEREO}, 0, 0, .flags = FLAGS, "hrir" },
732 { "multich", "single multichannel hrir file", 0, AV_OPT_TYPE_CONST, {.i64=HRIR_MULTI}, 0, 0, .flags = FLAGS, "hrir" },
736 AVFILTER_DEFINE_CLASS(headphone);
738 static const AVFilterPad outputs[] = {
741 .type = AVMEDIA_TYPE_AUDIO,
742 .config_props = config_output,
747 AVFilter ff_af_headphone = {
749 .description = NULL_IF_CONFIG_SMALL("Apply headphone binaural spatialization with HRTFs in additional streams."),
750 .priv_size = sizeof(HeadphoneContext),
751 .priv_class = &headphone_class,
754 .query_formats = query_formats,
755 .activate = activate,
758 .flags = AVFILTER_FLAG_SLICE_THREADS | AVFILTER_FLAG_DYNAMIC_INPUTS,