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