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