get rid of svn $ keywords
[platform/upstream/pulseaudio.git] / src / modules / module-combine.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <errno.h>
28
29 #include <pulse/timeval.h>
30 #include <pulse/xmalloc.h>
31
32 #include <pulsecore/macro.h>
33 #include <pulsecore/module.h>
34 #include <pulsecore/llist.h>
35 #include <pulsecore/sink.h>
36 #include <pulsecore/sink-input.h>
37 #include <pulsecore/memblockq.h>
38 #include <pulsecore/log.h>
39 #include <pulsecore/core-util.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/namereg.h>
42 #include <pulsecore/mutex.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/rtpoll.h>
46 #include <pulsecore/rtclock.h>
47 #include <pulsecore/core-error.h>
48
49 #include "module-combine-symdef.h"
50
51 PA_MODULE_AUTHOR("Lennart Poettering");
52 PA_MODULE_DESCRIPTION("Combine multiple sinks to one");
53 PA_MODULE_VERSION(PACKAGE_VERSION);
54 PA_MODULE_LOAD_ONCE(FALSE);
55 PA_MODULE_USAGE(
56         "sink_name=<name for the sink> "
57         "master=<master sink> "
58         "slaves=<slave sinks> "
59         "adjust_time=<seconds> "
60         "resample_method=<method> "
61         "format=<sample format> "
62         "channels=<number of channels> "
63         "rate=<sample rate> "
64         "channel_map=<channel map>");
65
66 #define DEFAULT_SINK_NAME "combined"
67 #define MEMBLOCKQ_MAXLENGTH (1024*1024*16)
68
69 #define DEFAULT_ADJUST_TIME 10
70
71 static const char* const valid_modargs[] = {
72     "sink_name",
73     "master",
74     "slaves",
75     "adjust_time",
76     "resample_method",
77     "format",
78     "channels",
79     "rate",
80     "channel_map",
81     NULL
82 };
83
84 struct output {
85     struct userdata *userdata;
86
87     pa_sink *sink;
88     pa_sink_input *sink_input;
89
90     pa_asyncmsgq *inq,    /* Message queue from the sink thread to this sink input */
91                  *outq;   /* Message queue from this sink input to the sink thread */
92     pa_rtpoll_item *inq_rtpoll_item, *outq_rtpoll_item;
93
94     pa_memblockq *memblockq;
95
96     pa_usec_t total_latency;
97
98     PA_LLIST_FIELDS(struct output);
99 };
100
101 struct userdata {
102     pa_core *core;
103     pa_module *module;
104     pa_sink *sink;
105
106     pa_thread *thread;
107     pa_thread_mq thread_mq;
108     pa_rtpoll *rtpoll;
109
110     pa_time_event *time_event;
111     uint32_t adjust_time;
112
113     pa_bool_t automatic;
114     size_t block_size;
115
116     pa_hook_slot *sink_new_slot, *sink_unlink_slot, *sink_state_changed_slot;
117
118     pa_resample_method_t resample_method;
119
120     struct timeval adjust_timestamp;
121
122     struct output *master;
123     pa_idxset* outputs; /* managed in main context */
124
125     struct {
126         PA_LLIST_HEAD(struct output, active_outputs); /* managed in IO thread context */
127         pa_atomic_t running;  /* we cache that value here, so that every thread can query it cheaply */
128         struct timeval timestamp;
129         pa_bool_t in_null_mode;
130     } thread_info;
131 };
132
133 enum {
134     SINK_MESSAGE_ADD_OUTPUT = PA_SINK_MESSAGE_MAX,
135     SINK_MESSAGE_REMOVE_OUTPUT,
136     SINK_MESSAGE_NEED
137 };
138
139 enum {
140     SINK_INPUT_MESSAGE_POST = PA_SINK_INPUT_MESSAGE_MAX,
141 };
142
143 static void output_free(struct output *o);
144 static int output_create_sink_input(struct output *o);
145 static void update_master(struct userdata *u, struct output *o);
146 static void pick_master(struct userdata *u, struct output *except);
147
148 static void adjust_rates(struct userdata *u) {
149     struct output *o;
150     pa_usec_t max_sink_latency = 0, min_total_latency = (pa_usec_t) -1, target_latency;
151     uint32_t base_rate;
152     uint32_t idx;
153
154     pa_assert(u);
155     pa_sink_assert_ref(u->sink);
156
157     if (pa_idxset_size(u->outputs) <= 0)
158         return;
159
160     if (!u->master)
161         return;
162
163     if (!PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)))
164         return;
165
166     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx)) {
167         pa_usec_t sink_latency;
168
169         if (!o->sink_input || !PA_SINK_IS_OPENED(pa_sink_get_state(o->sink)))
170             continue;
171
172         sink_latency = pa_sink_get_latency(o->sink);
173         o->total_latency = sink_latency + pa_sink_input_get_latency(o->sink_input);
174
175         if (sink_latency > max_sink_latency)
176             max_sink_latency = sink_latency;
177
178         if (min_total_latency == (pa_usec_t) -1 || o->total_latency < min_total_latency)
179             min_total_latency = o->total_latency;
180     }
181
182     if (min_total_latency == (pa_usec_t) -1)
183         return;
184
185     target_latency = max_sink_latency > min_total_latency ? max_sink_latency : min_total_latency;
186
187     pa_log_info("[%s] target latency is %0.0f usec.", u->sink->name, (float) target_latency);
188     pa_log_info("[%s] master %s latency %0.0f usec.", u->sink->name, u->master->sink->name, (float) u->master->total_latency);
189
190     base_rate = u->sink->sample_spec.rate;
191
192     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx)) {
193         uint32_t r = base_rate;
194
195         if (!o->sink_input || !PA_SINK_IS_OPENED(pa_sink_get_state(o->sink)))
196             continue;
197
198         if (o->total_latency < target_latency)
199             r -= (uint32_t) (((((double) target_latency - o->total_latency))/u->adjust_time)*r/PA_USEC_PER_SEC);
200         else if (o->total_latency > target_latency)
201             r += (uint32_t) (((((double) o->total_latency - target_latency))/u->adjust_time)*r/PA_USEC_PER_SEC);
202
203         if (r < (uint32_t) (base_rate*0.9) || r > (uint32_t) (base_rate*1.1)) {
204             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);
205             pa_sink_input_set_rate(o->sink_input, base_rate);
206         } else {
207             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);
208             pa_sink_input_set_rate(o->sink_input, r);
209         }
210     }
211 }
212
213 static void time_callback(pa_mainloop_api*a, pa_time_event* e, const struct timeval *tv, void *userdata) {
214     struct userdata *u = userdata;
215     struct timeval n;
216
217     pa_assert(u);
218     pa_assert(a);
219     pa_assert(u->time_event == e);
220
221     adjust_rates(u);
222
223     pa_gettimeofday(&n);
224     n.tv_sec += u->adjust_time;
225     u->sink->core->mainloop->time_restart(e, &n);
226 }
227
228 static void thread_func(void *userdata) {
229     struct userdata *u = userdata;
230
231     pa_assert(u);
232
233     pa_log_debug("Thread starting up");
234
235     if (u->core->realtime_scheduling)
236         pa_make_realtime(u->core->realtime_priority+1);
237
238     pa_thread_mq_install(&u->thread_mq);
239     pa_rtpoll_install(u->rtpoll);
240
241     pa_rtclock_get(&u->thread_info.timestamp);
242     u->thread_info.in_null_mode = FALSE;
243
244     for (;;) {
245         int ret;
246
247         /* If no outputs are connected, render some data and drop it immediately. */
248         if (u->sink->thread_info.state == PA_SINK_RUNNING && !u->thread_info.active_outputs) {
249             struct timeval now;
250
251             /* Just rewind if necessary, since we are in NULL mode, we
252              * don't have to pass this on */
253             pa_sink_process_rewind(u->sink, u->sink->thread_info.rewind_nbytes);
254             u->sink->thread_info.rewind_nbytes = 0;
255
256             pa_rtclock_get(&now);
257
258             if (!u->thread_info.in_null_mode || pa_timeval_cmp(&u->thread_info.timestamp, &now) <= 0) {
259                 pa_memchunk chunk;
260
261                 pa_sink_render_full(u->sink, u->block_size, &chunk);
262                 pa_memblock_unref(chunk.memblock);
263
264                 if (!u->thread_info.in_null_mode)
265                     u->thread_info.timestamp = now;
266
267                 pa_timeval_add(&u->thread_info.timestamp, pa_bytes_to_usec(u->block_size, &u->sink->sample_spec));
268             }
269
270             pa_rtpoll_set_timer_absolute(u->rtpoll, &u->thread_info.timestamp);
271             u->thread_info.in_null_mode = TRUE;
272
273         } else {
274             pa_rtpoll_set_timer_disabled(u->rtpoll);
275             u->thread_info.in_null_mode = FALSE;
276         }
277
278         /* Hmm, nothing to do. Let's sleep */
279         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0) {
280             pa_log_info("pa_rtpoll_run() = %i", ret);
281             goto fail;
282         }
283
284         if (ret == 0)
285             goto finish;
286     }
287
288 fail:
289     /* If this was no regular exit from the loop we have to continue
290      * processing messages until we received PA_MESSAGE_SHUTDOWN */
291     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
292     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
293
294 finish:
295     pa_log_debug("Thread shutting down");
296 }
297
298 /* Called from I/O thread context */
299 static void render_memblock(struct userdata *u, struct output *o, size_t length) {
300     pa_assert(u);
301     pa_assert(o);
302
303     /* We are run by the sink thread, on behalf of an output (o). The
304      * other output is waiting for us, hence it is safe to access its
305      * mainblockq and asyncmsgq directly. */
306
307     /* If we are not running, we cannot produce any data */
308     if (!pa_atomic_load(&u->thread_info.running))
309         return;
310
311     /* Maybe there's some data in the requesting output's queue
312      * now? */
313     while (pa_asyncmsgq_process_one(o->inq) > 0)
314         ;
315
316     /* Ok, now let's prepare some data if we really have to */
317     while (!pa_memblockq_is_readable(o->memblockq)) {
318         struct output *j;
319         pa_memchunk chunk;
320
321         /* Render data! */
322         pa_sink_render(u->sink, length, &chunk);
323
324         /* OK, let's send this data to the other threads */
325         for (j = u->thread_info.active_outputs; j; j = j->next)
326
327             /* Send to other outputs, which are not the requesting
328              * one */
329
330             if (j != o)
331                 pa_asyncmsgq_post(j->inq, PA_MSGOBJECT(j->sink_input), SINK_INPUT_MESSAGE_POST, NULL, 0, &chunk, NULL);
332
333         /* And place it directly into the requesting output's queue */
334         if (o)
335             pa_memblockq_push_align(o->memblockq, &chunk);
336
337         pa_memblock_unref(chunk.memblock);
338     }
339 }
340
341 /* Called from I/O thread context */
342 static void request_memblock(struct output *o, size_t length) {
343     pa_assert(o);
344     pa_sink_input_assert_ref(o->sink_input);
345     pa_sink_assert_ref(o->userdata->sink);
346
347     /* If another thread already prepared some data we received
348      * the data over the asyncmsgq, hence let's first process
349      * it. */
350     while (pa_asyncmsgq_process_one(o->inq) > 0)
351         ;
352
353     /* Check whether we're now readable */
354     if (pa_memblockq_is_readable(o->memblockq))
355         return;
356
357     /* OK, we need to prepare new data, but only if the sink is actually running */
358     if (pa_atomic_load(&o->userdata->thread_info.running))
359         pa_asyncmsgq_send(o->outq, PA_MSGOBJECT(o->userdata->sink), SINK_MESSAGE_NEED, o, length, NULL);
360 }
361
362 /* Called from I/O thread context */
363 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
364     struct output *o;
365
366     pa_sink_input_assert_ref(i);
367     pa_assert_se(o = i->userdata);
368
369     /* If necessary, get some new data */
370     request_memblock(o, nbytes);
371
372     if (pa_memblockq_peek(o->memblockq, chunk) < 0)
373         return -1;
374
375     pa_memblockq_drop(o->memblockq, chunk->length);
376     return 0;
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_read(
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_IS_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
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_IS_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_IS_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_IS_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_read(
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, pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
669             first = 0;
670         } else
671             e = pa_sprintf_malloc("%s, %s", t, pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_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_IS_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_IS_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", pa_strnull(pa_proplist_gets(o->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
727
728     pa_sink_input_new_data_init(&data);
729     data.sink = o->sink;
730     data.driver = __FILE__;
731     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, 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_sink_input_new_data_done(&data);
740
741     pa_xfree(t);
742
743     if (!o->sink_input)
744         return -1;
745
746     o->sink_input->parent.process_msg = sink_input_process_msg;
747     o->sink_input->pop = sink_input_pop_cb;
748     o->sink_input->attach = sink_input_attach_cb;
749     o->sink_input->detach = sink_input_detach_cb;
750     o->sink_input->kill = sink_input_kill_cb;
751     o->sink_input->userdata = o;
752
753
754     return 0;
755 }
756
757 static struct output *output_new(struct userdata *u, pa_sink *sink) {
758     struct output *o;
759
760     pa_assert(u);
761     pa_assert(sink);
762     pa_assert(u->sink);
763
764     o = pa_xnew(struct output, 1);
765     o->userdata = u;
766     o->inq = pa_asyncmsgq_new(0);
767     o->outq = pa_asyncmsgq_new(0);
768     o->inq_rtpoll_item = NULL;
769     o->outq_rtpoll_item = NULL;
770     o->sink = sink;
771     o->sink_input = NULL;
772     o->memblockq = pa_memblockq_new(
773             0,
774             MEMBLOCKQ_MAXLENGTH,
775             MEMBLOCKQ_MAXLENGTH,
776             pa_frame_size(&u->sink->sample_spec),
777             1,
778             0,
779             0,
780             NULL);
781
782     pa_assert_se(pa_idxset_put(u->outputs, o, NULL) == 0);
783
784     if (u->sink && PA_SINK_IS_LINKED(pa_sink_get_state(u->sink)))
785         pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_ADD_OUTPUT, o, 0, NULL);
786     else {
787         /* If the sink is not yet started, we need to do the activation ourselves */
788         PA_LLIST_PREPEND(struct output, u->thread_info.active_outputs, o);
789
790         o->outq_rtpoll_item = pa_rtpoll_item_new_asyncmsgq_read(
791                 u->rtpoll,
792                 PA_RTPOLL_EARLY-1,  /* This item is very important */
793                 o->outq);
794     }
795
796     if (PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)) || pa_sink_get_state(u->sink) == PA_SINK_INIT) {
797         pa_sink_suspend(sink, FALSE);
798
799         if (PA_SINK_IS_OPENED(pa_sink_get_state(sink)))
800             if (output_create_sink_input(o) < 0)
801                 goto fail;
802     }
803
804
805     update_description(u);
806
807     return o;
808
809 fail:
810
811     if (o) {
812         pa_idxset_remove_by_data(u->outputs, o, NULL);
813
814         if (o->sink_input) {
815             pa_sink_input_unlink(o->sink_input);
816             pa_sink_input_unref(o->sink_input);
817         }
818
819         if (o->memblockq)
820             pa_memblockq_free(o->memblockq);
821
822         if (o->inq)
823             pa_asyncmsgq_unref(o->inq);
824
825         if (o->outq)
826             pa_asyncmsgq_unref(o->outq);
827
828         pa_xfree(o);
829     }
830
831     return NULL;
832 }
833
834 static pa_hook_result_t sink_new_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
835     struct output *o;
836
837     pa_core_assert_ref(c);
838     pa_sink_assert_ref(s);
839     pa_assert(u);
840     pa_assert(u->automatic);
841
842     if (!(s->flags & PA_SINK_HARDWARE) || s == u->sink)
843         return PA_HOOK_OK;
844
845     pa_log_info("Configuring new sink: %s", s->name);
846
847     if (!(o = output_new(u, s))) {
848         pa_log("Failed to create sink input on sink '%s'.", s->name);
849         return PA_HOOK_OK;
850     }
851
852     if (o->sink_input)
853         pa_sink_input_put(o->sink_input);
854
855     pick_master(u, NULL);
856
857     return PA_HOOK_OK;
858 }
859
860 static pa_hook_result_t sink_unlink_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
861     struct output *o;
862     uint32_t idx;
863
864     pa_assert(c);
865     pa_sink_assert_ref(s);
866     pa_assert(u);
867
868     if (s == u->sink)
869         return PA_HOOK_OK;
870
871     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
872         if (o->sink == s)
873             break;
874
875     if (!o)
876         return PA_HOOK_OK;
877
878     pa_log_info("Unconfiguring sink: %s", s->name);
879
880     output_free(o);
881
882     return PA_HOOK_OK;
883 }
884
885 static pa_hook_result_t sink_state_changed_hook_cb(pa_core *c, pa_sink *s, struct userdata* u) {
886     struct output *o;
887     uint32_t idx;
888     pa_sink_state_t state;
889
890     if (s == u->sink)
891         return PA_HOOK_OK;
892
893     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
894         if (o->sink == s)
895             break;
896
897     if (!o)
898         return PA_HOOK_OK;
899
900     state = pa_sink_get_state(s);
901
902     if (PA_SINK_IS_OPENED(state) && PA_SINK_IS_OPENED(pa_sink_get_state(u->sink)) && !o->sink_input) {
903         enable_output(o);
904         pick_master(u, NULL);
905     }
906
907     if (state == PA_SINK_SUSPENDED && o->sink_input) {
908         disable_output(o);
909         pick_master(u, o);
910     }
911
912     return PA_HOOK_OK;
913 }
914
915 int pa__init(pa_module*m) {
916     struct userdata *u;
917     pa_modargs *ma = NULL;
918     const char *master_name, *slaves, *rm;
919     pa_sink *master_sink = NULL;
920     int resample_method = PA_RESAMPLER_TRIVIAL;
921     pa_sample_spec ss;
922     pa_channel_map map;
923     struct output *o;
924     uint32_t idx;
925     pa_sink_new_data data;
926
927     pa_assert(m);
928
929     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
930         pa_log("failed to parse module arguments");
931         goto fail;
932     }
933
934     if ((rm = pa_modargs_get_value(ma, "resample_method", NULL))) {
935         if ((resample_method = pa_parse_resample_method(rm)) < 0) {
936             pa_log("invalid resample method '%s'", rm);
937             goto fail;
938         }
939     }
940
941     u = pa_xnew(struct userdata, 1);
942     u->core = m->core;
943     u->module = m;
944     m->userdata = u;
945     u->sink = NULL;
946     u->master = NULL;
947     u->time_event = NULL;
948     u->adjust_time = DEFAULT_ADJUST_TIME;
949     u->rtpoll = pa_rtpoll_new();
950     pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
951     u->thread = NULL;
952     u->resample_method = resample_method;
953     u->outputs = pa_idxset_new(NULL, NULL);
954     memset(&u->adjust_timestamp, 0, sizeof(u->adjust_timestamp));
955     u->sink_new_slot = u->sink_unlink_slot = u->sink_state_changed_slot = NULL;
956     PA_LLIST_HEAD_INIT(struct output, u->thread_info.active_outputs);
957     pa_atomic_store(&u->thread_info.running, FALSE);
958     u->thread_info.in_null_mode = FALSE;
959
960     if (pa_modargs_get_value_u32(ma, "adjust_time", &u->adjust_time) < 0) {
961         pa_log("Failed to parse adjust_time value");
962         goto fail;
963     }
964
965     master_name = pa_modargs_get_value(ma, "master", NULL);
966     slaves = pa_modargs_get_value(ma, "slaves", NULL);
967     if (!master_name != !slaves) {
968         pa_log("No master or slave sinks specified");
969         goto fail;
970     }
971
972     if (master_name) {
973         if (!(master_sink = pa_namereg_get(m->core, master_name, PA_NAMEREG_SINK, 1))) {
974             pa_log("Invalid master sink '%s'", master_name);
975             goto fail;
976         }
977
978         ss = master_sink->sample_spec;
979         u->automatic = FALSE;
980     } else {
981         master_sink = NULL;
982         ss = m->core->default_sample_spec;
983         u->automatic = TRUE;
984     }
985
986     if ((pa_modargs_get_sample_spec(ma, &ss) < 0)) {
987         pa_log("Invalid sample specification.");
988         goto fail;
989     }
990
991     if (master_sink && ss.channels == master_sink->sample_spec.channels)
992         map = master_sink->channel_map;
993     else {
994         pa_assert_se(pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_AUX));
995         pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_DEFAULT);
996     }
997
998     if ((pa_modargs_get_channel_map(ma, NULL, &map) < 0)) {
999         pa_log("Invalid channel map.");
1000         goto fail;
1001     }
1002
1003     if (ss.channels != map.channels) {
1004         pa_log("Channel map and sample specification don't match.");
1005         goto fail;
1006     }
1007
1008     pa_sink_new_data_init(&data);
1009     data.name = pa_xstrdup(pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
1010     data.namereg_fail = FALSE;
1011     data.driver = __FILE__;
1012     data.module = m;
1013     pa_sink_new_data_set_sample_spec(&data, &ss);
1014     pa_sink_new_data_set_channel_map(&data, &map);
1015     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Simultaneous Output");
1016
1017     u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
1018     pa_sink_new_data_done(&data);
1019
1020     if (!u->sink) {
1021         pa_log("Failed to create sink");
1022         goto fail;
1023     }
1024
1025     u->sink->parent.process_msg = sink_process_msg;
1026 /*     u->sink->get_latency = sink_get_latency_cb; */
1027     u->sink->set_state = sink_set_state;
1028     u->sink->userdata = u;
1029
1030     pa_sink_set_rtpoll(u->sink, u->rtpoll);
1031     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1032
1033     u->block_size = pa_bytes_per_second(&ss) / 20; /* 50 ms */
1034     if (u->block_size <= 0)
1035         u->block_size = pa_frame_size(&ss);
1036
1037     if (!u->automatic) {
1038         const char*split_state;
1039         char *n = NULL;
1040         pa_assert(slaves);
1041
1042         /* The master and slaves have been specified manually */
1043
1044         if (!(u->master = output_new(u, master_sink))) {
1045             pa_log("Failed to create master sink input on sink '%s'.", master_sink->name);
1046             goto fail;
1047         }
1048
1049         split_state = NULL;
1050         while ((n = pa_split(slaves, ",", &split_state))) {
1051             pa_sink *slave_sink;
1052
1053             if (!(slave_sink = pa_namereg_get(m->core, n, PA_NAMEREG_SINK, 1)) || slave_sink == u->sink) {
1054                 pa_log("Invalid slave sink '%s'", n);
1055                 pa_xfree(n);
1056                 goto fail;
1057             }
1058
1059             pa_xfree(n);
1060
1061             if (!output_new(u, slave_sink)) {
1062                 pa_log("Failed to create slave sink input on sink '%s'.", slave_sink->name);
1063                 goto fail;
1064             }
1065         }
1066
1067         if (pa_idxset_size(u->outputs) <= 1)
1068             pa_log_warn("No slave sinks specified.");
1069
1070         u->sink_new_slot = NULL;
1071
1072     } else {
1073         pa_sink *s;
1074
1075         /* We're in automatic mode, we elect one hw sink to the master
1076          * and attach all other hw sinks as slaves to it */
1077
1078         for (s = pa_idxset_first(m->core->sinks, &idx); s; s = pa_idxset_next(m->core->sinks, &idx)) {
1079
1080             if (!(s->flags & PA_SINK_HARDWARE) || s == u->sink)
1081                 continue;
1082
1083             if (!output_new(u, s)) {
1084                 pa_log("Failed to create sink input on sink '%s'.", s->name);
1085                 goto fail;
1086             }
1087         }
1088
1089         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);
1090     }
1091
1092     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);
1093     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);
1094
1095     pick_master(u, NULL);
1096
1097     if (!(u->thread = pa_thread_new(thread_func, u))) {
1098         pa_log("Failed to create thread.");
1099         goto fail;
1100     }
1101
1102     /* Activate the sink and the sink inputs */
1103     pa_sink_put(u->sink);
1104
1105     for (o = pa_idxset_first(u->outputs, &idx); o; o = pa_idxset_next(u->outputs, &idx))
1106         if (o->sink_input)
1107             pa_sink_input_put(o->sink_input);
1108
1109     if (u->adjust_time > 0) {
1110         struct timeval tv;
1111         pa_gettimeofday(&tv);
1112         tv.tv_sec += u->adjust_time;
1113         u->time_event = m->core->mainloop->time_new(m->core->mainloop, &tv, time_callback, u);
1114     }
1115
1116     pa_modargs_free(ma);
1117
1118     return 0;
1119
1120 fail:
1121
1122     if (ma)
1123         pa_modargs_free(ma);
1124
1125     pa__done(m);
1126
1127     return -1;
1128 }
1129
1130 static void output_free(struct output *o) {
1131     pa_assert(o);
1132
1133     pick_master(o->userdata, o);
1134
1135     disable_output(o);
1136
1137     pa_assert_se(pa_idxset_remove_by_data(o->userdata->outputs, o, NULL));
1138
1139     update_description(o->userdata);
1140
1141     if (o->inq_rtpoll_item)
1142         pa_rtpoll_item_free(o->inq_rtpoll_item);
1143
1144     if (o->outq_rtpoll_item)
1145         pa_rtpoll_item_free(o->outq_rtpoll_item);
1146
1147     if (o->inq)
1148         pa_asyncmsgq_unref(o->inq);
1149
1150     if (o->outq)
1151         pa_asyncmsgq_unref(o->outq);
1152
1153     if (o->memblockq)
1154         pa_memblockq_free(o->memblockq);
1155
1156     pa_xfree(o);
1157 }
1158
1159 void pa__done(pa_module*m) {
1160     struct userdata *u;
1161     struct output *o;
1162
1163     pa_assert(m);
1164
1165     if (!(u = m->userdata))
1166         return;
1167
1168     if (u->sink_new_slot)
1169         pa_hook_slot_free(u->sink_new_slot);
1170
1171     if (u->sink_unlink_slot)
1172         pa_hook_slot_free(u->sink_unlink_slot);
1173
1174     if (u->sink_state_changed_slot)
1175         pa_hook_slot_free(u->sink_state_changed_slot);
1176
1177     if (u->outputs) {
1178         while ((o = pa_idxset_first(u->outputs, NULL)))
1179             output_free(o);
1180
1181         pa_idxset_free(u->outputs, NULL, NULL);
1182     }
1183
1184     if (u->sink)
1185         pa_sink_unlink(u->sink);
1186
1187     if (u->thread) {
1188         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1189         pa_thread_free(u->thread);
1190     }
1191
1192     pa_thread_mq_done(&u->thread_mq);
1193
1194     if (u->sink)
1195         pa_sink_unref(u->sink);
1196
1197     if (u->rtpoll)
1198         pa_rtpoll_free(u->rtpoll);
1199
1200     if (u->time_event)
1201         u->core->mainloop->time_free(u->time_event);
1202
1203     pa_xfree(u);
1204 }