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