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