• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***
2   This file is part of PulseAudio.
3 
4   Copyright 2004-2008 Lennart Poettering
5 
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2.1 of the License,
9   or (at your option) any later version.
10 
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15 
16   You should have received a copy of the GNU Lesser General Public License
17   along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
18 ***/
19 
20 /* TODO: Some plugins cause latency, and some even report it by using a control
21    out port. We don't currently use the latency information. */
22 
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26 
27 #include <math.h>
28 
29 #include <pulse/xmalloc.h>
30 
31 #include <pulsecore/i18n.h>
32 #include <pulsecore/namereg.h>
33 #include <pulsecore/sink.h>
34 #include <pulsecore/module.h>
35 #include <pulsecore/core-util.h>
36 #include <pulsecore/modargs.h>
37 #include <pulsecore/log.h>
38 #include <pulsecore/rtpoll.h>
39 #include <pulsecore/sample-util.h>
40 #include <pulsecore/ltdl-helper.h>
41 
42 #ifdef HAVE_DBUS
43 #include <pulsecore/protocol-dbus.h>
44 #include <pulsecore/dbus-util.h>
45 #endif
46 
47 #include "ladspa.h"
48 
49 PA_MODULE_AUTHOR("Lennart Poettering");
50 PA_MODULE_DESCRIPTION(_("Virtual LADSPA sink"));
51 PA_MODULE_VERSION(PACKAGE_VERSION);
52 PA_MODULE_LOAD_ONCE(false);
53 PA_MODULE_USAGE(
54     _("sink_name=<name for the sink> "
55       "sink_properties=<properties for the sink> "
56       "sink_input_properties=<properties for the sink input> "
57       "master=<name of sink to filter> "
58       "sink_master=<name of sink to filter> "
59       "format=<sample format> "
60       "rate=<sample rate> "
61       "channels=<number of channels> "
62       "channel_map=<input channel map> "
63       "plugin=<ladspa plugin name> "
64       "label=<ladspa plugin label> "
65       "control=<comma separated list of input control values> "
66       "input_ladspaport_map=<comma separated list of input LADSPA port names> "
67       "output_ladspaport_map=<comma separated list of output LADSPA port names> "
68       "autoloaded=<set if this module is being loaded automatically> "));
69 
70 #define MEMBLOCKQ_MAXLENGTH (16*1024*1024)
71 #define DEFAULT_AUTOLOADED false
72 
73 /* PLEASE NOTICE: The PortAudio ports and the LADSPA ports are two different concepts.
74 They are not related and where possible the names of the LADSPA port variables contains "ladspa" to avoid confusion */
75 
76 struct userdata {
77     pa_module *module;
78 
79     pa_sink *sink;
80     pa_sink_input *sink_input;
81 
82     const LADSPA_Descriptor *descriptor;
83     LADSPA_Handle handle[PA_CHANNELS_MAX];
84     unsigned long max_ladspaport_count, input_count, output_count, channels;
85     LADSPA_Data **input, **output;
86     size_t block_size;
87     LADSPA_Data *control;
88     long unsigned n_control;
89 
90     /* This is a dummy buffer. Every port must be connected, but we don't care
91     about control out ports. We connect them all to this single buffer. */
92     LADSPA_Data control_out;
93 
94     pa_memblockq *memblockq;
95 
96     bool *use_default;
97     pa_sample_spec ss;
98 
99 #ifdef HAVE_DBUS
100     pa_dbus_protocol *dbus_protocol;
101     char *dbus_path;
102 #endif
103 
104     bool auto_desc;
105     bool autoloaded;
106 };
107 
108 static const char* const valid_modargs[] = {
109     "sink_name",
110     "sink_properties",
111     "sink_input_properties",
112     "master",  /* Will be deprecated. */
113     "sink_master",
114     "format",
115     "rate",
116     "channels",
117     "channel_map",
118     "plugin",
119     "label",
120     "control",
121     "input_ladspaport_map",
122     "output_ladspaport_map",
123     "autoloaded",
124     NULL
125 };
126 
127 /* The PA_SINK_MESSAGE types that extend the predefined messages. */
128 enum {
129    LADSPA_SINK_MESSAGE_UPDATE_PARAMETERS = PA_SINK_MESSAGE_MAX
130 };
131 
132 static int write_control_parameters(struct userdata *u, double *control_values, bool *use_default);
133 static void connect_control_ports(struct userdata *u);
134 
135 #ifdef HAVE_DBUS
136 
137 #define LADSPA_IFACE "org.PulseAudio.Ext.Ladspa1"
138 #define LADSPA_ALGORITHM_PARAMETERS "AlgorithmParameters"
139 
140 /* TODO: add a PropertyChanged signal to tell that the algorithm parameters have been changed */
141 
142 enum ladspa_handler_index {
143     LADSPA_HANDLER_ALGORITHM_PARAMETERS,
144     LADSPA_HANDLER_MAX
145 };
146 
get_algorithm_parameters(DBusConnection * conn,DBusMessage * msg,void * _u)147 static void get_algorithm_parameters(DBusConnection *conn, DBusMessage *msg, void *_u) {
148     struct userdata *u;
149     DBusMessage *reply = NULL;
150     DBusMessageIter msg_iter, struct_iter;
151     unsigned long i;
152     double *control;
153     dbus_bool_t *use_default;
154 
155     pa_assert(conn);
156     pa_assert(msg);
157     pa_assert_se(u = _u);
158 
159     pa_assert_se((reply = dbus_message_new_method_return(msg)));
160     dbus_message_iter_init_append(reply, &msg_iter);
161 
162     dbus_message_iter_open_container(&msg_iter, DBUS_TYPE_STRUCT, NULL, &struct_iter);
163 
164     /* copying because of the D-Bus type mapping */
165     control = pa_xnew(double, u->n_control);
166     use_default = pa_xnew(dbus_bool_t, u->n_control);
167 
168     for (i = 0; i < u->n_control; i++) {
169         control[i] = (double) u->control[i];
170         use_default[i] = u->use_default[i];
171     }
172 
173     pa_dbus_append_basic_array(&struct_iter, DBUS_TYPE_DOUBLE, control, u->n_control);
174     pa_dbus_append_basic_array(&struct_iter, DBUS_TYPE_BOOLEAN, use_default, u->n_control);
175 
176     pa_assert_se(dbus_message_iter_close_container(&msg_iter, &struct_iter));
177 
178     pa_assert_se(dbus_connection_send(conn, reply, NULL));
179 
180     dbus_message_unref(reply);
181     pa_xfree(control);
182     pa_xfree(use_default);
183 }
184 
set_algorithm_parameters(DBusConnection * conn,DBusMessage * msg,DBusMessageIter * iter,void * _u)185 static void set_algorithm_parameters(DBusConnection *conn, DBusMessage *msg, DBusMessageIter *iter, void *_u) {
186     struct userdata *u;
187     DBusMessageIter array_iter, struct_iter;
188     int n_control = 0, n_use_default;
189     unsigned n_dbus_control, n_dbus_use_default;
190     double *read_values = NULL;
191     dbus_bool_t *read_defaults = NULL;
192     bool *use_defaults = NULL;
193     unsigned long i;
194 
195     pa_assert(conn);
196     pa_assert(msg);
197     pa_assert_se(u = _u);
198 
199     /* The property we are expecting has signature (adab), meaning that it's a
200        struct of two arrays, the first containing doubles and the second containing
201        booleans. The first array has the algorithm configuration values and the
202        second array has booleans indicating whether the matching algorithm
203        configuration value should use (or try to use) the default value provided by
204        the algorithm module. The PulseAudio D-Bus infrastructure will take care of
205        checking the argument types for us. */
206 
207     dbus_message_iter_recurse(iter, &struct_iter);
208 
209     dbus_message_iter_recurse(&struct_iter, &array_iter);
210     dbus_message_iter_get_fixed_array(&array_iter, &read_values, &n_control);
211 
212     dbus_message_iter_next(&struct_iter);
213     dbus_message_iter_recurse(&struct_iter, &array_iter);
214     dbus_message_iter_get_fixed_array(&array_iter, &read_defaults, &n_use_default);
215 
216     n_dbus_control = n_control; /* handle the unsignedness */
217     n_dbus_use_default = n_use_default;
218 
219     if (n_dbus_control != u->n_control || n_dbus_use_default != u->n_control) {
220         pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "Wrong number of array values (expected %lu)", u->n_control);
221         return;
222     }
223 
224     use_defaults = pa_xnew(bool, n_control);
225     for (i = 0; i < u->n_control; i++)
226         use_defaults[i] = read_defaults[i];
227 
228     if (write_control_parameters(u, read_values, use_defaults) < 0) {
229         pa_log_warn("Failed writing control parameters");
230         goto error;
231     }
232 
233     pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), LADSPA_SINK_MESSAGE_UPDATE_PARAMETERS, NULL, 0, NULL);
234 
235     pa_dbus_send_empty_reply(conn, msg);
236 
237     pa_xfree(use_defaults);
238     return;
239 
240 error:
241     pa_xfree(use_defaults);
242     pa_dbus_send_error(conn, msg, DBUS_ERROR_FAILED, "Internal error");
243 }
244 
245 static pa_dbus_property_handler ladspa_property_handlers[LADSPA_HANDLER_MAX] = {
246     [LADSPA_HANDLER_ALGORITHM_PARAMETERS] = {
247         .property_name = LADSPA_ALGORITHM_PARAMETERS,
248         .type = "(adab)",
249         .get_cb = get_algorithm_parameters,
250         .set_cb = set_algorithm_parameters
251     }
252 };
253 
ladspa_get_all(DBusConnection * conn,DBusMessage * msg,void * _u)254 static void ladspa_get_all(DBusConnection *conn, DBusMessage *msg, void *_u) {
255     struct userdata *u;
256     DBusMessage *reply = NULL;
257     DBusMessageIter msg_iter, dict_iter, dict_entry_iter, variant_iter, struct_iter;
258     const char *key = LADSPA_ALGORITHM_PARAMETERS;
259     double *control;
260     dbus_bool_t *use_default;
261     long unsigned i;
262 
263     pa_assert(conn);
264     pa_assert(msg);
265     pa_assert_se(u = _u);
266 
267     pa_assert_se((reply = dbus_message_new_method_return(msg)));
268 
269     /* Currently, on this interface, only a single property is returned. */
270 
271     dbus_message_iter_init_append(reply, &msg_iter);
272     pa_assert_se(dbus_message_iter_open_container(&msg_iter, DBUS_TYPE_ARRAY, "{sv}", &dict_iter));
273     pa_assert_se(dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry_iter));
274     pa_assert_se(dbus_message_iter_append_basic(&dict_entry_iter, DBUS_TYPE_STRING, &key));
275 
276     pa_assert_se(dbus_message_iter_open_container(&dict_entry_iter, DBUS_TYPE_VARIANT, "(adab)", &variant_iter));
277     pa_assert_se(dbus_message_iter_open_container(&variant_iter, DBUS_TYPE_STRUCT, NULL, &struct_iter));
278 
279     control = pa_xnew(double, u->n_control);
280     use_default = pa_xnew(dbus_bool_t, u->n_control);
281 
282     for (i = 0; i < u->n_control; i++) {
283         control[i] = (double) u->control[i];
284         use_default[i] = u->use_default[i];
285     }
286 
287     pa_dbus_append_basic_array(&struct_iter, DBUS_TYPE_DOUBLE, control, u->n_control);
288     pa_dbus_append_basic_array(&struct_iter, DBUS_TYPE_BOOLEAN, use_default, u->n_control);
289 
290     pa_assert_se(dbus_message_iter_close_container(&variant_iter, &struct_iter));
291     pa_assert_se(dbus_message_iter_close_container(&dict_entry_iter, &variant_iter));
292     pa_assert_se(dbus_message_iter_close_container(&dict_iter, &dict_entry_iter));
293     pa_assert_se(dbus_message_iter_close_container(&msg_iter, &dict_iter));
294 
295     pa_assert_se(dbus_connection_send(conn, reply, NULL));
296     dbus_message_unref(reply);
297     pa_xfree(control);
298     pa_xfree(use_default);
299 }
300 
301 static pa_dbus_interface_info ladspa_info = {
302     .name = LADSPA_IFACE,
303     .method_handlers = NULL,
304     .n_method_handlers = 0,
305     .property_handlers = ladspa_property_handlers,
306     .n_property_handlers = LADSPA_HANDLER_MAX,
307     .get_all_properties_cb = ladspa_get_all,
308     .signals = NULL,
309     .n_signals = 0
310 };
311 
dbus_init(struct userdata * u)312 static void dbus_init(struct userdata *u) {
313     pa_assert_se(u);
314 
315     u->dbus_protocol = pa_dbus_protocol_get(u->sink->core);
316     u->dbus_path = pa_sprintf_malloc("/org/pulseaudio/core1/sink%d", u->sink->index);
317 
318     pa_dbus_protocol_add_interface(u->dbus_protocol, u->dbus_path, &ladspa_info, u);
319 }
320 
dbus_done(struct userdata * u)321 static void dbus_done(struct userdata *u) {
322     pa_assert_se(u);
323 
324     if (!u->dbus_protocol) {
325         pa_assert(!u->dbus_path);
326         return;
327     }
328 
329     pa_dbus_protocol_remove_interface(u->dbus_protocol, u->dbus_path, ladspa_info.name);
330     pa_xfree(u->dbus_path);
331     pa_dbus_protocol_unref(u->dbus_protocol);
332 
333     u->dbus_path = NULL;
334     u->dbus_protocol = NULL;
335 }
336 
337 #endif /* HAVE_DBUS */
338 
339 /* Called from I/O thread context */
sink_process_msg_cb(pa_msgobject * o,int code,void * data,int64_t offset,pa_memchunk * chunk)340 static int sink_process_msg_cb(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
341     struct userdata *u = PA_SINK(o)->userdata;
342 
343     switch (code) {
344 
345     case PA_SINK_MESSAGE_GET_LATENCY:
346 
347         /* The sink is _put() before the sink input is, so let's
348          * make sure we don't access it in that time. Also, the
349          * sink input is first shut down, the sink second. */
350         if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
351             !PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state)) {
352             *((int64_t*) data) = 0;
353             return 0;
354         }
355 
356         *((int64_t*) data) =
357 
358             /* Get the latency of the master sink */
359             pa_sink_get_latency_within_thread(u->sink_input->sink, true) +
360 
361             /* Add the latency internal to our sink input on top */
362             pa_bytes_to_usec(pa_memblockq_get_length(u->sink_input->thread_info.render_memblockq), &u->sink_input->sink->sample_spec);
363 
364             /* Add resampler latency */
365             *((int64_t*) data) += pa_resampler_get_delay_usec(u->sink_input->thread_info.resampler);
366 
367         return 0;
368 
369     case LADSPA_SINK_MESSAGE_UPDATE_PARAMETERS:
370 
371         /* rewind the stream to throw away the previously rendered data */
372 
373         pa_log_debug("Requesting rewind due to parameter update.");
374         pa_sink_request_rewind(u->sink, -1);
375 
376         /* change the sink parameters */
377         connect_control_ports(u);
378 
379         return 0;
380     }
381 
382     return pa_sink_process_msg(o, code, data, offset, chunk);
383 }
384 
385 /* Called from main context */
sink_set_state_in_main_thread_cb(pa_sink * s,pa_sink_state_t state,pa_suspend_cause_t suspend_cause)386 static int sink_set_state_in_main_thread_cb(pa_sink *s, pa_sink_state_t state, pa_suspend_cause_t suspend_cause) {
387     struct userdata *u;
388 
389     pa_sink_assert_ref(s);
390     pa_assert_se(u = s->userdata);
391 
392     if (!PA_SINK_IS_LINKED(state) ||
393             !PA_SINK_INPUT_IS_LINKED(u->sink_input->state))
394         return 0;
395 
396     pa_sink_input_cork(u->sink_input, state == PA_SINK_SUSPENDED);
397     return 0;
398 }
399 
400 /* Called from the IO thread. */
sink_set_state_in_io_thread_cb(pa_sink * s,pa_sink_state_t new_state,pa_suspend_cause_t new_suspend_cause)401 static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
402     struct userdata *u;
403 
404     pa_assert(s);
405     pa_assert_se(u = s->userdata);
406 
407     /* When set to running or idle for the first time, request a rewind
408      * of the master sink to make sure we are heard immediately */
409     if (PA_SINK_IS_OPENED(new_state) && s->thread_info.state == PA_SINK_INIT) {
410         pa_log_debug("Requesting rewind due to state change.");
411         pa_sink_input_request_rewind(u->sink_input, 0, false, true, true);
412     }
413 
414     return 0;
415 }
416 
417 /* Called from I/O thread context */
sink_request_rewind_cb(pa_sink * s)418 static void sink_request_rewind_cb(pa_sink *s) {
419     struct userdata *u;
420 
421     pa_sink_assert_ref(s);
422     pa_assert_se(u = s->userdata);
423 
424     if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
425             !PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state))
426         return;
427 
428     /* Just hand this one over to the master sink */
429     pa_sink_input_request_rewind(u->sink_input,
430                                  s->thread_info.rewind_nbytes +
431                                  pa_memblockq_get_length(u->memblockq), true, false, false);
432 }
433 
434 /* Called from I/O thread context */
sink_update_requested_latency_cb(pa_sink * s)435 static void sink_update_requested_latency_cb(pa_sink *s) {
436     struct userdata *u;
437 
438     pa_sink_assert_ref(s);
439     pa_assert_se(u = s->userdata);
440 
441     if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
442             !PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state))
443         return;
444 
445     /* Just hand this one over to the master sink */
446     pa_sink_input_set_requested_latency_within_thread(
447         u->sink_input,
448         pa_sink_get_requested_latency_within_thread(s));
449 }
450 
451 /* Called from main context */
sink_set_mute_cb(pa_sink * s)452 static void sink_set_mute_cb(pa_sink *s) {
453     struct userdata *u;
454 
455     pa_sink_assert_ref(s);
456     pa_assert_se(u = s->userdata);
457 
458     if (!PA_SINK_IS_LINKED(s->state) ||
459             !PA_SINK_INPUT_IS_LINKED(u->sink_input->state))
460         return;
461 
462     pa_sink_input_set_mute(u->sink_input, s->muted, s->save_muted);
463 }
464 
465 /* Called from I/O thread context */
sink_input_pop_cb(pa_sink_input * i,size_t nbytes,pa_memchunk * chunk)466 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
467     struct userdata *u;
468     float *src, *dst;
469     size_t fs;
470     unsigned n, h, c;
471     pa_memchunk tchunk;
472 
473     pa_sink_input_assert_ref(i);
474     pa_assert(chunk);
475     pa_assert_se(u = i->userdata);
476 
477     if (!PA_SINK_IS_LINKED(u->sink->thread_info.state))
478         return -1;
479 
480     /* Hmm, process any rewind request that might be queued up */
481     pa_sink_process_rewind(u->sink, 0);
482 
483     while (pa_memblockq_peek(u->memblockq, &tchunk) < 0) {
484         pa_memchunk nchunk;
485 
486         pa_sink_render(u->sink, nbytes, &nchunk);
487         pa_memblockq_push(u->memblockq, &nchunk);
488         pa_memblock_unref(nchunk.memblock);
489     }
490 
491     tchunk.length = PA_MIN(nbytes, tchunk.length);
492     pa_assert(tchunk.length > 0);
493 
494     fs = pa_frame_size(&i->sample_spec);
495     n = (unsigned) (PA_MIN(tchunk.length, u->block_size) / fs);
496 
497     pa_assert(n > 0);
498 
499     chunk->index = 0;
500     chunk->length = n*fs;
501     chunk->memblock = pa_memblock_new(i->sink->core->mempool, chunk->length);
502 
503     pa_memblockq_drop(u->memblockq, chunk->length);
504 
505     src = pa_memblock_acquire_chunk(&tchunk);
506     dst = pa_memblock_acquire(chunk->memblock);
507 
508     for (h = 0; h < (u->channels / u->max_ladspaport_count); h++) {
509         for (c = 0; c < u->input_count; c++)
510             pa_sample_clamp(PA_SAMPLE_FLOAT32NE, u->input[c], sizeof(float), src+ h*u->max_ladspaport_count + c, u->channels*sizeof(float), n);
511         u->descriptor->run(u->handle[h], n);
512         for (c = 0; c < u->output_count; c++)
513             pa_sample_clamp(PA_SAMPLE_FLOAT32NE, dst + h*u->max_ladspaport_count + c, u->channels*sizeof(float), u->output[c], sizeof(float), n);
514     }
515 
516     pa_memblock_release(tchunk.memblock);
517     pa_memblock_release(chunk->memblock);
518 
519     pa_memblock_unref(tchunk.memblock);
520 
521     return 0;
522 }
523 
524 /* Called from I/O thread context */
sink_input_process_rewind_cb(pa_sink_input * i,size_t nbytes)525 static void sink_input_process_rewind_cb(pa_sink_input *i, size_t nbytes) {
526     struct userdata *u;
527     size_t amount = 0;
528 
529     pa_sink_input_assert_ref(i);
530     pa_assert_se(u = i->userdata);
531 
532     /* If the sink is not yet linked, there is nothing to rewind */
533     if (!PA_SINK_IS_LINKED(u->sink->thread_info.state))
534         return;
535 
536     if (u->sink->thread_info.rewind_nbytes > 0) {
537         size_t max_rewrite;
538 
539         max_rewrite = nbytes + pa_memblockq_get_length(u->memblockq);
540         amount = PA_MIN(u->sink->thread_info.rewind_nbytes, max_rewrite);
541         u->sink->thread_info.rewind_nbytes = 0;
542 
543         if (amount > 0) {
544             unsigned c;
545 
546             pa_memblockq_seek(u->memblockq, - (int64_t) amount, PA_SEEK_RELATIVE, true);
547 
548             pa_log_debug("Resetting plugin");
549 
550             /* Reset the plugin */
551             if (u->descriptor->deactivate)
552                 for (c = 0; c < (u->channels / u->max_ladspaport_count); c++)
553                     u->descriptor->deactivate(u->handle[c]);
554             if (u->descriptor->activate)
555                 for (c = 0; c < (u->channels / u->max_ladspaport_count); c++)
556                     u->descriptor->activate(u->handle[c]);
557         }
558     }
559 
560     pa_sink_process_rewind(u->sink, amount);
561     pa_memblockq_rewind(u->memblockq, nbytes);
562 }
563 
564 /* Called from I/O thread context */
sink_input_update_max_rewind_cb(pa_sink_input * i,size_t nbytes)565 static void sink_input_update_max_rewind_cb(pa_sink_input *i, size_t nbytes) {
566     struct userdata *u;
567 
568     pa_sink_input_assert_ref(i);
569     pa_assert_se(u = i->userdata);
570 
571     /* FIXME: Too small max_rewind:
572      * https://bugs.freedesktop.org/show_bug.cgi?id=53709 */
573     pa_memblockq_set_maxrewind(u->memblockq, nbytes);
574     pa_sink_set_max_rewind_within_thread(u->sink, nbytes);
575 }
576 
577 /* Called from I/O thread context */
sink_input_update_max_request_cb(pa_sink_input * i,size_t nbytes)578 static void sink_input_update_max_request_cb(pa_sink_input *i, size_t nbytes) {
579     struct userdata *u;
580 
581     pa_sink_input_assert_ref(i);
582     pa_assert_se(u = i->userdata);
583 
584     pa_sink_set_max_request_within_thread(u->sink, nbytes);
585 }
586 
587 /* Called from I/O thread context */
sink_input_update_sink_latency_range_cb(pa_sink_input * i)588 static void sink_input_update_sink_latency_range_cb(pa_sink_input *i) {
589     struct userdata *u;
590 
591     pa_sink_input_assert_ref(i);
592     pa_assert_se(u = i->userdata);
593 
594     pa_sink_set_latency_range_within_thread(u->sink, i->sink->thread_info.min_latency, i->sink->thread_info.max_latency);
595 }
596 
597 /* Called from I/O thread context */
sink_input_update_sink_fixed_latency_cb(pa_sink_input * i)598 static void sink_input_update_sink_fixed_latency_cb(pa_sink_input *i) {
599     struct userdata *u;
600 
601     pa_sink_input_assert_ref(i);
602     pa_assert_se(u = i->userdata);
603 
604     pa_sink_set_fixed_latency_within_thread(u->sink, i->sink->thread_info.fixed_latency);
605 }
606 
607 /* Called from I/O thread context */
sink_input_detach_cb(pa_sink_input * i)608 static void sink_input_detach_cb(pa_sink_input *i) {
609     struct userdata *u;
610 
611     pa_sink_input_assert_ref(i);
612     pa_assert_se(u = i->userdata);
613 
614     if (PA_SINK_IS_LINKED(u->sink->thread_info.state))
615         pa_sink_detach_within_thread(u->sink);
616 
617     pa_sink_set_rtpoll(u->sink, NULL);
618 }
619 
620 /* Called from I/O thread context */
sink_input_attach_cb(pa_sink_input * i)621 static void sink_input_attach_cb(pa_sink_input *i) {
622     struct userdata *u;
623 
624     pa_sink_input_assert_ref(i);
625     pa_assert_se(u = i->userdata);
626 
627     pa_sink_set_rtpoll(u->sink, i->sink->thread_info.rtpoll);
628     pa_sink_set_latency_range_within_thread(u->sink, i->sink->thread_info.min_latency, i->sink->thread_info.max_latency);
629     pa_sink_set_fixed_latency_within_thread(u->sink, i->sink->thread_info.fixed_latency);
630     pa_sink_set_max_request_within_thread(u->sink, pa_sink_input_get_max_request(i));
631 
632     /* FIXME: Too small max_rewind:
633      * https://bugs.freedesktop.org/show_bug.cgi?id=53709 */
634     pa_sink_set_max_rewind_within_thread(u->sink, pa_sink_input_get_max_rewind(i));
635 
636     if (PA_SINK_IS_LINKED(u->sink->thread_info.state))
637         pa_sink_attach_within_thread(u->sink);
638 }
639 
640 /* Called from main context */
sink_input_kill_cb(pa_sink_input * i)641 static void sink_input_kill_cb(pa_sink_input *i) {
642     struct userdata *u;
643 
644     pa_sink_input_assert_ref(i);
645     pa_assert_se(u = i->userdata);
646 
647     /* The order here matters! We first kill the sink so that streams
648      * can properly be moved away while the sink input is still connected
649      * to the master. */
650     pa_sink_input_cork(u->sink_input, true);
651     pa_sink_unlink(u->sink);
652     pa_sink_input_unlink(u->sink_input);
653 
654     pa_sink_input_unref(u->sink_input);
655     u->sink_input = NULL;
656 
657     pa_sink_unref(u->sink);
658     u->sink = NULL;
659 
660     pa_module_unload_request(u->module, true);
661 }
662 
663 /* Called from main context */
sink_input_may_move_to_cb(pa_sink_input * i,pa_sink * dest)664 static bool sink_input_may_move_to_cb(pa_sink_input *i, pa_sink *dest) {
665     struct userdata *u;
666 
667     pa_sink_input_assert_ref(i);
668     pa_assert_se(u = i->userdata);
669 
670     if (u->autoloaded)
671         return false;
672 
673     return u->sink != dest;
674 }
675 
676 /* Called from main context */
sink_input_moving_cb(pa_sink_input * i,pa_sink * dest)677 static void sink_input_moving_cb(pa_sink_input *i, pa_sink *dest) {
678     struct userdata *u;
679 
680     pa_sink_input_assert_ref(i);
681     pa_assert_se(u = i->userdata);
682 
683     if (dest) {
684         pa_sink_set_asyncmsgq(u->sink, dest->asyncmsgq);
685         pa_sink_update_flags(u->sink, PA_SINK_LATENCY|PA_SINK_DYNAMIC_LATENCY, dest->flags);
686     } else
687         pa_sink_set_asyncmsgq(u->sink, NULL);
688 
689     if (u->auto_desc && dest) {
690         const char *z;
691         pa_proplist *pl;
692 
693         pl = pa_proplist_new();
694         z = pa_proplist_gets(dest->proplist, PA_PROP_DEVICE_DESCRIPTION);
695         pa_proplist_setf(pl, PA_PROP_DEVICE_DESCRIPTION, "LADSPA Plugin %s on %s",
696                          pa_proplist_gets(u->sink->proplist, "device.ladspa.name"), z ? z : dest->name);
697 
698         pa_sink_update_proplist(u->sink, PA_UPDATE_REPLACE, pl);
699         pa_proplist_free(pl);
700     }
701 }
702 
703 /* Called from main context */
sink_input_mute_changed_cb(pa_sink_input * i)704 static void sink_input_mute_changed_cb(pa_sink_input *i) {
705     struct userdata *u;
706 
707     pa_sink_input_assert_ref(i);
708     pa_assert_se(u = i->userdata);
709 
710     pa_sink_mute_changed(u->sink, i->muted);
711 }
712 
713 /* Called from main context */
sink_input_suspend_cb(pa_sink_input * i,pa_sink_state_t old_state,pa_suspend_cause_t old_suspend_cause)714 static void sink_input_suspend_cb(pa_sink_input *i, pa_sink_state_t old_state, pa_suspend_cause_t old_suspend_cause) {
715     struct userdata *u;
716 
717     pa_sink_input_assert_ref(i);
718     pa_assert_se(u = i->userdata);
719 
720     if (!PA_SINK_IS_LINKED(u->sink->state))
721         return;
722 
723     if (i->sink->state != PA_SINK_SUSPENDED || i->sink->suspend_cause == PA_SUSPEND_IDLE)
724         pa_sink_suspend(u->sink, false, PA_SUSPEND_UNAVAILABLE);
725     else
726         pa_sink_suspend(u->sink, true, PA_SUSPEND_UNAVAILABLE);
727 }
728 
parse_control_parameters(struct userdata * u,const char * cdata,double * read_values,bool * use_default)729 static int parse_control_parameters(struct userdata *u, const char *cdata, double *read_values, bool *use_default) {
730     unsigned long p = 0;
731     const char *state = NULL;
732     char *k;
733 
734     pa_assert(read_values);
735     pa_assert(use_default);
736     pa_assert(u);
737 
738     pa_log_debug("Trying to read %lu control values", u->n_control);
739 
740     if (!cdata || u->n_control == 0)
741         return -1;
742 
743     pa_log_debug("cdata: '%s'", cdata);
744 
745     while ((k = pa_split(cdata, ",", &state)) && p < u->n_control) {
746         double f;
747 
748         if (*k == 0) {
749             pa_log_debug("Read empty config value (p=%lu)", p);
750             use_default[p++] = true;
751             pa_xfree(k);
752             continue;
753         }
754 
755         if (pa_atod(k, &f) < 0) {
756             pa_log_debug("Failed to parse control value '%s' (p=%lu)", k, p);
757             pa_xfree(k);
758             goto fail;
759         }
760 
761         pa_xfree(k);
762 
763         pa_log_debug("Read config value %f (p=%lu)", f, p);
764 
765         use_default[p] = false;
766         read_values[p++] = f;
767     }
768 
769     /* The previous loop doesn't take the last control value into account
770        if it is left empty, so we do it here. */
771     if (*cdata == 0 || cdata[strlen(cdata) - 1] == ',') {
772         if (p < u->n_control)
773             use_default[p] = true;
774         p++;
775     }
776 
777     if (p > u->n_control || k) {
778         pa_log("Too many control values passed, %lu expected.", u->n_control);
779         pa_xfree(k);
780         goto fail;
781     }
782 
783     if (p < u->n_control) {
784         pa_log("Not enough control values passed, %lu expected, %lu passed.", u->n_control, p);
785         goto fail;
786     }
787 
788     return 0;
789 
790 fail:
791     return -1;
792 }
793 
connect_control_ports(struct userdata * u)794 static void connect_control_ports(struct userdata *u) {
795     unsigned long p = 0, h = 0, c;
796     const LADSPA_Descriptor *d;
797 
798     pa_assert(u);
799     pa_assert_se(d = u->descriptor);
800 
801     for (p = 0; p < d->PortCount; p++) {
802         if (!LADSPA_IS_PORT_CONTROL(d->PortDescriptors[p]))
803             continue;
804 
805         if (LADSPA_IS_PORT_OUTPUT(d->PortDescriptors[p])) {
806             for (c = 0; c < (u->channels / u->max_ladspaport_count); c++)
807                 d->connect_port(u->handle[c], p, &u->control_out);
808             continue;
809         }
810 
811         /* input control port */
812 
813         pa_log_debug("Binding %f to port %s", u->control[h], d->PortNames[p]);
814 
815         for (c = 0; c < (u->channels / u->max_ladspaport_count); c++)
816             d->connect_port(u->handle[c], p, &u->control[h]);
817 
818         h++;
819     }
820 }
821 
validate_control_parameters(struct userdata * u,double * control_values,bool * use_default)822 static int validate_control_parameters(struct userdata *u, double *control_values, bool *use_default) {
823     unsigned long p = 0, h = 0;
824     const LADSPA_Descriptor *d;
825     pa_sample_spec ss;
826 
827     pa_assert(control_values);
828     pa_assert(use_default);
829     pa_assert(u);
830     pa_assert_se(d = u->descriptor);
831 
832     ss = u->ss;
833 
834     /* Iterate over all ports. Check for every control port that 1) it
835      * supports default values if a default value is provided and 2) the
836      * provided value is within the limits specified in the plugin. */
837 
838     for (p = 0; p < d->PortCount; p++) {
839         LADSPA_PortRangeHintDescriptor hint = d->PortRangeHints[p].HintDescriptor;
840 
841         if (!LADSPA_IS_PORT_CONTROL(d->PortDescriptors[p]))
842             continue;
843 
844         if (LADSPA_IS_PORT_OUTPUT(d->PortDescriptors[p]))
845             continue;
846 
847         if (use_default[h]) {
848             /* User wants to use default value. Check if the plugin
849              * provides it. */
850             if (!LADSPA_IS_HINT_HAS_DEFAULT(hint)) {
851                 pa_log_warn("Control port value left empty but plugin defines no default.");
852                 return -1;
853             }
854         }
855         else {
856             /* Check if the user-provided value is within the bounds. */
857             LADSPA_Data lower = d->PortRangeHints[p].LowerBound;
858             LADSPA_Data upper = d->PortRangeHints[p].UpperBound;
859 
860             if (LADSPA_IS_HINT_SAMPLE_RATE(hint)) {
861                 upper *= (LADSPA_Data) ss.rate;
862                 lower *= (LADSPA_Data) ss.rate;
863             }
864 
865             if (LADSPA_IS_HINT_BOUNDED_ABOVE(hint)) {
866                 if (control_values[h] > upper) {
867                     pa_log_warn("Control value %lu over upper bound: %f (upper bound: %f)", h, control_values[h], upper);
868                     return -1;
869                 }
870             }
871             if (LADSPA_IS_HINT_BOUNDED_BELOW(hint)) {
872                 if (control_values[h] < lower) {
873                     pa_log_warn("Control value %lu below lower bound: %f (lower bound: %f)", h, control_values[h], lower);
874                     return -1;
875                 }
876             }
877         }
878 
879         h++;
880     }
881 
882     return 0;
883 }
884 
write_control_parameters(struct userdata * u,double * control_values,bool * use_default)885 static int write_control_parameters(struct userdata *u, double *control_values, bool *use_default) {
886     unsigned long p = 0, h = 0, c;
887     const LADSPA_Descriptor *d;
888     pa_sample_spec ss;
889 
890     pa_assert(control_values);
891     pa_assert(use_default);
892     pa_assert(u);
893     pa_assert_se(d = u->descriptor);
894 
895     ss = u->ss;
896 
897     if (validate_control_parameters(u, control_values, use_default) < 0)
898         return -1;
899 
900     /* p iterates over all ports, h is the control port iterator */
901 
902     for (p = 0; p < d->PortCount; p++) {
903         LADSPA_PortRangeHintDescriptor hint = d->PortRangeHints[p].HintDescriptor;
904 
905         if (!LADSPA_IS_PORT_CONTROL(d->PortDescriptors[p]))
906             continue;
907 
908         if (LADSPA_IS_PORT_OUTPUT(d->PortDescriptors[p])) {
909             for (c = 0; c < (u->channels / u->max_ladspaport_count); c++)
910                 d->connect_port(u->handle[c], p, &u->control_out);
911             continue;
912         }
913 
914         if (use_default[h]) {
915 
916             LADSPA_Data lower, upper;
917 
918             lower = d->PortRangeHints[p].LowerBound;
919             upper = d->PortRangeHints[p].UpperBound;
920 
921             if (LADSPA_IS_HINT_SAMPLE_RATE(hint)) {
922                 lower *= (LADSPA_Data) ss.rate;
923                 upper *= (LADSPA_Data) ss.rate;
924             }
925 
926             switch (hint & LADSPA_HINT_DEFAULT_MASK) {
927 
928             case LADSPA_HINT_DEFAULT_MINIMUM:
929                 u->control[h] = lower;
930                 break;
931 
932             case LADSPA_HINT_DEFAULT_MAXIMUM:
933                 u->control[h] = upper;
934                 break;
935 
936             case LADSPA_HINT_DEFAULT_LOW:
937                 if (LADSPA_IS_HINT_LOGARITHMIC(hint))
938                     u->control[h] = (LADSPA_Data) exp(log(lower) * 0.75 + log(upper) * 0.25);
939                 else
940                     u->control[h] = (LADSPA_Data) (lower * 0.75 + upper * 0.25);
941                 break;
942 
943             case LADSPA_HINT_DEFAULT_MIDDLE:
944                 if (LADSPA_IS_HINT_LOGARITHMIC(hint))
945                     u->control[h] = (LADSPA_Data) exp(log(lower) * 0.5 + log(upper) * 0.5);
946                 else
947                     u->control[h] = (LADSPA_Data) (lower * 0.5 + upper * 0.5);
948                 break;
949 
950             case LADSPA_HINT_DEFAULT_HIGH:
951                 if (LADSPA_IS_HINT_LOGARITHMIC(hint))
952                     u->control[h] = (LADSPA_Data) exp(log(lower) * 0.25 + log(upper) * 0.75);
953                 else
954                     u->control[h] = (LADSPA_Data) (lower * 0.25 + upper * 0.75);
955                 break;
956 
957             case LADSPA_HINT_DEFAULT_0:
958                 u->control[h] = 0;
959                 break;
960 
961             case LADSPA_HINT_DEFAULT_1:
962                 u->control[h] = 1;
963                 break;
964 
965             case LADSPA_HINT_DEFAULT_100:
966                 u->control[h] = 100;
967                 break;
968 
969             case LADSPA_HINT_DEFAULT_440:
970                 u->control[h] = 440;
971                 break;
972 
973             default:
974                 pa_assert_not_reached();
975             }
976         }
977         else {
978             if (LADSPA_IS_HINT_INTEGER(hint)) {
979                 u->control[h] = roundf(control_values[h]);
980             }
981             else {
982                 u->control[h] = control_values[h];
983             }
984         }
985 
986         h++;
987     }
988 
989     /* set the use_default array to the user data */
990     memcpy(u->use_default, use_default, u->n_control * sizeof(u->use_default[0]));
991 
992     return 0;
993 }
994 
pa__init(pa_module * m)995 int pa__init(pa_module*m) {
996     struct userdata *u;
997     pa_sample_spec ss;
998     pa_channel_map map;
999     pa_modargs *ma;
1000     char *t;
1001     const char *master_name;
1002     pa_sink *master;
1003     pa_sink_input_new_data sink_input_data;
1004     pa_sink_new_data sink_data;
1005     const char *plugin, *label, *input_ladspaport_map, *output_ladspaport_map;
1006     LADSPA_Descriptor_Function descriptor_func;
1007     unsigned long input_ladspaport[PA_CHANNELS_MAX], output_ladspaport[PA_CHANNELS_MAX];
1008     const char *e, *cdata;
1009     const LADSPA_Descriptor *d;
1010     unsigned long p, h, j, n_control, c;
1011     pa_memchunk silence;
1012 
1013     pa_assert(m);
1014 
1015     pa_assert_cc(sizeof(LADSPA_Data) == sizeof(float));
1016 
1017     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1018         pa_log("Failed to parse module arguments.");
1019         goto fail;
1020     }
1021 
1022     master_name = pa_modargs_get_value(ma, "sink_master", NULL);
1023     if (!master_name) {
1024         master_name = pa_modargs_get_value(ma, "master", NULL);
1025         if (master_name)
1026             pa_log_warn("The 'master' module argument is deprecated and may be removed in the future, "
1027                         "please use the 'sink_master' argument instead.");
1028     }
1029 
1030     master = pa_namereg_get(m->core, master_name, PA_NAMEREG_SINK);
1031     if (!master) {
1032         pa_log("Master sink not found.");
1033         goto fail;
1034     }
1035 
1036     ss = master->sample_spec;
1037     ss.format = PA_SAMPLE_FLOAT32;
1038     map = master->channel_map;
1039     if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
1040         pa_log("Invalid sample format specification or channel map");
1041         goto fail;
1042     }
1043 
1044     if (ss.format != PA_SAMPLE_FLOAT32) {
1045         pa_log("LADSPA accepts float format only");
1046         goto fail;
1047     }
1048 
1049     if (!(plugin = pa_modargs_get_value(ma, "plugin", NULL))) {
1050         pa_log("Missing LADSPA plugin name");
1051         goto fail;
1052     }
1053 
1054     if (!(label = pa_modargs_get_value(ma, "label", NULL))) {
1055         pa_log("Missing LADSPA plugin label");
1056         goto fail;
1057     }
1058 
1059     if (!(input_ladspaport_map = pa_modargs_get_value(ma, "input_ladspaport_map", NULL)))
1060         pa_log_debug("Using default input ladspa port mapping");
1061 
1062     if (!(output_ladspaport_map = pa_modargs_get_value(ma, "output_ladspaport_map", NULL)))
1063         pa_log_debug("Using default output ladspa port mapping");
1064 
1065     cdata = pa_modargs_get_value(ma, "control", NULL);
1066 
1067     u = pa_xnew0(struct userdata, 1);
1068     u->module = m;
1069     m->userdata = u;
1070     u->max_ladspaport_count = 1; /*to avoid division by zero etc. in pa__done when failing before this value has been set*/
1071     u->channels = 0;
1072     u->input = NULL;
1073     u->output = NULL;
1074     u->ss = ss;
1075 
1076     if (!(e = getenv("LADSPA_PATH")))
1077         /* The LADSPA_PATH preprocessor macro isn't a string literal (i.e. it
1078          * doesn't contain quotes), because otherwise the build system would
1079          * have an extra burden of getting the escaping right (Windows paths
1080          * are especially tricky). PA_EXPAND_AND_STRINGIZE does the necessary
1081          * escaping. */
1082         e = PA_EXPAND_AND_STRINGIZE(LADSPA_PATH);
1083 
1084     /* FIXME: This is not exactly thread safe */
1085     t = pa_xstrdup(lt_dlgetsearchpath());
1086     lt_dlsetsearchpath(e);
1087     m->dl = lt_dlopenext(plugin);
1088     lt_dlsetsearchpath(t);
1089     pa_xfree(t);
1090 
1091     if (!m->dl) {
1092         pa_log("Failed to load LADSPA plugin: %s", lt_dlerror());
1093         goto fail;
1094     }
1095 
1096     if (!(descriptor_func = (LADSPA_Descriptor_Function) pa_load_sym(m->dl, NULL, "ladspa_descriptor"))) {
1097         pa_log("LADSPA module lacks ladspa_descriptor() symbol.");
1098         goto fail;
1099     }
1100 
1101     for (j = 0;; j++) {
1102 
1103         if (!(d = descriptor_func(j))) {
1104             pa_log("Failed to find plugin label '%s' in plugin '%s'.", label, plugin);
1105             goto fail;
1106         }
1107 
1108         if (pa_streq(d->Label, label))
1109             break;
1110     }
1111 
1112     u->descriptor = d;
1113 
1114     pa_log_debug("Module: %s", plugin);
1115     pa_log_debug("Label: %s", d->Label);
1116     pa_log_debug("Unique ID: %lu", d->UniqueID);
1117     pa_log_debug("Name: %s", d->Name);
1118     pa_log_debug("Maker: %s", d->Maker);
1119     pa_log_debug("Copyright: %s", d->Copyright);
1120 
1121     n_control = 0;
1122     u->channels = ss.channels;
1123 
1124     /*
1125     * Enumerate ladspa ports
1126     * Default mapping is in order given by the plugin
1127     */
1128     for (p = 0; p < d->PortCount; p++) {
1129         if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[p])) {
1130             if (LADSPA_IS_PORT_INPUT(d->PortDescriptors[p])) {
1131                 pa_log_debug("Port %lu is input: %s", p, d->PortNames[p]);
1132                 input_ladspaport[u->input_count] = p;
1133                 u->input_count++;
1134             } else if (LADSPA_IS_PORT_OUTPUT(d->PortDescriptors[p])) {
1135                 pa_log_debug("Port %lu is output: %s", p, d->PortNames[p]);
1136                 output_ladspaport[u->output_count] = p;
1137                 u->output_count++;
1138             }
1139         } else if (LADSPA_IS_PORT_CONTROL(d->PortDescriptors[p]) && LADSPA_IS_PORT_INPUT(d->PortDescriptors[p])) {
1140             pa_log_debug("Port %lu is control: %s", p, d->PortNames[p]);
1141             n_control++;
1142         } else
1143             pa_log_debug("Ignored port %s", d->PortNames[p]);
1144         /* XXX: Has anyone ever seen an in-place plugin with non-equal number of input and output ports? */
1145         /* Could be if the plugin is for up-mixing stereo to 5.1 channels */
1146         /* Or if the plugin is down-mixing 5.1 to two channel stereo or binaural encoded signal */
1147         if (u->input_count > u->max_ladspaport_count)
1148             u->max_ladspaport_count = u->input_count;
1149         else
1150             u->max_ladspaport_count = u->output_count;
1151     }
1152 
1153     if (u->channels % u->max_ladspaport_count) {
1154         pa_log("Cannot handle non-integral number of plugins required for given number of channels");
1155         goto fail;
1156     }
1157 
1158     pa_log_debug("Will run %lu plugin instances", u->channels / u->max_ladspaport_count);
1159 
1160     /* Parse data for input ladspa port map */
1161     if (input_ladspaport_map) {
1162         const char *state = NULL;
1163         char *pname;
1164         c = 0;
1165         while ((pname = pa_split(input_ladspaport_map, ",", &state))) {
1166             if (c == u->input_count) {
1167                 pa_log("Too many ports in input ladspa port map");
1168                 pa_xfree(pname);
1169                 goto fail;
1170             }
1171 
1172             for (p = 0; p < d->PortCount; p++) {
1173                 if (pa_streq(d->PortNames[p], pname)) {
1174                     if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[p]) && LADSPA_IS_PORT_INPUT(d->PortDescriptors[p])) {
1175                         input_ladspaport[c] = p;
1176                     } else {
1177                         pa_log("Port %s is not an audio input ladspa port", pname);
1178                         pa_xfree(pname);
1179                         goto fail;
1180                     }
1181                 }
1182             }
1183             c++;
1184             pa_xfree(pname);
1185         }
1186     }
1187 
1188     /* Parse data for output port map */
1189     if (output_ladspaport_map) {
1190         const char *state = NULL;
1191         char *pname;
1192         c = 0;
1193         while ((pname = pa_split(output_ladspaport_map, ",", &state))) {
1194             if (c == u->output_count) {
1195                 pa_log("Too many ports in output ladspa port map");
1196                 pa_xfree(pname);
1197                 goto fail;
1198             }
1199             for (p = 0; p < d->PortCount; p++) {
1200                 if (pa_streq(d->PortNames[p], pname)) {
1201                     if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[p]) && LADSPA_IS_PORT_OUTPUT(d->PortDescriptors[p])) {
1202                         output_ladspaport[c] = p;
1203                     } else {
1204                         pa_log("Port %s is not an output ladspa port", pname);
1205                         pa_xfree(pname);
1206                         goto fail;
1207                     }
1208                 }
1209             }
1210             c++;
1211             pa_xfree(pname);
1212         }
1213     }
1214 
1215     u->block_size = pa_frame_align(pa_mempool_block_size_max(m->core->mempool), &ss);
1216 
1217     /* Create buffers */
1218     if (LADSPA_IS_INPLACE_BROKEN(d->Properties)) {
1219         u->input = (LADSPA_Data**) pa_xnew(LADSPA_Data*, (unsigned) u->input_count);
1220         for (c = 0; c < u->input_count; c++)
1221             u->input[c] = (LADSPA_Data*) pa_xnew(uint8_t, (unsigned) u->block_size);
1222         u->output = (LADSPA_Data**) pa_xnew(LADSPA_Data*, (unsigned) u->output_count);
1223         for (c = 0; c < u->output_count; c++)
1224             u->output[c] = (LADSPA_Data*) pa_xnew(uint8_t, (unsigned) u->block_size);
1225     } else {
1226         u->input = (LADSPA_Data**) pa_xnew(LADSPA_Data*, (unsigned) u->max_ladspaport_count);
1227         for (c = 0; c < u->max_ladspaport_count; c++)
1228             u->input[c] = (LADSPA_Data*) pa_xnew(uint8_t, (unsigned) u->block_size);
1229         u->output = u->input;
1230     }
1231     /* Initialize plugin instances */
1232     for (h = 0; h < (u->channels / u->max_ladspaport_count); h++) {
1233         if (!(u->handle[h] = d->instantiate(d, ss.rate))) {
1234             pa_log("Failed to instantiate plugin %s with label %s", plugin, d->Label);
1235             goto fail;
1236         }
1237 
1238         for (c = 0; c < u->input_count; c++)
1239             d->connect_port(u->handle[h], input_ladspaport[c], u->input[c]);
1240         for (c = 0; c < u->output_count; c++)
1241             d->connect_port(u->handle[h], output_ladspaport[c], u->output[c]);
1242     }
1243 
1244     u->n_control = n_control;
1245 
1246     if (u->n_control > 0) {
1247         double *control_values;
1248         bool *use_default;
1249 
1250         /* temporary storage for parser */
1251         control_values = pa_xnew(double, (unsigned) u->n_control);
1252         use_default = pa_xnew(bool, (unsigned) u->n_control);
1253 
1254         /* real storage */
1255         u->control = pa_xnew(LADSPA_Data, (unsigned) u->n_control);
1256         u->use_default = pa_xnew(bool, (unsigned) u->n_control);
1257 
1258         if ((parse_control_parameters(u, cdata, control_values, use_default) < 0) ||
1259             (write_control_parameters(u, control_values, use_default) < 0)) {
1260             pa_xfree(control_values);
1261             pa_xfree(use_default);
1262 
1263             pa_log("Failed to parse, validate or set control parameters");
1264 
1265             goto fail;
1266         }
1267         connect_control_ports(u);
1268         pa_xfree(control_values);
1269         pa_xfree(use_default);
1270     }
1271 
1272     if (d->activate)
1273         for (c = 0; c < (u->channels / u->max_ladspaport_count); c++)
1274             d->activate(u->handle[c]);
1275 
1276     /* Create sink */
1277     pa_sink_new_data_init(&sink_data);
1278     sink_data.driver = __FILE__;
1279     sink_data.module = m;
1280     if (!(sink_data.name = pa_xstrdup(pa_modargs_get_value(ma, "sink_name", NULL))))
1281         sink_data.name = pa_sprintf_malloc("%s.ladspa", master->name);
1282     pa_sink_new_data_set_sample_spec(&sink_data, &ss);
1283     pa_sink_new_data_set_channel_map(&sink_data, &map);
1284     pa_proplist_sets(sink_data.proplist, PA_PROP_DEVICE_MASTER_DEVICE, master->name);
1285     pa_proplist_sets(sink_data.proplist, PA_PROP_DEVICE_CLASS, "filter");
1286     pa_proplist_sets(sink_data.proplist, "device.ladspa.module", plugin);
1287     pa_proplist_sets(sink_data.proplist, "device.ladspa.label", d->Label);
1288     pa_proplist_sets(sink_data.proplist, "device.ladspa.name", d->Name);
1289     pa_proplist_sets(sink_data.proplist, "device.ladspa.maker", d->Maker);
1290     pa_proplist_sets(sink_data.proplist, "device.ladspa.copyright", d->Copyright);
1291     pa_proplist_setf(sink_data.proplist, "device.ladspa.unique_id", "%lu", (unsigned long) d->UniqueID);
1292 
1293     if (pa_modargs_get_proplist(ma, "sink_properties", sink_data.proplist, PA_UPDATE_REPLACE) < 0) {
1294         pa_log("Invalid properties");
1295         pa_sink_new_data_done(&sink_data);
1296         goto fail;
1297     }
1298 
1299     u->autoloaded = DEFAULT_AUTOLOADED;
1300     if (pa_modargs_get_value_boolean(ma, "autoloaded", &u->autoloaded) < 0) {
1301         pa_log("Failed to parse autoloaded value");
1302         goto fail;
1303     }
1304 
1305     if ((u->auto_desc = !pa_proplist_contains(sink_data.proplist, PA_PROP_DEVICE_DESCRIPTION))) {
1306         const char *z;
1307 
1308         z = pa_proplist_gets(master->proplist, PA_PROP_DEVICE_DESCRIPTION);
1309         pa_proplist_setf(sink_data.proplist, PA_PROP_DEVICE_DESCRIPTION, "LADSPA Plugin %s on %s", d->Name, z ? z : master->name);
1310     }
1311 
1312     u->sink = pa_sink_new(m->core, &sink_data,
1313                           (master->flags & (PA_SINK_LATENCY|PA_SINK_DYNAMIC_LATENCY)) | PA_SINK_SHARE_VOLUME_WITH_MASTER);
1314     pa_sink_new_data_done(&sink_data);
1315 
1316     if (!u->sink) {
1317         pa_log("Failed to create sink.");
1318         goto fail;
1319     }
1320 
1321     u->sink->parent.process_msg = sink_process_msg_cb;
1322     u->sink->set_state_in_main_thread = sink_set_state_in_main_thread_cb;
1323     u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
1324     u->sink->update_requested_latency = sink_update_requested_latency_cb;
1325     u->sink->request_rewind = sink_request_rewind_cb;
1326     pa_sink_set_set_mute_callback(u->sink, sink_set_mute_cb);
1327     u->sink->userdata = u;
1328 
1329     pa_sink_set_asyncmsgq(u->sink, master->asyncmsgq);
1330 
1331     /* Create sink input */
1332     pa_sink_input_new_data_init(&sink_input_data);
1333     sink_input_data.driver = __FILE__;
1334     sink_input_data.module = m;
1335     pa_sink_input_new_data_set_sink(&sink_input_data, master, false, true);
1336     sink_input_data.origin_sink = u->sink;
1337     pa_proplist_sets(sink_input_data.proplist, PA_PROP_MEDIA_NAME, "LADSPA Stream");
1338     pa_proplist_sets(sink_input_data.proplist, PA_PROP_MEDIA_ROLE, "filter");
1339 
1340     if (pa_modargs_get_proplist(ma, "sink_input_properties", sink_input_data.proplist, PA_UPDATE_REPLACE) < 0) {
1341         pa_log("Invalid properties");
1342         pa_sink_input_new_data_done(&sink_input_data);
1343         goto fail;
1344     }
1345 
1346     pa_sink_input_new_data_set_sample_spec(&sink_input_data, &ss);
1347     pa_sink_input_new_data_set_channel_map(&sink_input_data, &map);
1348     sink_input_data.flags |= PA_SINK_INPUT_START_CORKED;
1349 
1350     pa_sink_input_new(&u->sink_input, m->core, &sink_input_data);
1351     pa_sink_input_new_data_done(&sink_input_data);
1352 
1353     if (!u->sink_input)
1354         goto fail;
1355 
1356     u->sink_input->pop = sink_input_pop_cb;
1357     u->sink_input->process_rewind = sink_input_process_rewind_cb;
1358     u->sink_input->update_max_rewind = sink_input_update_max_rewind_cb;
1359     u->sink_input->update_max_request = sink_input_update_max_request_cb;
1360     u->sink_input->update_sink_latency_range = sink_input_update_sink_latency_range_cb;
1361     u->sink_input->update_sink_fixed_latency = sink_input_update_sink_fixed_latency_cb;
1362     u->sink_input->kill = sink_input_kill_cb;
1363     u->sink_input->attach = sink_input_attach_cb;
1364     u->sink_input->detach = sink_input_detach_cb;
1365     u->sink_input->may_move_to = sink_input_may_move_to_cb;
1366     u->sink_input->moving = sink_input_moving_cb;
1367     u->sink_input->mute_changed = sink_input_mute_changed_cb;
1368     u->sink_input->suspend = sink_input_suspend_cb;
1369     u->sink_input->userdata = u;
1370 
1371     u->sink->input_to_master = u->sink_input;
1372 
1373     pa_sink_input_get_silence(u->sink_input, &silence);
1374     u->memblockq = pa_memblockq_new("module-ladspa-sink memblockq", 0, MEMBLOCKQ_MAXLENGTH, 0, &ss, 1, 1, 0, &silence);
1375     pa_memblock_unref(silence.memblock);
1376 
1377     /* The order here is important. The input must be put first,
1378      * otherwise streams might attach to the sink before the sink
1379      * input is attached to the master. */
1380     pa_sink_input_put(u->sink_input);
1381     pa_sink_put(u->sink);
1382     pa_sink_input_cork(u->sink_input, false);
1383 
1384 #ifdef HAVE_DBUS
1385     dbus_init(u);
1386 #endif
1387 
1388     pa_modargs_free(ma);
1389 
1390     return 0;
1391 
1392 fail:
1393     if (ma)
1394         pa_modargs_free(ma);
1395 
1396     pa__done(m);
1397 
1398     return -1;
1399 }
1400 
pa__get_n_used(pa_module * m)1401 int pa__get_n_used(pa_module *m) {
1402     struct userdata *u;
1403 
1404     pa_assert(m);
1405     pa_assert_se(u = m->userdata);
1406 
1407     return pa_sink_linked_by(u->sink);
1408 }
1409 
pa__done(pa_module * m)1410 void pa__done(pa_module*m) {
1411     struct userdata *u;
1412     unsigned c;
1413 
1414     pa_assert(m);
1415 
1416     if (!(u = m->userdata))
1417         return;
1418 
1419     /* See comments in sink_input_kill_cb() above regarding
1420     * destruction order! */
1421 
1422 #ifdef HAVE_DBUS
1423     dbus_done(u);
1424 #endif
1425 
1426     if (u->sink_input)
1427         pa_sink_input_cork(u->sink_input, true);
1428 
1429     if (u->sink)
1430         pa_sink_unlink(u->sink);
1431 
1432     if (u->sink_input) {
1433         pa_sink_input_unlink(u->sink_input);
1434         pa_sink_input_unref(u->sink_input);
1435     }
1436 
1437     if (u->sink)
1438         pa_sink_unref(u->sink);
1439 
1440     for (c = 0; c < (u->channels / u->max_ladspaport_count); c++) {
1441         if (u->handle[c]) {
1442             if (u->descriptor->deactivate)
1443                 u->descriptor->deactivate(u->handle[c]);
1444             u->descriptor->cleanup(u->handle[c]);
1445         }
1446     }
1447 
1448     if (u->output == u->input) {
1449         if (u->input != NULL) {
1450             for (c = 0; c < u->max_ladspaport_count; c++)
1451                 pa_xfree(u->input[c]);
1452             pa_xfree(u->input);
1453         }
1454     } else {
1455         if (u->input != NULL) {
1456             for (c = 0; c < u->input_count; c++)
1457                 pa_xfree(u->input[c]);
1458             pa_xfree(u->input);
1459         }
1460         if (u->output != NULL) {
1461             for (c = 0; c < u->output_count; c++)
1462                 pa_xfree(u->output[c]);
1463             pa_xfree(u->output);
1464         }
1465     }
1466 
1467     if (u->memblockq)
1468         pa_memblockq_free(u->memblockq);
1469 
1470     pa_xfree(u->control);
1471     pa_xfree(u->use_default);
1472     pa_xfree(u);
1473 }
1474