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