]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_ladspa.c
avfilter/af_ladspa: add latency compensation
[ffmpeg] / libavfilter / af_ladspa.c
1 /*
2  * Copyright (c) 2013 Paul B Mahol
3  * Copyright (c) 2011 Mina Nagy Zaki
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * LADSPA wrapper
25  */
26
27 #include <dlfcn.h>
28 #include <ladspa.h>
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/opt.h"
33 #include "audio.h"
34 #include "avfilter.h"
35 #include "internal.h"
36
37 typedef struct LADSPAContext {
38     const AVClass *class;
39     char *dl_name;
40     char *plugin;
41     char *options;
42     void *dl_handle;
43
44     unsigned long nb_inputs;
45     unsigned long *ipmap;      /* map input number to port number */
46
47     unsigned long nb_inputcontrols;
48     unsigned long *icmap;      /* map input control number to port number */
49     LADSPA_Data *ictlv;        /* input controls values */
50
51     unsigned long nb_outputs;
52     unsigned long *opmap;      /* map output number to port number */
53
54     unsigned long nb_outputcontrols;
55     unsigned long *ocmap;      /* map output control number to port number */
56     LADSPA_Data *octlv;        /* output controls values */
57
58     const LADSPA_Descriptor *desc;
59     int *ctl_needs_value;
60     int nb_handles;
61     LADSPA_Handle *handles;
62
63     int sample_rate;
64     int nb_samples;
65     int64_t pts;
66     int64_t duration;
67     int in_trim;
68     int out_pad;
69     int latency;
70 } LADSPAContext;
71
72 #define OFFSET(x) offsetof(LADSPAContext, x)
73 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
74 static const AVOption ladspa_options[] = {
75     { "file", "set library name or full path", OFFSET(dl_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
76     { "f",    "set library name or full path", OFFSET(dl_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
77     { "plugin", "set plugin name", OFFSET(plugin), AV_OPT_TYPE_STRING, .flags = FLAGS },
78     { "p",      "set plugin name", OFFSET(plugin), AV_OPT_TYPE_STRING, .flags = FLAGS },
79     { "controls", "set plugin options", OFFSET(options), AV_OPT_TYPE_STRING, .flags = FLAGS },
80     { "c",        "set plugin options", OFFSET(options), AV_OPT_TYPE_STRING, .flags = FLAGS },
81     { "sample_rate", "set sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64=44100}, 1, INT32_MAX, FLAGS },
82     { "s",           "set sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64=44100}, 1, INT32_MAX, FLAGS },
83     { "nb_samples", "set the number of samples per requested frame", OFFSET(nb_samples), AV_OPT_TYPE_INT, {.i64=1024}, 1, INT_MAX, FLAGS },
84     { "n",          "set the number of samples per requested frame", OFFSET(nb_samples), AV_OPT_TYPE_INT, {.i64=1024}, 1, INT_MAX, FLAGS },
85     { "duration", "set audio duration", OFFSET(duration), AV_OPT_TYPE_DURATION, {.i64=-1}, -1, INT64_MAX, FLAGS },
86     { "d",        "set audio duration", OFFSET(duration), AV_OPT_TYPE_DURATION, {.i64=-1}, -1, INT64_MAX, FLAGS },
87     { "latency", "enable latency compensation", OFFSET(latency), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
88     { "l",       "enable latency compensation", OFFSET(latency), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS },
89     { NULL }
90 };
91
92 AVFILTER_DEFINE_CLASS(ladspa);
93
94 static int find_latency(AVFilterContext *ctx, LADSPAContext *s)
95 {
96     int latency = 0;
97
98     for (int ctl = 0; ctl < s->nb_outputcontrols; ctl++) {
99         if (av_strcasecmp("latency", s->desc->PortNames[s->ocmap[ctl]]))
100             continue;
101
102         latency = lrintf(s->octlv[ctl]);
103         break;
104     }
105
106     return latency;
107 }
108
109 static void print_ctl_info(AVFilterContext *ctx, int level,
110                            LADSPAContext *s, int ctl, unsigned long *map,
111                            LADSPA_Data *values, int print)
112 {
113     const LADSPA_PortRangeHint *h = s->desc->PortRangeHints + map[ctl];
114
115     av_log(ctx, level, "c%i: %s [", ctl, s->desc->PortNames[map[ctl]]);
116
117     if (LADSPA_IS_HINT_TOGGLED(h->HintDescriptor)) {
118         av_log(ctx, level, "toggled (1 or 0)");
119
120         if (LADSPA_IS_HINT_HAS_DEFAULT(h->HintDescriptor))
121             av_log(ctx, level, " (default %i)", (int)values[ctl]);
122     } else {
123         if (LADSPA_IS_HINT_INTEGER(h->HintDescriptor)) {
124             av_log(ctx, level, "<int>");
125
126             if (LADSPA_IS_HINT_BOUNDED_BELOW(h->HintDescriptor))
127                 av_log(ctx, level, ", min: %i", (int)h->LowerBound);
128
129             if (LADSPA_IS_HINT_BOUNDED_ABOVE(h->HintDescriptor))
130                 av_log(ctx, level, ", max: %i", (int)h->UpperBound);
131
132             if (print)
133                 av_log(ctx, level, " (value %d)", (int)values[ctl]);
134             else if (LADSPA_IS_HINT_HAS_DEFAULT(h->HintDescriptor))
135                 av_log(ctx, level, " (default %d)", (int)values[ctl]);
136         } else {
137             av_log(ctx, level, "<float>");
138
139             if (LADSPA_IS_HINT_BOUNDED_BELOW(h->HintDescriptor))
140                 av_log(ctx, level, ", min: %f", h->LowerBound);
141
142             if (LADSPA_IS_HINT_BOUNDED_ABOVE(h->HintDescriptor))
143                 av_log(ctx, level, ", max: %f", h->UpperBound);
144
145             if (print)
146                 av_log(ctx, level, " (value %f)", values[ctl]);
147             else if (LADSPA_IS_HINT_HAS_DEFAULT(h->HintDescriptor))
148                 av_log(ctx, level, " (default %f)", values[ctl]);
149         }
150
151         if (LADSPA_IS_HINT_SAMPLE_RATE(h->HintDescriptor))
152             av_log(ctx, level, ", multiple of sample rate");
153
154         if (LADSPA_IS_HINT_LOGARITHMIC(h->HintDescriptor))
155             av_log(ctx, level, ", logarithmic scale");
156     }
157
158     av_log(ctx, level, "]\n");
159 }
160
161 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
162 {
163     AVFilterContext *ctx = inlink->dst;
164     LADSPAContext *s = ctx->priv;
165     AVFrame *out;
166     int i, h, p, new_out_samples;
167
168     av_assert0(in->channels == (s->nb_inputs * s->nb_handles));
169
170     if (!s->nb_outputs ||
171         (av_frame_is_writable(in) && s->nb_inputs == s->nb_outputs &&
172          s->in_trim == 0 && s->out_pad == 0 &&
173         !(s->desc->Properties & LADSPA_PROPERTY_INPLACE_BROKEN))) {
174         out = in;
175     } else {
176         out = ff_get_audio_buffer(ctx->outputs[0], in->nb_samples);
177         if (!out) {
178             av_frame_free(&in);
179             return AVERROR(ENOMEM);
180         }
181         av_frame_copy_props(out, in);
182     }
183
184     av_assert0(!s->nb_outputs || out->channels == (s->nb_outputs * s->nb_handles));
185
186     for (h = 0; h < s->nb_handles; h++) {
187         for (i = 0; i < s->nb_inputs; i++) {
188             p = s->nb_handles > 1 ? h : i;
189             s->desc->connect_port(s->handles[h], s->ipmap[i],
190                                   (LADSPA_Data*)in->extended_data[p]);
191         }
192
193         for (i = 0; i < s->nb_outputs; i++) {
194             p = s->nb_handles > 1 ? h : i;
195             s->desc->connect_port(s->handles[h], s->opmap[i],
196                                   (LADSPA_Data*)out->extended_data[p]);
197         }
198
199         s->desc->run(s->handles[h], in->nb_samples);
200         if (s->latency)
201             s->in_trim = s->out_pad = find_latency(ctx, s);
202         s->latency = 0;
203     }
204
205     for (i = 0; i < s->nb_outputcontrols; i++)
206         print_ctl_info(ctx, AV_LOG_VERBOSE, s, i, s->ocmap, s->octlv, 1);
207
208     if (out != in)
209         av_frame_free(&in);
210
211     new_out_samples = out->nb_samples;
212     if (s->in_trim > 0) {
213         int trim = FFMIN(new_out_samples, s->in_trim);
214
215         new_out_samples -= trim;
216         s->in_trim -= trim;
217     }
218
219     if (new_out_samples <= 0) {
220         av_frame_free(&out);
221         return 0;
222     } else if (new_out_samples < out->nb_samples) {
223         int offset = out->nb_samples - new_out_samples;
224         for (int ch = 0; ch < out->channels; ch++)
225             memmove(out->extended_data[ch], out->extended_data[ch] + sizeof(float) * offset,
226                     sizeof(float) * new_out_samples);
227         out->nb_samples = new_out_samples;
228     }
229
230     return ff_filter_frame(ctx->outputs[0], out);
231 }
232
233 static int request_frame(AVFilterLink *outlink)
234 {
235     AVFilterContext *ctx = outlink->src;
236     LADSPAContext *s = ctx->priv;
237     AVFrame *out;
238     int64_t t;
239     int i;
240
241     if (ctx->nb_inputs) {
242         int ret = ff_request_frame(ctx->inputs[0]);
243
244         if (ret == AVERROR_EOF && s->out_pad > 0) {
245             AVFrame *frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->out_pad));
246             if (!frame)
247                 return AVERROR(ENOMEM);
248
249             s->out_pad -= frame->nb_samples;
250             return filter_frame(ctx->inputs[0], frame);
251         }
252         return ret;
253     }
254
255     t = av_rescale(s->pts, AV_TIME_BASE, s->sample_rate);
256     if (s->duration >= 0 && t >= s->duration)
257         return AVERROR_EOF;
258
259     out = ff_get_audio_buffer(outlink, s->nb_samples);
260     if (!out)
261         return AVERROR(ENOMEM);
262
263     for (i = 0; i < s->nb_outputs; i++)
264         s->desc->connect_port(s->handles[0], s->opmap[i],
265                 (LADSPA_Data*)out->extended_data[i]);
266
267     s->desc->run(s->handles[0], s->nb_samples);
268
269     for (i = 0; i < s->nb_outputcontrols; i++)
270         print_ctl_info(ctx, AV_LOG_INFO, s, i, s->ocmap, s->octlv, 1);
271
272     out->sample_rate = s->sample_rate;
273     out->pts         = s->pts;
274     s->pts          += s->nb_samples;
275
276     return ff_filter_frame(outlink, out);
277 }
278
279 static void set_default_ctl_value(LADSPAContext *s, int ctl,
280                                   unsigned long *map, LADSPA_Data *values)
281 {
282     const LADSPA_PortRangeHint *h = s->desc->PortRangeHints + map[ctl];
283     const LADSPA_Data lower = h->LowerBound;
284     const LADSPA_Data upper = h->UpperBound;
285
286     if (LADSPA_IS_HINT_DEFAULT_MINIMUM(h->HintDescriptor)) {
287         values[ctl] = lower;
288     } else if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(h->HintDescriptor)) {
289         values[ctl] = upper;
290     } else if (LADSPA_IS_HINT_DEFAULT_0(h->HintDescriptor)) {
291         values[ctl] = 0.0;
292     } else if (LADSPA_IS_HINT_DEFAULT_1(h->HintDescriptor)) {
293         values[ctl] = 1.0;
294     } else if (LADSPA_IS_HINT_DEFAULT_100(h->HintDescriptor)) {
295         values[ctl] = 100.0;
296     } else if (LADSPA_IS_HINT_DEFAULT_440(h->HintDescriptor)) {
297         values[ctl] = 440.0;
298     } else if (LADSPA_IS_HINT_DEFAULT_LOW(h->HintDescriptor)) {
299         if (LADSPA_IS_HINT_LOGARITHMIC(h->HintDescriptor))
300             values[ctl] = exp(log(lower) * 0.75 + log(upper) * 0.25);
301         else
302             values[ctl] = lower * 0.75 + upper * 0.25;
303     } else if (LADSPA_IS_HINT_DEFAULT_MIDDLE(h->HintDescriptor)) {
304         if (LADSPA_IS_HINT_LOGARITHMIC(h->HintDescriptor))
305             values[ctl] = exp(log(lower) * 0.5 + log(upper) * 0.5);
306         else
307             values[ctl] = lower * 0.5 + upper * 0.5;
308     } else if (LADSPA_IS_HINT_DEFAULT_HIGH(h->HintDescriptor)) {
309         if (LADSPA_IS_HINT_LOGARITHMIC(h->HintDescriptor))
310             values[ctl] = exp(log(lower) * 0.25 + log(upper) * 0.75);
311         else
312             values[ctl] = lower * 0.25 + upper * 0.75;
313     }
314 }
315
316 static int connect_ports(AVFilterContext *ctx, AVFilterLink *link)
317 {
318     LADSPAContext *s = ctx->priv;
319     int i, j;
320
321     s->nb_handles = s->nb_inputs == 1 && s->nb_outputs == 1 ? link->channels : 1;
322     s->handles    = av_calloc(s->nb_handles, sizeof(*s->handles));
323     if (!s->handles)
324         return AVERROR(ENOMEM);
325
326     for (i = 0; i < s->nb_handles; i++) {
327         s->handles[i] = s->desc->instantiate(s->desc, link->sample_rate);
328         if (!s->handles[i]) {
329             av_log(ctx, AV_LOG_ERROR, "Could not instantiate plugin.\n");
330             return AVERROR_EXTERNAL;
331         }
332
333         // Connect the input control ports
334         for (j = 0; j < s->nb_inputcontrols; j++)
335             s->desc->connect_port(s->handles[i], s->icmap[j], s->ictlv + j);
336
337         // Connect the output control ports
338         for (j = 0; j < s->nb_outputcontrols; j++)
339             s->desc->connect_port(s->handles[i], s->ocmap[j], &s->octlv[j]);
340
341         if (s->desc->activate)
342             s->desc->activate(s->handles[i]);
343     }
344
345     av_log(ctx, AV_LOG_DEBUG, "handles: %d\n", s->nb_handles);
346
347     return 0;
348 }
349
350 static int config_input(AVFilterLink *inlink)
351 {
352     AVFilterContext *ctx = inlink->dst;
353
354     return connect_ports(ctx, inlink);
355 }
356
357 static int config_output(AVFilterLink *outlink)
358 {
359     AVFilterContext *ctx = outlink->src;
360     LADSPAContext *s = ctx->priv;
361     int ret;
362
363     if (ctx->nb_inputs) {
364         AVFilterLink *inlink = ctx->inputs[0];
365
366         outlink->format      = inlink->format;
367         outlink->sample_rate = inlink->sample_rate;
368         if (s->nb_inputs == s->nb_outputs) {
369             outlink->channel_layout = inlink->channel_layout;
370             outlink->channels = inlink->channels;
371         }
372
373         ret = 0;
374     } else {
375         outlink->sample_rate = s->sample_rate;
376         outlink->time_base   = (AVRational){1, s->sample_rate};
377
378         ret = connect_ports(ctx, outlink);
379     }
380
381     return ret;
382 }
383
384 static void count_ports(const LADSPA_Descriptor *desc,
385                         unsigned long *nb_inputs, unsigned long *nb_outputs)
386 {
387     LADSPA_PortDescriptor pd;
388     int i;
389
390     for (i = 0; i < desc->PortCount; i++) {
391         pd = desc->PortDescriptors[i];
392
393         if (LADSPA_IS_PORT_AUDIO(pd)) {
394             if (LADSPA_IS_PORT_INPUT(pd)) {
395                 (*nb_inputs)++;
396             } else if (LADSPA_IS_PORT_OUTPUT(pd)) {
397                 (*nb_outputs)++;
398             }
399         }
400     }
401 }
402
403 static void *try_load(const char *dir, const char *soname)
404 {
405     char *path = av_asprintf("%s/%s.so", dir, soname);
406     void *ret = NULL;
407
408     if (path) {
409         ret = dlopen(path, RTLD_LOCAL|RTLD_NOW);
410         av_free(path);
411     }
412
413     return ret;
414 }
415
416 static int set_control(AVFilterContext *ctx, unsigned long port, LADSPA_Data value)
417 {
418     LADSPAContext *s = ctx->priv;
419     const char *label = s->desc->Label;
420     LADSPA_PortRangeHint *h = (LADSPA_PortRangeHint *)s->desc->PortRangeHints +
421                               s->icmap[port];
422
423     if (port >= s->nb_inputcontrols) {
424         av_log(ctx, AV_LOG_ERROR, "Control c%ld is out of range [0 - %lu].\n",
425                port, s->nb_inputcontrols);
426         return AVERROR(EINVAL);
427     }
428
429     if (LADSPA_IS_HINT_BOUNDED_BELOW(h->HintDescriptor) &&
430             value < h->LowerBound) {
431         av_log(ctx, AV_LOG_ERROR,
432                 "%s: input control c%ld is below lower boundary of %0.4f.\n",
433                 label, port, h->LowerBound);
434         return AVERROR(EINVAL);
435     }
436
437     if (LADSPA_IS_HINT_BOUNDED_ABOVE(h->HintDescriptor) &&
438             value > h->UpperBound) {
439         av_log(ctx, AV_LOG_ERROR,
440                 "%s: input control c%ld is above upper boundary of %0.4f.\n",
441                 label, port, h->UpperBound);
442         return AVERROR(EINVAL);
443     }
444
445     s->ictlv[port] = value;
446
447     return 0;
448 }
449
450 static av_cold int init(AVFilterContext *ctx)
451 {
452     LADSPAContext *s = ctx->priv;
453     LADSPA_Descriptor_Function descriptor_fn;
454     const LADSPA_Descriptor *desc;
455     LADSPA_PortDescriptor pd;
456     AVFilterPad pad = { NULL };
457     char *p, *arg, *saveptr = NULL;
458     unsigned long nb_ports;
459     int i, j = 0;
460
461     if (!s->dl_name) {
462         av_log(ctx, AV_LOG_ERROR, "No plugin name provided\n");
463         return AVERROR(EINVAL);
464     }
465
466     if (s->dl_name[0] == '/' || s->dl_name[0] == '.') {
467         // argument is a path
468         s->dl_handle = dlopen(s->dl_name, RTLD_LOCAL|RTLD_NOW);
469     } else {
470         // argument is a shared object name
471         char *paths = av_strdup(getenv("LADSPA_PATH"));
472         const char *separator = ":";
473
474         if (paths) {
475             p = paths;
476             while ((arg = av_strtok(p, separator, &saveptr)) && !s->dl_handle) {
477                 s->dl_handle = try_load(arg, s->dl_name);
478                 p = NULL;
479             }
480         }
481
482         av_free(paths);
483         if (!s->dl_handle && (paths = av_asprintf("%s/.ladspa", getenv("HOME")))) {
484             s->dl_handle = try_load(paths, s->dl_name);
485             av_free(paths);
486         }
487
488         if (!s->dl_handle && (paths = av_asprintf("%s/.ladspa/lib", getenv("HOME")))) {
489             s->dl_handle = try_load(paths, s->dl_name);
490             av_free(paths);
491         }
492
493         if (!s->dl_handle)
494             s->dl_handle = try_load("/usr/local/lib/ladspa", s->dl_name);
495
496         if (!s->dl_handle)
497             s->dl_handle = try_load("/usr/lib/ladspa", s->dl_name);
498     }
499     if (!s->dl_handle) {
500         av_log(ctx, AV_LOG_ERROR, "Failed to load '%s'\n", s->dl_name);
501         return AVERROR(EINVAL);
502     }
503
504     descriptor_fn = dlsym(s->dl_handle, "ladspa_descriptor");
505     if (!descriptor_fn) {
506         av_log(ctx, AV_LOG_ERROR, "Could not find ladspa_descriptor: %s\n", dlerror());
507         return AVERROR(EINVAL);
508     }
509
510     // Find the requested plugin, or list plugins
511     if (!s->plugin) {
512         av_log(ctx, AV_LOG_INFO, "The '%s' library contains the following plugins:\n", s->dl_name);
513         av_log(ctx, AV_LOG_INFO, "I = Input Channels\n");
514         av_log(ctx, AV_LOG_INFO, "O = Output Channels\n");
515         av_log(ctx, AV_LOG_INFO, "I:O %-25s %s\n", "Plugin", "Description");
516         av_log(ctx, AV_LOG_INFO, "\n");
517         for (i = 0; desc = descriptor_fn(i); i++) {
518             unsigned long inputs = 0, outputs = 0;
519
520             count_ports(desc, &inputs, &outputs);
521             av_log(ctx, AV_LOG_INFO, "%lu:%lu %-25s %s\n", inputs, outputs, desc->Label,
522                    (char *)av_x_if_null(desc->Name, "?"));
523             av_log(ctx, AV_LOG_VERBOSE, "Maker: %s\n",
524                    (char *)av_x_if_null(desc->Maker, "?"));
525             av_log(ctx, AV_LOG_VERBOSE, "Copyright: %s\n",
526                    (char *)av_x_if_null(desc->Copyright, "?"));
527         }
528         return AVERROR_EXIT;
529     } else {
530         for (i = 0;; i++) {
531             desc = descriptor_fn(i);
532             if (!desc) {
533                 av_log(ctx, AV_LOG_ERROR, "Could not find plugin: %s\n", s->plugin);
534                 return AVERROR(EINVAL);
535             }
536
537             if (desc->Label && !strcmp(desc->Label, s->plugin))
538                 break;
539         }
540     }
541
542     s->desc  = desc;
543     nb_ports = desc->PortCount;
544
545     s->ipmap = av_calloc(nb_ports, sizeof(*s->ipmap));
546     s->opmap = av_calloc(nb_ports, sizeof(*s->opmap));
547     s->icmap = av_calloc(nb_ports, sizeof(*s->icmap));
548     s->ocmap = av_calloc(nb_ports, sizeof(*s->ocmap));
549     s->ictlv = av_calloc(nb_ports, sizeof(*s->ictlv));
550     s->octlv = av_calloc(nb_ports, sizeof(*s->octlv));
551     s->ctl_needs_value = av_calloc(nb_ports, sizeof(*s->ctl_needs_value));
552     if (!s->ipmap || !s->opmap || !s->icmap ||
553         !s->ocmap || !s->ictlv || !s->octlv || !s->ctl_needs_value)
554         return AVERROR(ENOMEM);
555
556     for (i = 0; i < nb_ports; i++) {
557         pd = desc->PortDescriptors[i];
558
559         if (LADSPA_IS_PORT_AUDIO(pd)) {
560             if (LADSPA_IS_PORT_INPUT(pd)) {
561                 s->ipmap[s->nb_inputs] = i;
562                 s->nb_inputs++;
563             } else if (LADSPA_IS_PORT_OUTPUT(pd)) {
564                 s->opmap[s->nb_outputs] = i;
565                 s->nb_outputs++;
566             }
567         } else if (LADSPA_IS_PORT_CONTROL(pd)) {
568             if (LADSPA_IS_PORT_INPUT(pd)) {
569                 s->icmap[s->nb_inputcontrols] = i;
570
571                 if (LADSPA_IS_HINT_HAS_DEFAULT(desc->PortRangeHints[i].HintDescriptor))
572                     set_default_ctl_value(s, s->nb_inputcontrols, s->icmap, s->ictlv);
573                 else
574                     s->ctl_needs_value[s->nb_inputcontrols] = 1;
575
576                 s->nb_inputcontrols++;
577             } else if (LADSPA_IS_PORT_OUTPUT(pd)) {
578                 s->ocmap[s->nb_outputcontrols] = i;
579                 s->nb_outputcontrols++;
580             }
581         }
582     }
583
584     // List Control Ports if "help" is specified
585     if (s->options && !strcmp(s->options, "help")) {
586         if (!s->nb_inputcontrols) {
587             av_log(ctx, AV_LOG_INFO,
588                    "The '%s' plugin does not have any input controls.\n",
589                    desc->Label);
590         } else {
591             av_log(ctx, AV_LOG_INFO,
592                    "The '%s' plugin has the following input controls:\n",
593                    desc->Label);
594             for (i = 0; i < s->nb_inputcontrols; i++)
595                 print_ctl_info(ctx, AV_LOG_INFO, s, i, s->icmap, s->ictlv, 0);
596         }
597         return AVERROR_EXIT;
598     }
599
600     // Parse control parameters
601     p = s->options;
602     while (s->options) {
603         LADSPA_Data val;
604         int ret;
605
606         if (!(arg = av_strtok(p, " |", &saveptr)))
607             break;
608         p = NULL;
609
610         if (av_sscanf(arg, "c%d=%f", &i, &val) != 2) {
611             if (av_sscanf(arg, "%f", &val) != 1) {
612                 av_log(ctx, AV_LOG_ERROR, "Invalid syntax.\n");
613                 return AVERROR(EINVAL);
614             }
615             i = j++;
616         }
617
618         if ((ret = set_control(ctx, i, val)) < 0)
619             return ret;
620         s->ctl_needs_value[i] = 0;
621     }
622
623     // Check if any controls are not set
624     for (i = 0; i < s->nb_inputcontrols; i++) {
625         if (s->ctl_needs_value[i]) {
626             av_log(ctx, AV_LOG_ERROR, "Control c%d must be set.\n", i);
627             print_ctl_info(ctx, AV_LOG_ERROR, s, i, s->icmap, s->ictlv, 0);
628             return AVERROR(EINVAL);
629         }
630     }
631
632     pad.type = AVMEDIA_TYPE_AUDIO;
633
634     if (s->nb_inputs) {
635         pad.name = av_asprintf("in0:%s%lu", desc->Label, s->nb_inputs);
636         if (!pad.name)
637             return AVERROR(ENOMEM);
638
639         pad.filter_frame = filter_frame;
640         pad.config_props = config_input;
641         if (ff_insert_inpad(ctx, ctx->nb_inputs, &pad) < 0) {
642             av_freep(&pad.name);
643             return AVERROR(ENOMEM);
644         }
645     }
646
647     av_log(ctx, AV_LOG_DEBUG, "ports: %lu\n", nb_ports);
648     av_log(ctx, AV_LOG_DEBUG, "inputs: %lu outputs: %lu\n",
649                               s->nb_inputs, s->nb_outputs);
650     av_log(ctx, AV_LOG_DEBUG, "input controls: %lu output controls: %lu\n",
651                               s->nb_inputcontrols, s->nb_outputcontrols);
652
653     return 0;
654 }
655
656 static int query_formats(AVFilterContext *ctx)
657 {
658     LADSPAContext *s = ctx->priv;
659     AVFilterFormats *formats;
660     AVFilterChannelLayouts *layouts;
661     static const enum AVSampleFormat sample_fmts[] = {
662         AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE };
663     int ret;
664
665     formats = ff_make_format_list(sample_fmts);
666     if (!formats)
667         return AVERROR(ENOMEM);
668     ret = ff_set_common_formats(ctx, formats);
669     if (ret < 0)
670         return ret;
671
672     if (s->nb_inputs) {
673         formats = ff_all_samplerates();
674         if (!formats)
675             return AVERROR(ENOMEM);
676
677         ret = ff_set_common_samplerates(ctx, formats);
678         if (ret < 0)
679             return ret;
680     } else {
681         int sample_rates[] = { s->sample_rate, -1 };
682
683         ret = ff_set_common_samplerates(ctx, ff_make_format_list(sample_rates));
684         if (ret < 0)
685             return ret;
686     }
687
688     if (s->nb_inputs == 1 && s->nb_outputs == 1) {
689         // We will instantiate multiple LADSPA_Handle, one over each channel
690         layouts = ff_all_channel_counts();
691         if (!layouts)
692             return AVERROR(ENOMEM);
693
694         ret = ff_set_common_channel_layouts(ctx, layouts);
695         if (ret < 0)
696             return ret;
697     } else if (s->nb_inputs == 2 && s->nb_outputs == 2) {
698         layouts = NULL;
699         ret = ff_add_channel_layout(&layouts, AV_CH_LAYOUT_STEREO);
700         if (ret < 0)
701             return ret;
702         ret = ff_set_common_channel_layouts(ctx, layouts);
703         if (ret < 0)
704             return ret;
705     } else {
706         AVFilterLink *outlink = ctx->outputs[0];
707
708         if (s->nb_inputs >= 1) {
709             AVFilterLink *inlink = ctx->inputs[0];
710             uint64_t inlayout = FF_COUNT2LAYOUT(s->nb_inputs);
711
712             layouts = NULL;
713             ret = ff_add_channel_layout(&layouts, inlayout);
714             if (ret < 0)
715                 return ret;
716             ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
717             if (ret < 0)
718                 return ret;
719
720             if (!s->nb_outputs) {
721                 ret = ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
722                 if (ret < 0)
723                     return ret;
724             }
725         }
726
727         if (s->nb_outputs >= 1) {
728             uint64_t outlayout = FF_COUNT2LAYOUT(s->nb_outputs);
729
730             layouts = NULL;
731             ret = ff_add_channel_layout(&layouts, outlayout);
732             if (ret < 0)
733                 return ret;
734             ret = ff_channel_layouts_ref(layouts, &outlink->in_channel_layouts);
735             if (ret < 0)
736                 return ret;
737         }
738     }
739
740     return 0;
741 }
742
743 static av_cold void uninit(AVFilterContext *ctx)
744 {
745     LADSPAContext *s = ctx->priv;
746     int i;
747
748     for (i = 0; i < s->nb_handles; i++) {
749         if (s->desc->deactivate)
750             s->desc->deactivate(s->handles[i]);
751         if (s->desc->cleanup)
752             s->desc->cleanup(s->handles[i]);
753     }
754
755     if (s->dl_handle)
756         dlclose(s->dl_handle);
757
758     av_freep(&s->ipmap);
759     av_freep(&s->opmap);
760     av_freep(&s->icmap);
761     av_freep(&s->ocmap);
762     av_freep(&s->ictlv);
763     av_freep(&s->octlv);
764     av_freep(&s->handles);
765     av_freep(&s->ctl_needs_value);
766
767     if (ctx->nb_inputs)
768         av_freep(&ctx->input_pads[0].name);
769 }
770
771 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
772                            char *res, int res_len, int flags)
773 {
774     LADSPA_Data value;
775     unsigned long port;
776
777     if (av_sscanf(cmd, "c%ld", &port) + av_sscanf(args, "%f", &value) != 2)
778         return AVERROR(EINVAL);
779
780     return set_control(ctx, port, value);
781 }
782
783 static const AVFilterPad ladspa_outputs[] = {
784     {
785         .name          = "default",
786         .type          = AVMEDIA_TYPE_AUDIO,
787         .config_props  = config_output,
788         .request_frame = request_frame,
789     },
790     { NULL }
791 };
792
793 AVFilter ff_af_ladspa = {
794     .name          = "ladspa",
795     .description   = NULL_IF_CONFIG_SMALL("Apply LADSPA effect."),
796     .priv_size     = sizeof(LADSPAContext),
797     .priv_class    = &ladspa_class,
798     .init          = init,
799     .uninit        = uninit,
800     .query_formats = query_formats,
801     .process_command = process_command,
802     .inputs        = 0,
803     .outputs       = ladspa_outputs,
804     .flags         = AVFILTER_FLAG_DYNAMIC_INPUTS,
805 };