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