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