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