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