udev: when a device appears that we cannot access right-away try again later on inotify
[pulseaudio-mirror.git] / src / modules / module-combine.c
blobe90ef11ca41aebb8b95d92267de2f4a1c61c04d3
1 /***
2 This file is part of PulseAudio.
4 Copyright 2004-2008 Lennart Poettering
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.
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.
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 ***/
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
26 #include <stdio.h>
27 #include <errno.h>
29 #include <pulse/rtclock.h>
30 #include <pulse/timeval.h>
31 #include <pulse/xmalloc.h>
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>
51 #include "module-combine-symdef.h"
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=<seconds> "
62 "resample_method=<method> "
63 "format=<sample format> "
64 "rate=<sample rate> "
65 "channels=<number of channels> "
66 "channel_map=<channel map>");
68 #define DEFAULT_SINK_NAME "combined"
70 #define MEMBLOCKQ_MAXLENGTH (1024*1024*16)
72 #define DEFAULT_ADJUST_TIME 10
74 #define BLOCK_USEC (PA_USEC_PER_MSEC * 200)
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
89 struct output {
90 struct userdata *userdata;
92 pa_sink *sink;
93 pa_sink_input *sink_input;
95 pa_bool_t ignore_state_change;
97 pa_asyncmsgq *inq, /* Message queue from the sink thread to this sink input */
98 *outq; /* Message queue from this sink input to the sink thread */
99 pa_rtpoll_item *inq_rtpoll_item_read, *inq_rtpoll_item_write;
100 pa_rtpoll_item *outq_rtpoll_item_read, *outq_rtpoll_item_write;
102 pa_memblockq *memblockq;
104 /* For communication of the stream latencies to the main thread */
105 pa_usec_t total_latency;
107 /* For coomunication of the stream parameters to the sink thread */
108 pa_atomic_t max_request;
109 pa_atomic_t requested_latency;
111 PA_LLIST_FIELDS(struct output);
114 struct userdata {
115 pa_core *core;
116 pa_module *module;
117 pa_sink *sink;
119 pa_thread *thread;
120 pa_thread_mq thread_mq;
121 pa_rtpoll *rtpoll;
123 pa_time_event *time_event;
124 uint32_t adjust_time;
126 pa_bool_t automatic;
127 pa_bool_t auto_desc;
129 pa_hook_slot *sink_put_slot, *sink_unlink_slot, *sink_state_changed_slot;
131 pa_resample_method_t resample_method;
133 pa_usec_t block_usec;
135 pa_idxset* outputs; /* managed in main context */
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;
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
156 enum {
157 SINK_INPUT_MESSAGE_POST = PA_SINK_INPUT_MESSAGE_MAX,
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);
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;
172 pa_assert(u);
173 pa_sink_assert_ref(u->sink);
175 if (pa_idxset_size(u->outputs) <= 0)
176 return;
178 if (!PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)))
179 return;
181 PA_IDXSET_FOREACH(o, u->outputs, idx) {
182 pa_usec_t sink_latency;
184 if (!o->sink_input || !PA_SINK_IS_OPENED(pa_sink_get_state(o->sink)))
185 continue;
187 o->total_latency = pa_sink_input_get_latency(o->sink_input, &sink_latency);
188 o->total_latency += sink_latency;
190 if (sink_latency > max_sink_latency)
191 max_sink_latency = sink_latency;
193 if (min_total_latency == (pa_usec_t) -1 || o->total_latency < min_total_latency)
194 min_total_latency = o->total_latency;
196 avg_total_latency += o->total_latency;
197 n++;
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);
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);
205 if (min_total_latency == (pa_usec_t) -1)
206 return;
208 avg_total_latency /= n;
210 target_latency = max_sink_latency > min_total_latency ? max_sink_latency : min_total_latency;
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);
215 base_rate = u->sink->sample_spec.rate;
217 PA_IDXSET_FOREACH(o, u->outputs, idx) {
218 uint32_t r = base_rate;
220 if (!o->sink_input || !PA_SINK_IS_OPENED(pa_sink_get_state(o->sink)))
221 continue;
223 if (o->total_latency < target_latency)
224 r -= (uint32_t) ((((double) (target_latency - o->total_latency))/(double)u->adjust_time)*(double)r/PA_USEC_PER_SEC);
225 else if (o->total_latency > target_latency)
226 r += (uint32_t) ((((double) (o->total_latency - target_latency))/(double)u->adjust_time)*(double)r/PA_USEC_PER_SEC);
228 if (r < (uint32_t) (base_rate*0.9) || r > (uint32_t) (base_rate*1.1)) {
229 pa_log_warn("[%s] sample rates too different, not adjusting (%u vs. %u).", o->sink_input->sink->name, base_rate, r);
230 pa_sink_input_set_rate(o->sink_input, base_rate);
231 } else {
232 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);
233 pa_sink_input_set_rate(o->sink_input, r);
237 pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_UPDATE_LATENCY, NULL, (int64_t) avg_total_latency, NULL);
240 static void time_callback(pa_mainloop_api *a, pa_time_event *e, const struct timeval *t, void *userdata) {
241 struct userdata *u = userdata;
243 pa_assert(u);
244 pa_assert(a);
245 pa_assert(u->time_event == e);
247 adjust_rates(u);
249 pa_core_rttime_restart(u->core, e, pa_rtclock_now() + u->adjust_time * PA_USEC_PER_SEC);
252 static void process_render_null(struct userdata *u, pa_usec_t now) {
253 size_t ate = 0;
254 pa_assert(u);
256 if (u->thread_info.in_null_mode)
257 u->thread_info.timestamp = now;
259 while (u->thread_info.timestamp < now + u->block_usec) {
260 pa_memchunk chunk;
262 pa_sink_render(u->sink, u->sink->thread_info.max_request, &chunk);
263 pa_memblock_unref(chunk.memblock);
265 u->thread_info.counter += chunk.length;
267 /* pa_log_debug("Ate %lu bytes.", (unsigned long) chunk.length); */
268 u->thread_info.timestamp += pa_bytes_to_usec(chunk.length, &u->sink->sample_spec);
270 ate += chunk.length;
272 if (ate >= u->sink->thread_info.max_request)
273 break;
276 /* pa_log_debug("Ate in sum %lu bytes (of %lu)", (unsigned long) ate, (unsigned long) nbytes); */
278 pa_smoother_put(u->thread_info.smoother, now,
279 pa_bytes_to_usec(u->thread_info.counter, &u->sink->sample_spec) - (u->thread_info.timestamp - now));
282 static void thread_func(void *userdata) {
283 struct userdata *u = userdata;
285 pa_assert(u);
287 pa_log_debug("Thread starting up");
289 if (u->core->realtime_scheduling)
290 pa_make_realtime(u->core->realtime_priority+1);
292 pa_thread_mq_install(&u->thread_mq);
294 u->thread_info.timestamp = pa_rtclock_now();
295 u->thread_info.in_null_mode = FALSE;
297 for (;;) {
298 int ret;
300 if (PA_SINK_IS_OPENED(u->sink->thread_info.state))
301 if (u->sink->thread_info.rewind_requested)
302 pa_sink_process_rewind(u->sink, 0);
304 /* If no outputs are connected, render some data and drop it immediately. */
305 if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && !u->thread_info.active_outputs) {
306 pa_usec_t now;
308 now = pa_rtclock_now();
310 if (!u->thread_info.in_null_mode || u->thread_info.timestamp <= now)
311 process_render_null(u, now);
313 pa_rtpoll_set_timer_absolute(u->rtpoll, u->thread_info.timestamp);
314 u->thread_info.in_null_mode = TRUE;
315 } else {
316 pa_rtpoll_set_timer_disabled(u->rtpoll);
317 u->thread_info.in_null_mode = FALSE;
320 /* Hmm, nothing to do. Let's sleep */
321 if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
322 pa_log_info("pa_rtpoll_run() = %i", ret);
323 goto fail;
326 if (ret == 0)
327 goto finish;
330 fail:
331 /* If this was no regular exit from the loop we have to continue
332 * processing messages until we received PA_MESSAGE_SHUTDOWN */
333 pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
334 pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
336 finish:
337 pa_log_debug("Thread shutting down");
340 /* Called from I/O thread context */
341 static void render_memblock(struct userdata *u, struct output *o, size_t length) {
342 pa_assert(u);
343 pa_assert(o);
345 /* We are run by the sink thread, on behalf of an output (o). The
346 * output is waiting for us, hence it is safe to access its
347 * mainblockq and asyncmsgq directly. */
349 /* If we are not running, we cannot produce any data */
350 if (!pa_atomic_load(&u->thread_info.running))
351 return;
353 /* Maybe there's some data in the requesting output's queue
354 * now? */
355 while (pa_asyncmsgq_process_one(o->inq) > 0)
358 /* Ok, now let's prepare some data if we really have to */
359 while (!pa_memblockq_is_readable(o->memblockq)) {
360 struct output *j;
361 pa_memchunk chunk;
363 /* Render data! */
364 pa_sink_render(u->sink, length, &chunk);
366 u->thread_info.counter += chunk.length;
368 /* OK, let's send this data to the other threads */
369 PA_LLIST_FOREACH(j, u->thread_info.active_outputs) {
370 if (j == o)
371 continue;
373 pa_asyncmsgq_post(j->inq, PA_MSGOBJECT(j->sink_input), SINK_INPUT_MESSAGE_POST, NULL, 0, &chunk, NULL);
376 /* And place it directly into the requesting output's queue */
377 pa_memblockq_push_align(o->memblockq, &chunk);
378 pa_memblock_unref(chunk.memblock);
382 /* Called from I/O thread context */
383 static void request_memblock(struct output *o, size_t length) {
384 pa_assert(o);
385 pa_sink_input_assert_ref(o->sink_input);
386 pa_sink_assert_ref(o->userdata->sink);
388 /* If another thread already prepared some data we received
389 * the data over the asyncmsgq, hence let's first process
390 * it. */
391 while (pa_asyncmsgq_process_one(o->inq) > 0)
394 /* Check whether we're now readable */
395 if (pa_memblockq_is_readable(o->memblockq))
396 return;
398 /* OK, we need to prepare new data, but only if the sink is actually running */
399 if (pa_atomic_load(&o->userdata->thread_info.running))
400 pa_asyncmsgq_send(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_NEED, o, (int64_t) length, NULL);
403 /* Called from I/O thread context */
404 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
405 struct output *o;
407 pa_sink_input_assert_ref(i);
408 pa_assert_se(o = i->userdata);
410 /* If necessary, get some new data */
411 request_memblock(o, nbytes);
413 /* pa_log("%s q size is %u + %u (%u/%u)", */
414 /* i->sink->name, */
415 /* pa_memblockq_get_nblocks(o->memblockq), */
416 /* pa_memblockq_get_nblocks(i->thread_info.render_memblockq), */
417 /* pa_memblockq_get_maxrewind(o->memblockq), */
418 /* pa_memblockq_get_maxrewind(i->thread_info.render_memblockq)); */
420 if (pa_memblockq_peek(o->memblockq, chunk) < 0)
421 return -1;
423 pa_memblockq_drop(o->memblockq, chunk->length);
425 return 0;
428 /* Called from I/O thread context */
429 static void sink_input_process_rewind_cb(pa_sink_input *i, size_t nbytes) {
430 struct output *o;
432 pa_sink_input_assert_ref(i);
433 pa_assert_se(o = i->userdata);
435 pa_memblockq_rewind(o->memblockq, nbytes);
438 /* Called from I/O thread context */
439 static void sink_input_update_max_rewind_cb(pa_sink_input *i, size_t nbytes) {
440 struct output *o;
442 pa_sink_input_assert_ref(i);
443 pa_assert_se(o = i->userdata);
445 pa_memblockq_set_maxrewind(o->memblockq, nbytes);
448 /* Called from I/O thread context */
449 static void sink_input_update_max_request_cb(pa_sink_input *i, size_t nbytes) {
450 struct output *o;
452 pa_sink_input_assert_ref(i);
453 pa_assert_se(o = i->userdata);
455 if (pa_atomic_load(&o->max_request) == (int) nbytes)
456 return;
458 pa_atomic_store(&o->max_request, (int) nbytes);
459 pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_MAX_REQUEST, NULL, 0, NULL, NULL);
462 /* Called from thread context */
463 static void sink_input_update_sink_requested_latency_cb(pa_sink_input *i) {
464 struct output *o;
465 pa_usec_t c;
467 pa_assert(i);
469 pa_sink_input_assert_ref(i);
470 pa_assert_se(o = i->userdata);
472 c = pa_sink_get_requested_latency_within_thread(i->sink);
474 if (c == (pa_usec_t) -1)
475 c = i->sink->thread_info.max_latency;
477 if (pa_atomic_load(&o->requested_latency) == (int) c)
478 return;
480 pa_atomic_store(&o->requested_latency, (int) c);
481 pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_REQUESTED_LATENCY, NULL, 0, NULL, NULL);
484 /* Called from I/O thread context */
485 static void sink_input_attach_cb(pa_sink_input *i) {
486 struct output *o;
487 pa_usec_t c;
489 pa_sink_input_assert_ref(i);
490 pa_assert_se(o = i->userdata);
492 /* Set up the queue from the sink thread to us */
493 pa_assert(!o->inq_rtpoll_item_read && !o->outq_rtpoll_item_write);
495 o->inq_rtpoll_item_read = pa_rtpoll_item_new_asyncmsgq_read(
496 i->sink->thread_info.rtpoll,
497 PA_RTPOLL_LATE, /* This one is not that important, since we check for data in _peek() anyway. */
498 o->inq);
500 o->outq_rtpoll_item_write = pa_rtpoll_item_new_asyncmsgq_write(
501 i->sink->thread_info.rtpoll,
502 PA_RTPOLL_EARLY,
503 o->outq);
505 pa_sink_input_request_rewind(i, 0, FALSE, TRUE, TRUE);
507 pa_atomic_store(&o->max_request, (int) pa_sink_input_get_max_request(i));
509 c = pa_sink_get_requested_latency_within_thread(i->sink);
510 pa_atomic_store(&o->requested_latency, (int) (c == (pa_usec_t) -1 ? 0 : c));
512 pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_MAX_REQUEST, NULL, 0, NULL, NULL);
513 pa_asyncmsgq_post(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_UPDATE_REQUESTED_LATENCY, NULL, 0, NULL, NULL);
516 /* Called from I/O thread context */
517 static void sink_input_detach_cb(pa_sink_input *i) {
518 struct output *o;
520 pa_sink_input_assert_ref(i);
521 pa_assert_se(o = i->userdata);
523 if (o->inq_rtpoll_item_read) {
524 pa_rtpoll_item_free(o->inq_rtpoll_item_read);
525 o->inq_rtpoll_item_read = NULL;
528 if (o->outq_rtpoll_item_write) {
529 pa_rtpoll_item_free(o->outq_rtpoll_item_write);
530 o->outq_rtpoll_item_write = NULL;
534 /* Called from main context */
535 static void sink_input_kill_cb(pa_sink_input *i) {
536 struct output *o;
538 pa_sink_input_assert_ref(i);
539 pa_assert_se(o = i->userdata);
541 pa_module_unload_request(o->userdata->module, TRUE);
542 output_free(o);
545 /* Called from thread context */
546 static int sink_input_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
547 struct output *o = PA_SINK_INPUT(obj)->userdata;
549 switch (code) {
551 case PA_SINK_INPUT_MESSAGE_GET_LATENCY: {
552 pa_usec_t *r = data;
554 *r = pa_bytes_to_usec(pa_memblockq_get_length(o->memblockq), &o->sink_input->sample_spec);
556 /* Fall through, the default handler will add in the extra
557 * latency added by the resampler */
558 break;
561 case SINK_INPUT_MESSAGE_POST:
563 if (PA_SINK_IS_OPENED(o->sink_input->sink->thread_info.state))
564 pa_memblockq_push_align(o->memblockq, chunk);
565 else
566 pa_memblockq_flush_write(o->memblockq);
568 return 0;
571 return pa_sink_input_process_msg(obj, code, data, offset, chunk);
574 /* Called from main context */
575 static void suspend(struct userdata *u) {
576 struct output *o;
577 uint32_t idx;
579 pa_assert(u);
581 /* Let's suspend by unlinking all streams */
582 PA_IDXSET_FOREACH(o, u->outputs, idx)
583 output_disable(o);
585 pa_log_info("Device suspended...");
588 /* Called from main context */
589 static void unsuspend(struct userdata *u) {
590 struct output *o;
591 uint32_t idx;
593 pa_assert(u);
595 /* Let's resume */
596 PA_IDXSET_FOREACH(o, u->outputs, idx)
597 output_enable(o);
599 pa_log_info("Resumed successfully...");
602 /* Called from main context */
603 static int sink_set_state(pa_sink *sink, pa_sink_state_t state) {
604 struct userdata *u;
606 pa_sink_assert_ref(sink);
607 pa_assert_se(u = sink->userdata);
609 /* Please note that in contrast to the ALSA modules we call
610 * suspend/unsuspend from main context here! */
612 switch (state) {
613 case PA_SINK_SUSPENDED:
614 pa_assert(PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)));
616 suspend(u);
617 break;
619 case PA_SINK_IDLE:
620 case PA_SINK_RUNNING:
622 if (pa_sink_get_state(u->sink) == PA_SINK_SUSPENDED)
623 unsuspend(u);
625 break;
627 case PA_SINK_UNLINKED:
628 case PA_SINK_INIT:
629 case PA_SINK_INVALID_STATE:
633 return 0;
636 /* Called from IO context */
637 static void update_max_request(struct userdata *u) {
638 size_t max_request = 0;
639 struct output *o;
641 pa_assert(u);
642 pa_sink_assert_io_context(u->sink);
644 /* Collects the max_request values of all streams and sets the
645 * largest one locally */
647 PA_LLIST_FOREACH(o, u->thread_info.active_outputs) {
648 size_t mr = (size_t) pa_atomic_load(&o->max_request);
650 if (mr > max_request)
651 max_request = mr;
654 if (max_request <= 0)
655 max_request = pa_usec_to_bytes(u->block_usec, &u->sink->sample_spec);
657 pa_sink_set_max_request_within_thread(u->sink, max_request);
660 /* Called from IO context */
661 static void update_fixed_latency(struct userdata *u) {
662 pa_usec_t fixed_latency = 0;
663 struct output *o;
665 pa_assert(u);
666 pa_sink_assert_io_context(u->sink);
668 /* Collects the requested_latency values of all streams and sets
669 * the largest one as fixed_latency locally */
671 PA_LLIST_FOREACH(o, u->thread_info.active_outputs) {
672 pa_usec_t rl = (size_t) pa_atomic_load(&o->requested_latency);
674 if (rl > fixed_latency)
675 fixed_latency = rl;
678 if (fixed_latency <= 0)
679 fixed_latency = u->block_usec;
681 pa_sink_set_fixed_latency_within_thread(u->sink, fixed_latency);
684 /* Called from thread context of the io thread */
685 static void output_add_within_thread(struct output *o) {
686 pa_assert(o);
687 pa_sink_assert_io_context(o->sink);
689 PA_LLIST_PREPEND(struct output, o->userdata->thread_info.active_outputs, o);
691 pa_assert(!o->outq_rtpoll_item_read && !o->inq_rtpoll_item_write);
693 o->outq_rtpoll_item_read = pa_rtpoll_item_new_asyncmsgq_read(
694 o->userdata->rtpoll,
695 PA_RTPOLL_EARLY-1, /* This item is very important */
696 o->outq);
697 o->inq_rtpoll_item_write = pa_rtpoll_item_new_asyncmsgq_write(
698 o->userdata->rtpoll,
699 PA_RTPOLL_EARLY,
700 o->inq);
703 /* Called from thread context of the io thread */
704 static void output_remove_within_thread(struct output *o) {
705 pa_assert(o);
706 pa_sink_assert_io_context(o->sink);
708 PA_LLIST_REMOVE(struct output, o->userdata->thread_info.active_outputs, o);
710 if (o->outq_rtpoll_item_read) {
711 pa_rtpoll_item_free(o->outq_rtpoll_item_read);
712 o->outq_rtpoll_item_read = NULL;
715 if (o->inq_rtpoll_item_write) {
716 pa_rtpoll_item_free(o->inq_rtpoll_item_write);
717 o->inq_rtpoll_item_write = NULL;
721 /* Called from thread context of the io thread */
722 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
723 struct userdata *u = PA_SINK(o)->userdata;
725 switch (code) {
727 case PA_SINK_MESSAGE_SET_STATE:
728 pa_atomic_store(&u->thread_info.running, PA_PTR_TO_UINT(data) == PA_SINK_RUNNING);
730 if (PA_PTR_TO_UINT(data) == PA_SINK_SUSPENDED)
731 pa_smoother_pause(u->thread_info.smoother, pa_rtclock_now());
732 else
733 pa_smoother_resume(u->thread_info.smoother, pa_rtclock_now(), TRUE);
735 break;
737 case PA_SINK_MESSAGE_GET_LATENCY: {
738 pa_usec_t x, y, c, *delay = data;
740 x = pa_rtclock_now();
741 y = pa_smoother_get(u->thread_info.smoother, x);
743 c = pa_bytes_to_usec(u->thread_info.counter, &u->sink->sample_spec);
745 if (y < c)
746 *delay = c - y;
747 else
748 *delay = 0;
750 return 0;
753 case SINK_MESSAGE_ADD_OUTPUT:
754 output_add_within_thread(data);
755 update_max_request(u);
756 update_fixed_latency(u);
757 return 0;
759 case SINK_MESSAGE_REMOVE_OUTPUT:
760 output_remove_within_thread(data);
761 update_max_request(u);
762 update_fixed_latency(u);
763 return 0;
765 case SINK_MESSAGE_NEED:
766 render_memblock(u, (struct output*) data, (size_t) offset);
767 return 0;
769 case SINK_MESSAGE_UPDATE_LATENCY: {
770 pa_usec_t x, y, latency = (pa_usec_t) offset;
772 x = pa_rtclock_now();
773 y = pa_bytes_to_usec(u->thread_info.counter, &u->sink->sample_spec);
775 if (y > latency)
776 y -= latency;
777 else
778 y = 0;
780 pa_smoother_put(u->thread_info.smoother, x, y);
781 return 0;
784 case SINK_MESSAGE_UPDATE_MAX_REQUEST:
785 update_max_request(u);
786 break;
788 case SINK_MESSAGE_UPDATE_REQUESTED_LATENCY:
789 update_fixed_latency(u);
790 break;
793 return pa_sink_process_msg(o, code, data, offset, chunk);
796 static void update_description(struct userdata *u) {
797 pa_bool_t first = TRUE;
798 char *t;
799 struct output *o;
800 uint32_t idx;
802 pa_assert(u);
804 if (!u->auto_desc)
805 return;
807 if (pa_idxset_isempty(u->outputs)) {
808 pa_sink_set_description(u->sink, "Simultaneous output");
809 return;
812 t = pa_xstrdup("Simultaneous output to");
814 PA_IDXSET_FOREACH(o, u->outputs, idx) {
815 char *e;
817 if (first) {
818 e = pa_sprintf_malloc("%s %s", t, pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
819 first = FALSE;
820 } else
821 e = pa_sprintf_malloc("%s, %s", t, pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
823 pa_xfree(t);
824 t = e;
827 pa_sink_set_description(u->sink, t);
828 pa_xfree(t);
831 static int output_create_sink_input(struct output *o) {
832 pa_sink_input_new_data data;
834 pa_assert(o);
836 if (o->sink_input)
837 return 0;
839 pa_sink_input_new_data_init(&data);
840 data.sink = o->sink;
841 data.driver = __FILE__;
842 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)));
843 pa_proplist_sets(data.proplist, PA_PROP_MEDIA_ROLE, "filter");
844 pa_sink_input_new_data_set_sample_spec(&data, &o->userdata->sink->sample_spec);
845 pa_sink_input_new_data_set_channel_map(&data, &o->userdata->sink->channel_map);
846 data.module = o->userdata->module;
847 data.resample_method = o->userdata->resample_method;
849 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);
851 pa_sink_input_new_data_done(&data);
853 if (!o->sink_input)
854 return -1;
856 o->sink_input->parent.process_msg = sink_input_process_msg;
857 o->sink_input->pop = sink_input_pop_cb;
858 o->sink_input->process_rewind = sink_input_process_rewind_cb;
859 o->sink_input->update_max_rewind = sink_input_update_max_rewind_cb;
860 o->sink_input->update_max_request = sink_input_update_max_request_cb;
861 o->sink_input->update_sink_requested_latency = sink_input_update_sink_requested_latency_cb;
862 o->sink_input->attach = sink_input_attach_cb;
863 o->sink_input->detach = sink_input_detach_cb;
864 o->sink_input->kill = sink_input_kill_cb;
865 o->sink_input->userdata = o;
867 pa_sink_input_set_requested_latency(o->sink_input, BLOCK_USEC);
869 return 0;
872 /* Called from main context */
873 static struct output *output_new(struct userdata *u, pa_sink *sink) {
874 struct output *o;
876 pa_assert(u);
877 pa_assert(sink);
878 pa_assert(u->sink);
880 o = pa_xnew0(struct output, 1);
881 o->userdata = u;
882 o->inq = pa_asyncmsgq_new(0);
883 o->outq = pa_asyncmsgq_new(0);
884 o->sink = sink;
885 o->memblockq = pa_memblockq_new(
887 MEMBLOCKQ_MAXLENGTH,
888 MEMBLOCKQ_MAXLENGTH,
889 pa_frame_size(&u->sink->sample_spec),
893 NULL);
895 pa_assert_se(pa_idxset_put(u->outputs, o, NULL) == 0);
896 update_description(u);
898 return o;
901 /* Called from main context */
902 static void output_free(struct output *o) {
903 pa_assert(o);
905 output_disable(o);
907 pa_assert_se(pa_idxset_remove_by_data(o->userdata->outputs, o, NULL));
908 update_description(o->userdata);
910 if (o->inq_rtpoll_item_read)
911 pa_rtpoll_item_free(o->inq_rtpoll_item_read);
912 if (o->inq_rtpoll_item_write)
913 pa_rtpoll_item_free(o->inq_rtpoll_item_write);
915 if (o->outq_rtpoll_item_read)
916 pa_rtpoll_item_free(o->outq_rtpoll_item_read);
917 if (o->outq_rtpoll_item_write)
918 pa_rtpoll_item_free(o->outq_rtpoll_item_write);
920 if (o->inq)
921 pa_asyncmsgq_unref(o->inq);
923 if (o->outq)
924 pa_asyncmsgq_unref(o->outq);
926 if (o->memblockq)
927 pa_memblockq_free(o->memblockq);
929 pa_xfree(o);
932 /* Called from main context */
933 static void output_enable(struct output *o) {
934 pa_assert(o);
936 if (o->sink_input)
937 return;
939 /* This might cause the sink to be resumed. The state change hook
940 * of the sink might hence be called from here, which might then
941 * cause us to be called in a loop. Make sure that state changes
942 * for this output don't cause this loop by setting a flag here */
943 o->ignore_state_change = TRUE;
945 if (output_create_sink_input(o) >= 0) {
947 if (pa_sink_get_state(o->sink) != PA_SINK_INIT) {
949 /* First we register the output. That means that the sink
950 * will start to pass data to this output. */
951 pa_asyncmsgq_send(o->userdata->sink->asyncmsgq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_ADD_OUTPUT, o, 0, NULL);
953 /* Then we enable the sink input. That means that the sink
954 * is now asked for new data. */
955 pa_sink_input_put(o->sink_input);
957 } else
958 /* Hmm the sink is not yet started, do things right here */
959 output_add_within_thread(o);
962 o->ignore_state_change = FALSE;
965 /* Called from main context */
966 static void output_disable(struct output *o) {
967 pa_assert(o);
969 if (!o->sink_input)
970 return;
972 /* First we disable the sink input. That means that the sink is
973 * not asked for new data anymore */
974 pa_sink_input_unlink(o->sink_input);
976 /* Then we unregister the output. That means that the sink doesn't
977 * pass any further data to this output */
978 pa_asyncmsgq_send(o->userdata->sink->asyncmsgq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_REMOVE_OUTPUT, o, 0, NULL);
980 /* Now dellocate the stream */
981 pa_sink_input_unref(o->sink_input);
982 o->sink_input = NULL;
984 /* Finally, drop all queued data */
985 pa_memblockq_flush_write(o->memblockq);
986 pa_asyncmsgq_flush(o->inq, FALSE);
987 pa_asyncmsgq_flush(o->outq, FALSE);
990 /* Called from main context */
991 static void output_verify(struct output *o) {
992 pa_assert(o);
994 if (PA_SINK_IS_OPENED(pa_sink_get_state(o->userdata->sink)))
995 output_enable(o);
996 else
997 output_disable(o);
1000 /* Called from main context */
1001 static pa_bool_t is_suitable_sink(struct userdata *u, pa_sink *s) {
1002 const char *t;
1004 pa_sink_assert_ref(s);
1006 if (s == u->sink)
1007 return FALSE;
1009 if (!(s->flags & PA_SINK_HARDWARE))
1010 return FALSE;
1012 if (!(s->flags & PA_SINK_LATENCY))
1013 return FALSE;
1015 if ((t = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_CLASS)))
1016 if (!pa_streq(t, "sound"))
1017 return FALSE;
1019 return TRUE;
1022 /* Called from main context */
1023 static pa_hook_result_t sink_put_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
1024 struct output *o;
1026 pa_core_assert_ref(c);
1027 pa_sink_assert_ref(s);
1028 pa_assert(u);
1029 pa_assert(u->automatic);
1031 if (!is_suitable_sink(u, s))
1032 return PA_HOOK_OK;
1034 pa_log_info("Configuring new sink: %s", s->name);
1035 if (!(o = output_new(u, s))) {
1036 pa_log("Failed to create sink input on sink '%s'.", s->name);
1037 return PA_HOOK_OK;
1040 output_verify(o);
1042 return PA_HOOK_OK;
1045 /* Called from main context */
1046 static struct output* find_output(struct userdata *u, pa_sink *s) {
1047 struct output *o;
1048 uint32_t idx;
1050 pa_assert(u);
1051 pa_assert(s);
1053 if (u->sink == s)
1054 return NULL;
1056 PA_IDXSET_FOREACH(o, u->outputs, idx)
1057 if (o->sink == s)
1058 return o;
1060 return NULL;
1063 /* Called from main context */
1064 static pa_hook_result_t sink_unlink_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
1065 struct output *o;
1067 pa_assert(c);
1068 pa_sink_assert_ref(s);
1069 pa_assert(u);
1071 if (!(o = find_output(u, s)))
1072 return PA_HOOK_OK;
1074 pa_log_info("Unconfiguring sink: %s", s->name);
1075 output_free(o);
1077 return PA_HOOK_OK;
1080 /* Called from main context */
1081 static pa_hook_result_t sink_state_changed_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
1082 struct output *o;
1084 if (!(o = find_output(u, s)))
1085 return PA_HOOK_OK;
1087 /* This state change might be triggered because we are creating a
1088 * stream here, in that case we don't want to create it a second
1089 * time here and enter a loop */
1090 if (o->ignore_state_change)
1091 return PA_HOOK_OK;
1093 output_verify(o);
1095 return PA_HOOK_OK;
1098 int pa__init(pa_module*m) {
1099 struct userdata *u;
1100 pa_modargs *ma = NULL;
1101 const char *slaves, *rm;
1102 int resample_method = PA_RESAMPLER_TRIVIAL;
1103 pa_sample_spec ss;
1104 pa_channel_map map;
1105 struct output *o;
1106 uint32_t idx;
1107 pa_sink_new_data data;
1109 pa_assert(m);
1111 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1112 pa_log("failed to parse module arguments");
1113 goto fail;
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;
1123 m->userdata = u = pa_xnew0(struct userdata, 1);
1124 u->core = m->core;
1125 u->module = m;
1126 u->adjust_time = DEFAULT_ADJUST_TIME;
1127 u->rtpoll = pa_rtpoll_new();
1128 pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
1129 u->resample_method = resample_method;
1130 u->outputs = pa_idxset_new(NULL, NULL);
1131 u->sink_put_slot = u->sink_unlink_slot = u->sink_state_changed_slot = NULL;
1132 PA_LLIST_HEAD_INIT(struct output, u->thread_info.active_outputs);
1133 pa_atomic_store(&u->thread_info.running, FALSE);
1134 u->thread_info.in_null_mode = FALSE;
1135 u->thread_info.counter = 0;
1136 u->thread_info.smoother = pa_smoother_new(
1137 PA_USEC_PER_SEC,
1138 PA_USEC_PER_SEC*2,
1139 TRUE,
1140 TRUE,
1143 FALSE);
1145 if (pa_modargs_get_value_u32(ma, "adjust_time", &u->adjust_time) < 0) {
1146 pa_log("Failed to parse adjust_time value");
1147 goto fail;
1150 slaves = pa_modargs_get_value(ma, "slaves", NULL);
1151 u->automatic = !slaves;
1153 ss = m->core->default_sample_spec;
1154 map = m->core->default_channel_map;
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;
1164 pa_sample_spec_init(&slaves_spec);
1166 while ((n = pa_split(slaves, ",", &split_state))) {
1167 pa_sink *slave_sink;
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;
1175 pa_xfree(n);
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;
1185 if (slaves_spec.rate < slave_sink->sample_spec.rate)
1186 slaves_spec.rate = slave_sink->sample_spec.rate;
1188 if (!pa_channel_map_equal(&slaves_map, &slave_sink->channel_map))
1189 slaves_spec.channels = 0;
1193 if (!is_first_slave) {
1194 if (slaves_spec.format != PA_SAMPLE_INVALID)
1195 ss.format = slaves_spec.format;
1197 ss.rate = slaves_spec.rate;
1199 if (slaves_spec.channels > 0) {
1200 map = slaves_map;
1201 ss.channels = slaves_map.channels;
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;
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");
1220 if (slaves)
1221 pa_proplist_sets(data.proplist, "combine.slaves", slaves);
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;
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");
1236 u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
1237 pa_sink_new_data_done(&data);
1239 if (!u->sink) {
1240 pa_log("Failed to create sink");
1241 goto fail;
1244 u->sink->parent.process_msg = sink_process_msg;
1245 u->sink->set_state = sink_set_state;
1246 u->sink->userdata = u;
1248 pa_sink_set_rtpoll(u->sink, u->rtpoll);
1249 pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
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));
1254 if (!u->automatic) {
1255 const char*split_state;
1256 char *n = NULL;
1257 pa_assert(slaves);
1259 /* The slaves have been specified manually */
1261 split_state = NULL;
1262 while ((n = pa_split(slaves, ",", &split_state))) {
1263 pa_sink *slave_sink;
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;
1271 pa_xfree(n);
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;
1279 if (pa_idxset_size(u->outputs) <= 1)
1280 pa_log_warn("No slave sinks specified.");
1282 u->sink_put_slot = NULL;
1284 } else {
1285 pa_sink *s;
1287 /* We're in automatic mode, we add every sink that matches our needs */
1289 PA_IDXSET_FOREACH(s, m->core->sinks, idx) {
1291 if (!is_suitable_sink(u, s))
1292 continue;
1294 if (!output_new(u, s)) {
1295 pa_log("Failed to create sink input on sink '%s'.", s->name);
1296 goto fail;
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);
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);
1306 if (!(u->thread = pa_thread_new(thread_func, u))) {
1307 pa_log("Failed to create thread.");
1308 goto fail;
1311 /* Activate the sink and the sink inputs */
1312 pa_sink_put(u->sink);
1314 PA_IDXSET_FOREACH(o, u->outputs, idx)
1315 output_verify(o);
1317 if (u->adjust_time > 0)
1318 u->time_event = pa_core_rttime_new(m->core, pa_rtclock_now() + u->adjust_time * PA_USEC_PER_SEC, time_callback, u);
1320 pa_modargs_free(ma);
1322 return 0;
1324 fail:
1326 if (ma)
1327 pa_modargs_free(ma);
1329 pa__done(m);
1331 return -1;
1334 void pa__done(pa_module*m) {
1335 struct userdata *u;
1336 struct output *o;
1338 pa_assert(m);
1340 if (!(u = m->userdata))
1341 return;
1343 if (u->sink_put_slot)
1344 pa_hook_slot_free(u->sink_put_slot);
1346 if (u->sink_unlink_slot)
1347 pa_hook_slot_free(u->sink_unlink_slot);
1349 if (u->sink_state_changed_slot)
1350 pa_hook_slot_free(u->sink_state_changed_slot);
1352 if (u->outputs) {
1353 while ((o = pa_idxset_first(u->outputs, NULL)))
1354 output_free(o);
1356 pa_idxset_free(u->outputs, NULL, NULL);
1359 if (u->sink)
1360 pa_sink_unlink(u->sink);
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);
1367 pa_thread_mq_done(&u->thread_mq);
1369 if (u->sink)
1370 pa_sink_unref(u->sink);
1372 if (u->rtpoll)
1373 pa_rtpoll_free(u->rtpoll);
1375 if (u->time_event)
1376 u->core->mainloop->time_free(u->time_event);
1378 if (u->thread_info.smoother)
1379 pa_smoother_free(u->thread_info.smoother);
1381 pa_xfree(u);