pump up version number and update changelog
[profile/ivi/pulseaudio-module-murphy-ivi.git] / combine / module-combine-sink.c
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, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #include <pulsecore/pulsecore-config.h>
23
24 #include <stdio.h>
25 #include <errno.h>
26
27 #include <pulse/rtclock.h>
28 #include <pulse/timeval.h>
29 #include <pulse/xmalloc.h>
30
31 #include <pulsecore/macro.h>
32 #include <pulsecore/module.h>
33 #include <pulsecore/llist.h>
34 #include <pulsecore/sink.h>
35 #include <pulsecore/sink-input.h>
36 #include <pulsecore/memblockq.h>
37 #include <pulsecore/log.h>
38 #include <pulsecore/core-rtclock.h>
39 #include <pulsecore/core-util.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/namereg.h>
42 #include <pulsecore/thread.h>
43 #include <pulsecore/thread-mq.h>
44 #include <pulsecore/rtpoll.h>
45 #include <pulsecore/time-smoother.h>
46 #include <pulsecore/strlist.h>
47
48 #include "module-combine-sink-symdef.h"
49
50 PA_MODULE_AUTHOR("Lennart Poettering");
51 PA_MODULE_DESCRIPTION("Combine multiple sinks to one");
52 PA_MODULE_VERSION(PACKAGE_VERSION);
53 PA_MODULE_LOAD_ONCE(false);
54 PA_MODULE_USAGE(
55         "sink_name=<name for the sink> "
56         "sink_properties=<properties for the sink> "
57         "slaves=<slave sinks> "
58         "adjust_time=<how often to readjust rates in s> "
59         "resample_method=<method> "
60         "format=<sample format> "
61         "rate=<sample rate> "
62         "channels=<number of channels> "
63         "channel_map=<channel map>");
64
65 #define DEFAULT_SINK_NAME "combined"
66
67 #define MEMBLOCKQ_MAXLENGTH (1024*1024*16)
68
69 #define DEFAULT_ADJUST_TIME_USEC (10*PA_USEC_PER_SEC)
70
71 #define BLOCK_USEC (PA_USEC_PER_MSEC * 200)
72
73 static const char* const valid_modargs[] = {
74     "sink_name",
75     "sink_properties",
76     "slaves",
77     "adjust_time",
78     "resample_method",
79     "format",
80     "rate",
81     "channels",
82     "channel_map",
83     NULL
84 };
85
86 #include "userdata.h"
87
88 enum {
89     SINK_MESSAGE_ADD_OUTPUT = PA_SINK_MESSAGE_MAX,
90     SINK_MESSAGE_REMOVE_OUTPUT,
91     SINK_MESSAGE_NEED,
92     SINK_MESSAGE_UPDATE_LATENCY,
93     SINK_MESSAGE_UPDATE_MAX_REQUEST,
94     SINK_MESSAGE_UPDATE_REQUESTED_LATENCY
95 };
96
97 enum {
98     SINK_INPUT_MESSAGE_POST = PA_SINK_INPUT_MESSAGE_MAX,
99 };
100
101 static void output_disable(struct output *o);
102 static void output_enable(struct output *o);
103 static void output_free(struct output *o);
104 static int output_create_sink_input(struct output *o);
105 static pa_sink_input *add_slave(struct userdata *u, pa_sink *sink);
106 static void remove_slave(struct userdata *u, pa_sink_input *i, pa_sink *s);
107 static int move_slave(struct userdata *u, pa_sink_input *i, pa_sink *s);
108
109 static void adjust_rates(struct userdata *u) {
110     struct output *o;
111     pa_usec_t max_sink_latency = 0, min_total_latency = (pa_usec_t) -1, target_latency, avg_total_latency = 0;
112     uint32_t base_rate;
113     uint32_t idx;
114     unsigned n = 0;
115
116     pa_assert(u);
117     pa_sink_assert_ref(u->sink);
118
119     if (pa_idxset_size(u->outputs) <= 0)
120         return;
121
122     if (!PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)))
123         return;
124
125     PA_IDXSET_FOREACH(o, u->outputs, idx) {
126         pa_usec_t sink_latency;
127
128         if (!o->sink_input || !PA_SINK_IS_OPENED(pa_sink_get_state(o->sink)))
129             continue;
130
131         o->total_latency = pa_sink_input_get_latency(o->sink_input, &sink_latency);
132         o->total_latency += sink_latency;
133
134         if (sink_latency > max_sink_latency)
135             max_sink_latency = sink_latency;
136
137         if (min_total_latency == (pa_usec_t) -1 || o->total_latency < min_total_latency)
138             min_total_latency = o->total_latency;
139
140         avg_total_latency += o->total_latency;
141         n++;
142
143         /* pa_log_debug("[%s] total=%0.2fms sink=%0.2fms ", o->sink->name, (double) o->total_latency / PA_USEC_PER_MSEC, (double) sink_latency / PA_USEC_PER_MSEC); */
144
145         if (o->total_latency > 10*PA_USEC_PER_SEC)
146             pa_log_warn("[%s] Total latency of output is very high (%0.2fms), most likely the audio timing in one of your drivers is broken.", o->sink->name, (double) o->total_latency / PA_USEC_PER_MSEC);
147     }
148
149     if (min_total_latency == (pa_usec_t) -1)
150         return;
151
152     avg_total_latency /= n;
153
154     target_latency = max_sink_latency > min_total_latency ? max_sink_latency : min_total_latency;
155
156     /*
157     pa_log_info("[%s] avg total latency is %0.2f msec.", u->sink->name, (double) avg_total_latency / PA_USEC_PER_MSEC);
158     pa_log_info("[%s] target latency is %0.2f msec.", u->sink->name, (double) target_latency / PA_USEC_PER_MSEC);
159     */
160
161     base_rate = u->sink->sample_spec.rate;
162
163     PA_IDXSET_FOREACH(o, u->outputs, idx) {
164         uint32_t new_rate = base_rate;
165         uint32_t current_rate;
166
167         if (!o->sink_input || !PA_SINK_IS_OPENED(pa_sink_get_state(o->sink)))
168             continue;
169
170         current_rate = o->sink_input->sample_spec.rate;
171
172         if (o->total_latency != target_latency)
173             new_rate += (uint32_t) (((double) o->total_latency - (double) target_latency) / (double) u->adjust_time * (double) new_rate);
174
175         if (new_rate < (uint32_t) (base_rate*0.8) || new_rate > (uint32_t) (base_rate*1.25)) {
176             pa_log_warn("[%s] sample rates too different, not adjusting (%u vs. %u).", o->sink_input->sink->name, base_rate, new_rate);
177             new_rate = base_rate;
178         } else {
179             if (base_rate < new_rate + 20 && new_rate < base_rate + 20)
180               new_rate = base_rate;
181             /* Do the adjustment in small steps; 2‰ can be considered inaudible */
182             if (new_rate < (uint32_t) (current_rate*0.998) || new_rate > (uint32_t) (current_rate*1.002)) {
183                 /* pa_log_info("[%s] new rate of %u Hz not within 2‰ of %u Hz, forcing smaller adjustment", o->sink_input->sink->name, new_rate, current_rate); */
184                 new_rate = PA_CLAMP(new_rate, (uint32_t) (current_rate*0.998), (uint32_t) (current_rate*1.002));
185             }
186             pa_log_info("[%s] new rate is %u Hz; ratio is %0.3f; latency is %0.2f msec.", o->sink_input->sink->name, new_rate, (double) new_rate / base_rate, (double) o->total_latency / PA_USEC_PER_MSEC);
187         }
188         pa_sink_input_set_rate(o->sink_input, new_rate);
189     }
190
191     pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_UPDATE_LATENCY, NULL, (int64_t) avg_total_latency, NULL);
192 }
193
194 static void time_callback(pa_mainloop_api *a, pa_time_event *e, const struct timeval *t, void *userdata) {
195     struct userdata *u = userdata;
196
197     pa_assert(u);
198     pa_assert(a);
199     pa_assert(u->time_event == e);
200
201     adjust_rates(u);
202
203     pa_core_rttime_restart(u->core, e, pa_rtclock_now() + u->adjust_time);
204 }
205
206 static void process_render_null(struct userdata *u, pa_usec_t now) {
207     size_t ate = 0;
208     pa_assert(u);
209
210     /* If we are not running, we cannot produce any data */
211     if (!pa_atomic_load(&u->thread_info.running))
212         return;
213
214     if (u->thread_info.in_null_mode)
215         u->thread_info.timestamp = now;
216
217     while (u->thread_info.timestamp < now + u->block_usec) {
218         pa_memchunk chunk;
219
220         pa_sink_render(u->sink, u->sink->thread_info.max_request, &chunk);
221         pa_memblock_unref(chunk.memblock);
222
223         u->thread_info.counter += chunk.length;
224
225 /*         pa_log_debug("Ate %lu bytes.", (unsigned long) chunk.length); */
226         u->thread_info.timestamp += pa_bytes_to_usec(chunk.length, &u->sink->sample_spec);
227
228         ate += chunk.length;
229
230         if (ate >= u->sink->thread_info.max_request)
231             break;
232     }
233
234 /*     pa_log_debug("Ate in sum %lu bytes (of %lu)", (unsigned long) ate, (unsigned long) nbytes); */
235
236     pa_smoother_put(u->thread_info.smoother, now,
237                     pa_bytes_to_usec(u->thread_info.counter, &u->sink->sample_spec) - (u->thread_info.timestamp - now));
238 }
239
240 static void thread_func(void *userdata) {
241     struct userdata *u = userdata;
242
243     pa_assert(u);
244
245     pa_log_debug("Thread starting up");
246
247     if (u->core->realtime_scheduling)
248         pa_make_realtime(u->core->realtime_priority+1);
249
250     pa_thread_mq_install(&u->thread_mq);
251
252     u->thread_info.timestamp = pa_rtclock_now();
253     u->thread_info.in_null_mode = false;
254
255     for (;;) {
256         int ret;
257
258         if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
259             if (u->sink->thread_info.rewind_requested)
260                 pa_sink_process_rewind(u->sink, 0);
261
262         /* If no outputs are connected, render some data and drop it immediately. */
263         if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && !u->thread_info.active_outputs) {
264             pa_usec_t now;
265
266             now = pa_rtclock_now();
267
268             if (!u->thread_info.in_null_mode || u->thread_info.timestamp <= now)
269                 process_render_null(u, now);
270
271             pa_rtpoll_set_timer_absolute(u->rtpoll, u->thread_info.timestamp);
272             u->thread_info.in_null_mode = true;
273         } else {
274             pa_rtpoll_set_timer_disabled(u->rtpoll);
275             u->thread_info.in_null_mode = false;
276         }
277
278         /* Hmm, nothing to do. Let's sleep */
279         if ((ret = pa_rtpoll_run(u->rtpoll, true)) < 0) {
280             pa_log_info("pa_rtpoll_run() = %i", ret);
281             goto fail;
282         }
283
284         if (ret == 0)
285             goto finish;
286     }
287
288 fail:
289     /* If this was no regular exit from the loop we have to continue
290      * processing messages until we received PA_MESSAGE_SHUTDOWN */
291     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
292     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
293
294 finish:
295     pa_log_debug("Thread shutting down");
296 }
297
298 /* Called from I/O thread context */
299 static void render_memblock(struct userdata *u, struct output *o, size_t length) {
300     pa_assert(u);
301     pa_assert(o);
302
303     /* We are run by the sink thread, on behalf of an output (o). The
304      * output is waiting for us, hence it is safe to access its
305      * mainblockq and asyncmsgq directly. */
306
307     /* If we are not running, we cannot produce any data */
308     if (!pa_atomic_load(&u->thread_info.running))
309         return;
310
311     /* Maybe there's some data in the requesting output's queue
312      * now? */
313     while (pa_asyncmsgq_process_one(o->inq) > 0)
314         ;
315
316     /* Ok, now let's prepare some data if we really have to */
317     while (!pa_memblockq_is_readable(o->memblockq)) {
318         struct output *j;
319         pa_memchunk chunk;
320
321         /* Render data! */
322         pa_sink_render(u->sink, length, &chunk);
323
324         u->thread_info.counter += chunk.length;
325
326         /* OK, let's send this data to the other threads */
327         PA_LLIST_FOREACH(j, u->thread_info.active_outputs) {
328             if (j == o)
329                 continue;
330
331             pa_asyncmsgq_post(j->inq, PA_MSGOBJECT(j->sink_input), SINK_INPUT_MESSAGE_POST, NULL, 0, &chunk, NULL);
332         }
333
334         /* And place it directly into the requesting output's queue */
335         pa_memblockq_push_align(o->memblockq, &chunk);
336         pa_memblock_unref(chunk.memblock);
337     }
338 }
339
340 /* Called from I/O thread context */
341 static void request_memblock(struct output *o, size_t length) {
342     pa_assert(o);
343     pa_sink_input_assert_ref(o->sink_input);
344     pa_sink_assert_ref(o->userdata->sink);
345
346     /* If another thread already prepared some data we received
347      * the data over the asyncmsgq, hence let's first process
348      * it. */
349     while (pa_asyncmsgq_process_one(o->inq) > 0)
350         ;
351
352     /* Check whether we're now readable */
353     if (pa_memblockq_is_readable(o->memblockq))
354         return;
355
356     /* OK, we need to prepare new data, but only if the sink is actually running */
357     if (pa_atomic_load(&o->userdata->thread_info.running))
358         pa_asyncmsgq_send(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_NEED, o, (int64_t) length, NULL);
359 }
360
361 /* Called from I/O thread context */
362 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
363     struct output *o;
364
365     pa_sink_input_assert_ref(i);
366     pa_assert_se(o = i->userdata);
367
368     /* If necessary, get some new data */
369     request_memblock(o, nbytes);
370
371     /* pa_log("%s q size is %u + %u (%u/%u)", */
372     /*        i->sink->name, */
373     /*        pa_memblockq_get_nblocks(o->memblockq), */
374     /*        pa_memblockq_get_nblocks(i->thread_info.render_memblockq), */
375     /*        pa_memblockq_get_maxrewind(o->memblockq), */
376     /*        pa_memblockq_get_maxrewind(i->thread_info.render_memblockq)); */
377
378     if (pa_memblockq_peek(o->memblockq, chunk) < 0)
379         return -1;
380
381     pa_memblockq_drop(o->memblockq, chunk->length);
382
383     return 0;
384 }
385
386 /* Called from I/O thread context */
387 static void sink_input_process_rewind_cb(pa_sink_input *i, size_t nbytes) {
388     struct output *o;
389
390     pa_sink_input_assert_ref(i);
391     pa_assert_se(o = i->userdata);
392
393     pa_memblockq_rewind(o->memblockq, nbytes);
394 }
395
396 /* Called from I/O thread context */
397 static void sink_input_update_max_rewind_cb(pa_sink_input *i, size_t nbytes) {
398     struct output *o;
399
400     pa_sink_input_assert_ref(i);
401     pa_assert_se(o = i->userdata);
402
403     pa_memblockq_set_maxrewind(o->memblockq, nbytes);
404 }
405
406 /* Called from I/O thread context */
407 static void sink_input_update_max_request_cb(pa_sink_input *i, size_t nbytes) {
408     struct output *o;
409
410     pa_sink_input_assert_ref(i);
411     pa_assert_se(o = i->userdata);
412
413     if (pa_atomic_load(&o->max_request) == (int) nbytes)
414         return;
415
416     pa_atomic_store(&o->max_request, (int) nbytes);
417     pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_MAX_REQUEST, NULL, 0, NULL, NULL);
418 }
419
420 /* Called from thread context */
421 static void sink_input_update_sink_requested_latency_cb(pa_sink_input *i) {
422     struct output *o;
423     pa_usec_t c;
424
425     pa_assert(i);
426
427     pa_sink_input_assert_ref(i);
428     pa_assert_se(o = i->userdata);
429
430     c = pa_sink_get_requested_latency_within_thread(i->sink);
431
432     if (c == (pa_usec_t) -1)
433         c = i->sink->thread_info.max_latency;
434
435     if (pa_atomic_load(&o->requested_latency) == (int) c)
436         return;
437
438     pa_atomic_store(&o->requested_latency, (int) c);
439     pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_REQUESTED_LATENCY, NULL, 0, NULL, NULL);
440 }
441
442 /* Called from I/O thread context */
443 static void sink_input_attach_cb(pa_sink_input *i) {
444     struct output *o;
445     pa_usec_t c;
446
447     pa_sink_input_assert_ref(i);
448     pa_assert_se(o = i->userdata);
449
450     /* Set up the queue from the sink thread to us */
451     pa_assert(!o->inq_rtpoll_item_read && !o->outq_rtpoll_item_write);
452
453     o->inq_rtpoll_item_read = pa_rtpoll_item_new_asyncmsgq_read(
454             i->sink->thread_info.rtpoll,
455             PA_RTPOLL_LATE,  /* This one is not that important, since we check for data in _peek() anyway. */
456             o->inq);
457
458     o->outq_rtpoll_item_write = pa_rtpoll_item_new_asyncmsgq_write(
459             i->sink->thread_info.rtpoll,
460             PA_RTPOLL_EARLY,
461             o->outq);
462
463     pa_sink_input_request_rewind(i, 0, false, true, true);
464
465     pa_atomic_store(&o->max_request, (int) pa_sink_input_get_max_request(i));
466
467     c = pa_sink_get_requested_latency_within_thread(i->sink);
468     pa_atomic_store(&o->requested_latency, (int) (c == (pa_usec_t) -1 ? 0 : c));
469
470     pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_MAX_REQUEST, NULL, 0, NULL, NULL);
471     pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_REQUESTED_LATENCY, NULL, 0, NULL, NULL);
472 }
473
474 /* Called from I/O thread context */
475 static void sink_input_detach_cb(pa_sink_input *i) {
476     struct output *o;
477
478     pa_sink_input_assert_ref(i);
479     pa_assert_se(o = i->userdata);
480
481     if (o->inq_rtpoll_item_read) {
482         pa_rtpoll_item_free(o->inq_rtpoll_item_read);
483         o->inq_rtpoll_item_read = NULL;
484     }
485
486     if (o->outq_rtpoll_item_write) {
487         pa_rtpoll_item_free(o->outq_rtpoll_item_write);
488         o->outq_rtpoll_item_write = NULL;
489     }
490 }
491
492 /* Called from main context */
493 static void sink_input_kill_cb(pa_sink_input *i) {
494     struct output *o;
495
496     pa_sink_input_assert_ref(i);
497     pa_assert_se(o = i->userdata);
498
499     pa_module_unload_request(o->userdata->module, true);
500     output_free(o);
501 }
502
503 /* Called from thread context */
504 static int sink_input_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
505     struct output *o = PA_SINK_INPUT(obj)->userdata;
506
507     switch (code) {
508
509         case PA_SINK_INPUT_MESSAGE_GET_LATENCY: {
510             pa_usec_t *r = data;
511
512             *r = pa_bytes_to_usec(pa_memblockq_get_length(o->memblockq), &o->sink_input->sample_spec);
513
514             /* Fall through, the default handler will add in the extra
515              * latency added by the resampler */
516             break;
517         }
518
519         case SINK_INPUT_MESSAGE_POST:
520
521             if (PA_SINK_IS_OPENED(o->sink_input->sink->thread_info.state))
522                 pa_memblockq_push_align(o->memblockq, chunk);
523             else
524                 pa_memblockq_flush_write(o->memblockq, true);
525
526             return 0;
527     }
528
529     return pa_sink_input_process_msg(obj, code, data, offset, chunk);
530 }
531
532 /* Called from main context */
533 static void suspend(struct userdata *u) {
534     struct output *o;
535     uint32_t idx;
536
537     pa_assert(u);
538
539     /* Let's suspend by unlinking all streams */
540     PA_IDXSET_FOREACH(o, u->outputs, idx)
541         output_disable(o);
542
543     pa_log_info("Device suspended...");
544 }
545
546 /* Called from main context */
547 static void unsuspend(struct userdata *u) {
548     struct output *o;
549     uint32_t idx;
550
551     pa_assert(u);
552
553     /* Let's resume */
554     PA_IDXSET_FOREACH(o, u->outputs, idx)
555         output_enable(o);
556
557     pa_log_info("Resumed successfully...");
558 }
559
560 /* Called from main context */
561 static int sink_set_state(pa_sink *sink, pa_sink_state_t state) {
562     struct userdata *u;
563
564     pa_sink_assert_ref(sink);
565     pa_assert_se(u = sink->userdata);
566
567     /* Please note that in contrast to the ALSA modules we call
568      * suspend/unsuspend from main context here! */
569
570     switch (state) {
571         case PA_SINK_SUSPENDED:
572             pa_assert(PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)));
573
574             suspend(u);
575             break;
576
577         case PA_SINK_IDLE:
578         case PA_SINK_RUNNING:
579
580             if (pa_sink_get_state(u->sink) == PA_SINK_SUSPENDED)
581                 unsuspend(u);
582
583             break;
584
585         case PA_SINK_UNLINKED:
586         case PA_SINK_INIT:
587         case PA_SINK_INVALID_STATE:
588             ;
589     }
590
591     return 0;
592 }
593
594 /* Called from IO context */
595 static void update_max_request(struct userdata *u) {
596     size_t max_request = 0;
597     struct output *o;
598
599     pa_assert(u);
600     pa_sink_assert_io_context(u->sink);
601
602     /* Collects the max_request values of all streams and sets the
603      * largest one locally */
604
605     PA_LLIST_FOREACH(o, u->thread_info.active_outputs) {
606         size_t mr = (size_t) pa_atomic_load(&o->max_request);
607
608         if (mr > max_request)
609             max_request = mr;
610     }
611
612     if (max_request <= 0)
613         max_request = pa_usec_to_bytes(u->block_usec, &u->sink->sample_spec);
614
615     pa_sink_set_max_request_within_thread(u->sink, max_request);
616 }
617
618 /* Called from IO context */
619 static void update_fixed_latency(struct userdata *u) {
620     pa_usec_t fixed_latency = 0;
621     struct output *o;
622
623     pa_assert(u);
624     pa_sink_assert_io_context(u->sink);
625
626     /* Collects the requested_latency values of all streams and sets
627      * the largest one as fixed_latency locally */
628
629     PA_LLIST_FOREACH(o, u->thread_info.active_outputs) {
630         pa_usec_t rl = (size_t) pa_atomic_load(&o->requested_latency);
631
632         if (rl > fixed_latency)
633             fixed_latency = rl;
634     }
635
636     if (fixed_latency <= 0)
637         fixed_latency = u->block_usec;
638
639     pa_sink_set_fixed_latency_within_thread(u->sink, fixed_latency);
640 }
641
642 /* Called from thread context of the io thread */
643 static void output_add_within_thread(struct output *o) {
644     pa_assert(o);
645     pa_sink_assert_io_context(o->sink);
646
647     PA_LLIST_PREPEND(struct output, o->userdata->thread_info.active_outputs, o);
648
649     pa_assert(!o->outq_rtpoll_item_read && !o->inq_rtpoll_item_write);
650
651     o->outq_rtpoll_item_read = pa_rtpoll_item_new_asyncmsgq_read(
652             o->userdata->rtpoll,
653             PA_RTPOLL_EARLY-1,  /* This item is very important */
654             o->outq);
655     o->inq_rtpoll_item_write = pa_rtpoll_item_new_asyncmsgq_write(
656             o->userdata->rtpoll,
657             PA_RTPOLL_EARLY,
658             o->inq);
659 }
660
661 /* Called from thread context of the io thread */
662 static void output_remove_within_thread(struct output *o) {
663     pa_assert(o);
664     pa_sink_assert_io_context(o->sink);
665
666     PA_LLIST_REMOVE(struct output, o->userdata->thread_info.active_outputs, o);
667
668     if (o->outq_rtpoll_item_read) {
669         pa_rtpoll_item_free(o->outq_rtpoll_item_read);
670         o->outq_rtpoll_item_read = NULL;
671     }
672
673     if (o->inq_rtpoll_item_write) {
674         pa_rtpoll_item_free(o->inq_rtpoll_item_write);
675         o->inq_rtpoll_item_write = NULL;
676     }
677 }
678
679 /* Called from thread context of the io thread */
680 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
681     struct userdata *u = PA_SINK(o)->userdata;
682
683     switch (code) {
684
685         case PA_SINK_MESSAGE_SET_STATE: {
686             bool running = (PA_PTR_TO_UINT(data) == PA_SINK_RUNNING);
687
688             pa_atomic_store(&u->thread_info.running, running);
689
690             if (running)
691                 pa_smoother_resume(u->thread_info.smoother, pa_rtclock_now(), true);
692             else
693                 pa_smoother_pause(u->thread_info.smoother, pa_rtclock_now());
694
695             break;
696         }
697
698         case PA_SINK_MESSAGE_GET_LATENCY: {
699             pa_usec_t x, y, c, *delay = data;
700
701             x = pa_rtclock_now();
702             y = pa_smoother_get(u->thread_info.smoother, x);
703
704             c = pa_bytes_to_usec(u->thread_info.counter, &u->sink->sample_spec);
705
706             if (y < c)
707                 *delay = c - y;
708             else
709                 *delay = 0;
710
711             return 0;
712         }
713
714         case SINK_MESSAGE_ADD_OUTPUT:
715             output_add_within_thread(data);
716             update_max_request(u);
717             update_fixed_latency(u);
718             return 0;
719
720         case SINK_MESSAGE_REMOVE_OUTPUT:
721             output_remove_within_thread(data);
722             update_max_request(u);
723             update_fixed_latency(u);
724             return 0;
725
726         case SINK_MESSAGE_NEED:
727             render_memblock(u, (struct output*) data, (size_t) offset);
728             return 0;
729
730         case SINK_MESSAGE_UPDATE_LATENCY: {
731             pa_usec_t x, y, latency = (pa_usec_t) offset;
732
733             x = pa_rtclock_now();
734             y = pa_bytes_to_usec(u->thread_info.counter, &u->sink->sample_spec);
735
736             if (y > latency)
737                 y -= latency;
738             else
739                 y = 0;
740
741             pa_smoother_put(u->thread_info.smoother, x, y);
742             return 0;
743         }
744
745         case SINK_MESSAGE_UPDATE_MAX_REQUEST:
746             update_max_request(u);
747             break;
748
749         case SINK_MESSAGE_UPDATE_REQUESTED_LATENCY:
750             update_fixed_latency(u);
751             break;
752 }
753
754     return pa_sink_process_msg(o, code, data, offset, chunk);
755 }
756
757 static void update_description(struct userdata *u) {
758     bool first = true;
759     char *t;
760     struct output *o;
761     uint32_t idx;
762
763     pa_assert(u);
764
765     if (!u->auto_desc)
766         return;
767
768     if (pa_idxset_isempty(u->outputs)) {
769         pa_sink_set_description(u->sink, "Simultaneous output");
770         return;
771     }
772
773     t = pa_xstrdup("Simultaneous output to");
774
775     PA_IDXSET_FOREACH(o, u->outputs, idx) {
776         char *e;
777
778         if (first) {
779             e = pa_sprintf_malloc("%s %s", t, pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
780             first = false;
781         } else
782             e = pa_sprintf_malloc("%s, %s", t, pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
783
784         pa_xfree(t);
785         t = e;
786     }
787
788     pa_sink_set_description(u->sink, t);
789     pa_xfree(t);
790 }
791
792 static int output_create_sink_input(struct output *o) {
793     pa_sink_input_new_data data;
794
795     pa_assert(o);
796
797     if (o->sink_input)
798         return 0;
799
800     pa_sink_input_new_data_init(&data);
801     pa_sink_input_new_data_set_sink(&data, o->sink, false);
802     data.driver = __FILE__;
803     pa_proplist_setf(data.proplist, PA_PROP_MEDIA_NAME, "Simultaneous output on %s", pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
804     pa_proplist_sets(data.proplist, PA_PROP_MEDIA_ROLE, "filter");
805     pa_sink_input_new_data_set_sample_spec(&data, &o->userdata->sink->sample_spec);
806     pa_sink_input_new_data_set_channel_map(&data, &o->userdata->sink->channel_map);
807     data.module = o->userdata->module;
808     data.resample_method = o->userdata->resample_method;
809     data.flags = PA_SINK_INPUT_VARIABLE_RATE|PA_SINK_INPUT_DONT_MOVE|PA_SINK_INPUT_NO_CREATE_ON_SUSPEND;
810
811     pa_sink_input_new(&o->sink_input, o->userdata->core, &data);
812
813     pa_sink_input_new_data_done(&data);
814
815     if (!o->sink_input)
816         return -1;
817
818     o->sink_input->parent.process_msg = sink_input_process_msg;
819     o->sink_input->pop = sink_input_pop_cb;
820     o->sink_input->process_rewind = sink_input_process_rewind_cb;
821     o->sink_input->update_max_rewind = sink_input_update_max_rewind_cb;
822     o->sink_input->update_max_request = sink_input_update_max_request_cb;
823     o->sink_input->update_sink_requested_latency = sink_input_update_sink_requested_latency_cb;
824     o->sink_input->attach = sink_input_attach_cb;
825     o->sink_input->detach = sink_input_detach_cb;
826     o->sink_input->kill = sink_input_kill_cb;
827     o->sink_input->userdata = o;
828
829     pa_sink_input_set_requested_latency(o->sink_input, BLOCK_USEC);
830
831     return 0;
832 }
833
834 /* Called from main context */
835 static struct output *output_new(struct userdata *u, pa_sink *sink) {
836     struct output *o;
837
838     pa_assert(u);
839     pa_assert(sink);
840     pa_assert(u->sink);
841
842     o = pa_xnew0(struct output, 1);
843     o->userdata = u;
844     o->inq = pa_asyncmsgq_new(0);
845     o->outq = pa_asyncmsgq_new(0);
846     o->sink = sink;
847     o->memblockq = pa_memblockq_new(
848             "module-combine-sink output memblockq",
849             0,
850             MEMBLOCKQ_MAXLENGTH,
851             MEMBLOCKQ_MAXLENGTH,
852             &u->sink->sample_spec,
853             1,
854             0,
855             0,
856             &u->sink->silence);
857
858     pa_assert_se(pa_idxset_put(u->outputs, o, NULL) == 0);
859     update_description(u);
860
861     return o;
862 }
863
864 /* Called from main context */
865 static void output_free(struct output *o) {
866     pa_assert(o);
867
868     output_disable(o);
869
870     pa_assert_se(pa_idxset_remove_by_data(o->userdata->outputs, o, NULL));
871     update_description(o->userdata);
872
873     if (o->inq_rtpoll_item_read)
874         pa_rtpoll_item_free(o->inq_rtpoll_item_read);
875     if (o->inq_rtpoll_item_write)
876         pa_rtpoll_item_free(o->inq_rtpoll_item_write);
877
878     if (o->outq_rtpoll_item_read)
879         pa_rtpoll_item_free(o->outq_rtpoll_item_read);
880     if (o->outq_rtpoll_item_write)
881         pa_rtpoll_item_free(o->outq_rtpoll_item_write);
882
883     if (o->inq)
884         pa_asyncmsgq_unref(o->inq);
885
886     if (o->outq)
887         pa_asyncmsgq_unref(o->outq);
888
889     if (o->memblockq)
890         pa_memblockq_free(o->memblockq);
891
892     pa_xfree(o);
893 }
894
895 /* Called from main context */
896 static void output_enable(struct output *o) {
897     pa_assert(o);
898
899     if (o->sink_input)
900         return;
901
902     /* This might cause the sink to be resumed. The state change hook
903      * of the sink might hence be called from here, which might then
904      * cause us to be called in a loop. Make sure that state changes
905      * for this output don't cause this loop by setting a flag here */
906     o->ignore_state_change = true;
907
908     if (output_create_sink_input(o) >= 0) {
909
910         if (pa_sink_get_state(o->sink) != PA_SINK_INIT) {
911
912             /* First we register the output. That means that the sink
913              * will start to pass data to this output. */
914             pa_asyncmsgq_send(o->userdata->sink->asyncmsgq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_ADD_OUTPUT, o, 0, NULL);
915
916             /* Then we enable the sink input. That means that the sink
917              * is now asked for new data. */
918             pa_sink_input_put(o->sink_input);
919
920         } else
921             /* Hmm the sink is not yet started, do things right here */
922             output_add_within_thread(o);
923     }
924
925     o->ignore_state_change = false;
926 }
927
928 /* Called from main context */
929 static void output_disable(struct output *o) {
930     pa_assert(o);
931
932     if (!o->sink_input)
933         return;
934
935     /* First we disable the sink input. That means that the sink is
936      * not asked for new data anymore  */
937     pa_sink_input_unlink(o->sink_input);
938
939     /* Then we unregister the output. That means that the sink doesn't
940      * pass any further data to this output */
941     pa_asyncmsgq_send(o->userdata->sink->asyncmsgq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_REMOVE_OUTPUT, o, 0, NULL);
942
943     /* Now deallocate the stream */
944     pa_sink_input_unref(o->sink_input);
945     o->sink_input = NULL;
946
947     /* Finally, drop all queued data */
948     pa_memblockq_flush_write(o->memblockq, true);
949     pa_asyncmsgq_flush(o->inq, false);
950     pa_asyncmsgq_flush(o->outq, false);
951 }
952
953 /* Called from main context */
954 static void output_verify(struct output *o) {
955     pa_assert(o);
956
957     if (PA_SINK_IS_OPENED(pa_sink_get_state(o->userdata->sink)))
958         output_enable(o);
959     else
960         output_disable(o);
961 }
962
963 /* Called from main context */
964 static bool is_suitable_sink(struct userdata *u, pa_sink *s) {
965     const char *t;
966
967     pa_sink_assert_ref(s);
968
969     if (s == u->sink)
970         return false;
971
972     if (!(s->flags & PA_SINK_HARDWARE))
973         return false;
974
975     if (!(s->flags & PA_SINK_LATENCY))
976         return false;
977
978     if ((t = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_CLASS)))
979         if (!pa_streq(t, "sound"))
980             return false;
981
982     return true;
983 }
984
985 /* Called from main context */
986 static pa_hook_result_t sink_put_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
987     struct output *o;
988
989     pa_core_assert_ref(c);
990     pa_sink_assert_ref(s);
991     pa_assert(u);
992
993     if (u->automatic) {
994         if (!is_suitable_sink(u, s))
995             return PA_HOOK_OK;
996     } else {
997         /* Check if the sink is a previously unlinked slave (non-automatic mode) */
998         pa_strlist *l = u->unlinked_slaves;
999
1000         while (l && !pa_streq(pa_strlist_data(l), s->name))
1001             l = pa_strlist_next(l);
1002
1003         if (!l) {
1004             pa_log_debug("This sink is not previously unlinked, so returning from sink put cb");
1005             return PA_HOOK_OK;
1006         }
1007
1008         u->unlinked_slaves = pa_strlist_remove(u->unlinked_slaves, s->name);
1009     }
1010
1011     pa_log_info("Configuring new sink: %s", s->name);
1012     if (!(o = output_new(u, s))) {
1013         pa_log("Failed to create sink input on sink '%s'.", s->name);
1014         return PA_HOOK_OK;
1015     }
1016
1017     output_verify(o);
1018
1019     return PA_HOOK_OK;
1020 }
1021
1022 /* Called from main context */
1023 static struct output* find_output(struct userdata *u, pa_sink *s) {
1024     struct output *o;
1025     uint32_t idx;
1026
1027     pa_assert(u);
1028     pa_assert(s);
1029
1030     if (u->sink == s)
1031         return NULL;
1032
1033     PA_IDXSET_FOREACH(o, u->outputs, idx)
1034         if (o->sink == s)
1035             return o;
1036
1037     return NULL;
1038 }
1039
1040 /* Called from main context */
1041 static pa_hook_result_t sink_unlink_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
1042     struct output *o;
1043
1044     pa_assert(c);
1045     pa_sink_assert_ref(s);
1046     pa_assert(u);
1047
1048     if (!(o = find_output(u, s)))
1049         return PA_HOOK_OK;
1050
1051     pa_log_info("Unconfiguring sink: %s", s->name);
1052
1053     if (!u->automatic && !u->no_reattach) {
1054         u->unlinked_slaves = pa_strlist_prepend(u->unlinked_slaves, s->name);
1055         pa_log_debug("Adding sink %s to the combine modules unlinked slaves list", s->name);
1056     }
1057
1058     output_free(o);
1059
1060     return PA_HOOK_OK;
1061 }
1062
1063 /* Called from main context */
1064 static pa_hook_result_t sink_state_changed_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
1065     struct output *o;
1066
1067     if (!(o = find_output(u, s)))
1068         return PA_HOOK_OK;
1069
1070     /* This state change might be triggered because we are creating a
1071      * stream here, in that case we don't want to create it a second
1072      * time here and enter a loop */
1073     if (o->ignore_state_change)
1074         return PA_HOOK_OK;
1075
1076     output_verify(o);
1077
1078     return PA_HOOK_OK;
1079 }
1080
1081 int pa__init(pa_module*m) {
1082     struct userdata *u;
1083     pa_modargs *ma = NULL;
1084     const char *slaves, *rm;
1085     int resample_method = PA_RESAMPLER_TRIVIAL;
1086     pa_sample_spec ss;
1087     pa_channel_map map;
1088     struct output *o;
1089     uint32_t idx;
1090     pa_sink_new_data data;
1091     uint32_t adjust_time_sec;
1092
1093     pa_assert(m);
1094
1095     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1096         pa_log("failed to parse module arguments");
1097         goto fail;
1098     }
1099
1100     if ((rm = pa_modargs_get_value(ma, "resample_method", NULL))) {
1101         if ((resample_method = pa_parse_resample_method(rm)) < 0) {
1102             pa_log("invalid resample method '%s'", rm);
1103             goto fail;
1104         }
1105     }
1106
1107     m->userdata = u = pa_xnew0(struct userdata, 1);
1108     u->core = m->core;
1109     u->module = m;
1110     u->rtpoll = pa_rtpoll_new();
1111     pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
1112     u->resample_method = resample_method;
1113     u->outputs = pa_idxset_new(NULL, NULL);
1114     u->thread_info.smoother = pa_smoother_new(
1115             PA_USEC_PER_SEC,
1116             PA_USEC_PER_SEC*2,
1117             true,
1118             true,
1119             10,
1120             pa_rtclock_now(),
1121             true);
1122
1123     u->add_slave = add_slave;
1124     u->remove_slave = remove_slave;
1125     u->move_slave = move_slave;
1126
1127     adjust_time_sec = DEFAULT_ADJUST_TIME_USEC / PA_USEC_PER_SEC;
1128     if (pa_modargs_get_value_u32(ma, "adjust_time", &adjust_time_sec) < 0) {
1129         pa_log("Failed to parse adjust_time value");
1130         goto fail;
1131     }
1132
1133     if (adjust_time_sec != DEFAULT_ADJUST_TIME_USEC / PA_USEC_PER_SEC)
1134         u->adjust_time = adjust_time_sec * PA_USEC_PER_SEC;
1135     else
1136         u->adjust_time = DEFAULT_ADJUST_TIME_USEC;
1137
1138     slaves = pa_modargs_get_value(ma, "slaves", NULL);
1139     u->automatic = !slaves;
1140
1141     ss = m->core->default_sample_spec;
1142     map = m->core->default_channel_map;
1143
1144     /* Check the specified slave sinks for sample_spec and channel_map to use for the combined sink */
1145     if (!u->automatic) {
1146         const char*split_state = NULL;
1147         char *n = NULL;
1148         pa_sample_spec slaves_spec;
1149         pa_channel_map slaves_map;
1150         bool is_first_slave = true;
1151
1152         pa_sample_spec_init(&slaves_spec);
1153
1154         while ((n = pa_split(slaves, ",", &split_state))) {
1155             pa_sink *slave_sink;
1156
1157             if (!(slave_sink = pa_namereg_get(m->core, n, PA_NAMEREG_SINK))) {
1158                 pa_log("Invalid slave sink '%s'", n);
1159                 pa_xfree(n);
1160                 goto fail;
1161             }
1162
1163             pa_xfree(n);
1164
1165             if (is_first_slave) {
1166                 slaves_spec = slave_sink->sample_spec;
1167                 slaves_map = slave_sink->channel_map;
1168                 is_first_slave = false;
1169             } else {
1170                 if (slaves_spec.format != slave_sink->sample_spec.format)
1171                     slaves_spec.format = PA_SAMPLE_INVALID;
1172
1173                 if (slaves_spec.rate < slave_sink->sample_spec.rate)
1174                     slaves_spec.rate = slave_sink->sample_spec.rate;
1175
1176                 if (!pa_channel_map_equal(&slaves_map, &slave_sink->channel_map))
1177                     slaves_spec.channels = 0;
1178             }
1179         }
1180
1181         if (!is_first_slave) {
1182             if (slaves_spec.format != PA_SAMPLE_INVALID)
1183                 ss.format = slaves_spec.format;
1184
1185             ss.rate = slaves_spec.rate;
1186
1187             if (slaves_spec.channels > 0) {
1188                 map = slaves_map;
1189                 ss.channels = slaves_map.channels;
1190             }
1191         }
1192     }
1193
1194     if ((pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0)) {
1195         pa_log("Invalid sample specification.");
1196         goto fail;
1197     }
1198
1199     pa_sink_new_data_init(&data);
1200     data.namereg_fail = false;
1201     data.driver = __FILE__;
1202     data.module = m;
1203     pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
1204     pa_sink_new_data_set_sample_spec(&data, &ss);
1205     pa_sink_new_data_set_channel_map(&data, &map);
1206     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "filter");
1207
1208     if (slaves)
1209         pa_proplist_sets(data.proplist, "combine.slaves", slaves);
1210
1211     if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
1212         pa_log("Invalid properties");
1213         pa_sink_new_data_done(&data);
1214         goto fail;
1215     }
1216
1217     /* Check proplist for a description & fill in a default value if not */
1218     u->auto_desc = false;
1219     if (NULL == pa_proplist_gets(data.proplist, PA_PROP_DEVICE_DESCRIPTION)) {
1220         u->auto_desc = true;
1221         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Simultaneous Output");
1222     }
1223
1224     u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
1225     pa_sink_new_data_done(&data);
1226
1227     if (!u->sink) {
1228         pa_log("Failed to create sink");
1229         goto fail;
1230     }
1231
1232     u->sink->parent.process_msg = sink_process_msg;
1233     u->sink->set_state = sink_set_state;
1234     u->sink->userdata = u;
1235
1236     pa_sink_set_rtpoll(u->sink, u->rtpoll);
1237     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1238
1239     u->block_usec = BLOCK_USEC;
1240     pa_sink_set_max_request(u->sink, pa_usec_to_bytes(u->block_usec, &u->sink->sample_spec));
1241
1242     if (!u->automatic) {
1243         const char*split_state;
1244         char *n = NULL;
1245         pa_assert(slaves);
1246
1247         /* The slaves have been specified manually */
1248
1249         split_state = NULL;
1250         while ((n = pa_split(slaves, ",", &split_state))) {
1251             pa_sink *slave_sink;
1252
1253             if (!(slave_sink = pa_namereg_get(m->core, n, PA_NAMEREG_SINK)) || slave_sink == u->sink) {
1254                 pa_log("Invalid slave sink '%s'", n);
1255                 pa_xfree(n);
1256                 goto fail;
1257             }
1258
1259             pa_xfree(n);
1260
1261             if (!output_new(u, slave_sink)) {
1262                 pa_log("Failed to create slave sink input on sink '%s'.", slave_sink->name);
1263                 goto fail;
1264             }
1265         }
1266
1267         if (pa_idxset_size(u->outputs) < 1)
1268             pa_log_warn("No slave sinks specified.");
1269
1270         u->sink_put_slot = NULL;
1271
1272     } else {
1273         pa_sink *s;
1274
1275         /* We're in automatic mode, we add every sink that matches our needs  */
1276
1277         PA_IDXSET_FOREACH(s, m->core->sinks, idx) {
1278
1279             if (!is_suitable_sink(u, s))
1280                 continue;
1281
1282             if (!output_new(u, s)) {
1283                 pa_log("Failed to create sink input on sink '%s'.", s->name);
1284                 goto fail;
1285             }
1286         }
1287     }
1288
1289     u->sink_put_slot = pa_hook_connect(&m->core->hooks[PA_CORE_HOOK_SINK_PUT], PA_HOOK_LATE, (pa_hook_cb_t) sink_put_hook_cb, u);
1290     u->sink_unlink_slot = pa_hook_connect(&m->core->hooks[PA_CORE_HOOK_SINK_UNLINK], PA_HOOK_EARLY, (pa_hook_cb_t) sink_unlink_hook_cb, u);
1291     u->sink_state_changed_slot = pa_hook_connect(&m->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED], PA_HOOK_NORMAL, (pa_hook_cb_t) sink_state_changed_hook_cb, u);
1292
1293     if (!(u->thread = pa_thread_new("combine", thread_func, u))) {
1294         pa_log("Failed to create thread.");
1295         goto fail;
1296     }
1297
1298     /* Activate the sink and the sink inputs */
1299     pa_sink_put(u->sink);
1300
1301     PA_IDXSET_FOREACH(o, u->outputs, idx)
1302         output_verify(o);
1303
1304     if (u->adjust_time > 0)
1305         u->time_event = pa_core_rttime_new(m->core, pa_rtclock_now() + u->adjust_time, time_callback, u);
1306
1307     pa_modargs_free(ma);
1308
1309     return 0;
1310
1311 fail:
1312
1313     if (ma)
1314         pa_modargs_free(ma);
1315
1316     pa__done(m);
1317
1318     return -1;
1319 }
1320
1321 void pa__done(pa_module*m) {
1322     struct userdata *u;
1323     struct output *o;
1324
1325     pa_assert(m);
1326
1327     if (!(u = m->userdata))
1328         return;
1329
1330     pa_strlist_free(u->unlinked_slaves);
1331
1332     if (u->sink_put_slot)
1333         pa_hook_slot_free(u->sink_put_slot);
1334
1335     if (u->sink_unlink_slot)
1336         pa_hook_slot_free(u->sink_unlink_slot);
1337
1338     if (u->sink_state_changed_slot)
1339         pa_hook_slot_free(u->sink_state_changed_slot);
1340
1341     if (u->outputs) {
1342         while ((o = pa_idxset_first(u->outputs, NULL)))
1343             output_free(o);
1344
1345         pa_idxset_free(u->outputs, NULL);
1346     }
1347
1348     if (u->sink)
1349         pa_sink_unlink(u->sink);
1350
1351     if (u->thread) {
1352         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1353         pa_thread_free(u->thread);
1354     }
1355
1356     pa_thread_mq_done(&u->thread_mq);
1357
1358     if (u->sink)
1359         pa_sink_unref(u->sink);
1360
1361     if (u->rtpoll)
1362         pa_rtpoll_free(u->rtpoll);
1363
1364     if (u->time_event)
1365         u->core->mainloop->time_free(u->time_event);
1366
1367     if (u->thread_info.smoother)
1368         pa_smoother_free(u->thread_info.smoother);
1369
1370     pa_xfree(u);
1371 }
1372
1373 static pa_sink_input *add_slave(struct userdata *u, pa_sink *sink) {
1374     struct output *o;
1375
1376     pa_assert(u);
1377     pa_assert(sink);
1378
1379     pa_log_debug("Adding a slave to module combine");
1380
1381     if (!(o = output_new(u, sink))) {
1382         pa_log("Failed to create slave sink input on sink '%s'.", sink->name);
1383         return NULL;
1384     }
1385
1386     output_verify(o);
1387
1388     return o->sink_input;
1389 }
1390
1391 static void remove_slave(struct userdata *u, pa_sink_input *i, pa_sink *s) {
1392     struct output *o;
1393
1394     pa_assert(u);
1395     pa_assert(i || s);
1396
1397     if (s == NULL)
1398         s = i->sink;
1399
1400     o = find_output(u, s);
1401
1402     if (o == NULL) {
1403         pa_log_debug("Couldn't find output in module combine");
1404         return;
1405     }
1406
1407     output_disable(o);
1408     output_free(o);
1409 }
1410
1411 static int move_slave(struct userdata *u, pa_sink_input *i, pa_sink *s) {
1412     struct output *o;
1413     int sts;
1414
1415     pa_assert(u);
1416     pa_assert(i);
1417     pa_assert(s);
1418
1419     pa_assert(i->sink);
1420
1421     o = find_output(u, i->sink);
1422
1423     if (o == NULL) {
1424         pa_log_debug("Could not find output with sink %s for moving", s->name);
1425         return -1;
1426     }
1427
1428     if (i->sink == s)
1429         return 0;
1430
1431     i->flags &= ~(pa_sink_input_flags_t)PA_SINK_INPUT_DONT_MOVE;
1432
1433     sts = pa_sink_input_move_to(i, s, false);
1434
1435     i->flags |= (pa_sink_input_flags_t)PA_SINK_INPUT_DONT_MOVE;
1436
1437
1438     if (sts < 0)
1439         return -1;
1440
1441     o->sink = s;
1442
1443     return 0;
1444 }