deal with a possibly failing pa_channel_map_init_auto() correctly
[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*170)
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_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_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_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).", o->sink_input->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.", o->sink_input->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             pa_rtclock_get(&now);
254
255             if (!u->thread_info.in_null_mode || pa_timeval_cmp(&u->thread_info.timestamp, &now) <= 0) {
256                 pa_sink_skip(u->sink, u->block_size);
257
258                 if (!u->thread_info.in_null_mode)
259                     u->thread_info.timestamp = now;
260
261                 pa_timeval_add(&u->thread_info.timestamp, pa_bytes_to_usec(u->block_size, &u->sink->sample_spec));
262             }
263
264             pa_rtpoll_set_timer_absolute(u->rtpoll, &u->thread_info.timestamp);
265             u->thread_info.in_null_mode = TRUE;
266
267         } else {
268             pa_rtpoll_set_timer_disabled(u->rtpoll);
269             u->thread_info.in_null_mode = FALSE;
270         }
271
272         /* Hmm, nothing to do. Let's sleep */
273         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
274             pa_log_info("pa_rtpoll_run() = %i", ret);
275             goto fail;
276         }
277
278         if (ret == 0)
279             goto finish;
280     }
281
282 fail:
283     /* If this was no regular exit from the loop we have to continue
284      * processing messages until we received PA_MESSAGE_SHUTDOWN */
285     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
286     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
287
288 finish:
289     pa_log_debug("Thread shutting down");
290 }
291
292 /* Called from I/O thread context */
293 static void render_memblock(struct userdata *u, struct output *o, size_t length) {
294     pa_assert(u);
295     pa_assert(o);
296
297     /* We are run by the sink thread, on behalf of an output (o). The
298      * other output is waiting for us, hence it is safe to access its
299      * mainblockq and asyncmsgq directly. */
300
301     /* If we are not running, we cannot produce any data */
302     if (!pa_atomic_load(&u->thread_info.running))
303         return;
304
305     /* Maybe there's some data in the requesting output's queue
306      * now? */
307     while (pa_asyncmsgq_process_one(o->inq) > 0)
308         ;
309
310     /* Ok, now let's prepare some data if we really have to */
311     while (!pa_memblockq_is_readable(o->memblockq)) {
312         struct output *j;
313         pa_memchunk chunk;
314
315         /* Render data! */
316         pa_sink_render(u->sink, length, &chunk);
317
318         /* OK, let's send this data to the other threads */
319         for (j = u->thread_info.active_outputs; j; j = j->next)
320
321             /* Send to other outputs, which are not the requesting
322              * one */
323
324             if (j != o)
325                 pa_asyncmsgq_post(j->inq, PA_MSGOBJECT(j->sink_input), SINK_INPUT_MESSAGE_POST, NULL, 0, &chunk, NULL);
326
327         /* And place it directly into the requesting output's queue */
328         if (o)
329             pa_memblockq_push_align(o->memblockq, &chunk);
330
331         pa_memblock_unref(chunk.memblock);
332     }
333 }
334
335 /* Called from I/O thread context */
336 static void request_memblock(struct output *o, size_t length) {
337     pa_assert(o);
338     pa_sink_input_assert_ref(o->sink_input);
339     pa_sink_assert_ref(o->userdata->sink);
340
341     /* If another thread already prepared some data we received
342      * the data over the asyncmsgq, hence let's first process
343      * it. */
344     while (pa_asyncmsgq_process_one(o->inq) > 0)
345         ;
346
347     /* Check whether we're now readable */
348     if (pa_memblockq_is_readable(o->memblockq))
349         return;
350
351     /* OK, we need to prepare new data, but only if the sink is actually running */
352     if (pa_atomic_load(&o->userdata->thread_info.running))
353         pa_asyncmsgq_send(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_NEED, o, length, NULL);
354 }
355
356 /* Called from I/O thread context */
357 static int sink_input_peek_cb(pa_sink_input *i, size_t length, pa_memchunk *chunk) {
358     struct output *o;
359
360     pa_sink_input_assert_ref(i);
361     pa_assert_se(o = i->userdata);
362
363     /* If necessary, get some new data */
364     request_memblock(o, length);
365
366     return pa_memblockq_peek(o->memblockq, chunk);
367 }
368
369 /* Called from I/O thread context */
370 static void sink_input_drop_cb(pa_sink_input *i, size_t length) {
371     struct output *o;
372
373     pa_sink_input_assert_ref(i);
374     pa_assert(length > 0);
375     pa_assert_se(o = i->userdata);
376
377     pa_memblockq_drop(o->memblockq, length);
378 }
379
380 /* Called from I/O thread context */
381 static void sink_input_attach_cb(pa_sink_input *i) {
382     struct output *o;
383
384     pa_sink_input_assert_ref(i);
385     pa_assert_se(o = i->userdata);
386
387     /* Set up the queue from the sink thread to us */
388     pa_assert(!o->inq_rtpoll_item);
389     o->inq_rtpoll_item = pa_rtpoll_item_new_asyncmsgq(
390             i->sink->rtpoll,
391             PA_RTPOLL_LATE,  /* This one is not that important, since we check for data in _peek() anyway. */
392             o->inq);
393 }
394
395 /* Called from I/O thread context */
396 static void sink_input_detach_cb(pa_sink_input *i) {
397     struct output *o;
398
399     pa_sink_input_assert_ref(i);
400     pa_assert_se(o = i->userdata);
401
402     /* Shut down the queue from the sink thread to us */
403     pa_assert(o->inq_rtpoll_item);
404     pa_rtpoll_item_free(o->inq_rtpoll_item);
405     o->inq_rtpoll_item = NULL;
406 }
407
408 /* Called from main context */
409 static void sink_input_kill_cb(pa_sink_input *i) {
410     struct output *o;
411
412     pa_sink_input_assert_ref(i);
413     pa_assert(o = i->userdata);
414
415     pa_module_unload_request(o->userdata->module);
416     output_free(o);
417 }
418
419 /* Called from thread context */
420 static int sink_input_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
421     struct output *o = PA_SINK_INPUT(obj)->userdata;
422
423     switch (code) {
424
425         case PA_SINK_INPUT_MESSAGE_GET_LATENCY: {
426              pa_usec_t *r = data;
427
428             *r = pa_bytes_to_usec(pa_memblockq_get_length(o->memblockq), &o->sink_input->sample_spec);
429
430             /* Fall through, the default handler will add in the extra
431              * latency added by the resampler */
432             break;
433         }
434
435         case SINK_INPUT_MESSAGE_POST:
436
437             if (PA_SINK_OPENED(o->sink_input->sink->thread_info.state))
438                 pa_memblockq_push_align(o->memblockq, chunk);
439             else
440                 pa_memblockq_flush(o->memblockq);
441
442             break;
443     }
444
445     return pa_sink_input_process_msg(obj, code, data, offset, chunk);
446 }
447
448 /* Called from main context */
449 static void disable_output(struct output *o) {
450     pa_assert(o);
451
452     if (!o->sink_input)
453         return;
454
455     pa_asyncmsgq_send(o->userdata->sink->asyncmsgq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_REMOVE_OUTPUT, o, 0, NULL);
456     pa_sink_input_unlink(o->sink_input);
457     pa_sink_input_unref(o->sink_input);
458     o->sink_input = NULL;
459
460 }
461
462 /* Called from main context */
463 static void enable_output(struct output *o) {
464     pa_assert(o);
465
466     if (o->sink_input)
467         return;
468
469     if (output_create_sink_input(o) >= 0) {
470
471         pa_memblockq_flush(o->memblockq);
472
473         pa_sink_input_put(o->sink_input);
474
475         if (o->userdata->sink && PA_SINK_LINKED(pa_sink_get_state(o->userdata->sink)))
476             pa_asyncmsgq_send(o->userdata->sink->asyncmsgq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_ADD_OUTPUT, o, 0, NULL);
477     }
478 }
479
480 /* Called from main context */
481 static void suspend(struct userdata *u) {
482     struct output *o;
483     uint32_t idx;
484
485     pa_assert(u);
486
487     /* Let's suspend by unlinking all streams */
488     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
489         disable_output(o);
490
491     pick_master(u, NULL);
492
493     pa_log_info("Device suspended...");
494 }
495
496 /* Called from main context */
497 static void unsuspend(struct userdata *u) {
498     struct output *o;
499     uint32_t idx;
500
501     pa_assert(u);
502
503     /* Let's resume */
504     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx)) {
505
506         pa_sink_suspend(o->sink, FALSE);
507
508         if (PA_SINK_OPENED(pa_sink_get_state(o->sink)))
509             enable_output(o);
510     }
511
512     pick_master(u, NULL);
513
514     pa_log_info("Resumed successfully...");
515 }
516
517 /* Called from main context */
518 static int sink_set_state(pa_sink *sink, pa_sink_state_t state) {
519     struct userdata *u;
520
521     pa_sink_assert_ref(sink);
522     pa_assert_se(u = sink->userdata);
523
524     /* Please note that in contrast to the ALSA modules we call
525      * suspend/unsuspend from main context here! */
526
527     switch (state) {
528         case PA_SINK_SUSPENDED:
529             pa_assert(PA_SINK_OPENED(pa_sink_get_state(u->sink)));
530
531             suspend(u);
532             break;
533
534         case PA_SINK_IDLE:
535         case PA_SINK_RUNNING:
536
537             if (pa_sink_get_state(u->sink) == PA_SINK_SUSPENDED)
538                 unsuspend(u);
539
540             break;
541
542         case PA_SINK_UNLINKED:
543         case PA_SINK_INIT:
544             ;
545     }
546
547     return 0;
548 }
549
550 /* Called from thread context of the master */
551 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
552     struct userdata *u = PA_SINK(o)->userdata;
553
554     switch (code) {
555
556         case PA_SINK_MESSAGE_SET_STATE:
557             pa_atomic_store(&u->thread_info.running, PA_PTR_TO_UINT(data) == PA_SINK_RUNNING);
558             break;
559
560         case PA_SINK_MESSAGE_GET_LATENCY:
561
562             /* This code will only be called when running in NULL
563              * mode, i.e. when no output is attached. See
564              * sink_get_latency_cb() below */
565
566             if (u->thread_info.in_null_mode) {
567                 struct timeval now;
568
569                 if (pa_timeval_cmp(&u->thread_info.timestamp, pa_rtclock_get(&now)) > 0) {
570                     *((pa_usec_t*) data) = pa_timeval_diff(&u->thread_info.timestamp, &now);
571                     break;
572                 }
573             }
574
575             *((pa_usec_t*) data) = 0;
576
577             break;
578
579         case SINK_MESSAGE_ADD_OUTPUT: {
580             struct output *op = data;
581
582             PA_LLIST_PREPEND(struct output, u->thread_info.active_outputs, op);
583
584             pa_assert(!op->outq_rtpoll_item);
585
586             /* Create pa_asyncmsgq to the sink thread */
587
588             op->outq_rtpoll_item = pa_rtpoll_item_new_asyncmsgq(
589                     u->rtpoll,
590                     PA_RTPOLL_EARLY-1,  /* This item is very important */
591                     op->outq);
592
593             return 0;
594         }
595
596         case SINK_MESSAGE_REMOVE_OUTPUT: {
597             struct output *op = data;
598
599             PA_LLIST_REMOVE(struct output, u->thread_info.active_outputs, op);
600
601             /* Remove the q that leads from this output to the sink thread */
602
603             pa_assert(op->outq_rtpoll_item);
604             pa_rtpoll_item_free(op->outq_rtpoll_item);
605             op->outq_rtpoll_item = NULL;
606
607             return 0;
608         }
609
610         case SINK_MESSAGE_NEED:
611             render_memblock(u, data, (size_t) offset);
612             return 0;
613     }
614
615     return pa_sink_process_msg(o, code, data, offset, chunk);
616 }
617
618 /* Called from main context */
619 static pa_usec_t sink_get_latency_cb(pa_sink *s) {
620     struct userdata *u;
621
622     pa_sink_assert_ref(s);
623     pa_assert_se(u = s->userdata);
624
625     if (u->master) {
626         /* If we have a master sink, we just return the latency of it
627          * and add our own buffering on top */
628
629         if (!u->master->sink_input)
630             return 0;
631
632         return
633             pa_sink_input_get_latency(u->master->sink_input) +
634             pa_sink_get_latency(u->master->sink);
635
636     } else {
637         pa_usec_t usec = 0;
638
639         /* We have no master, hence let's ask our own thread which
640          * implements the NULL sink */
641
642         if (pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY, &usec, 0, NULL) < 0)
643             return 0;
644
645         return usec;
646     }
647 }
648
649 static void update_description(struct userdata *u) {
650     int first = 1;
651     char *t;
652     struct output *o;
653     uint32_t idx;
654
655     pa_assert(u);
656
657     if (pa_idxset_isempty(u->outputs)) {
658         pa_sink_set_description(u->sink, "Simultaneous output");
659         return;
660     }
661
662     t = pa_xstrdup("Simultaneous output to");
663
664     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx)) {
665         char *e;
666
667         if (first) {
668             e = pa_sprintf_malloc("%s %s", t, o->sink->description);
669             first = 0;
670         } else
671             e = pa_sprintf_malloc("%s, %s", t, o->sink->description);
672
673         pa_xfree(t);
674         t = e;
675     }
676
677     pa_sink_set_description(u->sink, t);
678     pa_xfree(t);
679 }
680
681 static void update_master(struct userdata *u, struct output *o) {
682     pa_assert(u);
683
684     if (u->master == o)
685         return;
686
687     if ((u->master = o))
688         pa_log_info("Master sink is now '%s'", o->sink_input->sink->name);
689     else
690         pa_log_info("No master selected, lacking suitable outputs.");
691 }
692
693 static void pick_master(struct userdata *u, struct output *except) {
694     struct output *o;
695     uint32_t idx;
696     pa_assert(u);
697
698     if (u->master &&
699         u->master != except &&
700         u->master->sink_input &&
701         PA_SINK_OPENED(pa_sink_get_state(u->master->sink))) {
702         update_master(u, u->master);
703         return;
704     }
705
706     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
707         if (o != except &&
708             o->sink_input &&
709             PA_SINK_OPENED(pa_sink_get_state(o->sink))) {
710             update_master(u, o);
711             return;
712         }
713
714     update_master(u, NULL);
715 }
716
717 static int output_create_sink_input(struct output *o) {
718     pa_sink_input_new_data data;
719     char *t;
720
721     pa_assert(o);
722
723     if (o->sink_input)
724         return 0;
725
726     t = pa_sprintf_malloc("Simultaneous output on %s", o->sink->description);
727
728     pa_sink_input_new_data_init(&data);
729     data.sink = o->sink;
730     data.driver = __FILE__;
731     data.name = t;
732     pa_sink_input_new_data_set_sample_spec(&data, &o->userdata->sink->sample_spec);
733     pa_sink_input_new_data_set_channel_map(&data, &o->userdata->sink->channel_map);
734     data.module = o->userdata->module;
735     data.resample_method = o->userdata->resample_method;
736
737     o->sink_input = pa_sink_input_new(o->userdata->core, &data, PA_SINK_INPUT_VARIABLE_RATE|PA_SINK_INPUT_DONT_MOVE);
738
739     pa_xfree(t);
740
741     if (!o->sink_input)
742         return -1;
743
744     o->sink_input->parent.process_msg = sink_input_process_msg;
745     o->sink_input->peek = sink_input_peek_cb;
746     o->sink_input->drop = sink_input_drop_cb;
747     o->sink_input->attach = sink_input_attach_cb;
748     o->sink_input->detach = sink_input_detach_cb;
749     o->sink_input->kill = sink_input_kill_cb;
750     o->sink_input->userdata = o;
751
752
753     return 0;
754 }
755
756 static struct output *output_new(struct userdata *u, pa_sink *sink) {
757     struct output *o;
758
759     pa_assert(u);
760     pa_assert(sink);
761     pa_assert(u->sink);
762
763     o = pa_xnew(struct output, 1);
764     o->userdata = u;
765     o->inq = pa_asyncmsgq_new(0);
766     o->outq = pa_asyncmsgq_new(0);
767     o->inq_rtpoll_item = NULL;
768     o->outq_rtpoll_item = NULL;
769     o->sink = sink;
770     o->sink_input = NULL;
771     o->memblockq = pa_memblockq_new(
772             0,
773             MEMBLOCKQ_MAXLENGTH,
774             MEMBLOCKQ_MAXLENGTH,
775             pa_frame_size(&u->sink->sample_spec),
776             1,
777             0,
778             NULL);
779
780     pa_assert_se(pa_idxset_put(u->outputs, o, NULL) == 0);
781
782     if (u->sink && PA_SINK_LINKED(pa_sink_get_state(u->sink)))
783         pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_ADD_OUTPUT, o, 0, NULL);
784     else {
785         /* If the sink is not yet started, we need to do the activation ourselves */
786         PA_LLIST_PREPEND(struct output, u->thread_info.active_outputs, o);
787
788         o->outq_rtpoll_item = pa_rtpoll_item_new_asyncmsgq(
789                 u->rtpoll,
790                 PA_RTPOLL_EARLY-1,  /* This item is very important */
791                 o->outq);
792     }
793
794     if (PA_SINK_OPENED(pa_sink_get_state(u->sink)) || pa_sink_get_state(u->sink) == PA_SINK_INIT) {
795         pa_sink_suspend(sink, FALSE);
796
797         if (PA_SINK_OPENED(pa_sink_get_state(sink)))
798             if (output_create_sink_input(o) < 0)
799                 goto fail;
800     }
801
802
803     update_description(u);
804
805     return o;
806
807 fail:
808
809     if (o) {
810         pa_idxset_remove_by_data(u->outputs, o, NULL);
811
812         if (o->sink_input) {
813             pa_sink_input_unlink(o->sink_input);
814             pa_sink_input_unref(o->sink_input);
815         }
816
817         if (o->memblockq)
818             pa_memblockq_free(o->memblockq);
819
820         if (o->inq)
821             pa_asyncmsgq_unref(o->inq);
822
823         if (o->outq)
824             pa_asyncmsgq_unref(o->outq);
825
826         pa_xfree(o);
827     }
828
829     return NULL;
830 }
831
832 static pa_hook_result_t sink_new_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
833     struct output *o;
834
835     pa_core_assert_ref(c);
836     pa_sink_assert_ref(s);
837     pa_assert(u);
838     pa_assert(u->automatic);
839
840     if (!(s->flags & PA_SINK_HARDWARE) || s == u->sink)
841         return PA_HOOK_OK;
842
843     pa_log_info("Configuring new sink: %s", s->name);
844
845     if (!(o = output_new(u, s))) {
846         pa_log("Failed to create sink input on sink '%s'.", s->name);
847         return PA_HOOK_OK;
848     }
849
850     if (o->sink_input)
851         pa_sink_input_put(o->sink_input);
852
853     pick_master(u, NULL);
854
855     return PA_HOOK_OK;
856 }
857
858 static pa_hook_result_t sink_unlink_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
859     struct output *o;
860     uint32_t idx;
861
862     pa_assert(c);
863     pa_sink_assert_ref(s);
864     pa_assert(u);
865
866     if (s == u->sink)
867         return PA_HOOK_OK;
868
869     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
870         if (o->sink == s)
871             break;
872
873     if (!o)
874         return PA_HOOK_OK;
875
876     pa_log_info("Unconfiguring sink: %s", s->name);
877
878     output_free(o);
879
880     return PA_HOOK_OK;
881 }
882
883 static pa_hook_result_t sink_state_changed_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
884     struct output *o;
885     uint32_t idx;
886     pa_sink_state_t state;
887
888     if (s == u->sink)
889         return PA_HOOK_OK;
890
891     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
892         if (o->sink == s)
893             break;
894
895     if (!o)
896         return PA_HOOK_OK;
897
898     state = pa_sink_get_state(s);
899
900     if (PA_SINK_OPENED(state) && PA_SINK_OPENED(pa_sink_get_state(u->sink)) && !o->sink_input) {
901         enable_output(o);
902         pick_master(u, NULL);
903     }
904
905     if (state == PA_SINK_SUSPENDED && o->sink_input) {
906         disable_output(o);
907         pick_master(u, o);
908     }
909
910     return PA_HOOK_OK;
911 }
912
913 int pa__init(pa_module*m) {
914     struct userdata *u;
915     pa_modargs *ma = NULL;
916     const char *master_name, *slaves, *rm;
917     pa_sink *master_sink = NULL;
918     int resample_method = PA_RESAMPLER_TRIVIAL;
919     pa_sample_spec ss;
920     pa_channel_map map;
921     struct output *o;
922     uint32_t idx;
923
924     pa_assert(m);
925
926     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
927         pa_log("failed to parse module arguments");
928         goto fail;
929     }
930
931     if ((rm = pa_modargs_get_value(ma, "resample_method", NULL))) {
932         if ((resample_method = pa_parse_resample_method(rm)) < 0) {
933             pa_log("invalid resample method '%s'", rm);
934             goto fail;
935         }
936     }
937
938     u = pa_xnew(struct userdata, 1);
939     u->core = m->core;
940     u->module = m;
941     m->userdata = u;
942     u->sink = NULL;
943     u->master = NULL;
944     u->time_event = NULL;
945     u->adjust_time = DEFAULT_ADJUST_TIME;
946     pa_thread_mq_init(&u->thread_mq, m->core->mainloop);
947     u->rtpoll = pa_rtpoll_new();
948     u->thread = NULL;
949     u->resample_method = resample_method;
950     u->outputs = pa_idxset_new(NULL, NULL);
951     memset(&u->adjust_timestamp, 0, sizeof(u->adjust_timestamp));
952     u->sink_new_slot = u->sink_unlink_slot = u->sink_state_changed_slot = NULL;
953     PA_LLIST_HEAD_INIT(struct output, u->thread_info.active_outputs);
954     pa_atomic_store(&u->thread_info.running, FALSE);
955     u->thread_info.in_null_mode = FALSE;
956     pa_rtpoll_item_new_asyncmsgq(u->rtpoll, PA_RTPOLL_EARLY, u->thread_mq.inq);
957
958     if (pa_modargs_get_value_u32(ma, "adjust_time", &u->adjust_time) < 0) {
959         pa_log("Failed to parse adjust_time value");
960         goto fail;
961     }
962
963     master_name = pa_modargs_get_value(ma, "master", NULL);
964     slaves = pa_modargs_get_value(ma, "slaves", NULL);
965     if (!master_name != !slaves) {
966         pa_log("No master or slave sinks specified");
967         goto fail;
968     }
969
970     if (master_name) {
971         if (!(master_sink = pa_namereg_get(m->core, master_name, PA_NAMEREG_SINK, 1))) {
972             pa_log("Invalid master sink '%s'", master_name);
973             goto fail;
974         }
975
976         ss = master_sink->sample_spec;
977         u->automatic = FALSE;
978     } else {
979         master_sink = NULL;
980         ss = m->core->default_sample_spec;
981         u->automatic = TRUE;
982     }
983
984     if ((pa_modargs_get_sample_spec(ma, &ss) < 0)) {
985         pa_log("Invalid sample specification.");
986         goto fail;
987     }
988
989     if (master_sink && ss.channels == master_sink->sample_spec.channels)
990         map = master_sink->channel_map;
991     else {
992         pa_assert_se(pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_AUX));
993         pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_DEFAULT);
994     }
995
996     if ((pa_modargs_get_channel_map(ma, NULL, &map) < 0)) {
997         pa_log("Invalid channel map.");
998         goto fail;
999     }
1000
1001     if (ss.channels != map.channels) {
1002         pa_log("Channel map and sample specification don't match.");
1003         goto fail;
1004     }
1005
1006     if (!(u->sink = pa_sink_new(m->core, __FILE__, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME), 0, &ss, &map))) {
1007         pa_log("Failed to create sink");
1008         goto fail;
1009     }
1010
1011     u->sink->parent.process_msg = sink_process_msg;
1012     u->sink->get_latency = sink_get_latency_cb;
1013     u->sink->set_state = sink_set_state;
1014     u->sink->userdata = u;
1015
1016     u->sink->flags = PA_SINK_LATENCY;
1017     pa_sink_set_module(u->sink, m);
1018     pa_sink_set_description(u->sink, "Simultaneous output");
1019     pa_sink_set_rtpoll(u->sink, u->rtpoll);
1020     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1021
1022     u->block_size = pa_bytes_per_second(&ss) / 20; /* 50 ms */
1023     if (u->block_size <= 0)
1024         u->block_size = pa_frame_size(&ss);
1025
1026     if (!u->automatic) {
1027         const char*split_state;
1028         char *n = NULL;
1029         pa_assert(slaves);
1030
1031         /* The master and slaves have been specified manually */
1032
1033         if (!(u->master = output_new(u, master_sink))) {
1034             pa_log("Failed to create master sink input on sink '%s'.", master_sink->name);
1035             goto fail;
1036         }
1037
1038         split_state = NULL;
1039         while ((n = pa_split(slaves, ",", &split_state))) {
1040             pa_sink *slave_sink;
1041
1042             if (!(slave_sink = pa_namereg_get(m->core, n, PA_NAMEREG_SINK, 1)) || slave_sink == u->sink) {
1043                 pa_log("Invalid slave sink '%s'", n);
1044                 pa_xfree(n);
1045                 goto fail;
1046             }
1047
1048             pa_xfree(n);
1049
1050             if (!output_new(u, slave_sink)) {
1051                 pa_log("Failed to create slave sink input on sink '%s'.", slave_sink->name);
1052                 goto fail;
1053             }
1054         }
1055
1056         if (pa_idxset_size(u->outputs) <= 1)
1057             pa_log_warn("No slave sinks specified.");
1058
1059         u->sink_new_slot = NULL;
1060
1061     } else {
1062         pa_sink *s;
1063
1064         /* We're in automatic mode, we elect one hw sink to the master
1065          * and attach all other hw sinks as slaves to it */
1066
1067         for (s = pa_idxset_first(m->core->sinks, &idx); s; s = pa_idxset_next(m->core->sinks, &idx)) {
1068
1069             if (!(s->flags & PA_SINK_HARDWARE) || s == u->sink)
1070                 continue;
1071
1072             if (!output_new(u, s)) {
1073                 pa_log("Failed to create sink input on sink '%s'.", s->name);
1074                 goto fail;
1075             }
1076         }
1077
1078         u->sink_new_slot = pa_hook_connect(&m->core->hooks[PA_CORE_HOOK_SINK_NEW_POST], (pa_hook_cb_t) sink_new_hook_cb, u);
1079     }
1080
1081     u->sink_unlink_slot = pa_hook_connect(&m->core->hooks[PA_CORE_HOOK_SINK_UNLINK], (pa_hook_cb_t) sink_unlink_hook_cb, u);
1082     u->sink_state_changed_slot = pa_hook_connect(&m->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED], (pa_hook_cb_t) sink_state_changed_hook_cb, u);
1083
1084     pick_master(u, NULL);
1085
1086     if (!(u->thread = pa_thread_new(thread_func, u))) {
1087         pa_log("Failed to create thread.");
1088         goto fail;
1089     }
1090
1091     /* Activate the sink and the sink inputs */
1092     pa_sink_put(u->sink);
1093
1094     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
1095         if (o->sink_input)
1096             pa_sink_input_put(o->sink_input);
1097
1098     if (u->adjust_time > 0) {
1099         struct timeval tv;
1100         pa_gettimeofday(&tv);
1101         tv.tv_sec += u->adjust_time;
1102         u->time_event = m->core->mainloop->time_new(m->core->mainloop, &tv, time_callback, u);
1103     }
1104
1105     pa_modargs_free(ma);
1106
1107     return 0;
1108
1109 fail:
1110
1111     if (ma)
1112         pa_modargs_free(ma);
1113
1114     pa__done(m);
1115
1116     return -1;
1117 }
1118
1119 static void output_free(struct output *o) {
1120     pa_assert(o);
1121
1122     pick_master(o->userdata, o);
1123
1124     disable_output(o);
1125
1126     pa_assert_se(pa_idxset_remove_by_data(o->userdata->outputs, o, NULL));
1127
1128     update_description(o->userdata);
1129
1130     if (o->inq_rtpoll_item)
1131         pa_rtpoll_item_free(o->inq_rtpoll_item);
1132
1133     if (o->outq_rtpoll_item)
1134         pa_rtpoll_item_free(o->outq_rtpoll_item);
1135
1136     if (o->inq)
1137         pa_asyncmsgq_unref(o->inq);
1138
1139     if (o->outq)
1140         pa_asyncmsgq_unref(o->outq);
1141
1142     if (o->memblockq)
1143         pa_memblockq_free(o->memblockq);
1144
1145     pa_xfree(o);
1146 }
1147
1148 void pa__done(pa_module*m) {
1149     struct userdata *u;
1150     struct output *o;
1151
1152     pa_assert(m);
1153
1154     if (!(u = m->userdata))
1155         return;
1156
1157     if (u->sink_new_slot)
1158         pa_hook_slot_free(u->sink_new_slot);
1159
1160     if (u->sink_unlink_slot)
1161         pa_hook_slot_free(u->sink_unlink_slot);
1162
1163     if (u->sink_state_changed_slot)
1164         pa_hook_slot_free(u->sink_state_changed_slot);
1165
1166     if (u->outputs) {
1167         while ((o = pa_idxset_first(u->outputs, NULL)))
1168             output_free(o);
1169
1170         pa_idxset_free(u->outputs, NULL, NULL);
1171     }
1172
1173     if (u->sink)
1174         pa_sink_unlink(u->sink);
1175
1176     if (u->thread) {
1177         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1178         pa_thread_free(u->thread);
1179     }
1180
1181     pa_thread_mq_done(&u->thread_mq);
1182
1183     if (u->sink)
1184         pa_sink_unref(u->sink);
1185
1186     if (u->rtpoll)
1187         pa_rtpoll_free(u->rtpoll);
1188
1189     if (u->time_event)
1190         u->core->mainloop->time_free(u->time_event);
1191
1192     pa_xfree(u);
1193 }