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