Merge commit '38ded3bb31bc49664641965f856a35f432a8a956'
[platform/upstream/pulseaudio.git] / src / pulsecore / sink.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
6
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as published
9   by the Free Software Foundation; either version 2 of the License,
10   or (at your option) any later version.
11
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with PulseAudio; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20   USA.
21 ***/
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdio.h>
30
31 #include <pulse/introspect.h>
32 #include <pulse/utf8.h>
33 #include <pulse/xmalloc.h>
34 #include <pulse/timeval.h>
35 #include <pulse/util.h>
36
37 #include <pulsecore/sink-input.h>
38 #include <pulsecore/namereg.h>
39 #include <pulsecore/core-util.h>
40 #include <pulsecore/sample-util.h>
41 #include <pulsecore/core-subscribe.h>
42 #include <pulsecore/log.h>
43 #include <pulsecore/macro.h>
44 #include <pulsecore/play-memblockq.h>
45
46 #include "sink.h"
47
48 #define MAX_MIX_CHANNELS 32
49 #define MIX_BUFFER_LENGTH (PA_PAGE_SIZE)
50 #define DEFAULT_MIN_LATENCY (4*PA_USEC_PER_MSEC)
51
52 static PA_DEFINE_CHECK_TYPE(pa_sink, pa_msgobject);
53
54 static void sink_free(pa_object *s);
55
56 pa_sink_new_data* pa_sink_new_data_init(pa_sink_new_data *data) {
57     pa_assert(data);
58
59     memset(data, 0, sizeof(*data));
60     data->proplist = pa_proplist_new();
61
62     return data;
63 }
64
65 void pa_sink_new_data_set_name(pa_sink_new_data *data, const char *name) {
66     pa_assert(data);
67
68     pa_xfree(data->name);
69     data->name = pa_xstrdup(name);
70 }
71
72 void pa_sink_new_data_set_sample_spec(pa_sink_new_data *data, const pa_sample_spec *spec) {
73     pa_assert(data);
74
75     if ((data->sample_spec_is_set = !!spec))
76         data->sample_spec = *spec;
77 }
78
79 void pa_sink_new_data_set_channel_map(pa_sink_new_data *data, const pa_channel_map *map) {
80     pa_assert(data);
81
82     if ((data->channel_map_is_set = !!map))
83         data->channel_map = *map;
84 }
85
86 void pa_sink_new_data_set_volume(pa_sink_new_data *data, const pa_cvolume *volume) {
87     pa_assert(data);
88
89     if ((data->volume_is_set = !!volume))
90         data->volume = *volume;
91 }
92
93 void pa_sink_new_data_set_muted(pa_sink_new_data *data, pa_bool_t mute) {
94     pa_assert(data);
95
96     data->muted_is_set = TRUE;
97     data->muted = !!mute;
98 }
99
100 void pa_sink_new_data_done(pa_sink_new_data *data) {
101     pa_assert(data);
102
103     pa_xfree(data->name);
104     pa_proplist_free(data->proplist);
105 }
106
107 /* Called from main context */
108 static void reset_callbacks(pa_sink *s) {
109     pa_assert(s);
110
111     s->set_state = NULL;
112     s->get_volume = NULL;
113     s->set_volume = NULL;
114     s->get_mute = NULL;
115     s->set_mute = NULL;
116     s->request_rewind = NULL;
117     s->update_requested_latency = NULL;
118 }
119
120 /* Called from main context */
121 pa_sink* pa_sink_new(
122         pa_core *core,
123         pa_sink_new_data *data,
124         pa_sink_flags_t flags) {
125
126     pa_sink *s;
127     const char *name;
128     char st[PA_SAMPLE_SPEC_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX];
129     pa_source_new_data source_data;
130     const char *dn;
131     char *pt;
132
133     pa_assert(core);
134     pa_assert(data);
135     pa_assert(data->name);
136
137     s = pa_msgobject_new(pa_sink);
138
139     if (!(name = pa_namereg_register(core, data->name, PA_NAMEREG_SINK, s, data->namereg_fail))) {
140         pa_xfree(s);
141         return NULL;
142     }
143
144     pa_sink_new_data_set_name(data, name);
145
146     if (pa_hook_fire(&core->hooks[PA_CORE_HOOK_SINK_NEW], data) < 0) {
147         pa_xfree(s);
148         pa_namereg_unregister(core, name);
149         return NULL;
150     }
151
152     pa_return_null_if_fail(!data->driver || pa_utf8_valid(data->driver));
153     pa_return_null_if_fail(data->name && pa_utf8_valid(data->name) && data->name[0]);
154
155     pa_return_null_if_fail(data->sample_spec_is_set && pa_sample_spec_valid(&data->sample_spec));
156
157     if (!data->channel_map_is_set)
158         pa_return_null_if_fail(pa_channel_map_init_auto(&data->channel_map, data->sample_spec.channels, PA_CHANNEL_MAP_DEFAULT));
159
160     pa_return_null_if_fail(pa_channel_map_valid(&data->channel_map));
161     pa_return_null_if_fail(data->channel_map.channels == data->sample_spec.channels);
162
163     if (!data->volume_is_set)
164         pa_cvolume_reset(&data->volume, data->sample_spec.channels);
165
166     pa_return_null_if_fail(pa_cvolume_valid(&data->volume));
167     pa_return_null_if_fail(data->volume.channels == data->sample_spec.channels);
168
169     if (!data->muted_is_set)
170         data->muted = FALSE;
171
172     if (data->card)
173         pa_proplist_update(data->proplist, PA_UPDATE_MERGE, data->card->proplist);
174
175     if (pa_hook_fire(&core->hooks[PA_CORE_HOOK_SINK_FIXATE], data) < 0) {
176         pa_xfree(s);
177         pa_namereg_unregister(core, name);
178         return NULL;
179     }
180
181     s->parent.parent.free = sink_free;
182     s->parent.process_msg = pa_sink_process_msg;
183
184     s->core = core;
185     s->state = PA_SINK_INIT;
186     s->flags = flags;
187     s->name = pa_xstrdup(name);
188     s->proplist = pa_proplist_copy(data->proplist);
189     s->driver = pa_xstrdup(pa_path_get_filename(data->driver));
190     s->module = data->module;
191     s->card = data->card;
192
193     s->sample_spec = data->sample_spec;
194     s->channel_map = data->channel_map;
195
196     s->inputs = pa_idxset_new(NULL, NULL);
197     s->n_corked = 0;
198
199     s->virtual_volume = data->volume;
200     pa_cvolume_reset(&s->soft_volume, s->sample_spec.channels);
201     s->base_volume = PA_VOLUME_NORM;
202     s->n_volume_steps = PA_VOLUME_NORM+1;
203     s->muted = data->muted;
204     s->refresh_volume = s->refresh_muted = FALSE;
205
206     reset_callbacks(s);
207     s->userdata = NULL;
208
209     s->asyncmsgq = NULL;
210     s->rtpoll = NULL;
211
212     pa_silence_memchunk_get(
213             &core->silence_cache,
214             core->mempool,
215             &s->silence,
216             &s->sample_spec,
217             0);
218
219     s->thread_info.inputs = pa_hashmap_new(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func);
220     s->thread_info.soft_volume =  s->soft_volume;
221     s->thread_info.soft_muted = s->muted;
222     s->thread_info.state = s->state;
223     s->thread_info.rewind_nbytes = 0;
224     s->thread_info.rewind_requested = FALSE;
225     s->thread_info.max_rewind = 0;
226     s->thread_info.max_request = 0;
227     s->thread_info.requested_latency_valid = FALSE;
228     s->thread_info.requested_latency = 0;
229     s->thread_info.min_latency = DEFAULT_MIN_LATENCY;
230     s->thread_info.max_latency = 0;
231
232     pa_assert_se(pa_idxset_put(core->sinks, s, &s->index) >= 0);
233
234     if (s->card)
235         pa_assert_se(pa_idxset_put(s->card->sinks, s, NULL) >= 0);
236
237     pt = pa_proplist_to_string_sep(s->proplist, "\n    ");
238     pa_log_info("Created sink %u \"%s\" with sample spec %s and channel map %s\n    %s",
239                 s->index,
240                 s->name,
241                 pa_sample_spec_snprint(st, sizeof(st), &s->sample_spec),
242                 pa_channel_map_snprint(cm, sizeof(cm), &s->channel_map),
243                 pt);
244     pa_xfree(pt);
245
246     pa_source_new_data_init(&source_data);
247     pa_source_new_data_set_sample_spec(&source_data, &s->sample_spec);
248     pa_source_new_data_set_channel_map(&source_data, &s->channel_map);
249     source_data.name = pa_sprintf_malloc("%s.monitor", name);
250     source_data.driver = data->driver;
251     source_data.module = data->module;
252     source_data.card = data->card;
253
254     dn = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
255     pa_proplist_setf(source_data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Monitor of %s", dn ? dn : s->name);
256     pa_proplist_sets(source_data.proplist, PA_PROP_DEVICE_CLASS, "monitor");
257
258     s->monitor_source = pa_source_new(core, &source_data, PA_SOURCE_LATENCY);
259
260     pa_source_new_data_done(&source_data);
261
262     if (!s->monitor_source) {
263         pa_sink_unlink(s);
264         pa_sink_unref(s);
265         return NULL;
266     }
267
268     s->monitor_source->monitor_of = s;
269
270     pa_source_set_latency_range(s->monitor_source, s->thread_info.min_latency, s->thread_info.max_latency);
271     pa_source_set_max_rewind(s->monitor_source, s->thread_info.max_rewind);
272
273     return s;
274 }
275
276 /* Called from main context */
277 static int sink_set_state(pa_sink *s, pa_sink_state_t state) {
278     int ret;
279     pa_bool_t suspend_change;
280     pa_sink_state_t original_state;
281
282     pa_assert(s);
283
284     if (s->state == state)
285         return 0;
286
287     original_state = s->state;
288
289     suspend_change =
290         (original_state == PA_SINK_SUSPENDED && PA_SINK_IS_OPENED(state)) ||
291         (PA_SINK_IS_OPENED(original_state) && state == PA_SINK_SUSPENDED);
292
293     if (s->set_state)
294         if ((ret = s->set_state(s, state)) < 0)
295             return ret;
296
297     if (s->asyncmsgq)
298         if ((ret = pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_STATE, PA_UINT_TO_PTR(state), 0, NULL)) < 0) {
299
300             if (s->set_state)
301                 s->set_state(s, original_state);
302
303             return ret;
304         }
305
306     s->state = state;
307
308     if (state != PA_SINK_UNLINKED) { /* if we enter UNLINKED state pa_sink_unlink() will fire the apropriate events */
309         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED], s);
310         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
311     }
312
313     if (suspend_change) {
314         pa_sink_input *i;
315         uint32_t idx;
316
317         /* We're suspending or resuming, tell everyone about it */
318
319         for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx)))
320             if (s->state == PA_SINK_SUSPENDED &&
321                 (i->flags & PA_SINK_INPUT_FAIL_ON_SUSPEND))
322                 pa_sink_input_kill(i);
323             else if (i->suspend)
324                 i->suspend(i, state == PA_SINK_SUSPENDED);
325     }
326
327     return 0;
328 }
329
330 /* Called from main context */
331 void pa_sink_put(pa_sink* s) {
332     pa_sink_assert_ref(s);
333
334     pa_assert(s->state == PA_SINK_INIT);
335
336     /* The following fields must be initialized properly when calling _put() */
337     pa_assert(s->asyncmsgq);
338     pa_assert(s->rtpoll);
339     pa_assert(!s->thread_info.min_latency || !s->thread_info.max_latency ||
340               s->thread_info.min_latency <= s->thread_info.max_latency);
341
342     if (!(s->flags & PA_SINK_HW_VOLUME_CTRL)) {
343         s->flags |= PA_SINK_DECIBEL_VOLUME;
344
345         s->thread_info.soft_volume = s->soft_volume;
346         s->thread_info.soft_muted = s->muted;
347     }
348
349     if (s->flags & PA_SINK_DECIBEL_VOLUME)
350         s->n_volume_steps = PA_VOLUME_NORM+1;
351
352     if (s->core->flat_volumes)
353         if (s->flags & PA_SINK_DECIBEL_VOLUME)
354             s->flags |= PA_SINK_FLAT_VOLUME;
355
356     pa_assert_se(sink_set_state(s, PA_SINK_IDLE) == 0);
357
358     pa_source_put(s->monitor_source);
359
360     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_NEW, s->index);
361     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PUT], s);
362 }
363
364 /* Called from main context */
365 void pa_sink_unlink(pa_sink* s) {
366     pa_bool_t linked;
367     pa_sink_input *i, *j = NULL;
368
369     pa_assert(s);
370
371     /* Please note that pa_sink_unlink() does more than simply
372      * reversing pa_sink_put(). It also undoes the registrations
373      * already done in pa_sink_new()! */
374
375     /* All operations here shall be idempotent, i.e. pa_sink_unlink()
376      * may be called multiple times on the same sink without bad
377      * effects. */
378
379     linked = PA_SINK_IS_LINKED(s->state);
380
381     if (linked)
382         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_UNLINK], s);
383
384     if (s->state != PA_SINK_UNLINKED)
385         pa_namereg_unregister(s->core, s->name);
386     pa_idxset_remove_by_data(s->core->sinks, s, NULL);
387
388     if (s->card)
389         pa_idxset_remove_by_data(s->card->sinks, s, NULL);
390
391     while ((i = pa_idxset_first(s->inputs, NULL))) {
392         pa_assert(i != j);
393         pa_sink_input_kill(i);
394         j = i;
395     }
396
397     if (linked)
398         sink_set_state(s, PA_SINK_UNLINKED);
399     else
400         s->state = PA_SINK_UNLINKED;
401
402     reset_callbacks(s);
403
404     if (s->monitor_source)
405         pa_source_unlink(s->monitor_source);
406
407     if (linked) {
408         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_REMOVE, s->index);
409         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_UNLINK_POST], s);
410     }
411 }
412
413 /* Called from main context */
414 static void sink_free(pa_object *o) {
415     pa_sink *s = PA_SINK(o);
416     pa_sink_input *i;
417
418     pa_assert(s);
419     pa_assert(pa_sink_refcnt(s) == 0);
420
421     if (PA_SINK_IS_LINKED(s->state))
422         pa_sink_unlink(s);
423
424     pa_log_info("Freeing sink %u \"%s\"", s->index, s->name);
425
426     if (s->monitor_source) {
427         pa_source_unref(s->monitor_source);
428         s->monitor_source = NULL;
429     }
430
431     pa_idxset_free(s->inputs, NULL, NULL);
432
433     while ((i = pa_hashmap_steal_first(s->thread_info.inputs)))
434         pa_sink_input_unref(i);
435
436     pa_hashmap_free(s->thread_info.inputs, NULL, NULL);
437
438     if (s->silence.memblock)
439         pa_memblock_unref(s->silence.memblock);
440
441     pa_xfree(s->name);
442     pa_xfree(s->driver);
443
444     if (s->proplist)
445         pa_proplist_free(s->proplist);
446
447     pa_xfree(s);
448 }
449
450 /* Called from main context */
451 void pa_sink_set_asyncmsgq(pa_sink *s, pa_asyncmsgq *q) {
452     pa_sink_assert_ref(s);
453
454     s->asyncmsgq = q;
455
456     if (s->monitor_source)
457         pa_source_set_asyncmsgq(s->monitor_source, q);
458 }
459
460 /* Called from main context */
461 void pa_sink_set_rtpoll(pa_sink *s, pa_rtpoll *p) {
462     pa_sink_assert_ref(s);
463
464     s->rtpoll = p;
465     if (s->monitor_source)
466         pa_source_set_rtpoll(s->monitor_source, p);
467 }
468
469 /* Called from main context */
470 int pa_sink_update_status(pa_sink*s) {
471     pa_sink_assert_ref(s);
472     pa_assert(PA_SINK_IS_LINKED(s->state));
473
474     if (s->state == PA_SINK_SUSPENDED)
475         return 0;
476
477     return sink_set_state(s, pa_sink_used_by(s) ? PA_SINK_RUNNING : PA_SINK_IDLE);
478 }
479
480 /* Called from main context */
481 int pa_sink_suspend(pa_sink *s, pa_bool_t suspend) {
482     pa_sink_assert_ref(s);
483     pa_assert(PA_SINK_IS_LINKED(s->state));
484
485     if (suspend)
486         return sink_set_state(s, PA_SINK_SUSPENDED);
487     else
488         return sink_set_state(s, pa_sink_used_by(s) ? PA_SINK_RUNNING : PA_SINK_IDLE);
489 }
490
491 /* Called from main context */
492 pa_queue *pa_sink_move_all_start(pa_sink *s) {
493     pa_queue *q;
494     pa_sink_input *i, *n;
495     uint32_t idx;
496
497     pa_sink_assert_ref(s);
498     pa_assert(PA_SINK_IS_LINKED(s->state));
499
500     q = pa_queue_new();
501
502     for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = n) {
503         n = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx));
504
505         if (pa_sink_input_start_move(i) >= 0)
506             pa_queue_push(q, pa_sink_input_ref(i));
507     }
508
509     return q;
510 }
511
512 /* Called from main context */
513 void pa_sink_move_all_finish(pa_sink *s, pa_queue *q, pa_bool_t save) {
514     pa_sink_input *i;
515
516     pa_sink_assert_ref(s);
517     pa_assert(PA_SINK_IS_LINKED(s->state));
518     pa_assert(q);
519
520     while ((i = PA_SINK_INPUT(pa_queue_pop(q)))) {
521         if (pa_sink_input_finish_move(i, s, save) < 0)
522             pa_sink_input_kill(i);
523
524         pa_sink_input_unref(i);
525     }
526
527     pa_queue_free(q, NULL, NULL);
528 }
529
530 /* Called from main context */
531 void pa_sink_move_all_fail(pa_queue *q) {
532     pa_sink_input *i;
533     pa_assert(q);
534
535     while ((i = PA_SINK_INPUT(pa_queue_pop(q)))) {
536         if (pa_hook_fire(&i->core->hooks[PA_CORE_HOOK_SINK_INPUT_MOVE_FAIL], i) == PA_HOOK_OK) {
537             pa_sink_input_kill(i);
538             pa_sink_input_unref(i);
539         }
540     }
541
542     pa_queue_free(q, NULL, NULL);
543 }
544
545 /* Called from IO thread context */
546 void pa_sink_process_rewind(pa_sink *s, size_t nbytes) {
547     pa_sink_input *i;
548     void *state = NULL;
549     pa_sink_assert_ref(s);
550     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
551
552     /* If nobody requested this and this is actually no real rewind
553      * then we can short cut this */
554     if (!s->thread_info.rewind_requested && nbytes <= 0)
555         return;
556
557     s->thread_info.rewind_nbytes = 0;
558     s->thread_info.rewind_requested = FALSE;
559
560     if (s->thread_info.state == PA_SINK_SUSPENDED)
561         return;
562
563     if (nbytes > 0)
564         pa_log_debug("Processing rewind...");
565
566     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL))) {
567         pa_sink_input_assert_ref(i);
568         pa_sink_input_process_rewind(i, nbytes);
569     }
570
571     if (nbytes > 0)
572         if (s->monitor_source && PA_SOURCE_IS_LINKED(s->monitor_source->thread_info.state))
573             pa_source_process_rewind(s->monitor_source, nbytes);
574 }
575
576 /* Called from IO thread context */
577 static unsigned fill_mix_info(pa_sink *s, size_t *length, pa_mix_info *info, unsigned maxinfo) {
578     pa_sink_input *i;
579     unsigned n = 0;
580     void *state = NULL;
581     size_t mixlength = *length;
582
583     pa_sink_assert_ref(s);
584     pa_assert(info);
585
586     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)) && maxinfo > 0) {
587         pa_sink_input_assert_ref(i);
588
589         pa_sink_input_peek(i, *length, &info->chunk, &info->volume);
590
591         if (mixlength == 0 || info->chunk.length < mixlength)
592             mixlength = info->chunk.length;
593
594         if (pa_memblock_is_silence(info->chunk.memblock)) {
595             pa_memblock_unref(info->chunk.memblock);
596             continue;
597         }
598
599         info->userdata = pa_sink_input_ref(i);
600
601         pa_assert(info->chunk.memblock);
602         pa_assert(info->chunk.length > 0);
603
604         info++;
605         n++;
606         maxinfo--;
607     }
608
609     if (mixlength > 0)
610         *length = mixlength;
611
612     return n;
613 }
614
615 /* Called from IO thread context */
616 static void inputs_drop(pa_sink *s, pa_mix_info *info, unsigned n, pa_memchunk *result) {
617     pa_sink_input *i;
618     void *state = NULL;
619     unsigned p = 0;
620     unsigned n_unreffed = 0;
621
622     pa_sink_assert_ref(s);
623     pa_assert(result);
624     pa_assert(result->memblock);
625     pa_assert(result->length > 0);
626
627     /* We optimize for the case where the order of the inputs has not changed */
628
629     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL))) {
630         unsigned j;
631         pa_mix_info* m = NULL;
632
633         pa_sink_input_assert_ref(i);
634
635         /* Let's try to find the matching entry info the pa_mix_info array */
636         for (j = 0; j < n; j ++) {
637
638             if (info[p].userdata == i) {
639                 m = info + p;
640                 break;
641             }
642
643             p++;
644             if (p >= n)
645                 p = 0;
646         }
647
648         /* Drop read data */
649         pa_sink_input_drop(i, result->length);
650
651         if (s->monitor_source && PA_SOURCE_IS_LINKED(s->monitor_source->thread_info.state)) {
652
653             if (pa_hashmap_size(i->thread_info.direct_outputs) > 0) {
654                 void *ostate = NULL;
655                 pa_source_output *o;
656                 pa_memchunk c;
657
658                 if (m && m->chunk.memblock) {
659                     c = m->chunk;
660                     pa_memblock_ref(c.memblock);
661                     pa_assert(result->length <= c.length);
662                     c.length = result->length;
663
664                     pa_memchunk_make_writable(&c, 0);
665                     pa_volume_memchunk(&c, &s->sample_spec, &m->volume);
666                 } else {
667                     c = s->silence;
668                     pa_memblock_ref(c.memblock);
669                     pa_assert(result->length <= c.length);
670                     c.length = result->length;
671                 }
672
673                 while ((o = pa_hashmap_iterate(i->thread_info.direct_outputs, &ostate, NULL))) {
674                     pa_source_output_assert_ref(o);
675                     pa_assert(o->direct_on_input == i);
676                     pa_source_post_direct(s->monitor_source, o, &c);
677                 }
678
679                 pa_memblock_unref(c.memblock);
680             }
681         }
682
683         if (m) {
684             if (m->chunk.memblock)
685                 pa_memblock_unref(m->chunk.memblock);
686                 pa_memchunk_reset(&m->chunk);
687
688             pa_sink_input_unref(m->userdata);
689             m->userdata = NULL;
690
691             n_unreffed += 1;
692         }
693     }
694
695     /* Now drop references to entries that are included in the
696      * pa_mix_info array but don't exist anymore */
697
698     if (n_unreffed < n) {
699         for (; n > 0; info++, n--) {
700             if (info->userdata)
701                 pa_sink_input_unref(info->userdata);
702             if (info->chunk.memblock)
703                 pa_memblock_unref(info->chunk.memblock);
704         }
705     }
706
707     if (s->monitor_source && PA_SOURCE_IS_LINKED(s->monitor_source->thread_info.state))
708         pa_source_post(s->monitor_source, result);
709 }
710
711 /* Called from IO thread context */
712 void pa_sink_render(pa_sink*s, size_t length, pa_memchunk *result) {
713     pa_mix_info info[MAX_MIX_CHANNELS];
714     unsigned n;
715     size_t block_size_max;
716
717     pa_sink_assert_ref(s);
718     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
719     pa_assert(pa_frame_aligned(length, &s->sample_spec));
720     pa_assert(result);
721
722     pa_sink_ref(s);
723
724     pa_assert(!s->thread_info.rewind_requested);
725     pa_assert(s->thread_info.rewind_nbytes == 0);
726
727     if (s->thread_info.state == PA_SINK_SUSPENDED) {
728         result->memblock = pa_memblock_ref(s->silence.memblock);
729         result->index = s->silence.index;
730         result->length = PA_MIN(s->silence.length, length);
731         return;
732     }
733
734     if (length <= 0)
735         length = pa_frame_align(MIX_BUFFER_LENGTH, &s->sample_spec);
736
737     block_size_max = pa_mempool_block_size_max(s->core->mempool);
738     if (length > block_size_max)
739         length = pa_frame_align(block_size_max, &s->sample_spec);
740
741     pa_assert(length > 0);
742
743     n = fill_mix_info(s, &length, info, MAX_MIX_CHANNELS);
744
745     if (n == 0) {
746
747         *result = s->silence;
748         pa_memblock_ref(result->memblock);
749
750         if (result->length > length)
751             result->length = length;
752
753     } else if (n == 1) {
754         pa_cvolume volume;
755
756         *result = info[0].chunk;
757         pa_memblock_ref(result->memblock);
758
759         if (result->length > length)
760             result->length = length;
761
762         pa_sw_cvolume_multiply(&volume, &s->thread_info.soft_volume, &info[0].volume);
763
764         if (s->thread_info.soft_muted || !pa_cvolume_is_norm(&volume)) {
765             pa_memchunk_make_writable(result, 0);
766             if (s->thread_info.soft_muted || pa_cvolume_is_muted(&volume))
767                 pa_silence_memchunk(result, &s->sample_spec);
768             else
769                 pa_volume_memchunk(result, &s->sample_spec, &volume);
770         }
771     } else {
772         void *ptr;
773         result->memblock = pa_memblock_new(s->core->mempool, length);
774
775         ptr = pa_memblock_acquire(result->memblock);
776         result->length = pa_mix(info, n,
777                                 ptr, length,
778                                 &s->sample_spec,
779                                 &s->thread_info.soft_volume,
780                                 s->thread_info.soft_muted);
781         pa_memblock_release(result->memblock);
782
783         result->index = 0;
784     }
785
786     inputs_drop(s, info, n, result);
787
788     pa_sink_unref(s);
789 }
790
791 /* Called from IO thread context */
792 void pa_sink_render_into(pa_sink*s, pa_memchunk *target) {
793     pa_mix_info info[MAX_MIX_CHANNELS];
794     unsigned n;
795     size_t length, block_size_max;
796
797     pa_sink_assert_ref(s);
798     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
799     pa_assert(target);
800     pa_assert(target->memblock);
801     pa_assert(target->length > 0);
802     pa_assert(pa_frame_aligned(target->length, &s->sample_spec));
803
804     pa_sink_ref(s);
805
806     pa_assert(!s->thread_info.rewind_requested);
807     pa_assert(s->thread_info.rewind_nbytes == 0);
808
809     if (s->thread_info.state == PA_SINK_SUSPENDED) {
810         pa_silence_memchunk(target, &s->sample_spec);
811         return;
812     }
813
814     length = target->length;
815     block_size_max = pa_mempool_block_size_max(s->core->mempool);
816     if (length > block_size_max)
817         length = pa_frame_align(block_size_max, &s->sample_spec);
818
819     pa_assert(length > 0);
820
821     n = fill_mix_info(s, &length, info, MAX_MIX_CHANNELS);
822
823     if (n == 0) {
824         if (target->length > length)
825             target->length = length;
826
827         pa_silence_memchunk(target, &s->sample_spec);
828     } else if (n == 1) {
829         pa_cvolume volume;
830
831         if (target->length > length)
832             target->length = length;
833
834         pa_sw_cvolume_multiply(&volume, &s->thread_info.soft_volume, &info[0].volume);
835
836         if (s->thread_info.soft_muted || pa_cvolume_is_muted(&volume))
837             pa_silence_memchunk(target, &s->sample_spec);
838         else {
839             pa_memchunk vchunk;
840
841             vchunk = info[0].chunk;
842             pa_memblock_ref(vchunk.memblock);
843
844             if (vchunk.length > length)
845                 vchunk.length = length;
846
847             if (!pa_cvolume_is_norm(&volume)) {
848                 pa_memchunk_make_writable(&vchunk, 0);
849                 pa_volume_memchunk(&vchunk, &s->sample_spec, &volume);
850             }
851
852             pa_memchunk_memcpy(target, &vchunk);
853             pa_memblock_unref(vchunk.memblock);
854         }
855
856     } else {
857         void *ptr;
858
859         ptr = pa_memblock_acquire(target->memblock);
860
861         target->length = pa_mix(info, n,
862                                 (uint8_t*) ptr + target->index, length,
863                                 &s->sample_spec,
864                                 &s->thread_info.soft_volume,
865                                 s->thread_info.soft_muted);
866
867         pa_memblock_release(target->memblock);
868     }
869
870     inputs_drop(s, info, n, target);
871
872     pa_sink_unref(s);
873 }
874
875 /* Called from IO thread context */
876 void pa_sink_render_into_full(pa_sink *s, pa_memchunk *target) {
877     pa_memchunk chunk;
878     size_t l, d;
879
880     pa_sink_assert_ref(s);
881     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
882     pa_assert(target);
883     pa_assert(target->memblock);
884     pa_assert(target->length > 0);
885     pa_assert(pa_frame_aligned(target->length, &s->sample_spec));
886
887     pa_sink_ref(s);
888
889     pa_assert(!s->thread_info.rewind_requested);
890     pa_assert(s->thread_info.rewind_nbytes == 0);
891
892     l = target->length;
893     d = 0;
894     while (l > 0) {
895         chunk = *target;
896         chunk.index += d;
897         chunk.length -= d;
898
899         pa_sink_render_into(s, &chunk);
900
901         d += chunk.length;
902         l -= chunk.length;
903     }
904
905     pa_sink_unref(s);
906 }
907
908 /* Called from IO thread context */
909 void pa_sink_render_full(pa_sink *s, size_t length, pa_memchunk *result) {
910     pa_sink_assert_ref(s);
911     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
912     pa_assert(length > 0);
913     pa_assert(pa_frame_aligned(length, &s->sample_spec));
914     pa_assert(result);
915
916     pa_assert(!s->thread_info.rewind_requested);
917     pa_assert(s->thread_info.rewind_nbytes == 0);
918
919     /*** This needs optimization ***/
920
921     result->index = 0;
922     result->length = length;
923     result->memblock = pa_memblock_new(s->core->mempool, length);
924
925     pa_sink_render_into_full(s, result);
926 }
927
928 /* Called from main thread */
929 pa_usec_t pa_sink_get_latency(pa_sink *s) {
930     pa_usec_t usec = 0;
931
932     pa_sink_assert_ref(s);
933     pa_assert(PA_SINK_IS_LINKED(s->state));
934
935     /* The returned value is supposed to be in the time domain of the sound card! */
936
937     if (s->state == PA_SINK_SUSPENDED)
938         return 0;
939
940     if (!(s->flags & PA_SINK_LATENCY))
941         return 0;
942
943     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY, &usec, 0, NULL) == 0);
944
945     return usec;
946 }
947
948 /* Called from main thread */
949 void pa_sink_update_flat_volume(pa_sink *s, pa_cvolume *new_volume) {
950     pa_sink_input *i;
951     uint32_t idx;
952
953     pa_sink_assert_ref(s);
954     pa_assert(new_volume);
955     pa_assert(PA_SINK_IS_LINKED(s->state));
956     pa_assert(s->flags & PA_SINK_FLAT_VOLUME);
957
958     /* This is called whenever a sink input volume changes and we
959      * might need to fix up the sink volume accordingly. Please note
960      * that we don't actually update the sinks volume here, we only
961      * return how it needs to be updated. The caller should then call
962      * pa_sink_set_flat_volume().*/
963
964     if (pa_idxset_isempty(s->inputs)) {
965         /* In the special case that we have no sink input we leave the
966          * volume unmodified. */
967         *new_volume = s->virtual_volume;
968         return;
969     }
970
971     pa_cvolume_mute(new_volume, s->channel_map.channels);
972
973     /* First let's determine the new maximum volume of all inputs
974      * connected to this sink */
975     for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx))) {
976         unsigned c;
977         pa_cvolume remapped_volume;
978
979         remapped_volume = i->virtual_volume;
980         pa_cvolume_remap(&remapped_volume, &i->channel_map, &s->channel_map);
981
982         for (c = 0; c < new_volume->channels; c++)
983             if (remapped_volume.values[c] > new_volume->values[c])
984                 new_volume->values[c] = remapped_volume.values[c];
985     }
986
987     /* Then, let's update the soft volumes of all inputs connected
988      * to this sink */
989     for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx))) {
990         pa_cvolume remapped_new_volume;
991
992         remapped_new_volume = *new_volume;
993         pa_cvolume_remap(&remapped_new_volume, &s->channel_map, &i->channel_map);
994         pa_sw_cvolume_divide(&i->soft_volume, &i->virtual_volume, &remapped_new_volume);
995         pa_sw_cvolume_multiply(&i->soft_volume, &i->soft_volume, &i->volume_factor);
996
997         /* Hooks have the ability to play games with i->soft_volume */
998         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_INPUT_SET_VOLUME], i);
999
1000         /* We don't issue PA_SINK_INPUT_MESSAGE_SET_VOLUME because
1001          * we want the update to have atomically with the sink
1002          * volume update, hence we do it within the
1003          * pa_sink_set_flat_volume() call below*/
1004     }
1005 }
1006
1007 /* Called from main thread */
1008 void pa_sink_propagate_flat_volume(pa_sink *s, const pa_cvolume *old_volume) {
1009     pa_sink_input *i;
1010     uint32_t idx;
1011
1012     pa_sink_assert_ref(s);
1013     pa_assert(old_volume);
1014     pa_assert(PA_SINK_IS_LINKED(s->state));
1015     pa_assert(s->flags & PA_SINK_FLAT_VOLUME);
1016
1017     /* This is called whenever the sink volume changes that is not
1018      * caused by a sink input volume change. We need to fix up the
1019      * sink input volumes accordingly */
1020
1021     for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx))) {
1022         pa_cvolume remapped_old_volume, remapped_new_volume, fixed_volume;
1023         unsigned c;
1024
1025         remapped_new_volume = s->virtual_volume;
1026         pa_cvolume_remap(&remapped_new_volume, &s->channel_map, &i->channel_map);
1027
1028         remapped_old_volume = *old_volume;
1029         pa_cvolume_remap(&remapped_old_volume, &s->channel_map, &i->channel_map);
1030
1031         for (c = 0; c < i->sample_spec.channels; c++)
1032
1033             if (remapped_old_volume.values[c] == PA_VOLUME_MUTED)
1034                 fixed_volume.values[c] = PA_VOLUME_MUTED;
1035             else
1036                 fixed_volume.values[c] = (pa_volume_t)
1037                     ((uint64_t) i->virtual_volume.values[c] *
1038                      (uint64_t) remapped_new_volume.values[c] /
1039                      (uint64_t) remapped_old_volume.values[c]);
1040
1041         fixed_volume.channels = i->virtual_volume.channels;
1042
1043         if (!pa_cvolume_equal(&fixed_volume, &i->virtual_volume)) {
1044             i->virtual_volume = fixed_volume;
1045
1046             /* The virtual volume changed, let's tell people so */
1047             pa_subscription_post(i->core, PA_SUBSCRIPTION_EVENT_SINK_INPUT|PA_SUBSCRIPTION_EVENT_CHANGE, i->index);
1048         }
1049     }
1050 }
1051
1052 /* Called from main thread */
1053 void pa_sink_set_volume(pa_sink *s, const pa_cvolume *volume, pa_bool_t propagate, pa_bool_t sendmsg) {
1054     pa_cvolume old_virtual_volume;
1055     pa_bool_t virtual_volume_changed;
1056
1057     pa_sink_assert_ref(s);
1058     pa_assert(PA_SINK_IS_LINKED(s->state));
1059     pa_assert(volume);
1060     pa_assert(pa_cvolume_valid(volume));
1061     pa_assert(pa_cvolume_compatible(volume, &s->sample_spec));
1062
1063     old_virtual_volume = s->virtual_volume;
1064     s->virtual_volume = *volume;
1065     virtual_volume_changed = !pa_cvolume_equal(&old_virtual_volume, &s->virtual_volume);
1066
1067     /* Propagate this volume change back to the inputs */
1068     if (virtual_volume_changed)
1069         if (propagate && (s->flags & PA_SINK_FLAT_VOLUME))
1070             pa_sink_propagate_flat_volume(s, &old_virtual_volume);
1071
1072     if (s->set_volume) {
1073         /* If we have a function set_volume(), then we do not apply a
1074          * soft volume by default. However, set_volume() is apply one
1075          * to s->soft_volume */
1076
1077         pa_cvolume_reset(&s->soft_volume, s->sample_spec.channels);
1078         s->set_volume(s);
1079
1080     } else
1081         /* If we have no function set_volume(), then the soft volume
1082          * becomes the virtual volume */
1083         s->soft_volume = s->virtual_volume;
1084
1085     /* This tells the sink that soft and/or virtual volume changed */
1086     if (sendmsg)
1087         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL) == 0);
1088
1089     if (virtual_volume_changed)
1090         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1091 }
1092
1093 /* Called from main thread. Only to be called by sink implementor */
1094 void pa_sink_set_soft_volume(pa_sink *s, const pa_cvolume *volume) {
1095     pa_sink_assert_ref(s);
1096     pa_assert(volume);
1097
1098     s->soft_volume = *volume;
1099
1100     if (PA_SINK_IS_LINKED(s->state))
1101         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL) == 0);
1102     else
1103         s->thread_info.soft_volume = *volume;
1104 }
1105
1106 /* Called from main thread */
1107 const pa_cvolume *pa_sink_get_volume(pa_sink *s, pa_bool_t force_refresh) {
1108     pa_sink_assert_ref(s);
1109
1110     if (s->refresh_volume || force_refresh) {
1111         struct pa_cvolume old_virtual_volume = s->virtual_volume;
1112
1113         if (s->get_volume)
1114             s->get_volume(s);
1115
1116         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_VOLUME, NULL, 0, NULL) == 0);
1117
1118         if (!pa_cvolume_equal(&old_virtual_volume, &s->virtual_volume)) {
1119
1120             if (s->flags & PA_SINK_FLAT_VOLUME)
1121                 pa_sink_propagate_flat_volume(s, &old_virtual_volume);
1122
1123             pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1124         }
1125     }
1126
1127     return &s->virtual_volume;
1128 }
1129
1130 /* Called from main thread */
1131 void pa_sink_set_mute(pa_sink *s, pa_bool_t mute) {
1132     pa_bool_t old_muted;
1133
1134     pa_sink_assert_ref(s);
1135     pa_assert(PA_SINK_IS_LINKED(s->state));
1136
1137     old_muted = s->muted;
1138     s->muted = mute;
1139
1140     if (s->set_mute)
1141         s->set_mute(s);
1142
1143     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_MUTE, NULL, 0, NULL) == 0);
1144
1145     if (old_muted != s->muted)
1146         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1147 }
1148
1149 /* Called from main thread */
1150 pa_bool_t pa_sink_get_mute(pa_sink *s, pa_bool_t force_refresh) {
1151
1152     pa_sink_assert_ref(s);
1153
1154     if (s->refresh_muted || force_refresh) {
1155         pa_bool_t old_muted = s->muted;
1156
1157         if (s->get_mute)
1158             s->get_mute(s);
1159
1160         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_MUTE, NULL, 0, NULL) == 0);
1161
1162         if (old_muted != s->muted)
1163             pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1164     }
1165
1166     return s->muted;
1167 }
1168
1169 /* Called from main thread */
1170 pa_bool_t pa_sink_update_proplist(pa_sink *s, pa_update_mode_t mode, pa_proplist *p) {
1171
1172     pa_sink_assert_ref(s);
1173     pa_assert(p);
1174
1175     pa_proplist_update(s->proplist, mode, p);
1176
1177     if (PA_SINK_IS_LINKED(s->state)) {
1178         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PROPLIST_CHANGED], s);
1179         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1180     }
1181
1182     return TRUE;
1183 }
1184
1185 /* Called from main thread */
1186 void pa_sink_set_description(pa_sink *s, const char *description) {
1187     const char *old;
1188     pa_sink_assert_ref(s);
1189
1190     if (!description && !pa_proplist_contains(s->proplist, PA_PROP_DEVICE_DESCRIPTION))
1191         return;
1192
1193     old = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
1194
1195     if (old && description && !strcmp(old, description))
1196         return;
1197
1198     if (description)
1199         pa_proplist_sets(s->proplist, PA_PROP_DEVICE_DESCRIPTION, description);
1200     else
1201         pa_proplist_unset(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
1202
1203     if (s->monitor_source) {
1204         char *n;
1205
1206         n = pa_sprintf_malloc("Monitor Source of %s", description ? description : s->name);
1207         pa_source_set_description(s->monitor_source, n);
1208         pa_xfree(n);
1209     }
1210
1211     if (PA_SINK_IS_LINKED(s->state)) {
1212         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1213         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PROPLIST_CHANGED], s);
1214     }
1215 }
1216
1217 /* Called from main thread */
1218 unsigned pa_sink_linked_by(pa_sink *s) {
1219     unsigned ret;
1220
1221     pa_sink_assert_ref(s);
1222     pa_assert(PA_SINK_IS_LINKED(s->state));
1223
1224     ret = pa_idxset_size(s->inputs);
1225
1226     /* We add in the number of streams connected to us here. Please
1227      * note the asymmmetry to pa_sink_used_by()! */
1228
1229     if (s->monitor_source)
1230         ret += pa_source_linked_by(s->monitor_source);
1231
1232     return ret;
1233 }
1234
1235 /* Called from main thread */
1236 unsigned pa_sink_used_by(pa_sink *s) {
1237     unsigned ret;
1238
1239     pa_sink_assert_ref(s);
1240     pa_assert(PA_SINK_IS_LINKED(s->state));
1241
1242     ret = pa_idxset_size(s->inputs);
1243     pa_assert(ret >= s->n_corked);
1244
1245     /* Streams connected to our monitor source do not matter for
1246      * pa_sink_used_by()!.*/
1247
1248     return ret - s->n_corked;
1249 }
1250
1251 /* Called from main thread */
1252 unsigned pa_sink_check_suspend(pa_sink *s) {
1253     unsigned ret;
1254     pa_sink_input *i;
1255     uint32_t idx;
1256
1257     pa_sink_assert_ref(s);
1258
1259     if (!PA_SINK_IS_LINKED(s->state))
1260         return 0;
1261
1262     ret = 0;
1263
1264     for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx))) {
1265         pa_sink_input_state_t st;
1266
1267         st = pa_sink_input_get_state(i);
1268         pa_assert(PA_SINK_INPUT_IS_LINKED(st));
1269
1270         if (st == PA_SINK_INPUT_CORKED)
1271             continue;
1272
1273         if (i->flags & PA_SINK_INPUT_DONT_INHIBIT_AUTO_SUSPEND)
1274             continue;
1275
1276         ret ++;
1277     }
1278
1279     if (s->monitor_source)
1280         ret += pa_source_check_suspend(s->monitor_source);
1281
1282     return ret;
1283 }
1284
1285 /* Called from the IO thread */
1286 static void sync_input_volumes_within_thread(pa_sink *s) {
1287     pa_sink_input *i;
1288     void *state = NULL;
1289
1290     pa_sink_assert_ref(s);
1291
1292     while ((i = PA_SINK_INPUT(pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))) {
1293         if (pa_cvolume_equal(&i->thread_info.soft_volume, &i->soft_volume))
1294             continue;
1295
1296         i->thread_info.soft_volume = i->soft_volume;
1297         pa_sink_input_request_rewind(i, 0, TRUE, FALSE, FALSE);
1298     }
1299 }
1300
1301 /* Called from IO thread, except when it is not */
1302 int pa_sink_process_msg(pa_msgobject *o, int code, void *userdata, int64_t offset, pa_memchunk *chunk) {
1303     pa_sink *s = PA_SINK(o);
1304     pa_sink_assert_ref(s);
1305
1306     switch ((pa_sink_message_t) code) {
1307
1308         case PA_SINK_MESSAGE_ADD_INPUT: {
1309             pa_sink_input *i = PA_SINK_INPUT(userdata);
1310
1311             /* If you change anything here, make sure to change the
1312              * sink input handling a few lines down at
1313              * PA_SINK_MESSAGE_FINISH_MOVE, too. */
1314
1315             pa_hashmap_put(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index), pa_sink_input_ref(i));
1316
1317             /* Since the caller sleeps in pa_sink_input_put(), we can
1318              * safely access data outside of thread_info even though
1319              * it is mutable */
1320
1321             if ((i->thread_info.sync_prev = i->sync_prev)) {
1322                 pa_assert(i->sink == i->thread_info.sync_prev->sink);
1323                 pa_assert(i->sync_prev->sync_next == i);
1324                 i->thread_info.sync_prev->thread_info.sync_next = i;
1325             }
1326
1327             if ((i->thread_info.sync_next = i->sync_next)) {
1328                 pa_assert(i->sink == i->thread_info.sync_next->sink);
1329                 pa_assert(i->sync_next->sync_prev == i);
1330                 i->thread_info.sync_next->thread_info.sync_prev = i;
1331             }
1332
1333             pa_assert(!i->thread_info.attached);
1334             i->thread_info.attached = TRUE;
1335
1336             if (i->attach)
1337                 i->attach(i);
1338
1339             pa_sink_input_set_state_within_thread(i, i->state);
1340
1341             /* The requested latency of the sink input needs to be
1342              * fixed up and then configured on the sink */
1343
1344             if (i->thread_info.requested_sink_latency != (pa_usec_t) -1)
1345                 pa_sink_input_set_requested_latency_within_thread(i, i->thread_info.requested_sink_latency);
1346
1347             pa_sink_input_update_max_rewind(i, s->thread_info.max_rewind);
1348             pa_sink_input_update_max_request(i, s->thread_info.max_request);
1349
1350             /* We don't rewind here automatically. This is left to the
1351              * sink input implementor because some sink inputs need a
1352              * slow start, i.e. need some time to buffer client
1353              * samples before beginning streaming. */
1354
1355             /* In flat volume mode we need to update the volume as
1356              * well */
1357             return o->process_msg(o, PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL);
1358         }
1359
1360         case PA_SINK_MESSAGE_REMOVE_INPUT: {
1361             pa_sink_input *i = PA_SINK_INPUT(userdata);
1362
1363             /* If you change anything here, make sure to change the
1364              * sink input handling a few lines down at
1365              * PA_SINK_MESSAGE_PREPAPRE_MOVE, too. */
1366
1367             if (i->detach)
1368                 i->detach(i);
1369
1370             pa_sink_input_set_state_within_thread(i, i->state);
1371
1372             pa_assert(i->thread_info.attached);
1373             i->thread_info.attached = FALSE;
1374
1375             /* Since the caller sleeps in pa_sink_input_unlink(),
1376              * we can safely access data outside of thread_info even
1377              * though it is mutable */
1378
1379             pa_assert(!i->sync_prev);
1380             pa_assert(!i->sync_next);
1381
1382             if (i->thread_info.sync_prev) {
1383                 i->thread_info.sync_prev->thread_info.sync_next = i->thread_info.sync_prev->sync_next;
1384                 i->thread_info.sync_prev = NULL;
1385             }
1386
1387             if (i->thread_info.sync_next) {
1388                 i->thread_info.sync_next->thread_info.sync_prev = i->thread_info.sync_next->sync_prev;
1389                 i->thread_info.sync_next = NULL;
1390             }
1391
1392             if (pa_hashmap_remove(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index)))
1393                 pa_sink_input_unref(i);
1394
1395             pa_sink_invalidate_requested_latency(s);
1396             pa_sink_request_rewind(s, (size_t) -1);
1397
1398             /* In flat volume mode we need to update the volume as
1399              * well */
1400             return o->process_msg(o, PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL);
1401         }
1402
1403         case PA_SINK_MESSAGE_START_MOVE: {
1404             pa_sink_input *i = PA_SINK_INPUT(userdata);
1405
1406             /* We don't support moving synchronized streams. */
1407             pa_assert(!i->sync_prev);
1408             pa_assert(!i->sync_next);
1409             pa_assert(!i->thread_info.sync_next);
1410             pa_assert(!i->thread_info.sync_prev);
1411
1412             if (i->thread_info.state != PA_SINK_INPUT_CORKED) {
1413                 pa_usec_t usec = 0;
1414                 size_t sink_nbytes, total_nbytes;
1415
1416                 /* Get the latency of the sink */
1417                 if (!(s->flags & PA_SINK_LATENCY) ||
1418                     PA_MSGOBJECT(s)->process_msg(PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY, &usec, 0, NULL) < 0)
1419                     usec = 0;
1420
1421                 sink_nbytes = pa_usec_to_bytes(usec, &s->sample_spec);
1422                 total_nbytes = sink_nbytes + pa_memblockq_get_length(i->thread_info.render_memblockq);
1423
1424                 if (total_nbytes > 0) {
1425                     i->thread_info.rewrite_nbytes = i->thread_info.resampler ? pa_resampler_request(i->thread_info.resampler, total_nbytes) : total_nbytes;
1426                     i->thread_info.rewrite_flush = TRUE;
1427                     pa_sink_input_process_rewind(i, sink_nbytes);
1428                 }
1429             }
1430
1431             if (i->detach)
1432                 i->detach(i);
1433
1434             pa_assert(i->thread_info.attached);
1435             i->thread_info.attached = FALSE;
1436
1437             /* Let's remove the sink input ...*/
1438             if (pa_hashmap_remove(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index)))
1439                 pa_sink_input_unref(i);
1440
1441             pa_sink_invalidate_requested_latency(s);
1442
1443             pa_log_debug("Requesting rewind due to started move");
1444             pa_sink_request_rewind(s, (size_t) -1);
1445
1446             /* In flat volume mode we need to update the volume as
1447              * well */
1448             return o->process_msg(o, PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL);
1449         }
1450
1451         case PA_SINK_MESSAGE_FINISH_MOVE: {
1452             pa_sink_input *i = PA_SINK_INPUT(userdata);
1453
1454             /* We don't support moving synchronized streams. */
1455             pa_assert(!i->sync_prev);
1456             pa_assert(!i->sync_next);
1457             pa_assert(!i->thread_info.sync_next);
1458             pa_assert(!i->thread_info.sync_prev);
1459
1460             pa_hashmap_put(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index), pa_sink_input_ref(i));
1461
1462             pa_assert(!i->thread_info.attached);
1463             i->thread_info.attached = TRUE;
1464
1465             if (i->attach)
1466                 i->attach(i);
1467
1468             if (i->thread_info.requested_sink_latency != (pa_usec_t) -1)
1469                 pa_sink_input_set_requested_latency_within_thread(i, i->thread_info.requested_sink_latency);
1470
1471             pa_sink_input_update_max_rewind(i, s->thread_info.max_rewind);
1472             pa_sink_input_update_max_request(i, s->thread_info.max_request);
1473
1474             if (i->thread_info.state != PA_SINK_INPUT_CORKED) {
1475                 pa_usec_t usec = 0;
1476                 size_t nbytes;
1477
1478                 /* Get the latency of the sink */
1479                 if (!(s->flags & PA_SINK_LATENCY) ||
1480                     PA_MSGOBJECT(s)->process_msg(PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY, &usec, 0, NULL) < 0)
1481                     usec = 0;
1482
1483                 nbytes = pa_usec_to_bytes(usec, &s->sample_spec);
1484
1485                 if (nbytes > 0)
1486                     pa_sink_input_drop(i, nbytes);
1487
1488                 pa_log_debug("Requesting rewind due to finished move");
1489                 pa_sink_request_rewind(s, nbytes);
1490             }
1491
1492             /* In flat volume mode we need to update the volume as
1493              * well */
1494             return o->process_msg(o, PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL);
1495         }
1496
1497         case PA_SINK_MESSAGE_SET_VOLUME:
1498
1499             if (!pa_cvolume_equal(&s->thread_info.soft_volume, &s->soft_volume)) {
1500                 s->thread_info.soft_volume = s->soft_volume;
1501                 pa_sink_request_rewind(s, (size_t) -1);
1502             }
1503
1504             if (s->flags & PA_SINK_FLAT_VOLUME)
1505                 sync_input_volumes_within_thread(s);
1506
1507             return 0;
1508
1509         case PA_SINK_MESSAGE_GET_VOLUME:
1510             return 0;
1511
1512         case PA_SINK_MESSAGE_SET_MUTE:
1513
1514             if (s->thread_info.soft_muted != s->muted) {
1515                 s->thread_info.soft_muted = s->muted;
1516                 pa_sink_request_rewind(s, (size_t) -1);
1517             }
1518
1519             return 0;
1520
1521         case PA_SINK_MESSAGE_GET_MUTE:
1522             return 0;
1523
1524         case PA_SINK_MESSAGE_SET_STATE:
1525
1526             s->thread_info.state = PA_PTR_TO_UINT(userdata);
1527
1528             if (s->thread_info.state == PA_SINK_SUSPENDED)
1529                 s->thread_info.rewind_requested = FALSE;
1530
1531             return 0;
1532
1533         case PA_SINK_MESSAGE_DETACH:
1534
1535             /* Detach all streams */
1536             pa_sink_detach_within_thread(s);
1537             return 0;
1538
1539         case PA_SINK_MESSAGE_ATTACH:
1540
1541             /* Reattach all streams */
1542             pa_sink_attach_within_thread(s);
1543             return 0;
1544
1545         case PA_SINK_MESSAGE_GET_REQUESTED_LATENCY: {
1546
1547             pa_usec_t *usec = userdata;
1548             *usec = pa_sink_get_requested_latency_within_thread(s);
1549
1550             if (*usec == (pa_usec_t) -1)
1551                 *usec = s->thread_info.max_latency;
1552
1553             return 0;
1554         }
1555
1556         case PA_SINK_MESSAGE_SET_LATENCY_RANGE: {
1557             pa_usec_t *r = userdata;
1558
1559             pa_sink_update_latency_range(s, r[0], r[1]);
1560
1561             return 0;
1562         }
1563
1564         case PA_SINK_MESSAGE_GET_LATENCY_RANGE: {
1565             pa_usec_t *r = userdata;
1566
1567             r[0] = s->thread_info.min_latency;
1568             r[1] = s->thread_info.max_latency;
1569
1570             return 0;
1571         }
1572
1573         case PA_SINK_MESSAGE_GET_MAX_REWIND:
1574
1575             *((size_t*) userdata) = s->thread_info.max_rewind;
1576             return 0;
1577
1578         case PA_SINK_MESSAGE_GET_MAX_REQUEST:
1579
1580             *((size_t*) userdata) = s->thread_info.max_request;
1581             return 0;
1582
1583         case PA_SINK_MESSAGE_GET_LATENCY:
1584         case PA_SINK_MESSAGE_MAX:
1585             ;
1586     }
1587
1588     return -1;
1589 }
1590
1591 /* Called from main thread */
1592 int pa_sink_suspend_all(pa_core *c, pa_bool_t suspend) {
1593     pa_sink *sink;
1594     uint32_t idx;
1595     int ret = 0;
1596
1597     pa_core_assert_ref(c);
1598
1599     for (sink = PA_SINK(pa_idxset_first(c->sinks, &idx)); sink; sink = PA_SINK(pa_idxset_next(c->sinks, &idx)))
1600         ret -= pa_sink_suspend(sink, suspend) < 0;
1601
1602     return ret;
1603 }
1604
1605 /* Called from main thread */
1606 void pa_sink_detach(pa_sink *s) {
1607     pa_sink_assert_ref(s);
1608     pa_assert(PA_SINK_IS_LINKED(s->state));
1609
1610     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_DETACH, NULL, 0, NULL) == 0);
1611 }
1612
1613 /* Called from main thread */
1614 void pa_sink_attach(pa_sink *s) {
1615     pa_sink_assert_ref(s);
1616     pa_assert(PA_SINK_IS_LINKED(s->state));
1617
1618     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_ATTACH, NULL, 0, NULL) == 0);
1619 }
1620
1621 /* Called from IO thread */
1622 void pa_sink_detach_within_thread(pa_sink *s) {
1623     pa_sink_input *i;
1624     void *state = NULL;
1625
1626     pa_sink_assert_ref(s);
1627     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1628
1629     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1630         if (i->detach)
1631             i->detach(i);
1632
1633     if (s->monitor_source)
1634         pa_source_detach_within_thread(s->monitor_source);
1635 }
1636
1637 /* Called from IO thread */
1638 void pa_sink_attach_within_thread(pa_sink *s) {
1639     pa_sink_input *i;
1640     void *state = NULL;
1641
1642     pa_sink_assert_ref(s);
1643     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1644
1645     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1646         if (i->attach)
1647             i->attach(i);
1648
1649     if (s->monitor_source)
1650         pa_source_attach_within_thread(s->monitor_source);
1651 }
1652
1653 /* Called from IO thread */
1654 void pa_sink_request_rewind(pa_sink*s, size_t nbytes) {
1655     pa_sink_assert_ref(s);
1656     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1657
1658     if (s->thread_info.state == PA_SINK_SUSPENDED)
1659         return;
1660
1661     if (nbytes == (size_t) -1)
1662         nbytes = s->thread_info.max_rewind;
1663
1664     nbytes = PA_MIN(nbytes, s->thread_info.max_rewind);
1665
1666     if (s->thread_info.rewind_requested &&
1667         nbytes <= s->thread_info.rewind_nbytes)
1668         return;
1669
1670     s->thread_info.rewind_nbytes = nbytes;
1671     s->thread_info.rewind_requested = TRUE;
1672
1673     if (s->request_rewind)
1674         s->request_rewind(s);
1675 }
1676
1677 /* Called from IO thread */
1678 pa_usec_t pa_sink_get_requested_latency_within_thread(pa_sink *s) {
1679     pa_usec_t result = (pa_usec_t) -1;
1680     pa_sink_input *i;
1681     void *state = NULL;
1682     pa_usec_t monitor_latency;
1683
1684     pa_sink_assert_ref(s);
1685
1686     if (s->thread_info.requested_latency_valid)
1687         return s->thread_info.requested_latency;
1688
1689     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1690
1691         if (i->thread_info.requested_sink_latency != (pa_usec_t) -1 &&
1692             (result == (pa_usec_t) -1 || result > i->thread_info.requested_sink_latency))
1693             result = i->thread_info.requested_sink_latency;
1694
1695     monitor_latency = pa_source_get_requested_latency_within_thread(s->monitor_source);
1696
1697     if (monitor_latency != (pa_usec_t) -1 &&
1698         (result == (pa_usec_t) -1 || result > monitor_latency))
1699         result = monitor_latency;
1700
1701     if (result != (pa_usec_t) -1) {
1702         if (s->thread_info.max_latency > 0 && result > s->thread_info.max_latency)
1703             result = s->thread_info.max_latency;
1704
1705         if (s->thread_info.min_latency > 0 && result < s->thread_info.min_latency)
1706             result = s->thread_info.min_latency;
1707     }
1708
1709     s->thread_info.requested_latency = result;
1710     s->thread_info.requested_latency_valid = TRUE;
1711
1712     return result;
1713 }
1714
1715 /* Called from main thread */
1716 pa_usec_t pa_sink_get_requested_latency(pa_sink *s) {
1717     pa_usec_t usec = 0;
1718
1719     pa_sink_assert_ref(s);
1720     pa_assert(PA_SINK_IS_LINKED(s->state));
1721
1722     if (s->state == PA_SINK_SUSPENDED)
1723         return 0;
1724
1725     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_REQUESTED_LATENCY, &usec, 0, NULL) == 0);
1726     return usec;
1727 }
1728
1729 /* Called from IO thread */
1730 void pa_sink_set_max_rewind(pa_sink *s, size_t max_rewind) {
1731     pa_sink_input *i;
1732     void *state = NULL;
1733
1734     pa_sink_assert_ref(s);
1735
1736     if (max_rewind == s->thread_info.max_rewind)
1737         return;
1738
1739     s->thread_info.max_rewind = max_rewind;
1740
1741     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
1742         while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1743             pa_sink_input_update_max_rewind(i, s->thread_info.max_rewind);
1744     }
1745
1746     if (s->monitor_source)
1747         pa_source_set_max_rewind(s->monitor_source, s->thread_info.max_rewind);
1748 }
1749
1750 /* Called from IO thread */
1751 void pa_sink_set_max_request(pa_sink *s, size_t max_request) {
1752     void *state = NULL;
1753
1754     pa_sink_assert_ref(s);
1755
1756     if (max_request == s->thread_info.max_request)
1757         return;
1758
1759     s->thread_info.max_request = max_request;
1760
1761     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
1762         pa_sink_input *i;
1763
1764         while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1765             pa_sink_input_update_max_request(i, s->thread_info.max_request);
1766     }
1767 }
1768
1769 /* Called from IO thread */
1770 void pa_sink_invalidate_requested_latency(pa_sink *s) {
1771     pa_sink_input *i;
1772     void *state = NULL;
1773
1774     pa_sink_assert_ref(s);
1775
1776     s->thread_info.requested_latency_valid = FALSE;
1777
1778     if (s->update_requested_latency)
1779         s->update_requested_latency(s);
1780
1781     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1782         if (i->update_sink_requested_latency)
1783             i->update_sink_requested_latency(i);
1784 }
1785
1786 /* Called from main thread */
1787 void pa_sink_set_latency_range(pa_sink *s, pa_usec_t min_latency, pa_usec_t max_latency) {
1788     pa_sink_assert_ref(s);
1789
1790     /* min_latency == 0:           no limit
1791      * min_latency == (size_t) -1: default limit
1792      * min_latency anything else:  specified limit
1793      *
1794      * Similar for max_latency */
1795
1796     if (min_latency == (pa_usec_t) -1)
1797         min_latency = DEFAULT_MIN_LATENCY;
1798
1799     if (max_latency == (pa_usec_t) -1)
1800         max_latency = min_latency;
1801
1802     pa_assert(!min_latency || !max_latency ||
1803               min_latency <= max_latency);
1804
1805     if (PA_SINK_IS_LINKED(s->state)) {
1806         pa_usec_t r[2];
1807
1808         r[0] = min_latency;
1809         r[1] = max_latency;
1810
1811         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_LATENCY_RANGE, r, 0, NULL) == 0);
1812     } else {
1813         s->thread_info.min_latency = min_latency;
1814         s->thread_info.max_latency = max_latency;
1815
1816         s->monitor_source->thread_info.min_latency = min_latency;
1817         s->monitor_source->thread_info.max_latency = max_latency;
1818
1819         s->thread_info.requested_latency_valid = s->monitor_source->thread_info.requested_latency_valid = FALSE;
1820     }
1821 }
1822
1823 /* Called from main thread */
1824 void pa_sink_get_latency_range(pa_sink *s, pa_usec_t *min_latency, pa_usec_t *max_latency) {
1825    pa_sink_assert_ref(s);
1826    pa_assert(min_latency);
1827    pa_assert(max_latency);
1828
1829    if (PA_SINK_IS_LINKED(s->state)) {
1830        pa_usec_t r[2] = { 0, 0 };
1831
1832        pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY_RANGE, r, 0, NULL) == 0);
1833
1834        *min_latency = r[0];
1835        *max_latency = r[1];
1836    } else {
1837        *min_latency = s->thread_info.min_latency;
1838        *max_latency = s->thread_info.max_latency;
1839    }
1840 }
1841
1842 /* Called from IO thread */
1843 void pa_sink_update_latency_range(pa_sink *s, pa_usec_t min_latency, pa_usec_t max_latency) {
1844     pa_sink_input *i;
1845     void *state = NULL;
1846
1847     pa_sink_assert_ref(s);
1848
1849     pa_assert(!min_latency || !max_latency ||
1850               min_latency <= max_latency);
1851
1852     s->thread_info.min_latency = min_latency;
1853     s->thread_info.max_latency = max_latency;
1854
1855     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
1856         if (i->update_sink_latency_range)
1857             i->update_sink_latency_range(i);
1858
1859     pa_sink_invalidate_requested_latency(s);
1860
1861     pa_source_update_latency_range(s->monitor_source, min_latency, max_latency);
1862 }
1863
1864 /* Called from main context */
1865 size_t pa_sink_get_max_rewind(pa_sink *s) {
1866     size_t r;
1867     pa_sink_assert_ref(s);
1868
1869     if (!PA_SINK_IS_LINKED(s->state))
1870         return s->thread_info.max_rewind;
1871
1872     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_MAX_REWIND, &r, 0, NULL) == 0);
1873
1874     return r;
1875 }
1876
1877 /* Called from main context */
1878 size_t pa_sink_get_max_request(pa_sink *s) {
1879     size_t r;
1880     pa_sink_assert_ref(s);
1881
1882     if (!PA_SINK_IS_LINKED(s->state))
1883         return s->thread_info.max_request;
1884
1885     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_MAX_REQUEST, &r, 0, NULL) == 0);
1886
1887     return r;
1888 }