replace sink/source SET_STATE handlers with callbacks
[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.1 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, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28
29 #include <pulse/introspect.h>
30 #include <pulse/format.h>
31 #include <pulse/utf8.h>
32 #include <pulse/xmalloc.h>
33 #include <pulse/timeval.h>
34 #include <pulse/util.h>
35 #include <pulse/rtclock.h>
36 #include <pulse/internal.h>
37
38 #include <pulsecore/i18n.h>
39 #include <pulsecore/sink-input.h>
40 #include <pulsecore/namereg.h>
41 #include <pulsecore/core-util.h>
42 #include <pulsecore/sample-util.h>
43 #include <pulsecore/mix.h>
44 #include <pulsecore/core-subscribe.h>
45 #include <pulsecore/log.h>
46 #include <pulsecore/macro.h>
47 #include <pulsecore/play-memblockq.h>
48 #include <pulsecore/flist.h>
49
50 #include "sink.h"
51
52 #define MAX_MIX_CHANNELS 32
53 #define MIX_BUFFER_LENGTH (pa_page_size())
54 #define ABSOLUTE_MIN_LATENCY (500)
55 #define ABSOLUTE_MAX_LATENCY (10*PA_USEC_PER_SEC)
56 #define DEFAULT_FIXED_LATENCY (250*PA_USEC_PER_MSEC)
57
58 PA_DEFINE_PUBLIC_CLASS(pa_sink, pa_msgobject);
59
60 struct pa_sink_volume_change {
61     pa_usec_t at;
62     pa_cvolume hw_volume;
63
64     PA_LLIST_FIELDS(pa_sink_volume_change);
65 };
66
67 struct sink_message_set_port {
68     pa_device_port *port;
69     int ret;
70 };
71
72 static void sink_free(pa_object *s);
73
74 static void pa_sink_volume_change_push(pa_sink *s);
75 static void pa_sink_volume_change_flush(pa_sink *s);
76 static void pa_sink_volume_change_rewind(pa_sink *s, size_t nbytes);
77
78 pa_sink_new_data* pa_sink_new_data_init(pa_sink_new_data *data) {
79     pa_assert(data);
80
81     pa_zero(*data);
82     data->proplist = pa_proplist_new();
83     data->ports = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) pa_device_port_unref);
84
85     return data;
86 }
87
88 void pa_sink_new_data_set_name(pa_sink_new_data *data, const char *name) {
89     pa_assert(data);
90
91     pa_xfree(data->name);
92     data->name = pa_xstrdup(name);
93 }
94
95 void pa_sink_new_data_set_sample_spec(pa_sink_new_data *data, const pa_sample_spec *spec) {
96     pa_assert(data);
97
98     if ((data->sample_spec_is_set = !!spec))
99         data->sample_spec = *spec;
100 }
101
102 void pa_sink_new_data_set_channel_map(pa_sink_new_data *data, const pa_channel_map *map) {
103     pa_assert(data);
104
105     if ((data->channel_map_is_set = !!map))
106         data->channel_map = *map;
107 }
108
109 void pa_sink_new_data_set_alternate_sample_rate(pa_sink_new_data *data, const uint32_t alternate_sample_rate) {
110     pa_assert(data);
111
112     data->alternate_sample_rate_is_set = true;
113     data->alternate_sample_rate = alternate_sample_rate;
114 }
115
116 void pa_sink_new_data_set_volume(pa_sink_new_data *data, const pa_cvolume *volume) {
117     pa_assert(data);
118
119     if ((data->volume_is_set = !!volume))
120         data->volume = *volume;
121 }
122
123 void pa_sink_new_data_set_muted(pa_sink_new_data *data, bool mute) {
124     pa_assert(data);
125
126     data->muted_is_set = true;
127     data->muted = mute;
128 }
129
130 void pa_sink_new_data_set_port(pa_sink_new_data *data, const char *port) {
131     pa_assert(data);
132
133     pa_xfree(data->active_port);
134     data->active_port = pa_xstrdup(port);
135 }
136
137 void pa_sink_new_data_done(pa_sink_new_data *data) {
138     pa_assert(data);
139
140     pa_proplist_free(data->proplist);
141
142     if (data->ports)
143         pa_hashmap_free(data->ports);
144
145     pa_xfree(data->name);
146     pa_xfree(data->active_port);
147 }
148
149 /* Called from main context */
150 static void reset_callbacks(pa_sink *s) {
151     pa_assert(s);
152
153     s->set_state_in_main_thread = NULL;
154     s->set_state_in_io_thread = NULL;
155     s->get_volume = NULL;
156     s->set_volume = NULL;
157     s->write_volume = NULL;
158     s->get_mute = NULL;
159     s->set_mute = NULL;
160     s->request_rewind = NULL;
161     s->update_requested_latency = NULL;
162     s->set_port = NULL;
163     s->get_formats = NULL;
164     s->set_formats = NULL;
165     s->reconfigure = NULL;
166 }
167
168 /* Called from main context */
169 pa_sink* pa_sink_new(
170         pa_core *core,
171         pa_sink_new_data *data,
172         pa_sink_flags_t flags) {
173
174     pa_sink *s;
175     const char *name;
176     char st[PA_SAMPLE_SPEC_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX];
177     pa_source_new_data source_data;
178     const char *dn;
179     char *pt;
180
181     pa_assert(core);
182     pa_assert(data);
183     pa_assert(data->name);
184     pa_assert_ctl_context();
185
186     s = pa_msgobject_new(pa_sink);
187
188     if (!(name = pa_namereg_register(core, data->name, PA_NAMEREG_SINK, s, data->namereg_fail))) {
189         pa_log_debug("Failed to register name %s.", data->name);
190         pa_xfree(s);
191         return NULL;
192     }
193
194     pa_sink_new_data_set_name(data, name);
195
196     if (pa_hook_fire(&core->hooks[PA_CORE_HOOK_SINK_NEW], data) < 0) {
197         pa_xfree(s);
198         pa_namereg_unregister(core, name);
199         return NULL;
200     }
201
202     /* FIXME, need to free s here on failure */
203
204     pa_return_null_if_fail(!data->driver || pa_utf8_valid(data->driver));
205     pa_return_null_if_fail(data->name && pa_utf8_valid(data->name) && data->name[0]);
206
207     pa_return_null_if_fail(data->sample_spec_is_set && pa_sample_spec_valid(&data->sample_spec));
208
209     if (!data->channel_map_is_set)
210         pa_return_null_if_fail(pa_channel_map_init_auto(&data->channel_map, data->sample_spec.channels, PA_CHANNEL_MAP_DEFAULT));
211
212     pa_return_null_if_fail(pa_channel_map_valid(&data->channel_map));
213     pa_return_null_if_fail(data->channel_map.channels == data->sample_spec.channels);
214
215     /* FIXME: There should probably be a general function for checking whether
216      * the sink volume is allowed to be set, like there is for sink inputs. */
217     pa_assert(!data->volume_is_set || !(flags & PA_SINK_SHARE_VOLUME_WITH_MASTER));
218
219     if (!data->volume_is_set) {
220         pa_cvolume_reset(&data->volume, data->sample_spec.channels);
221         data->save_volume = false;
222     }
223
224     pa_return_null_if_fail(pa_cvolume_valid(&data->volume));
225     pa_return_null_if_fail(pa_cvolume_compatible(&data->volume, &data->sample_spec));
226
227     if (!data->muted_is_set)
228         data->muted = false;
229
230     if (data->card)
231         pa_proplist_update(data->proplist, PA_UPDATE_MERGE, data->card->proplist);
232
233     pa_device_init_description(data->proplist, data->card);
234     pa_device_init_icon(data->proplist, true);
235     pa_device_init_intended_roles(data->proplist);
236
237     if (!data->active_port) {
238         pa_device_port *p = pa_device_port_find_best(data->ports);
239         if (p)
240             pa_sink_new_data_set_port(data, p->name);
241     }
242
243     if (pa_hook_fire(&core->hooks[PA_CORE_HOOK_SINK_FIXATE], data) < 0) {
244         pa_xfree(s);
245         pa_namereg_unregister(core, name);
246         return NULL;
247     }
248
249     s->parent.parent.free = sink_free;
250     s->parent.process_msg = pa_sink_process_msg;
251
252     s->core = core;
253     s->state = PA_SINK_INIT;
254     s->flags = flags;
255     s->priority = 0;
256     s->suspend_cause = data->suspend_cause;
257     pa_sink_set_mixer_dirty(s, false);
258     s->name = pa_xstrdup(name);
259     s->proplist = pa_proplist_copy(data->proplist);
260     s->driver = pa_xstrdup(pa_path_get_filename(data->driver));
261     s->module = data->module;
262     s->card = data->card;
263
264     s->priority = pa_device_init_priority(s->proplist);
265
266     s->sample_spec = data->sample_spec;
267     s->channel_map = data->channel_map;
268     s->default_sample_rate = s->sample_spec.rate;
269
270     if (data->alternate_sample_rate_is_set)
271         s->alternate_sample_rate = data->alternate_sample_rate;
272     else
273         s->alternate_sample_rate = s->core->alternate_sample_rate;
274
275     if (s->sample_spec.rate == s->alternate_sample_rate) {
276         pa_log_warn("Default and alternate sample rates are the same.");
277         s->alternate_sample_rate = 0;
278     }
279
280     s->inputs = pa_idxset_new(NULL, NULL);
281     s->n_corked = 0;
282     s->input_to_master = NULL;
283
284     s->reference_volume = s->real_volume = data->volume;
285     pa_cvolume_reset(&s->soft_volume, s->sample_spec.channels);
286     s->base_volume = PA_VOLUME_NORM;
287     s->n_volume_steps = PA_VOLUME_NORM+1;
288     s->muted = data->muted;
289     s->refresh_volume = s->refresh_muted = false;
290
291     reset_callbacks(s);
292     s->userdata = NULL;
293
294     s->asyncmsgq = NULL;
295
296     /* As a minor optimization we just steal the list instead of
297      * copying it here */
298     s->ports = data->ports;
299     data->ports = NULL;
300
301     s->active_port = NULL;
302     s->save_port = false;
303
304     if (data->active_port)
305         if ((s->active_port = pa_hashmap_get(s->ports, data->active_port)))
306             s->save_port = data->save_port;
307
308     /* Hopefully the active port has already been assigned in the previous call
309        to pa_device_port_find_best, but better safe than sorry */
310     if (!s->active_port)
311         s->active_port = pa_device_port_find_best(s->ports);
312
313     if (s->active_port)
314         s->port_latency_offset = s->active_port->latency_offset;
315     else
316         s->port_latency_offset = 0;
317
318     s->save_volume = data->save_volume;
319     s->save_muted = data->save_muted;
320
321     pa_silence_memchunk_get(
322             &core->silence_cache,
323             core->mempool,
324             &s->silence,
325             &s->sample_spec,
326             0);
327
328     s->thread_info.rtpoll = NULL;
329     s->thread_info.inputs = pa_hashmap_new_full(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func, NULL,
330                                                 (pa_free_cb_t) pa_sink_input_unref);
331     s->thread_info.soft_volume =  s->soft_volume;
332     s->thread_info.soft_muted = s->muted;
333     s->thread_info.state = s->state;
334     s->thread_info.rewind_nbytes = 0;
335     s->thread_info.rewind_requested = false;
336     s->thread_info.max_rewind = 0;
337     s->thread_info.max_request = 0;
338     s->thread_info.requested_latency_valid = false;
339     s->thread_info.requested_latency = 0;
340     s->thread_info.min_latency = ABSOLUTE_MIN_LATENCY;
341     s->thread_info.max_latency = ABSOLUTE_MAX_LATENCY;
342     s->thread_info.fixed_latency = flags & PA_SINK_DYNAMIC_LATENCY ? 0 : DEFAULT_FIXED_LATENCY;
343
344     PA_LLIST_HEAD_INIT(pa_sink_volume_change, s->thread_info.volume_changes);
345     s->thread_info.volume_changes_tail = NULL;
346     pa_sw_cvolume_divide(&s->thread_info.current_hw_volume, &s->real_volume, &s->soft_volume);
347     s->thread_info.volume_change_safety_margin = core->deferred_volume_safety_margin_usec;
348     s->thread_info.volume_change_extra_delay = core->deferred_volume_extra_delay_usec;
349     s->thread_info.port_latency_offset = s->port_latency_offset;
350
351     /* FIXME: This should probably be moved to pa_sink_put() */
352     pa_assert_se(pa_idxset_put(core->sinks, s, &s->index) >= 0);
353
354     if (s->card)
355         pa_assert_se(pa_idxset_put(s->card->sinks, s, NULL) >= 0);
356
357     pt = pa_proplist_to_string_sep(s->proplist, "\n    ");
358     pa_log_info("Created sink %u \"%s\" with sample spec %s and channel map %s\n    %s",
359                 s->index,
360                 s->name,
361                 pa_sample_spec_snprint(st, sizeof(st), &s->sample_spec),
362                 pa_channel_map_snprint(cm, sizeof(cm), &s->channel_map),
363                 pt);
364     pa_xfree(pt);
365
366     pa_source_new_data_init(&source_data);
367     pa_source_new_data_set_sample_spec(&source_data, &s->sample_spec);
368     pa_source_new_data_set_channel_map(&source_data, &s->channel_map);
369     pa_source_new_data_set_alternate_sample_rate(&source_data, s->alternate_sample_rate);
370     source_data.name = pa_sprintf_malloc("%s.monitor", name);
371     source_data.driver = data->driver;
372     source_data.module = data->module;
373     source_data.card = data->card;
374
375     dn = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
376     pa_proplist_setf(source_data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Monitor of %s", dn ? dn : s->name);
377     pa_proplist_sets(source_data.proplist, PA_PROP_DEVICE_CLASS, "monitor");
378
379     s->monitor_source = pa_source_new(core, &source_data,
380                                       ((flags & PA_SINK_LATENCY) ? PA_SOURCE_LATENCY : 0) |
381                                       ((flags & PA_SINK_DYNAMIC_LATENCY) ? PA_SOURCE_DYNAMIC_LATENCY : 0));
382
383     pa_source_new_data_done(&source_data);
384
385     if (!s->monitor_source) {
386         pa_sink_unlink(s);
387         pa_sink_unref(s);
388         return NULL;
389     }
390
391     s->monitor_source->monitor_of = s;
392
393     pa_source_set_latency_range(s->monitor_source, s->thread_info.min_latency, s->thread_info.max_latency);
394     pa_source_set_fixed_latency(s->monitor_source, s->thread_info.fixed_latency);
395     pa_source_set_max_rewind(s->monitor_source, s->thread_info.max_rewind);
396
397     return s;
398 }
399
400 /* Called from main context */
401 static int sink_set_state(pa_sink *s, pa_sink_state_t state, pa_suspend_cause_t suspend_cause) {
402     int ret = 0;
403     bool state_changed;
404     bool suspend_cause_changed;
405     bool suspending;
406     bool resuming;
407
408     pa_assert(s);
409     pa_assert_ctl_context();
410
411     state_changed = state != s->state;
412     suspend_cause_changed = suspend_cause != s->suspend_cause;
413
414     if (!state_changed && !suspend_cause_changed)
415         return 0;
416
417     suspending = PA_SINK_IS_OPENED(s->state) && state == PA_SINK_SUSPENDED;
418     resuming = s->state == PA_SINK_SUSPENDED && PA_SINK_IS_OPENED(state);
419
420     /* If we are resuming, suspend_cause must be 0. */
421     pa_assert(!resuming || !suspend_cause);
422
423     /* Here's something to think about: what to do with the suspend cause if
424      * resuming the sink fails? The old suspend cause will be incorrect, so we
425      * can't use that. On the other hand, if we set no suspend cause (as is the
426      * case currently), then it looks strange to have a sink suspended without
427      * any cause. It might be a good idea to add a new "resume failed" suspend
428      * cause, or it might just add unnecessary complexity, given that the
429      * current approach of not setting any suspend cause works well enough. */
430
431     if (s->set_state_in_main_thread) {
432         ret = s->set_state_in_main_thread(s, state, suspend_cause);
433         /* set_state_in_main_thread() is allowed to fail only when resuming. */
434         pa_assert(ret >= 0 || resuming);
435     }
436
437     if (ret >= 0 && s->asyncmsgq && state_changed)
438         if ((ret = pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_STATE, PA_UINT_TO_PTR(state), 0, NULL)) < 0) {
439             /* SET_STATE is allowed to fail only when resuming. */
440             pa_assert(resuming);
441
442             if (s->set_state_in_main_thread)
443                 s->set_state_in_main_thread(s, PA_SINK_SUSPENDED, 0);
444         }
445
446     if (suspend_cause_changed) {
447         char old_cause_buf[PA_SUSPEND_CAUSE_TO_STRING_BUF_SIZE];
448         char new_cause_buf[PA_SUSPEND_CAUSE_TO_STRING_BUF_SIZE];
449
450         pa_log_debug("%s: suspend_cause: %s -> %s", s->name, pa_suspend_cause_to_string(s->suspend_cause, old_cause_buf),
451                      pa_suspend_cause_to_string(suspend_cause, new_cause_buf));
452         s->suspend_cause = suspend_cause;
453     }
454
455     if (ret < 0)
456         goto finish;
457
458     if (state_changed) {
459         pa_log_debug("%s: state: %s -> %s", s->name, pa_sink_state_to_string(s->state), pa_sink_state_to_string(state));
460         s->state = state;
461
462         /* If we enter UNLINKED state, then we don't send change notifications.
463          * pa_sink_unlink() will send unlink notifications instead. */
464         if (state != PA_SINK_UNLINKED) {
465             pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_STATE_CHANGED], s);
466             pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
467         }
468     }
469
470     if (suspending || resuming) {
471         pa_sink_input *i;
472         uint32_t idx;
473
474         /* We're suspending or resuming, tell everyone about it */
475
476         PA_IDXSET_FOREACH(i, s->inputs, idx)
477             if (s->state == PA_SINK_SUSPENDED &&
478                 (i->flags & PA_SINK_INPUT_KILL_ON_SUSPEND))
479                 pa_sink_input_kill(i);
480             else if (i->suspend)
481                 i->suspend(i, state == PA_SINK_SUSPENDED);
482     }
483
484 finish:
485     if ((suspending || resuming || suspend_cause_changed) && s->monitor_source && state != PA_SINK_UNLINKED)
486         pa_source_sync_suspend(s->monitor_source);
487
488     return ret;
489 }
490
491 void pa_sink_set_get_volume_callback(pa_sink *s, pa_sink_cb_t cb) {
492     pa_assert(s);
493
494     s->get_volume = cb;
495 }
496
497 void pa_sink_set_set_volume_callback(pa_sink *s, pa_sink_cb_t cb) {
498     pa_sink_flags_t flags;
499
500     pa_assert(s);
501     pa_assert(!s->write_volume || cb);
502
503     s->set_volume = cb;
504
505     /* Save the current flags so we can tell if they've changed */
506     flags = s->flags;
507
508     if (cb) {
509         /* The sink implementor is responsible for setting decibel volume support */
510         s->flags |= PA_SINK_HW_VOLUME_CTRL;
511     } else {
512         s->flags &= ~PA_SINK_HW_VOLUME_CTRL;
513         /* See note below in pa_sink_put() about volume sharing and decibel volumes */
514         pa_sink_enable_decibel_volume(s, !(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER));
515     }
516
517     /* If the flags have changed after init, let any clients know via a change event */
518     if (s->state != PA_SINK_INIT && flags != s->flags)
519         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
520 }
521
522 void pa_sink_set_write_volume_callback(pa_sink *s, pa_sink_cb_t cb) {
523     pa_sink_flags_t flags;
524
525     pa_assert(s);
526     pa_assert(!cb || s->set_volume);
527
528     s->write_volume = cb;
529
530     /* Save the current flags so we can tell if they've changed */
531     flags = s->flags;
532
533     if (cb)
534         s->flags |= PA_SINK_DEFERRED_VOLUME;
535     else
536         s->flags &= ~PA_SINK_DEFERRED_VOLUME;
537
538     /* If the flags have changed after init, let any clients know via a change event */
539     if (s->state != PA_SINK_INIT && flags != s->flags)
540         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
541 }
542
543 void pa_sink_set_get_mute_callback(pa_sink *s, pa_sink_get_mute_cb_t cb) {
544     pa_assert(s);
545
546     s->get_mute = cb;
547 }
548
549 void pa_sink_set_set_mute_callback(pa_sink *s, pa_sink_cb_t cb) {
550     pa_sink_flags_t flags;
551
552     pa_assert(s);
553
554     s->set_mute = cb;
555
556     /* Save the current flags so we can tell if they've changed */
557     flags = s->flags;
558
559     if (cb)
560         s->flags |= PA_SINK_HW_MUTE_CTRL;
561     else
562         s->flags &= ~PA_SINK_HW_MUTE_CTRL;
563
564     /* If the flags have changed after init, let any clients know via a change event */
565     if (s->state != PA_SINK_INIT && flags != s->flags)
566         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
567 }
568
569 static void enable_flat_volume(pa_sink *s, bool enable) {
570     pa_sink_flags_t flags;
571
572     pa_assert(s);
573
574     /* Always follow the overall user preference here */
575     enable = enable && s->core->flat_volumes;
576
577     /* Save the current flags so we can tell if they've changed */
578     flags = s->flags;
579
580     if (enable)
581         s->flags |= PA_SINK_FLAT_VOLUME;
582     else
583         s->flags &= ~PA_SINK_FLAT_VOLUME;
584
585     /* If the flags have changed after init, let any clients know via a change event */
586     if (s->state != PA_SINK_INIT && flags != s->flags)
587         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
588 }
589
590 void pa_sink_enable_decibel_volume(pa_sink *s, bool enable) {
591     pa_sink_flags_t flags;
592
593     pa_assert(s);
594
595     /* Save the current flags so we can tell if they've changed */
596     flags = s->flags;
597
598     if (enable) {
599         s->flags |= PA_SINK_DECIBEL_VOLUME;
600         enable_flat_volume(s, true);
601     } else {
602         s->flags &= ~PA_SINK_DECIBEL_VOLUME;
603         enable_flat_volume(s, false);
604     }
605
606     /* If the flags have changed after init, let any clients know via a change event */
607     if (s->state != PA_SINK_INIT && flags != s->flags)
608         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
609 }
610
611 /* Called from main context */
612 void pa_sink_put(pa_sink* s) {
613     pa_sink_assert_ref(s);
614     pa_assert_ctl_context();
615
616     pa_assert(s->state == PA_SINK_INIT);
617     pa_assert(!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER) || pa_sink_is_filter(s));
618
619     /* The following fields must be initialized properly when calling _put() */
620     pa_assert(s->asyncmsgq);
621     pa_assert(s->thread_info.min_latency <= s->thread_info.max_latency);
622
623     /* Generally, flags should be initialized via pa_sink_new(). As a
624      * special exception we allow some volume related flags to be set
625      * between _new() and _put() by the callback setter functions above.
626      *
627      * Thus we implement a couple safeguards here which ensure the above
628      * setters were used (or at least the implementor made manual changes
629      * in a compatible way).
630      *
631      * Note: All of these flags set here can change over the life time
632      * of the sink. */
633     pa_assert(!(s->flags & PA_SINK_HW_VOLUME_CTRL) || s->set_volume);
634     pa_assert(!(s->flags & PA_SINK_DEFERRED_VOLUME) || s->write_volume);
635     pa_assert(!(s->flags & PA_SINK_HW_MUTE_CTRL) || s->set_mute);
636
637     /* XXX: Currently decibel volume is disabled for all sinks that use volume
638      * sharing. When the master sink supports decibel volume, it would be good
639      * to have the flag also in the filter sink, but currently we don't do that
640      * so that the flags of the filter sink never change when it's moved from
641      * a master sink to another. One solution for this problem would be to
642      * remove user-visible volume altogether from filter sinks when volume
643      * sharing is used, but the current approach was easier to implement... */
644     /* We always support decibel volumes in software, otherwise we leave it to
645      * the sink implementor to set this flag as needed.
646      *
647      * Note: This flag can also change over the life time of the sink. */
648     if (!(s->flags & PA_SINK_HW_VOLUME_CTRL) && !(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
649         pa_sink_enable_decibel_volume(s, true);
650         s->soft_volume = s->reference_volume;
651     }
652
653     /* If the sink implementor support DB volumes by itself, we should always
654      * try and enable flat volumes too */
655     if ((s->flags & PA_SINK_DECIBEL_VOLUME))
656         enable_flat_volume(s, true);
657
658     if (s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER) {
659         pa_sink *root_sink = pa_sink_get_master(s);
660
661         pa_assert(root_sink);
662
663         s->reference_volume = root_sink->reference_volume;
664         pa_cvolume_remap(&s->reference_volume, &root_sink->channel_map, &s->channel_map);
665
666         s->real_volume = root_sink->real_volume;
667         pa_cvolume_remap(&s->real_volume, &root_sink->channel_map, &s->channel_map);
668     } else
669         /* We assume that if the sink implementor changed the default
670          * volume he did so in real_volume, because that is the usual
671          * place where he is supposed to place his changes.  */
672         s->reference_volume = s->real_volume;
673
674     s->thread_info.soft_volume = s->soft_volume;
675     s->thread_info.soft_muted = s->muted;
676     pa_sw_cvolume_divide(&s->thread_info.current_hw_volume, &s->real_volume, &s->soft_volume);
677
678     pa_assert((s->flags & PA_SINK_HW_VOLUME_CTRL)
679               || (s->base_volume == PA_VOLUME_NORM
680                   && ((s->flags & PA_SINK_DECIBEL_VOLUME || (s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)))));
681     pa_assert(!(s->flags & PA_SINK_DECIBEL_VOLUME) || s->n_volume_steps == PA_VOLUME_NORM+1);
682     pa_assert(!(s->flags & PA_SINK_DYNAMIC_LATENCY) == !(s->thread_info.fixed_latency == 0));
683     pa_assert(!(s->flags & PA_SINK_LATENCY) == !(s->monitor_source->flags & PA_SOURCE_LATENCY));
684     pa_assert(!(s->flags & PA_SINK_DYNAMIC_LATENCY) == !(s->monitor_source->flags & PA_SOURCE_DYNAMIC_LATENCY));
685
686     pa_assert(s->monitor_source->thread_info.fixed_latency == s->thread_info.fixed_latency);
687     pa_assert(s->monitor_source->thread_info.min_latency == s->thread_info.min_latency);
688     pa_assert(s->monitor_source->thread_info.max_latency == s->thread_info.max_latency);
689
690     if (s->suspend_cause)
691         pa_assert_se(sink_set_state(s, PA_SINK_SUSPENDED, s->suspend_cause) == 0);
692     else
693         pa_assert_se(sink_set_state(s, PA_SINK_IDLE, 0) == 0);
694
695     pa_source_put(s->monitor_source);
696
697     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_NEW, s->index);
698     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PUT], s);
699
700     /* This function must be called after the PA_CORE_HOOK_SINK_PUT hook,
701      * because module-switch-on-connect needs to know the old default sink */
702     pa_core_update_default_sink(s->core);
703 }
704
705 /* Called from main context */
706 void pa_sink_unlink(pa_sink* s) {
707     bool linked;
708     pa_sink_input *i, PA_UNUSED *j = NULL;
709
710     pa_sink_assert_ref(s);
711     pa_assert_ctl_context();
712
713     /* Please note that pa_sink_unlink() does more than simply
714      * reversing pa_sink_put(). It also undoes the registrations
715      * already done in pa_sink_new()! */
716
717     if (s->unlink_requested)
718         return;
719
720     s->unlink_requested = true;
721
722     linked = PA_SINK_IS_LINKED(s->state);
723
724     if (linked)
725         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_UNLINK], s);
726
727     if (s->state != PA_SINK_UNLINKED)
728         pa_namereg_unregister(s->core, s->name);
729     pa_idxset_remove_by_data(s->core->sinks, s, NULL);
730
731     pa_core_update_default_sink(s->core);
732
733     if (s->card)
734         pa_idxset_remove_by_data(s->card->sinks, s, NULL);
735
736     while ((i = pa_idxset_first(s->inputs, NULL))) {
737         pa_assert(i != j);
738         pa_sink_input_kill(i);
739         j = i;
740     }
741
742     if (linked)
743         sink_set_state(s, PA_SINK_UNLINKED, 0);
744     else
745         s->state = PA_SINK_UNLINKED;
746
747     reset_callbacks(s);
748
749     if (s->monitor_source)
750         pa_source_unlink(s->monitor_source);
751
752     if (linked) {
753         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_REMOVE, s->index);
754         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_UNLINK_POST], s);
755     }
756 }
757
758 /* Called from main context */
759 static void sink_free(pa_object *o) {
760     pa_sink *s = PA_SINK(o);
761
762     pa_assert(s);
763     pa_assert_ctl_context();
764     pa_assert(pa_sink_refcnt(s) == 0);
765     pa_assert(!PA_SINK_IS_LINKED(s->state));
766
767     pa_log_info("Freeing sink %u \"%s\"", s->index, s->name);
768
769     pa_sink_volume_change_flush(s);
770
771     if (s->monitor_source) {
772         pa_source_unref(s->monitor_source);
773         s->monitor_source = NULL;
774     }
775
776     pa_idxset_free(s->inputs, NULL);
777     pa_hashmap_free(s->thread_info.inputs);
778
779     if (s->silence.memblock)
780         pa_memblock_unref(s->silence.memblock);
781
782     pa_xfree(s->name);
783     pa_xfree(s->driver);
784
785     if (s->proplist)
786         pa_proplist_free(s->proplist);
787
788     if (s->ports)
789         pa_hashmap_free(s->ports);
790
791     pa_xfree(s);
792 }
793
794 /* Called from main context, and not while the IO thread is active, please */
795 void pa_sink_set_asyncmsgq(pa_sink *s, pa_asyncmsgq *q) {
796     pa_sink_assert_ref(s);
797     pa_assert_ctl_context();
798
799     s->asyncmsgq = q;
800
801     if (s->monitor_source)
802         pa_source_set_asyncmsgq(s->monitor_source, q);
803 }
804
805 /* Called from main context, and not while the IO thread is active, please */
806 void pa_sink_update_flags(pa_sink *s, pa_sink_flags_t mask, pa_sink_flags_t value) {
807     pa_sink_flags_t old_flags;
808     pa_sink_input *input;
809     uint32_t idx;
810
811     pa_sink_assert_ref(s);
812     pa_assert_ctl_context();
813
814     /* For now, allow only a minimal set of flags to be changed. */
815     pa_assert((mask & ~(PA_SINK_DYNAMIC_LATENCY|PA_SINK_LATENCY)) == 0);
816
817     old_flags = s->flags;
818     s->flags = (s->flags & ~mask) | (value & mask);
819
820     if (s->flags == old_flags)
821         return;
822
823     if ((s->flags & PA_SINK_LATENCY) != (old_flags & PA_SINK_LATENCY))
824         pa_log_debug("Sink %s: LATENCY flag %s.", s->name, (s->flags & PA_SINK_LATENCY) ? "enabled" : "disabled");
825
826     if ((s->flags & PA_SINK_DYNAMIC_LATENCY) != (old_flags & PA_SINK_DYNAMIC_LATENCY))
827         pa_log_debug("Sink %s: DYNAMIC_LATENCY flag %s.",
828                      s->name, (s->flags & PA_SINK_DYNAMIC_LATENCY) ? "enabled" : "disabled");
829
830     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK | PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
831     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_FLAGS_CHANGED], s);
832
833     if (s->monitor_source)
834         pa_source_update_flags(s->monitor_source,
835                                ((mask & PA_SINK_LATENCY) ? PA_SOURCE_LATENCY : 0) |
836                                ((mask & PA_SINK_DYNAMIC_LATENCY) ? PA_SOURCE_DYNAMIC_LATENCY : 0),
837                                ((value & PA_SINK_LATENCY) ? PA_SOURCE_LATENCY : 0) |
838                                ((value & PA_SINK_DYNAMIC_LATENCY) ? PA_SOURCE_DYNAMIC_LATENCY : 0));
839
840     PA_IDXSET_FOREACH(input, s->inputs, idx) {
841         if (input->origin_sink)
842             pa_sink_update_flags(input->origin_sink, mask, value);
843     }
844 }
845
846 /* Called from IO context, or before _put() from main context */
847 void pa_sink_set_rtpoll(pa_sink *s, pa_rtpoll *p) {
848     pa_sink_assert_ref(s);
849     pa_sink_assert_io_context(s);
850
851     s->thread_info.rtpoll = p;
852
853     if (s->monitor_source)
854         pa_source_set_rtpoll(s->monitor_source, p);
855 }
856
857 /* Called from main context */
858 int pa_sink_update_status(pa_sink*s) {
859     pa_sink_assert_ref(s);
860     pa_assert_ctl_context();
861     pa_assert(PA_SINK_IS_LINKED(s->state));
862
863     if (s->state == PA_SINK_SUSPENDED)
864         return 0;
865
866     return sink_set_state(s, pa_sink_used_by(s) ? PA_SINK_RUNNING : PA_SINK_IDLE, 0);
867 }
868
869 /* Called from any context - must be threadsafe */
870 void pa_sink_set_mixer_dirty(pa_sink *s, bool is_dirty) {
871     pa_atomic_store(&s->mixer_dirty, is_dirty ? 1 : 0);
872 }
873
874 /* Called from main context */
875 int pa_sink_suspend(pa_sink *s, bool suspend, pa_suspend_cause_t cause) {
876     pa_suspend_cause_t merged_cause;
877
878     pa_sink_assert_ref(s);
879     pa_assert_ctl_context();
880     pa_assert(PA_SINK_IS_LINKED(s->state));
881     pa_assert(cause != 0);
882
883     if (suspend)
884         merged_cause = s->suspend_cause | cause;
885     else
886         merged_cause = s->suspend_cause & ~cause;
887
888     if (!(merged_cause & PA_SUSPEND_SESSION) && (pa_atomic_load(&s->mixer_dirty) != 0)) {
889         /* This might look racy but isn't: If somebody sets mixer_dirty exactly here,
890            it'll be handled just fine. */
891         pa_sink_set_mixer_dirty(s, false);
892         pa_log_debug("Mixer is now accessible. Updating alsa mixer settings.");
893         if (s->active_port && s->set_port) {
894             if (s->flags & PA_SINK_DEFERRED_VOLUME) {
895                 struct sink_message_set_port msg = { .port = s->active_port, .ret = 0 };
896                 pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_PORT, &msg, 0, NULL) == 0);
897             }
898             else
899                 s->set_port(s, s->active_port);
900         }
901         else {
902             if (s->set_mute)
903                 s->set_mute(s);
904             if (s->set_volume)
905                 s->set_volume(s);
906         }
907     }
908
909     if (merged_cause)
910         return sink_set_state(s, PA_SINK_SUSPENDED, merged_cause);
911     else
912         return sink_set_state(s, pa_sink_used_by(s) ? PA_SINK_RUNNING : PA_SINK_IDLE, 0);
913 }
914
915 /* Called from main context */
916 pa_queue *pa_sink_move_all_start(pa_sink *s, pa_queue *q) {
917     pa_sink_input *i, *n;
918     uint32_t idx;
919
920     pa_sink_assert_ref(s);
921     pa_assert_ctl_context();
922     pa_assert(PA_SINK_IS_LINKED(s->state));
923
924     if (!q)
925         q = pa_queue_new();
926
927     for (i = PA_SINK_INPUT(pa_idxset_first(s->inputs, &idx)); i; i = n) {
928         n = PA_SINK_INPUT(pa_idxset_next(s->inputs, &idx));
929
930         pa_sink_input_ref(i);
931
932         if (pa_sink_input_start_move(i) >= 0)
933             pa_queue_push(q, i);
934         else
935             pa_sink_input_unref(i);
936     }
937
938     return q;
939 }
940
941 /* Called from main context */
942 void pa_sink_move_all_finish(pa_sink *s, pa_queue *q, bool save) {
943     pa_sink_input *i;
944
945     pa_sink_assert_ref(s);
946     pa_assert_ctl_context();
947     pa_assert(PA_SINK_IS_LINKED(s->state));
948     pa_assert(q);
949
950     while ((i = PA_SINK_INPUT(pa_queue_pop(q)))) {
951         if (PA_SINK_INPUT_IS_LINKED(i->state)) {
952             if (pa_sink_input_finish_move(i, s, save) < 0)
953                 pa_sink_input_fail_move(i);
954
955         }
956         pa_sink_input_unref(i);
957     }
958
959     pa_queue_free(q, NULL);
960 }
961
962 /* Called from main context */
963 void pa_sink_move_all_fail(pa_queue *q) {
964     pa_sink_input *i;
965
966     pa_assert_ctl_context();
967     pa_assert(q);
968
969     while ((i = PA_SINK_INPUT(pa_queue_pop(q)))) {
970         pa_sink_input_fail_move(i);
971         pa_sink_input_unref(i);
972     }
973
974     pa_queue_free(q, NULL);
975 }
976
977  /* Called from IO thread context */
978 size_t pa_sink_process_input_underruns(pa_sink *s, size_t left_to_play) {
979     pa_sink_input *i;
980     void *state = NULL;
981     size_t result = 0;
982
983     pa_sink_assert_ref(s);
984     pa_sink_assert_io_context(s);
985
986     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state) {
987         size_t uf = i->thread_info.underrun_for_sink;
988
989         /* Propagate down the filter tree */
990         if (i->origin_sink) {
991             size_t filter_result, left_to_play_origin;
992
993             /* The recursive call works in the origin sink domain ... */
994             left_to_play_origin = pa_convert_size(left_to_play, &i->sink->sample_spec, &i->origin_sink->sample_spec);
995
996             /* .. and returns the time to sleep before waking up. We need the
997              * underrun duration for comparisons, so we undo the subtraction on
998              * the return value... */
999             filter_result = left_to_play_origin - pa_sink_process_input_underruns(i->origin_sink, left_to_play_origin);
1000
1001             /* ... and convert it back to the master sink domain */
1002             filter_result = pa_convert_size(filter_result, &i->origin_sink->sample_spec, &i->sink->sample_spec);
1003
1004             /* Remember the longest underrun so far */
1005             if (filter_result > result)
1006                 result = filter_result;
1007         }
1008
1009         if (uf == 0) {
1010             /* No underrun here, move on */
1011             continue;
1012         } else if (uf >= left_to_play) {
1013             /* The sink has possibly consumed all the data the sink input provided */
1014             pa_sink_input_process_underrun(i);
1015         } else if (uf > result) {
1016             /* Remember the longest underrun so far */
1017             result = uf;
1018         }
1019     }
1020
1021     if (result > 0)
1022         pa_log_debug("%s: Found underrun %ld bytes ago (%ld bytes ahead in playback buffer)", s->name,
1023                 (long) result, (long) left_to_play - result);
1024     return left_to_play - result;
1025 }
1026
1027 /* Called from IO thread context */
1028 void pa_sink_process_rewind(pa_sink *s, size_t nbytes) {
1029     pa_sink_input *i;
1030     void *state = NULL;
1031
1032     pa_sink_assert_ref(s);
1033     pa_sink_assert_io_context(s);
1034     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1035
1036     /* If nobody requested this and this is actually no real rewind
1037      * then we can short cut this. Please note that this means that
1038      * not all rewind requests triggered upstream will always be
1039      * translated in actual requests! */
1040     if (!s->thread_info.rewind_requested && nbytes <= 0)
1041         return;
1042
1043     s->thread_info.rewind_nbytes = 0;
1044     s->thread_info.rewind_requested = false;
1045
1046     if (nbytes > 0) {
1047         pa_log_debug("Processing rewind...");
1048         if (s->flags & PA_SINK_DEFERRED_VOLUME)
1049             pa_sink_volume_change_rewind(s, nbytes);
1050     }
1051
1052     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state) {
1053         pa_sink_input_assert_ref(i);
1054         pa_sink_input_process_rewind(i, nbytes);
1055     }
1056
1057     if (nbytes > 0) {
1058         if (s->monitor_source && PA_SOURCE_IS_LINKED(s->monitor_source->thread_info.state))
1059             pa_source_process_rewind(s->monitor_source, nbytes);
1060     }
1061 }
1062
1063 /* Called from IO thread context */
1064 static unsigned fill_mix_info(pa_sink *s, size_t *length, pa_mix_info *info, unsigned maxinfo) {
1065     pa_sink_input *i;
1066     unsigned n = 0;
1067     void *state = NULL;
1068     size_t mixlength = *length;
1069
1070     pa_sink_assert_ref(s);
1071     pa_sink_assert_io_context(s);
1072     pa_assert(info);
1073
1074     while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)) && maxinfo > 0) {
1075         pa_sink_input_assert_ref(i);
1076
1077         pa_sink_input_peek(i, *length, &info->chunk, &info->volume);
1078
1079         if (mixlength == 0 || info->chunk.length < mixlength)
1080             mixlength = info->chunk.length;
1081
1082         if (pa_memblock_is_silence(info->chunk.memblock)) {
1083             pa_memblock_unref(info->chunk.memblock);
1084             continue;
1085         }
1086
1087         info->userdata = pa_sink_input_ref(i);
1088
1089         pa_assert(info->chunk.memblock);
1090         pa_assert(info->chunk.length > 0);
1091
1092         info++;
1093         n++;
1094         maxinfo--;
1095     }
1096
1097     if (mixlength > 0)
1098         *length = mixlength;
1099
1100     return n;
1101 }
1102
1103 /* Called from IO thread context */
1104 static void inputs_drop(pa_sink *s, pa_mix_info *info, unsigned n, pa_memchunk *result) {
1105     pa_sink_input *i;
1106     void *state;
1107     unsigned p = 0;
1108     unsigned n_unreffed = 0;
1109
1110     pa_sink_assert_ref(s);
1111     pa_sink_assert_io_context(s);
1112     pa_assert(result);
1113     pa_assert(result->memblock);
1114     pa_assert(result->length > 0);
1115
1116     /* We optimize for the case where the order of the inputs has not changed */
1117
1118     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state) {
1119         unsigned j;
1120         pa_mix_info* m = NULL;
1121
1122         pa_sink_input_assert_ref(i);
1123
1124         /* Let's try to find the matching entry info the pa_mix_info array */
1125         for (j = 0; j < n; j ++) {
1126
1127             if (info[p].userdata == i) {
1128                 m = info + p;
1129                 break;
1130             }
1131
1132             p++;
1133             if (p >= n)
1134                 p = 0;
1135         }
1136
1137         /* Drop read data */
1138         pa_sink_input_drop(i, result->length);
1139
1140         if (s->monitor_source && PA_SOURCE_IS_LINKED(s->monitor_source->thread_info.state)) {
1141
1142             if (pa_hashmap_size(i->thread_info.direct_outputs) > 0) {
1143                 void *ostate = NULL;
1144                 pa_source_output *o;
1145                 pa_memchunk c;
1146
1147                 if (m && m->chunk.memblock) {
1148                     c = m->chunk;
1149                     pa_memblock_ref(c.memblock);
1150                     pa_assert(result->length <= c.length);
1151                     c.length = result->length;
1152
1153                     pa_memchunk_make_writable(&c, 0);
1154                     pa_volume_memchunk(&c, &s->sample_spec, &m->volume);
1155                 } else {
1156                     c = s->silence;
1157                     pa_memblock_ref(c.memblock);
1158                     pa_assert(result->length <= c.length);
1159                     c.length = result->length;
1160                 }
1161
1162                 while ((o = pa_hashmap_iterate(i->thread_info.direct_outputs, &ostate, NULL))) {
1163                     pa_source_output_assert_ref(o);
1164                     pa_assert(o->direct_on_input == i);
1165                     pa_source_post_direct(s->monitor_source, o, &c);
1166                 }
1167
1168                 pa_memblock_unref(c.memblock);
1169             }
1170         }
1171
1172         if (m) {
1173             if (m->chunk.memblock) {
1174                 pa_memblock_unref(m->chunk.memblock);
1175                 pa_memchunk_reset(&m->chunk);
1176             }
1177
1178             pa_sink_input_unref(m->userdata);
1179             m->userdata = NULL;
1180
1181             n_unreffed += 1;
1182         }
1183     }
1184
1185     /* Now drop references to entries that are included in the
1186      * pa_mix_info array but don't exist anymore */
1187
1188     if (n_unreffed < n) {
1189         for (; n > 0; info++, n--) {
1190             if (info->userdata)
1191                 pa_sink_input_unref(info->userdata);
1192             if (info->chunk.memblock)
1193                 pa_memblock_unref(info->chunk.memblock);
1194         }
1195     }
1196
1197     if (s->monitor_source && PA_SOURCE_IS_LINKED(s->monitor_source->thread_info.state))
1198         pa_source_post(s->monitor_source, result);
1199 }
1200
1201 /* Called from IO thread context */
1202 void pa_sink_render(pa_sink*s, size_t length, pa_memchunk *result) {
1203     pa_mix_info info[MAX_MIX_CHANNELS];
1204     unsigned n;
1205     size_t block_size_max;
1206
1207     pa_sink_assert_ref(s);
1208     pa_sink_assert_io_context(s);
1209     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1210     pa_assert(pa_frame_aligned(length, &s->sample_spec));
1211     pa_assert(result);
1212
1213     pa_assert(!s->thread_info.rewind_requested);
1214     pa_assert(s->thread_info.rewind_nbytes == 0);
1215
1216     if (s->thread_info.state == PA_SINK_SUSPENDED) {
1217         result->memblock = pa_memblock_ref(s->silence.memblock);
1218         result->index = s->silence.index;
1219         result->length = PA_MIN(s->silence.length, length);
1220         return;
1221     }
1222
1223     pa_sink_ref(s);
1224
1225     if (length <= 0)
1226         length = pa_frame_align(MIX_BUFFER_LENGTH, &s->sample_spec);
1227
1228     block_size_max = pa_mempool_block_size_max(s->core->mempool);
1229     if (length > block_size_max)
1230         length = pa_frame_align(block_size_max, &s->sample_spec);
1231
1232     pa_assert(length > 0);
1233
1234     n = fill_mix_info(s, &length, info, MAX_MIX_CHANNELS);
1235
1236     if (n == 0) {
1237
1238         *result = s->silence;
1239         pa_memblock_ref(result->memblock);
1240
1241         if (result->length > length)
1242             result->length = length;
1243
1244     } else if (n == 1) {
1245         pa_cvolume volume;
1246
1247         *result = info[0].chunk;
1248         pa_memblock_ref(result->memblock);
1249
1250         if (result->length > length)
1251             result->length = length;
1252
1253         pa_sw_cvolume_multiply(&volume, &s->thread_info.soft_volume, &info[0].volume);
1254
1255         if (s->thread_info.soft_muted || pa_cvolume_is_muted(&volume)) {
1256             pa_memblock_unref(result->memblock);
1257             pa_silence_memchunk_get(&s->core->silence_cache,
1258                                     s->core->mempool,
1259                                     result,
1260                                     &s->sample_spec,
1261                                     result->length);
1262         } else if (!pa_cvolume_is_norm(&volume)) {
1263             pa_memchunk_make_writable(result, 0);
1264             pa_volume_memchunk(result, &s->sample_spec, &volume);
1265         }
1266     } else {
1267         void *ptr;
1268         result->memblock = pa_memblock_new(s->core->mempool, length);
1269
1270         ptr = pa_memblock_acquire(result->memblock);
1271         result->length = pa_mix(info, n,
1272                                 ptr, length,
1273                                 &s->sample_spec,
1274                                 &s->thread_info.soft_volume,
1275                                 s->thread_info.soft_muted);
1276         pa_memblock_release(result->memblock);
1277
1278         result->index = 0;
1279     }
1280
1281     inputs_drop(s, info, n, result);
1282
1283     pa_sink_unref(s);
1284 }
1285
1286 /* Called from IO thread context */
1287 void pa_sink_render_into(pa_sink*s, pa_memchunk *target) {
1288     pa_mix_info info[MAX_MIX_CHANNELS];
1289     unsigned n;
1290     size_t length, block_size_max;
1291
1292     pa_sink_assert_ref(s);
1293     pa_sink_assert_io_context(s);
1294     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1295     pa_assert(target);
1296     pa_assert(target->memblock);
1297     pa_assert(target->length > 0);
1298     pa_assert(pa_frame_aligned(target->length, &s->sample_spec));
1299
1300     pa_assert(!s->thread_info.rewind_requested);
1301     pa_assert(s->thread_info.rewind_nbytes == 0);
1302
1303     if (s->thread_info.state == PA_SINK_SUSPENDED) {
1304         pa_silence_memchunk(target, &s->sample_spec);
1305         return;
1306     }
1307
1308     pa_sink_ref(s);
1309
1310     length = target->length;
1311     block_size_max = pa_mempool_block_size_max(s->core->mempool);
1312     if (length > block_size_max)
1313         length = pa_frame_align(block_size_max, &s->sample_spec);
1314
1315     pa_assert(length > 0);
1316
1317     n = fill_mix_info(s, &length, info, MAX_MIX_CHANNELS);
1318
1319     if (n == 0) {
1320         if (target->length > length)
1321             target->length = length;
1322
1323         pa_silence_memchunk(target, &s->sample_spec);
1324     } else if (n == 1) {
1325         pa_cvolume volume;
1326
1327         if (target->length > length)
1328             target->length = length;
1329
1330         pa_sw_cvolume_multiply(&volume, &s->thread_info.soft_volume, &info[0].volume);
1331
1332         if (s->thread_info.soft_muted || pa_cvolume_is_muted(&volume))
1333             pa_silence_memchunk(target, &s->sample_spec);
1334         else {
1335             pa_memchunk vchunk;
1336
1337             vchunk = info[0].chunk;
1338             pa_memblock_ref(vchunk.memblock);
1339
1340             if (vchunk.length > length)
1341                 vchunk.length = length;
1342
1343             if (!pa_cvolume_is_norm(&volume)) {
1344                 pa_memchunk_make_writable(&vchunk, 0);
1345                 pa_volume_memchunk(&vchunk, &s->sample_spec, &volume);
1346             }
1347
1348             pa_memchunk_memcpy(target, &vchunk);
1349             pa_memblock_unref(vchunk.memblock);
1350         }
1351
1352     } else {
1353         void *ptr;
1354
1355         ptr = pa_memblock_acquire(target->memblock);
1356
1357         target->length = pa_mix(info, n,
1358                                 (uint8_t*) ptr + target->index, length,
1359                                 &s->sample_spec,
1360                                 &s->thread_info.soft_volume,
1361                                 s->thread_info.soft_muted);
1362
1363         pa_memblock_release(target->memblock);
1364     }
1365
1366     inputs_drop(s, info, n, target);
1367
1368     pa_sink_unref(s);
1369 }
1370
1371 /* Called from IO thread context */
1372 void pa_sink_render_into_full(pa_sink *s, pa_memchunk *target) {
1373     pa_memchunk chunk;
1374     size_t l, d;
1375
1376     pa_sink_assert_ref(s);
1377     pa_sink_assert_io_context(s);
1378     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1379     pa_assert(target);
1380     pa_assert(target->memblock);
1381     pa_assert(target->length > 0);
1382     pa_assert(pa_frame_aligned(target->length, &s->sample_spec));
1383
1384     pa_assert(!s->thread_info.rewind_requested);
1385     pa_assert(s->thread_info.rewind_nbytes == 0);
1386
1387     if (s->thread_info.state == PA_SINK_SUSPENDED) {
1388         pa_silence_memchunk(target, &s->sample_spec);
1389         return;
1390     }
1391
1392     pa_sink_ref(s);
1393
1394     l = target->length;
1395     d = 0;
1396     while (l > 0) {
1397         chunk = *target;
1398         chunk.index += d;
1399         chunk.length -= d;
1400
1401         pa_sink_render_into(s, &chunk);
1402
1403         d += chunk.length;
1404         l -= chunk.length;
1405     }
1406
1407     pa_sink_unref(s);
1408 }
1409
1410 /* Called from IO thread context */
1411 void pa_sink_render_full(pa_sink *s, size_t length, pa_memchunk *result) {
1412     pa_sink_assert_ref(s);
1413     pa_sink_assert_io_context(s);
1414     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1415     pa_assert(length > 0);
1416     pa_assert(pa_frame_aligned(length, &s->sample_spec));
1417     pa_assert(result);
1418
1419     pa_assert(!s->thread_info.rewind_requested);
1420     pa_assert(s->thread_info.rewind_nbytes == 0);
1421
1422     pa_sink_ref(s);
1423
1424     pa_sink_render(s, length, result);
1425
1426     if (result->length < length) {
1427         pa_memchunk chunk;
1428
1429         pa_memchunk_make_writable(result, length);
1430
1431         chunk.memblock = result->memblock;
1432         chunk.index = result->index + result->length;
1433         chunk.length = length - result->length;
1434
1435         pa_sink_render_into_full(s, &chunk);
1436
1437         result->length = length;
1438     }
1439
1440     pa_sink_unref(s);
1441 }
1442
1443 /* Called from main thread */
1444 int pa_sink_reconfigure(pa_sink *s, pa_sample_spec *spec, bool passthrough) {
1445     int ret = -1;
1446     pa_sample_spec desired_spec;
1447     uint32_t default_rate = s->default_sample_rate;
1448     uint32_t alternate_rate = s->alternate_sample_rate;
1449     uint32_t idx;
1450     pa_sink_input *i;
1451     bool default_rate_is_usable = false;
1452     bool alternate_rate_is_usable = false;
1453     bool avoid_resampling = s->core->avoid_resampling;
1454
1455     /* We currently only try to reconfigure the sample rate */
1456
1457     if (pa_sample_spec_equal(spec, &s->sample_spec))
1458         return 0;
1459
1460     if (!s->reconfigure)
1461         return -1;
1462
1463     if (PA_UNLIKELY(default_rate == alternate_rate && !passthrough && !avoid_resampling)) {
1464         pa_log_debug("Default and alternate sample rates are the same, so there is no point in switching.");
1465         return -1;
1466     }
1467
1468     if (PA_SINK_IS_RUNNING(s->state)) {
1469         pa_log_info("Cannot update rate, SINK_IS_RUNNING, will keep using %u Hz",
1470                     s->sample_spec.rate);
1471         return -1;
1472     }
1473
1474     if (s->monitor_source) {
1475         if (PA_SOURCE_IS_RUNNING(s->monitor_source->state) == true) {
1476             pa_log_info("Cannot update rate, monitor source is RUNNING");
1477             return -1;
1478         }
1479     }
1480
1481     if (PA_UNLIKELY(!pa_sample_spec_valid(spec)))
1482         return -1;
1483
1484     desired_spec = s->sample_spec;
1485
1486     if (passthrough) {
1487         /* We have to try to use the sink input rate */
1488         desired_spec.rate = spec->rate;
1489
1490     } else if (avoid_resampling && (spec->rate >= default_rate || spec->rate >= alternate_rate)) {
1491         /* We just try to set the sink input's sample rate if it's not too low */
1492         desired_spec.rate = spec->rate;
1493
1494     } else if (default_rate == spec->rate || alternate_rate == spec->rate) {
1495         /* We can directly try to use this rate */
1496         desired_spec.rate = spec->rate;
1497
1498     } else {
1499         /* See if we can pick a rate that results in less resampling effort */
1500         if (default_rate % 11025 == 0 && spec->rate % 11025 == 0)
1501             default_rate_is_usable = true;
1502         if (default_rate % 4000 == 0 && spec->rate % 4000 == 0)
1503             default_rate_is_usable = true;
1504         if (alternate_rate && alternate_rate % 11025 == 0 && spec->rate % 11025 == 0)
1505             alternate_rate_is_usable = true;
1506         if (alternate_rate && alternate_rate % 4000 == 0 && spec->rate % 4000 == 0)
1507             alternate_rate_is_usable = true;
1508
1509         if (alternate_rate_is_usable && !default_rate_is_usable)
1510             desired_spec.rate = alternate_rate;
1511         else
1512             desired_spec.rate = default_rate;
1513     }
1514
1515     if (pa_sample_spec_equal(&desired_spec, &s->sample_spec) && passthrough == pa_sink_is_passthrough(s))
1516         return -1;
1517
1518     if (!passthrough && pa_sink_used_by(s) > 0)
1519         return -1;
1520
1521     pa_log_debug("Suspending sink %s due to changing format.", s->name);
1522     pa_sink_suspend(s, true, PA_SUSPEND_INTERNAL);
1523
1524     if (s->reconfigure(s, &desired_spec, passthrough) >= 0) {
1525         /* update monitor source as well */
1526         if (s->monitor_source && !passthrough)
1527             pa_source_reconfigure(s->monitor_source, &desired_spec, false);
1528         pa_log_info("Changed format successfully");
1529
1530         PA_IDXSET_FOREACH(i, s->inputs, idx) {
1531             if (i->state == PA_SINK_INPUT_CORKED)
1532                 pa_sink_input_update_rate(i);
1533         }
1534
1535         ret = 0;
1536     }
1537
1538     pa_sink_suspend(s, false, PA_SUSPEND_INTERNAL);
1539
1540     return ret;
1541 }
1542
1543 /* Called from main thread */
1544 pa_usec_t pa_sink_get_latency(pa_sink *s) {
1545     int64_t usec = 0;
1546
1547     pa_sink_assert_ref(s);
1548     pa_assert_ctl_context();
1549     pa_assert(PA_SINK_IS_LINKED(s->state));
1550
1551     /* The returned value is supposed to be in the time domain of the sound card! */
1552
1553     if (s->state == PA_SINK_SUSPENDED)
1554         return 0;
1555
1556     if (!(s->flags & PA_SINK_LATENCY))
1557         return 0;
1558
1559     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY, &usec, 0, NULL) == 0);
1560
1561     /* the return value is unsigned, so check that the offset can be added to usec without
1562      * underflowing. */
1563     if (-s->port_latency_offset <= usec)
1564         usec += s->port_latency_offset;
1565     else
1566         usec = 0;
1567
1568     return (pa_usec_t)usec;
1569 }
1570
1571 /* Called from IO thread */
1572 int64_t pa_sink_get_latency_within_thread(pa_sink *s, bool allow_negative) {
1573     int64_t usec = 0;
1574     pa_msgobject *o;
1575
1576     pa_sink_assert_ref(s);
1577     pa_sink_assert_io_context(s);
1578     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
1579
1580     /* The returned value is supposed to be in the time domain of the sound card! */
1581
1582     if (s->thread_info.state == PA_SINK_SUSPENDED)
1583         return 0;
1584
1585     if (!(s->flags & PA_SINK_LATENCY))
1586         return 0;
1587
1588     o = PA_MSGOBJECT(s);
1589
1590     /* FIXME: We probably should make this a proper vtable callback instead of going through process_msg() */
1591
1592     o->process_msg(o, PA_SINK_MESSAGE_GET_LATENCY, &usec, 0, NULL);
1593
1594     /* If allow_negative is false, the call should only return positive values, */
1595     usec += s->thread_info.port_latency_offset;
1596     if (!allow_negative && usec < 0)
1597         usec = 0;
1598
1599     return usec;
1600 }
1601
1602 /* Called from the main thread (and also from the IO thread while the main
1603  * thread is waiting).
1604  *
1605  * When a sink uses volume sharing, it never has the PA_SINK_FLAT_VOLUME flag
1606  * set. Instead, flat volume mode is detected by checking whether the root sink
1607  * has the flag set. */
1608 bool pa_sink_flat_volume_enabled(pa_sink *s) {
1609     pa_sink_assert_ref(s);
1610
1611     s = pa_sink_get_master(s);
1612
1613     if (PA_LIKELY(s))
1614         return (s->flags & PA_SINK_FLAT_VOLUME);
1615     else
1616         return false;
1617 }
1618
1619 /* Called from the main thread (and also from the IO thread while the main
1620  * thread is waiting). */
1621 pa_sink *pa_sink_get_master(pa_sink *s) {
1622     pa_sink_assert_ref(s);
1623
1624     while (s && (s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
1625         if (PA_UNLIKELY(!s->input_to_master))
1626             return NULL;
1627
1628         s = s->input_to_master->sink;
1629     }
1630
1631     return s;
1632 }
1633
1634 /* Called from main context */
1635 bool pa_sink_is_filter(pa_sink *s) {
1636     pa_sink_assert_ref(s);
1637
1638     return (s->input_to_master != NULL);
1639 }
1640
1641 /* Called from main context */
1642 bool pa_sink_is_passthrough(pa_sink *s) {
1643     pa_sink_input *alt_i;
1644     uint32_t idx;
1645
1646     pa_sink_assert_ref(s);
1647
1648     /* one and only one PASSTHROUGH input can possibly be connected */
1649     if (pa_idxset_size(s->inputs) == 1) {
1650         alt_i = pa_idxset_first(s->inputs, &idx);
1651
1652         if (pa_sink_input_is_passthrough(alt_i))
1653             return true;
1654     }
1655
1656     return false;
1657 }
1658
1659 /* Called from main context */
1660 void pa_sink_enter_passthrough(pa_sink *s) {
1661     pa_cvolume volume;
1662
1663     /* The sink implementation is reconfigured for passthrough in
1664      * pa_sink_reconfigure(). This function sets the PA core objects to
1665      * passthrough mode. */
1666
1667     /* disable the monitor in passthrough mode */
1668     if (s->monitor_source) {
1669         pa_log_debug("Suspending monitor source %s, because the sink is entering the passthrough mode.", s->monitor_source->name);
1670         pa_source_suspend(s->monitor_source, true, PA_SUSPEND_PASSTHROUGH);
1671     }
1672
1673     /* set the volume to NORM */
1674     s->saved_volume = *pa_sink_get_volume(s, true);
1675     s->saved_save_volume = s->save_volume;
1676
1677     pa_cvolume_set(&volume, s->sample_spec.channels, PA_MIN(s->base_volume, PA_VOLUME_NORM));
1678     pa_sink_set_volume(s, &volume, true, false);
1679
1680     pa_log_debug("Suspending/Restarting sink %s to enter passthrough mode", s->name);
1681 }
1682
1683 /* Called from main context */
1684 void pa_sink_leave_passthrough(pa_sink *s) {
1685     /* Unsuspend monitor */
1686     if (s->monitor_source) {
1687         pa_log_debug("Resuming monitor source %s, because the sink is leaving the passthrough mode.", s->monitor_source->name);
1688         pa_source_suspend(s->monitor_source, false, PA_SUSPEND_PASSTHROUGH);
1689     }
1690
1691     /* Restore sink volume to what it was before we entered passthrough mode */
1692     pa_sink_set_volume(s, &s->saved_volume, true, s->saved_save_volume);
1693
1694     pa_cvolume_init(&s->saved_volume);
1695     s->saved_save_volume = false;
1696
1697 }
1698
1699 /* Called from main context. */
1700 static void compute_reference_ratio(pa_sink_input *i) {
1701     unsigned c = 0;
1702     pa_cvolume remapped;
1703     pa_cvolume ratio;
1704
1705     pa_assert(i);
1706     pa_assert(pa_sink_flat_volume_enabled(i->sink));
1707
1708     /*
1709      * Calculates the reference ratio from the sink's reference
1710      * volume. This basically calculates:
1711      *
1712      * i->reference_ratio = i->volume / i->sink->reference_volume
1713      */
1714
1715     remapped = i->sink->reference_volume;
1716     pa_cvolume_remap(&remapped, &i->sink->channel_map, &i->channel_map);
1717
1718     ratio = i->reference_ratio;
1719
1720     for (c = 0; c < i->sample_spec.channels; c++) {
1721
1722         /* We don't update when the sink volume is 0 anyway */
1723         if (remapped.values[c] <= PA_VOLUME_MUTED)
1724             continue;
1725
1726         /* Don't update the reference ratio unless necessary */
1727         if (pa_sw_volume_multiply(
1728                     ratio.values[c],
1729                     remapped.values[c]) == i->volume.values[c])
1730             continue;
1731
1732         ratio.values[c] = pa_sw_volume_divide(
1733                 i->volume.values[c],
1734                 remapped.values[c]);
1735     }
1736
1737     pa_sink_input_set_reference_ratio(i, &ratio);
1738 }
1739
1740 /* Called from main context. Only called for the root sink in volume sharing
1741  * cases, except for internal recursive calls. */
1742 static void compute_reference_ratios(pa_sink *s) {
1743     uint32_t idx;
1744     pa_sink_input *i;
1745
1746     pa_sink_assert_ref(s);
1747     pa_assert_ctl_context();
1748     pa_assert(PA_SINK_IS_LINKED(s->state));
1749     pa_assert(pa_sink_flat_volume_enabled(s));
1750
1751     PA_IDXSET_FOREACH(i, s->inputs, idx) {
1752         compute_reference_ratio(i);
1753
1754         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)
1755                 && PA_SINK_IS_LINKED(i->origin_sink->state))
1756             compute_reference_ratios(i->origin_sink);
1757     }
1758 }
1759
1760 /* Called from main context. Only called for the root sink in volume sharing
1761  * cases, except for internal recursive calls. */
1762 static void compute_real_ratios(pa_sink *s) {
1763     pa_sink_input *i;
1764     uint32_t idx;
1765
1766     pa_sink_assert_ref(s);
1767     pa_assert_ctl_context();
1768     pa_assert(PA_SINK_IS_LINKED(s->state));
1769     pa_assert(pa_sink_flat_volume_enabled(s));
1770
1771     PA_IDXSET_FOREACH(i, s->inputs, idx) {
1772         unsigned c;
1773         pa_cvolume remapped;
1774
1775         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
1776             /* The origin sink uses volume sharing, so this input's real ratio
1777              * is handled as a special case - the real ratio must be 0 dB, and
1778              * as a result i->soft_volume must equal i->volume_factor. */
1779             pa_cvolume_reset(&i->real_ratio, i->real_ratio.channels);
1780             i->soft_volume = i->volume_factor;
1781
1782             if (PA_SINK_IS_LINKED(i->origin_sink->state))
1783                 compute_real_ratios(i->origin_sink);
1784
1785             continue;
1786         }
1787
1788         /*
1789          * This basically calculates:
1790          *
1791          * i->real_ratio := i->volume / s->real_volume
1792          * i->soft_volume := i->real_ratio * i->volume_factor
1793          */
1794
1795         remapped = s->real_volume;
1796         pa_cvolume_remap(&remapped, &s->channel_map, &i->channel_map);
1797
1798         i->real_ratio.channels = i->sample_spec.channels;
1799         i->soft_volume.channels = i->sample_spec.channels;
1800
1801         for (c = 0; c < i->sample_spec.channels; c++) {
1802
1803             if (remapped.values[c] <= PA_VOLUME_MUTED) {
1804                 /* We leave i->real_ratio untouched */
1805                 i->soft_volume.values[c] = PA_VOLUME_MUTED;
1806                 continue;
1807             }
1808
1809             /* Don't lose accuracy unless necessary */
1810             if (pa_sw_volume_multiply(
1811                         i->real_ratio.values[c],
1812                         remapped.values[c]) != i->volume.values[c])
1813
1814                 i->real_ratio.values[c] = pa_sw_volume_divide(
1815                         i->volume.values[c],
1816                         remapped.values[c]);
1817
1818             i->soft_volume.values[c] = pa_sw_volume_multiply(
1819                     i->real_ratio.values[c],
1820                     i->volume_factor.values[c]);
1821         }
1822
1823         /* We don't copy the soft_volume to the thread_info data
1824          * here. That must be done by the caller */
1825     }
1826 }
1827
1828 static pa_cvolume *cvolume_remap_minimal_impact(
1829         pa_cvolume *v,
1830         const pa_cvolume *template,
1831         const pa_channel_map *from,
1832         const pa_channel_map *to) {
1833
1834     pa_cvolume t;
1835
1836     pa_assert(v);
1837     pa_assert(template);
1838     pa_assert(from);
1839     pa_assert(to);
1840     pa_assert(pa_cvolume_compatible_with_channel_map(v, from));
1841     pa_assert(pa_cvolume_compatible_with_channel_map(template, to));
1842
1843     /* Much like pa_cvolume_remap(), but tries to minimize impact when
1844      * mapping from sink input to sink volumes:
1845      *
1846      * If template is a possible remapping from v it is used instead
1847      * of remapping anew.
1848      *
1849      * If the channel maps don't match we set an all-channel volume on
1850      * the sink to ensure that changing a volume on one stream has no
1851      * effect that cannot be compensated for in another stream that
1852      * does not have the same channel map as the sink. */
1853
1854     if (pa_channel_map_equal(from, to))
1855         return v;
1856
1857     t = *template;
1858     if (pa_cvolume_equal(pa_cvolume_remap(&t, to, from), v)) {
1859         *v = *template;
1860         return v;
1861     }
1862
1863     pa_cvolume_set(v, to->channels, pa_cvolume_max(v));
1864     return v;
1865 }
1866
1867 /* Called from main thread. Only called for the root sink in volume sharing
1868  * cases, except for internal recursive calls. */
1869 static void get_maximum_input_volume(pa_sink *s, pa_cvolume *max_volume, const pa_channel_map *channel_map) {
1870     pa_sink_input *i;
1871     uint32_t idx;
1872
1873     pa_sink_assert_ref(s);
1874     pa_assert(max_volume);
1875     pa_assert(channel_map);
1876     pa_assert(pa_sink_flat_volume_enabled(s));
1877
1878     PA_IDXSET_FOREACH(i, s->inputs, idx) {
1879         pa_cvolume remapped;
1880
1881         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
1882             if (PA_SINK_IS_LINKED(i->origin_sink->state))
1883                 get_maximum_input_volume(i->origin_sink, max_volume, channel_map);
1884
1885             /* Ignore this input. The origin sink uses volume sharing, so this
1886              * input's volume will be set to be equal to the root sink's real
1887              * volume. Obviously this input's current volume must not then
1888              * affect what the root sink's real volume will be. */
1889             continue;
1890         }
1891
1892         remapped = i->volume;
1893         cvolume_remap_minimal_impact(&remapped, max_volume, &i->channel_map, channel_map);
1894         pa_cvolume_merge(max_volume, max_volume, &remapped);
1895     }
1896 }
1897
1898 /* Called from main thread. Only called for the root sink in volume sharing
1899  * cases, except for internal recursive calls. */
1900 static bool has_inputs(pa_sink *s) {
1901     pa_sink_input *i;
1902     uint32_t idx;
1903
1904     pa_sink_assert_ref(s);
1905
1906     PA_IDXSET_FOREACH(i, s->inputs, idx) {
1907         if (!i->origin_sink || !(i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER) || has_inputs(i->origin_sink))
1908             return true;
1909     }
1910
1911     return false;
1912 }
1913
1914 /* Called from main thread. Only called for the root sink in volume sharing
1915  * cases, except for internal recursive calls. */
1916 static void update_real_volume(pa_sink *s, const pa_cvolume *new_volume, pa_channel_map *channel_map) {
1917     pa_sink_input *i;
1918     uint32_t idx;
1919
1920     pa_sink_assert_ref(s);
1921     pa_assert(new_volume);
1922     pa_assert(channel_map);
1923
1924     s->real_volume = *new_volume;
1925     pa_cvolume_remap(&s->real_volume, channel_map, &s->channel_map);
1926
1927     PA_IDXSET_FOREACH(i, s->inputs, idx) {
1928         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
1929             if (pa_sink_flat_volume_enabled(s)) {
1930                 pa_cvolume new_input_volume;
1931
1932                 /* Follow the root sink's real volume. */
1933                 new_input_volume = *new_volume;
1934                 pa_cvolume_remap(&new_input_volume, channel_map, &i->channel_map);
1935                 pa_sink_input_set_volume_direct(i, &new_input_volume);
1936                 compute_reference_ratio(i);
1937             }
1938
1939             if (PA_SINK_IS_LINKED(i->origin_sink->state))
1940                 update_real_volume(i->origin_sink, new_volume, channel_map);
1941         }
1942     }
1943 }
1944
1945 /* Called from main thread. Only called for the root sink in shared volume
1946  * cases. */
1947 static void compute_real_volume(pa_sink *s) {
1948     pa_sink_assert_ref(s);
1949     pa_assert_ctl_context();
1950     pa_assert(PA_SINK_IS_LINKED(s->state));
1951     pa_assert(pa_sink_flat_volume_enabled(s));
1952     pa_assert(!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER));
1953
1954     /* This determines the maximum volume of all streams and sets
1955      * s->real_volume accordingly. */
1956
1957     if (!has_inputs(s)) {
1958         /* In the special case that we have no sink inputs we leave the
1959          * volume unmodified. */
1960         update_real_volume(s, &s->reference_volume, &s->channel_map);
1961         return;
1962     }
1963
1964     pa_cvolume_mute(&s->real_volume, s->channel_map.channels);
1965
1966     /* First let's determine the new maximum volume of all inputs
1967      * connected to this sink */
1968     get_maximum_input_volume(s, &s->real_volume, &s->channel_map);
1969     update_real_volume(s, &s->real_volume, &s->channel_map);
1970
1971     /* Then, let's update the real ratios/soft volumes of all inputs
1972      * connected to this sink */
1973     compute_real_ratios(s);
1974 }
1975
1976 /* Called from main thread. Only called for the root sink in shared volume
1977  * cases, except for internal recursive calls. */
1978 static void propagate_reference_volume(pa_sink *s) {
1979     pa_sink_input *i;
1980     uint32_t idx;
1981
1982     pa_sink_assert_ref(s);
1983     pa_assert_ctl_context();
1984     pa_assert(PA_SINK_IS_LINKED(s->state));
1985     pa_assert(pa_sink_flat_volume_enabled(s));
1986
1987     /* This is called whenever the sink volume changes that is not
1988      * caused by a sink input volume change. We need to fix up the
1989      * sink input volumes accordingly */
1990
1991     PA_IDXSET_FOREACH(i, s->inputs, idx) {
1992         pa_cvolume new_volume;
1993
1994         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
1995             if (PA_SINK_IS_LINKED(i->origin_sink->state))
1996                 propagate_reference_volume(i->origin_sink);
1997
1998             /* Since the origin sink uses volume sharing, this input's volume
1999              * needs to be updated to match the root sink's real volume, but
2000              * that will be done later in update_real_volume(). */
2001             continue;
2002         }
2003
2004         /* This basically calculates:
2005          *
2006          * i->volume := s->reference_volume * i->reference_ratio  */
2007
2008         new_volume = s->reference_volume;
2009         pa_cvolume_remap(&new_volume, &s->channel_map, &i->channel_map);
2010         pa_sw_cvolume_multiply(&new_volume, &new_volume, &i->reference_ratio);
2011         pa_sink_input_set_volume_direct(i, &new_volume);
2012     }
2013 }
2014
2015 /* Called from main thread. Only called for the root sink in volume sharing
2016  * cases, except for internal recursive calls. The return value indicates
2017  * whether any reference volume actually changed. */
2018 static bool update_reference_volume(pa_sink *s, const pa_cvolume *v, const pa_channel_map *channel_map, bool save) {
2019     pa_cvolume volume;
2020     bool reference_volume_changed;
2021     pa_sink_input *i;
2022     uint32_t idx;
2023
2024     pa_sink_assert_ref(s);
2025     pa_assert(PA_SINK_IS_LINKED(s->state));
2026     pa_assert(v);
2027     pa_assert(channel_map);
2028     pa_assert(pa_cvolume_valid(v));
2029
2030     volume = *v;
2031     pa_cvolume_remap(&volume, channel_map, &s->channel_map);
2032
2033     reference_volume_changed = !pa_cvolume_equal(&volume, &s->reference_volume);
2034     pa_sink_set_reference_volume_direct(s, &volume);
2035
2036     s->save_volume = (!reference_volume_changed && s->save_volume) || save;
2037
2038     if (!reference_volume_changed && !(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER))
2039         /* If the root sink's volume doesn't change, then there can't be any
2040          * changes in the other sinks in the sink tree either.
2041          *
2042          * It's probably theoretically possible that even if the root sink's
2043          * volume changes slightly, some filter sink doesn't change its volume
2044          * due to rounding errors. If that happens, we still want to propagate
2045          * the changed root sink volume to the sinks connected to the
2046          * intermediate sink that didn't change its volume. This theoretical
2047          * possibility is the reason why we have that !(s->flags &
2048          * PA_SINK_SHARE_VOLUME_WITH_MASTER) condition. Probably nobody would
2049          * notice even if we returned here false always if
2050          * reference_volume_changed is false. */
2051         return false;
2052
2053     PA_IDXSET_FOREACH(i, s->inputs, idx) {
2054         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)
2055                 && PA_SINK_IS_LINKED(i->origin_sink->state))
2056             update_reference_volume(i->origin_sink, v, channel_map, false);
2057     }
2058
2059     return true;
2060 }
2061
2062 /* Called from main thread */
2063 void pa_sink_set_volume(
2064         pa_sink *s,
2065         const pa_cvolume *volume,
2066         bool send_msg,
2067         bool save) {
2068
2069     pa_cvolume new_reference_volume;
2070     pa_sink *root_sink;
2071
2072     pa_sink_assert_ref(s);
2073     pa_assert_ctl_context();
2074     pa_assert(PA_SINK_IS_LINKED(s->state));
2075     pa_assert(!volume || pa_cvolume_valid(volume));
2076     pa_assert(volume || pa_sink_flat_volume_enabled(s));
2077     pa_assert(!volume || volume->channels == 1 || pa_cvolume_compatible(volume, &s->sample_spec));
2078
2079     /* make sure we don't change the volume when a PASSTHROUGH input is connected ...
2080      * ... *except* if we're being invoked to reset the volume to ensure 0 dB gain */
2081     if (pa_sink_is_passthrough(s) && (!volume || !pa_cvolume_is_norm(volume))) {
2082         pa_log_warn("Cannot change volume, Sink is connected to PASSTHROUGH input");
2083         return;
2084     }
2085
2086     /* In case of volume sharing, the volume is set for the root sink first,
2087      * from which it's then propagated to the sharing sinks. */
2088     root_sink = pa_sink_get_master(s);
2089
2090     if (PA_UNLIKELY(!root_sink))
2091         return;
2092
2093     /* As a special exception we accept mono volumes on all sinks --
2094      * even on those with more complex channel maps */
2095
2096     if (volume) {
2097         if (pa_cvolume_compatible(volume, &s->sample_spec))
2098             new_reference_volume = *volume;
2099         else {
2100             new_reference_volume = s->reference_volume;
2101             pa_cvolume_scale(&new_reference_volume, pa_cvolume_max(volume));
2102         }
2103
2104         pa_cvolume_remap(&new_reference_volume, &s->channel_map, &root_sink->channel_map);
2105
2106         if (update_reference_volume(root_sink, &new_reference_volume, &root_sink->channel_map, save)) {
2107             if (pa_sink_flat_volume_enabled(root_sink)) {
2108                 /* OK, propagate this volume change back to the inputs */
2109                 propagate_reference_volume(root_sink);
2110
2111                 /* And now recalculate the real volume */
2112                 compute_real_volume(root_sink);
2113             } else
2114                 update_real_volume(root_sink, &root_sink->reference_volume, &root_sink->channel_map);
2115         }
2116
2117     } else {
2118         /* If volume is NULL we synchronize the sink's real and
2119          * reference volumes with the stream volumes. */
2120
2121         pa_assert(pa_sink_flat_volume_enabled(root_sink));
2122
2123         /* Ok, let's determine the new real volume */
2124         compute_real_volume(root_sink);
2125
2126         /* Let's 'push' the reference volume if necessary */
2127         pa_cvolume_merge(&new_reference_volume, &s->reference_volume, &root_sink->real_volume);
2128         /* If the sink and its root don't have the same number of channels, we need to remap */
2129         if (s != root_sink && !pa_channel_map_equal(&s->channel_map, &root_sink->channel_map))
2130             pa_cvolume_remap(&new_reference_volume, &s->channel_map, &root_sink->channel_map);
2131         update_reference_volume(root_sink, &new_reference_volume, &root_sink->channel_map, save);
2132
2133         /* Now that the reference volume is updated, we can update the streams'
2134          * reference ratios. */
2135         compute_reference_ratios(root_sink);
2136     }
2137
2138     if (root_sink->set_volume) {
2139         /* If we have a function set_volume(), then we do not apply a
2140          * soft volume by default. However, set_volume() is free to
2141          * apply one to root_sink->soft_volume */
2142
2143         pa_cvolume_reset(&root_sink->soft_volume, root_sink->sample_spec.channels);
2144         if (!(root_sink->flags & PA_SINK_DEFERRED_VOLUME))
2145             root_sink->set_volume(root_sink);
2146
2147     } else
2148         /* If we have no function set_volume(), then the soft volume
2149          * becomes the real volume */
2150         root_sink->soft_volume = root_sink->real_volume;
2151
2152     /* This tells the sink that soft volume and/or real volume changed */
2153     if (send_msg)
2154         pa_assert_se(pa_asyncmsgq_send(root_sink->asyncmsgq, PA_MSGOBJECT(root_sink), PA_SINK_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL) == 0);
2155 }
2156
2157 /* Called from the io thread if sync volume is used, otherwise from the main thread.
2158  * Only to be called by sink implementor */
2159 void pa_sink_set_soft_volume(pa_sink *s, const pa_cvolume *volume) {
2160
2161     pa_sink_assert_ref(s);
2162     pa_assert(!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER));
2163
2164     if (s->flags & PA_SINK_DEFERRED_VOLUME)
2165         pa_sink_assert_io_context(s);
2166     else
2167         pa_assert_ctl_context();
2168
2169     if (!volume)
2170         pa_cvolume_reset(&s->soft_volume, s->sample_spec.channels);
2171     else
2172         s->soft_volume = *volume;
2173
2174     if (PA_SINK_IS_LINKED(s->state) && !(s->flags & PA_SINK_DEFERRED_VOLUME))
2175         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_VOLUME, NULL, 0, NULL) == 0);
2176     else
2177         s->thread_info.soft_volume = s->soft_volume;
2178 }
2179
2180 /* Called from the main thread. Only called for the root sink in volume sharing
2181  * cases, except for internal recursive calls. */
2182 static void propagate_real_volume(pa_sink *s, const pa_cvolume *old_real_volume) {
2183     pa_sink_input *i;
2184     uint32_t idx;
2185
2186     pa_sink_assert_ref(s);
2187     pa_assert(old_real_volume);
2188     pa_assert_ctl_context();
2189     pa_assert(PA_SINK_IS_LINKED(s->state));
2190
2191     /* This is called when the hardware's real volume changes due to
2192      * some external event. We copy the real volume into our
2193      * reference volume and then rebuild the stream volumes based on
2194      * i->real_ratio which should stay fixed. */
2195
2196     if (!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)) {
2197         if (pa_cvolume_equal(old_real_volume, &s->real_volume))
2198             return;
2199
2200         /* 1. Make the real volume the reference volume */
2201         update_reference_volume(s, &s->real_volume, &s->channel_map, true);
2202     }
2203
2204     if (pa_sink_flat_volume_enabled(s)) {
2205
2206         PA_IDXSET_FOREACH(i, s->inputs, idx) {
2207             pa_cvolume new_volume;
2208
2209             /* 2. Since the sink's reference and real volumes are equal
2210              * now our ratios should be too. */
2211             pa_sink_input_set_reference_ratio(i, &i->real_ratio);
2212
2213             /* 3. Recalculate the new stream reference volume based on the
2214              * reference ratio and the sink's reference volume.
2215              *
2216              * This basically calculates:
2217              *
2218              * i->volume = s->reference_volume * i->reference_ratio
2219              *
2220              * This is identical to propagate_reference_volume() */
2221             new_volume = s->reference_volume;
2222             pa_cvolume_remap(&new_volume, &s->channel_map, &i->channel_map);
2223             pa_sw_cvolume_multiply(&new_volume, &new_volume, &i->reference_ratio);
2224             pa_sink_input_set_volume_direct(i, &new_volume);
2225
2226             if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER)
2227                     && PA_SINK_IS_LINKED(i->origin_sink->state))
2228                 propagate_real_volume(i->origin_sink, old_real_volume);
2229         }
2230     }
2231
2232     /* Something got changed in the hardware. It probably makes sense
2233      * to save changed hw settings given that hw volume changes not
2234      * triggered by PA are almost certainly done by the user. */
2235     if (!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER))
2236         s->save_volume = true;
2237 }
2238
2239 /* Called from io thread */
2240 void pa_sink_update_volume_and_mute(pa_sink *s) {
2241     pa_assert(s);
2242     pa_sink_assert_io_context(s);
2243
2244     pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_UPDATE_VOLUME_AND_MUTE, NULL, 0, NULL, NULL);
2245 }
2246
2247 /* Called from main thread */
2248 const pa_cvolume *pa_sink_get_volume(pa_sink *s, bool force_refresh) {
2249     pa_sink_assert_ref(s);
2250     pa_assert_ctl_context();
2251     pa_assert(PA_SINK_IS_LINKED(s->state));
2252
2253     if (s->refresh_volume || force_refresh) {
2254         struct pa_cvolume old_real_volume;
2255
2256         pa_assert(!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER));
2257
2258         old_real_volume = s->real_volume;
2259
2260         if (!(s->flags & PA_SINK_DEFERRED_VOLUME) && s->get_volume)
2261             s->get_volume(s);
2262
2263         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_VOLUME, NULL, 0, NULL) == 0);
2264
2265         update_real_volume(s, &s->real_volume, &s->channel_map);
2266         propagate_real_volume(s, &old_real_volume);
2267     }
2268
2269     return &s->reference_volume;
2270 }
2271
2272 /* Called from main thread. In volume sharing cases, only the root sink may
2273  * call this. */
2274 void pa_sink_volume_changed(pa_sink *s, const pa_cvolume *new_real_volume) {
2275     pa_cvolume old_real_volume;
2276
2277     pa_sink_assert_ref(s);
2278     pa_assert_ctl_context();
2279     pa_assert(PA_SINK_IS_LINKED(s->state));
2280     pa_assert(!(s->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER));
2281
2282     /* The sink implementor may call this if the volume changed to make sure everyone is notified */
2283
2284     old_real_volume = s->real_volume;
2285     update_real_volume(s, new_real_volume, &s->channel_map);
2286     propagate_real_volume(s, &old_real_volume);
2287 }
2288
2289 /* Called from main thread */
2290 void pa_sink_set_mute(pa_sink *s, bool mute, bool save) {
2291     bool old_muted;
2292
2293     pa_sink_assert_ref(s);
2294     pa_assert_ctl_context();
2295
2296     old_muted = s->muted;
2297
2298     if (mute == old_muted) {
2299         s->save_muted |= save;
2300         return;
2301     }
2302
2303     s->muted = mute;
2304     s->save_muted = save;
2305
2306     if (!(s->flags & PA_SINK_DEFERRED_VOLUME) && s->set_mute) {
2307         s->set_mute_in_progress = true;
2308         s->set_mute(s);
2309         s->set_mute_in_progress = false;
2310     }
2311
2312     if (!PA_SINK_IS_LINKED(s->state))
2313         return;
2314
2315     pa_log_debug("The mute of sink %s changed from %s to %s.", s->name, pa_yes_no(old_muted), pa_yes_no(mute));
2316     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_MUTE, NULL, 0, NULL) == 0);
2317     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
2318     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_MUTE_CHANGED], s);
2319 }
2320
2321 /* Called from main thread */
2322 bool pa_sink_get_mute(pa_sink *s, bool force_refresh) {
2323
2324     pa_sink_assert_ref(s);
2325     pa_assert_ctl_context();
2326     pa_assert(PA_SINK_IS_LINKED(s->state));
2327
2328     if ((s->refresh_muted || force_refresh) && s->get_mute) {
2329         bool mute;
2330
2331         if (s->flags & PA_SINK_DEFERRED_VOLUME) {
2332             if (pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_MUTE, &mute, 0, NULL) >= 0)
2333                 pa_sink_mute_changed(s, mute);
2334         } else {
2335             if (s->get_mute(s, &mute) >= 0)
2336                 pa_sink_mute_changed(s, mute);
2337         }
2338     }
2339
2340     return s->muted;
2341 }
2342
2343 /* Called from main thread */
2344 void pa_sink_mute_changed(pa_sink *s, bool new_muted) {
2345     pa_sink_assert_ref(s);
2346     pa_assert_ctl_context();
2347     pa_assert(PA_SINK_IS_LINKED(s->state));
2348
2349     if (s->set_mute_in_progress)
2350         return;
2351
2352     /* pa_sink_set_mute() does this same check, so this may appear redundant,
2353      * but we must have this here also, because the save parameter of
2354      * pa_sink_set_mute() would otherwise have unintended side effects (saving
2355      * the mute state when it shouldn't be saved). */
2356     if (new_muted == s->muted)
2357         return;
2358
2359     pa_sink_set_mute(s, new_muted, true);
2360 }
2361
2362 /* Called from main thread */
2363 bool pa_sink_update_proplist(pa_sink *s, pa_update_mode_t mode, pa_proplist *p) {
2364     pa_sink_assert_ref(s);
2365     pa_assert_ctl_context();
2366
2367     if (p)
2368         pa_proplist_update(s->proplist, mode, p);
2369
2370     if (PA_SINK_IS_LINKED(s->state)) {
2371         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PROPLIST_CHANGED], s);
2372         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
2373     }
2374
2375     return true;
2376 }
2377
2378 /* Called from main thread */
2379 /* FIXME -- this should be dropped and be merged into pa_sink_update_proplist() */
2380 void pa_sink_set_description(pa_sink *s, const char *description) {
2381     const char *old;
2382     pa_sink_assert_ref(s);
2383     pa_assert_ctl_context();
2384
2385     if (!description && !pa_proplist_contains(s->proplist, PA_PROP_DEVICE_DESCRIPTION))
2386         return;
2387
2388     old = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
2389
2390     if (old && description && pa_streq(old, description))
2391         return;
2392
2393     if (description)
2394         pa_proplist_sets(s->proplist, PA_PROP_DEVICE_DESCRIPTION, description);
2395     else
2396         pa_proplist_unset(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
2397
2398     if (s->monitor_source) {
2399         char *n;
2400
2401         n = pa_sprintf_malloc("Monitor Source of %s", description ? description : s->name);
2402         pa_source_set_description(s->monitor_source, n);
2403         pa_xfree(n);
2404     }
2405
2406     if (PA_SINK_IS_LINKED(s->state)) {
2407         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
2408         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PROPLIST_CHANGED], s);
2409     }
2410 }
2411
2412 /* Called from main thread */
2413 unsigned pa_sink_linked_by(pa_sink *s) {
2414     unsigned ret;
2415
2416     pa_sink_assert_ref(s);
2417     pa_assert_ctl_context();
2418     pa_assert(PA_SINK_IS_LINKED(s->state));
2419
2420     ret = pa_idxset_size(s->inputs);
2421
2422     /* We add in the number of streams connected to us here. Please
2423      * note the asymmetry to pa_sink_used_by()! */
2424
2425     if (s->monitor_source)
2426         ret += pa_source_linked_by(s->monitor_source);
2427
2428     return ret;
2429 }
2430
2431 /* Called from main thread */
2432 unsigned pa_sink_used_by(pa_sink *s) {
2433     unsigned ret;
2434
2435     pa_sink_assert_ref(s);
2436     pa_assert_ctl_context();
2437     pa_assert(PA_SINK_IS_LINKED(s->state));
2438
2439     ret = pa_idxset_size(s->inputs);
2440     pa_assert(ret >= s->n_corked);
2441
2442     /* Streams connected to our monitor source do not matter for
2443      * pa_sink_used_by()!.*/
2444
2445     return ret - s->n_corked;
2446 }
2447
2448 /* Called from main thread */
2449 unsigned pa_sink_check_suspend(pa_sink *s, pa_sink_input *ignore_input, pa_source_output *ignore_output) {
2450     unsigned ret;
2451     pa_sink_input *i;
2452     uint32_t idx;
2453
2454     pa_sink_assert_ref(s);
2455     pa_assert_ctl_context();
2456
2457     if (!PA_SINK_IS_LINKED(s->state))
2458         return 0;
2459
2460     ret = 0;
2461
2462     PA_IDXSET_FOREACH(i, s->inputs, idx) {
2463         pa_sink_input_state_t st;
2464
2465         if (i == ignore_input)
2466             continue;
2467
2468         st = pa_sink_input_get_state(i);
2469
2470         /* We do not assert here. It is perfectly valid for a sink input to
2471          * be in the INIT state (i.e. created, marked done but not yet put)
2472          * and we should not care if it's unlinked as it won't contribute
2473          * towards our busy status.
2474          */
2475         if (!PA_SINK_INPUT_IS_LINKED(st))
2476             continue;
2477
2478         if (st == PA_SINK_INPUT_CORKED)
2479             continue;
2480
2481         if (i->flags & PA_SINK_INPUT_DONT_INHIBIT_AUTO_SUSPEND)
2482             continue;
2483
2484         ret ++;
2485     }
2486
2487     if (s->monitor_source)
2488         ret += pa_source_check_suspend(s->monitor_source, ignore_output);
2489
2490     return ret;
2491 }
2492
2493 const char *pa_sink_state_to_string(pa_sink_state_t state) {
2494     switch (state) {
2495         case PA_SINK_INIT:          return "INIT";
2496         case PA_SINK_IDLE:          return "IDLE";
2497         case PA_SINK_RUNNING:       return "RUNNING";
2498         case PA_SINK_SUSPENDED:     return "SUSPENDED";
2499         case PA_SINK_UNLINKED:      return "UNLINKED";
2500         case PA_SINK_INVALID_STATE: return "INVALID_STATE";
2501     }
2502
2503     pa_assert_not_reached();
2504 }
2505
2506 /* Called from the IO thread */
2507 static void sync_input_volumes_within_thread(pa_sink *s) {
2508     pa_sink_input *i;
2509     void *state = NULL;
2510
2511     pa_sink_assert_ref(s);
2512     pa_sink_assert_io_context(s);
2513
2514     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state) {
2515         if (pa_cvolume_equal(&i->thread_info.soft_volume, &i->soft_volume))
2516             continue;
2517
2518         i->thread_info.soft_volume = i->soft_volume;
2519         pa_sink_input_request_rewind(i, 0, true, false, false);
2520     }
2521 }
2522
2523 /* Called from the IO thread. Only called for the root sink in volume sharing
2524  * cases, except for internal recursive calls. */
2525 static void set_shared_volume_within_thread(pa_sink *s) {
2526     pa_sink_input *i = NULL;
2527     void *state = NULL;
2528
2529     pa_sink_assert_ref(s);
2530
2531     PA_MSGOBJECT(s)->process_msg(PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_VOLUME_SYNCED, NULL, 0, NULL);
2532
2533     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state) {
2534         if (i->origin_sink && (i->origin_sink->flags & PA_SINK_SHARE_VOLUME_WITH_MASTER))
2535             set_shared_volume_within_thread(i->origin_sink);
2536     }
2537 }
2538
2539 /* Called from IO thread, except when it is not */
2540 int pa_sink_process_msg(pa_msgobject *o, int code, void *userdata, int64_t offset, pa_memchunk *chunk) {
2541     pa_sink *s = PA_SINK(o);
2542     pa_sink_assert_ref(s);
2543
2544     switch ((pa_sink_message_t) code) {
2545
2546         case PA_SINK_MESSAGE_ADD_INPUT: {
2547             pa_sink_input *i = PA_SINK_INPUT(userdata);
2548
2549             /* If you change anything here, make sure to change the
2550              * sink input handling a few lines down at
2551              * PA_SINK_MESSAGE_FINISH_MOVE, too. */
2552
2553             pa_hashmap_put(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index), pa_sink_input_ref(i));
2554
2555             /* Since the caller sleeps in pa_sink_input_put(), we can
2556              * safely access data outside of thread_info even though
2557              * it is mutable */
2558
2559             if ((i->thread_info.sync_prev = i->sync_prev)) {
2560                 pa_assert(i->sink == i->thread_info.sync_prev->sink);
2561                 pa_assert(i->sync_prev->sync_next == i);
2562                 i->thread_info.sync_prev->thread_info.sync_next = i;
2563             }
2564
2565             if ((i->thread_info.sync_next = i->sync_next)) {
2566                 pa_assert(i->sink == i->thread_info.sync_next->sink);
2567                 pa_assert(i->sync_next->sync_prev == i);
2568                 i->thread_info.sync_next->thread_info.sync_prev = i;
2569             }
2570
2571             pa_sink_input_attach(i);
2572
2573             pa_sink_input_set_state_within_thread(i, i->state);
2574
2575             /* The requested latency of the sink input needs to be fixed up and
2576              * then configured on the sink. If this causes the sink latency to
2577              * go down, the sink implementor is responsible for doing a rewind
2578              * in the update_requested_latency() callback to ensure that the
2579              * sink buffer doesn't contain more data than what the new latency
2580              * allows.
2581              *
2582              * XXX: Does it really make sense to push this responsibility to
2583              * the sink implementors? Wouldn't it be better to do it once in
2584              * the core than many times in the modules? */
2585
2586             if (i->thread_info.requested_sink_latency != (pa_usec_t) -1)
2587                 pa_sink_input_set_requested_latency_within_thread(i, i->thread_info.requested_sink_latency);
2588
2589             pa_sink_input_update_max_rewind(i, s->thread_info.max_rewind);
2590             pa_sink_input_update_max_request(i, s->thread_info.max_request);
2591
2592             /* We don't rewind here automatically. This is left to the
2593              * sink input implementor because some sink inputs need a
2594              * slow start, i.e. need some time to buffer client
2595              * samples before beginning streaming.
2596              *
2597              * XXX: Does it really make sense to push this functionality to
2598              * the sink implementors? Wouldn't it be better to do it once in
2599              * the core than many times in the modules? */
2600
2601             /* In flat volume mode we need to update the volume as
2602              * well */
2603             return o->process_msg(o, PA_SINK_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL);
2604         }
2605
2606         case PA_SINK_MESSAGE_REMOVE_INPUT: {
2607             pa_sink_input *i = PA_SINK_INPUT(userdata);
2608
2609             /* If you change anything here, make sure to change the
2610              * sink input handling a few lines down at
2611              * PA_SINK_MESSAGE_START_MOVE, too. */
2612
2613             pa_sink_input_detach(i);
2614
2615             pa_sink_input_set_state_within_thread(i, i->state);
2616
2617             /* Since the caller sleeps in pa_sink_input_unlink(),
2618              * we can safely access data outside of thread_info even
2619              * though it is mutable */
2620
2621             pa_assert(!i->sync_prev);
2622             pa_assert(!i->sync_next);
2623
2624             if (i->thread_info.sync_prev) {
2625                 i->thread_info.sync_prev->thread_info.sync_next = i->thread_info.sync_prev->sync_next;
2626                 i->thread_info.sync_prev = NULL;
2627             }
2628
2629             if (i->thread_info.sync_next) {
2630                 i->thread_info.sync_next->thread_info.sync_prev = i->thread_info.sync_next->sync_prev;
2631                 i->thread_info.sync_next = NULL;
2632             }
2633
2634             pa_hashmap_remove_and_free(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index));
2635             pa_sink_invalidate_requested_latency(s, true);
2636             pa_sink_request_rewind(s, (size_t) -1);
2637
2638             /* In flat volume mode we need to update the volume as
2639              * well */
2640             return o->process_msg(o, PA_SINK_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL);
2641         }
2642
2643         case PA_SINK_MESSAGE_START_MOVE: {
2644             pa_sink_input *i = PA_SINK_INPUT(userdata);
2645
2646             /* We don't support moving synchronized streams. */
2647             pa_assert(!i->sync_prev);
2648             pa_assert(!i->sync_next);
2649             pa_assert(!i->thread_info.sync_next);
2650             pa_assert(!i->thread_info.sync_prev);
2651
2652             if (i->thread_info.state != PA_SINK_INPUT_CORKED) {
2653                 pa_usec_t usec = 0;
2654                 size_t sink_nbytes, total_nbytes;
2655
2656                 /* The old sink probably has some audio from this
2657                  * stream in its buffer. We want to "take it back" as
2658                  * much as possible and play it to the new sink. We
2659                  * don't know at this point how much the old sink can
2660                  * rewind. We have to pick something, and that
2661                  * something is the full latency of the old sink here.
2662                  * So we rewind the stream buffer by the sink latency
2663                  * amount, which may be more than what we should
2664                  * rewind. This can result in a chunk of audio being
2665                  * played both to the old sink and the new sink.
2666                  *
2667                  * FIXME: Fix this code so that we don't have to make
2668                  * guesses about how much the sink will actually be
2669                  * able to rewind. If someone comes up with a solution
2670                  * for this, something to note is that the part of the
2671                  * latency that the old sink couldn't rewind should
2672                  * ideally be compensated after the stream has moved
2673                  * to the new sink by adding silence. The new sink
2674                  * most likely can't start playing the moved stream
2675                  * immediately, and that gap should be removed from
2676                  * the "compensation silence" (at least at the time of
2677                  * writing this, the move finish code will actually
2678                  * already take care of dropping the new sink's
2679                  * unrewindable latency, so taking into account the
2680                  * unrewindable latency of the old sink is the only
2681                  * problem).
2682                  *
2683                  * The render_memblockq contents are discarded,
2684                  * because when the sink changes, the format of the
2685                  * audio stored in the render_memblockq may change
2686                  * too, making the stored audio invalid. FIXME:
2687                  * However, the read and write indices are moved back
2688                  * the same amount, so if they are not the same now,
2689                  * they won't be the same after the rewind either. If
2690                  * the write index of the render_memblockq is ahead of
2691                  * the read index, then the render_memblockq will feed
2692                  * the new sink some silence first, which it shouldn't
2693                  * do. The write index should be flushed to be the
2694                  * same as the read index. */
2695
2696                 /* Get the latency of the sink */
2697                 usec = pa_sink_get_latency_within_thread(s, false);
2698                 sink_nbytes = pa_usec_to_bytes(usec, &s->sample_spec);
2699                 total_nbytes = sink_nbytes + pa_memblockq_get_length(i->thread_info.render_memblockq);
2700
2701                 if (total_nbytes > 0) {
2702                     i->thread_info.rewrite_nbytes = i->thread_info.resampler ? pa_resampler_request(i->thread_info.resampler, total_nbytes) : total_nbytes;
2703                     i->thread_info.rewrite_flush = true;
2704                     pa_sink_input_process_rewind(i, sink_nbytes);
2705                 }
2706             }
2707
2708             pa_sink_input_detach(i);
2709
2710             /* Let's remove the sink input ...*/
2711             pa_hashmap_remove_and_free(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index));
2712
2713             pa_sink_invalidate_requested_latency(s, true);
2714
2715             pa_log_debug("Requesting rewind due to started move");
2716             pa_sink_request_rewind(s, (size_t) -1);
2717
2718             /* In flat volume mode we need to update the volume as
2719              * well */
2720             return o->process_msg(o, PA_SINK_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL);
2721         }
2722
2723         case PA_SINK_MESSAGE_FINISH_MOVE: {
2724             pa_sink_input *i = PA_SINK_INPUT(userdata);
2725
2726             /* We don't support moving synchronized streams. */
2727             pa_assert(!i->sync_prev);
2728             pa_assert(!i->sync_next);
2729             pa_assert(!i->thread_info.sync_next);
2730             pa_assert(!i->thread_info.sync_prev);
2731
2732             pa_hashmap_put(s->thread_info.inputs, PA_UINT32_TO_PTR(i->index), pa_sink_input_ref(i));
2733
2734             pa_sink_input_attach(i);
2735
2736             if (i->thread_info.state != PA_SINK_INPUT_CORKED) {
2737                 pa_usec_t usec = 0;
2738                 size_t nbytes;
2739
2740                 /* In the ideal case the new sink would start playing
2741                  * the stream immediately. That requires the sink to
2742                  * be able to rewind all of its latency, which usually
2743                  * isn't possible, so there will probably be some gap
2744                  * before the moved stream becomes audible. We then
2745                  * have two possibilities: 1) start playing the stream
2746                  * from where it is now, or 2) drop the unrewindable
2747                  * latency of the sink from the stream. With option 1
2748                  * we won't lose any audio but the stream will have a
2749                  * pause. With option 2 we may lose some audio but the
2750                  * stream time will be somewhat in sync with the wall
2751                  * clock. Lennart seems to have chosen option 2 (one
2752                  * of the reasons might have been that option 1 is
2753                  * actually much harder to implement), so we drop the
2754                  * latency of the new sink from the moved stream and
2755                  * hope that the sink will undo most of that in the
2756                  * rewind. */
2757
2758                 /* Get the latency of the sink */
2759                 usec = pa_sink_get_latency_within_thread(s, false);
2760                 nbytes = pa_usec_to_bytes(usec, &s->sample_spec);
2761
2762                 if (nbytes > 0)
2763                     pa_sink_input_drop(i, nbytes);
2764
2765                 pa_log_debug("Requesting rewind due to finished move");
2766                 pa_sink_request_rewind(s, nbytes);
2767             }
2768
2769             /* Updating the requested sink latency has to be done
2770              * after the sink rewind request, not before, because
2771              * otherwise the sink may limit the rewind amount
2772              * needlessly. */
2773
2774             if (i->thread_info.requested_sink_latency != (pa_usec_t) -1)
2775                 pa_sink_input_set_requested_latency_within_thread(i, i->thread_info.requested_sink_latency);
2776
2777             pa_sink_input_update_max_rewind(i, s->thread_info.max_rewind);
2778             pa_sink_input_update_max_request(i, s->thread_info.max_request);
2779
2780             return o->process_msg(o, PA_SINK_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL);
2781         }
2782
2783         case PA_SINK_MESSAGE_SET_SHARED_VOLUME: {
2784             pa_sink *root_sink = pa_sink_get_master(s);
2785
2786             if (PA_LIKELY(root_sink))
2787                 set_shared_volume_within_thread(root_sink);
2788
2789             return 0;
2790         }
2791
2792         case PA_SINK_MESSAGE_SET_VOLUME_SYNCED:
2793
2794             if (s->flags & PA_SINK_DEFERRED_VOLUME) {
2795                 s->set_volume(s);
2796                 pa_sink_volume_change_push(s);
2797             }
2798             /* Fall through ... */
2799
2800         case PA_SINK_MESSAGE_SET_VOLUME:
2801
2802             if (!pa_cvolume_equal(&s->thread_info.soft_volume, &s->soft_volume)) {
2803                 s->thread_info.soft_volume = s->soft_volume;
2804                 pa_sink_request_rewind(s, (size_t) -1);
2805             }
2806
2807             /* Fall through ... */
2808
2809         case PA_SINK_MESSAGE_SYNC_VOLUMES:
2810             sync_input_volumes_within_thread(s);
2811             return 0;
2812
2813         case PA_SINK_MESSAGE_GET_VOLUME:
2814
2815             if ((s->flags & PA_SINK_DEFERRED_VOLUME) && s->get_volume) {
2816                 s->get_volume(s);
2817                 pa_sink_volume_change_flush(s);
2818                 pa_sw_cvolume_divide(&s->thread_info.current_hw_volume, &s->real_volume, &s->soft_volume);
2819             }
2820
2821             /* In case sink implementor reset SW volume. */
2822             if (!pa_cvolume_equal(&s->thread_info.soft_volume, &s->soft_volume)) {
2823                 s->thread_info.soft_volume = s->soft_volume;
2824                 pa_sink_request_rewind(s, (size_t) -1);
2825             }
2826
2827             return 0;
2828
2829         case PA_SINK_MESSAGE_SET_MUTE:
2830
2831             if (s->thread_info.soft_muted != s->muted) {
2832                 s->thread_info.soft_muted = s->muted;
2833                 pa_sink_request_rewind(s, (size_t) -1);
2834             }
2835
2836             if (s->flags & PA_SINK_DEFERRED_VOLUME && s->set_mute)
2837                 s->set_mute(s);
2838
2839             return 0;
2840
2841         case PA_SINK_MESSAGE_GET_MUTE:
2842
2843             if (s->flags & PA_SINK_DEFERRED_VOLUME && s->get_mute)
2844                 return s->get_mute(s, userdata);
2845
2846             return 0;
2847
2848         case PA_SINK_MESSAGE_SET_STATE: {
2849
2850             bool suspend_change =
2851                 (s->thread_info.state == PA_SINK_SUSPENDED && PA_SINK_IS_OPENED(PA_PTR_TO_UINT(userdata))) ||
2852                 (PA_SINK_IS_OPENED(s->thread_info.state) && PA_PTR_TO_UINT(userdata) == PA_SINK_SUSPENDED);
2853
2854             if (s->set_state_in_io_thread) {
2855                 int r;
2856
2857                 if ((r = s->set_state_in_io_thread(s, PA_PTR_TO_UINT(userdata))) < 0)
2858                     return r;
2859             }
2860
2861             s->thread_info.state = PA_PTR_TO_UINT(userdata);
2862
2863             if (s->thread_info.state == PA_SINK_SUSPENDED) {
2864                 s->thread_info.rewind_nbytes = 0;
2865                 s->thread_info.rewind_requested = false;
2866             }
2867
2868             if (suspend_change) {
2869                 pa_sink_input *i;
2870                 void *state = NULL;
2871
2872                 while ((i = pa_hashmap_iterate(s->thread_info.inputs, &state, NULL)))
2873                     if (i->suspend_within_thread)
2874                         i->suspend_within_thread(i, s->thread_info.state == PA_SINK_SUSPENDED);
2875             }
2876
2877             return 0;
2878         }
2879
2880         case PA_SINK_MESSAGE_GET_REQUESTED_LATENCY: {
2881
2882             pa_usec_t *usec = userdata;
2883             *usec = pa_sink_get_requested_latency_within_thread(s);
2884
2885             /* Yes, that's right, the IO thread will see -1 when no
2886              * explicit requested latency is configured, the main
2887              * thread will see max_latency */
2888             if (*usec == (pa_usec_t) -1)
2889                 *usec = s->thread_info.max_latency;
2890
2891             return 0;
2892         }
2893
2894         case PA_SINK_MESSAGE_SET_LATENCY_RANGE: {
2895             pa_usec_t *r = userdata;
2896
2897             pa_sink_set_latency_range_within_thread(s, r[0], r[1]);
2898
2899             return 0;
2900         }
2901
2902         case PA_SINK_MESSAGE_GET_LATENCY_RANGE: {
2903             pa_usec_t *r = userdata;
2904
2905             r[0] = s->thread_info.min_latency;
2906             r[1] = s->thread_info.max_latency;
2907
2908             return 0;
2909         }
2910
2911         case PA_SINK_MESSAGE_GET_FIXED_LATENCY:
2912
2913             *((pa_usec_t*) userdata) = s->thread_info.fixed_latency;
2914             return 0;
2915
2916         case PA_SINK_MESSAGE_SET_FIXED_LATENCY:
2917
2918             pa_sink_set_fixed_latency_within_thread(s, (pa_usec_t) offset);
2919             return 0;
2920
2921         case PA_SINK_MESSAGE_GET_MAX_REWIND:
2922
2923             *((size_t*) userdata) = s->thread_info.max_rewind;
2924             return 0;
2925
2926         case PA_SINK_MESSAGE_GET_MAX_REQUEST:
2927
2928             *((size_t*) userdata) = s->thread_info.max_request;
2929             return 0;
2930
2931         case PA_SINK_MESSAGE_SET_MAX_REWIND:
2932
2933             pa_sink_set_max_rewind_within_thread(s, (size_t) offset);
2934             return 0;
2935
2936         case PA_SINK_MESSAGE_SET_MAX_REQUEST:
2937
2938             pa_sink_set_max_request_within_thread(s, (size_t) offset);
2939             return 0;
2940
2941         case PA_SINK_MESSAGE_SET_PORT:
2942
2943             pa_assert(userdata);
2944             if (s->set_port) {
2945                 struct sink_message_set_port *msg_data = userdata;
2946                 msg_data->ret = s->set_port(s, msg_data->port);
2947             }
2948             return 0;
2949
2950         case PA_SINK_MESSAGE_UPDATE_VOLUME_AND_MUTE:
2951             /* This message is sent from IO-thread and handled in main thread. */
2952             pa_assert_ctl_context();
2953
2954             /* Make sure we're not messing with main thread when no longer linked */
2955             if (!PA_SINK_IS_LINKED(s->state))
2956                 return 0;
2957
2958             pa_sink_get_volume(s, true);
2959             pa_sink_get_mute(s, true);
2960             return 0;
2961
2962         case PA_SINK_MESSAGE_SET_PORT_LATENCY_OFFSET:
2963             s->thread_info.port_latency_offset = offset;
2964             return 0;
2965
2966         case PA_SINK_MESSAGE_GET_LATENCY:
2967         case PA_SINK_MESSAGE_MAX:
2968             ;
2969     }
2970
2971     return -1;
2972 }
2973
2974 /* Called from main thread */
2975 int pa_sink_suspend_all(pa_core *c, bool suspend, pa_suspend_cause_t cause) {
2976     pa_sink *sink;
2977     uint32_t idx;
2978     int ret = 0;
2979
2980     pa_core_assert_ref(c);
2981     pa_assert_ctl_context();
2982     pa_assert(cause != 0);
2983
2984     PA_IDXSET_FOREACH(sink, c->sinks, idx) {
2985         int r;
2986
2987         if ((r = pa_sink_suspend(sink, suspend, cause)) < 0)
2988             ret = r;
2989     }
2990
2991     return ret;
2992 }
2993
2994 /* Called from IO thread */
2995 void pa_sink_detach_within_thread(pa_sink *s) {
2996     pa_sink_input *i;
2997     void *state = NULL;
2998
2999     pa_sink_assert_ref(s);
3000     pa_sink_assert_io_context(s);
3001     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
3002
3003     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3004         pa_sink_input_detach(i);
3005
3006     if (s->monitor_source)
3007         pa_source_detach_within_thread(s->monitor_source);
3008 }
3009
3010 /* Called from IO thread */
3011 void pa_sink_attach_within_thread(pa_sink *s) {
3012     pa_sink_input *i;
3013     void *state = NULL;
3014
3015     pa_sink_assert_ref(s);
3016     pa_sink_assert_io_context(s);
3017     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
3018
3019     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3020         pa_sink_input_attach(i);
3021
3022     if (s->monitor_source)
3023         pa_source_attach_within_thread(s->monitor_source);
3024 }
3025
3026 /* Called from IO thread */
3027 void pa_sink_request_rewind(pa_sink*s, size_t nbytes) {
3028     pa_sink_assert_ref(s);
3029     pa_sink_assert_io_context(s);
3030     pa_assert(PA_SINK_IS_LINKED(s->thread_info.state));
3031
3032     if (nbytes == (size_t) -1)
3033         nbytes = s->thread_info.max_rewind;
3034
3035     nbytes = PA_MIN(nbytes, s->thread_info.max_rewind);
3036
3037     if (s->thread_info.rewind_requested &&
3038         nbytes <= s->thread_info.rewind_nbytes)
3039         return;
3040
3041     s->thread_info.rewind_nbytes = nbytes;
3042     s->thread_info.rewind_requested = true;
3043
3044     if (s->request_rewind)
3045         s->request_rewind(s);
3046 }
3047
3048 /* Called from IO thread */
3049 pa_usec_t pa_sink_get_requested_latency_within_thread(pa_sink *s) {
3050     pa_usec_t result = (pa_usec_t) -1;
3051     pa_sink_input *i;
3052     void *state = NULL;
3053     pa_usec_t monitor_latency;
3054
3055     pa_sink_assert_ref(s);
3056     pa_sink_assert_io_context(s);
3057
3058     if (!(s->flags & PA_SINK_DYNAMIC_LATENCY))
3059         return PA_CLAMP(s->thread_info.fixed_latency, s->thread_info.min_latency, s->thread_info.max_latency);
3060
3061     if (s->thread_info.requested_latency_valid)
3062         return s->thread_info.requested_latency;
3063
3064     PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3065         if (i->thread_info.requested_sink_latency != (pa_usec_t) -1 &&
3066             (result == (pa_usec_t) -1 || result > i->thread_info.requested_sink_latency))
3067             result = i->thread_info.requested_sink_latency;
3068
3069     monitor_latency = pa_source_get_requested_latency_within_thread(s->monitor_source);
3070
3071     if (monitor_latency != (pa_usec_t) -1 &&
3072         (result == (pa_usec_t) -1 || result > monitor_latency))
3073         result = monitor_latency;
3074
3075     if (result != (pa_usec_t) -1)
3076         result = PA_CLAMP(result, s->thread_info.min_latency, s->thread_info.max_latency);
3077
3078     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
3079         /* Only cache if properly initialized */
3080         s->thread_info.requested_latency = result;
3081         s->thread_info.requested_latency_valid = true;
3082     }
3083
3084     return result;
3085 }
3086
3087 /* Called from main thread */
3088 pa_usec_t pa_sink_get_requested_latency(pa_sink *s) {
3089     pa_usec_t usec = 0;
3090
3091     pa_sink_assert_ref(s);
3092     pa_assert_ctl_context();
3093     pa_assert(PA_SINK_IS_LINKED(s->state));
3094
3095     if (s->state == PA_SINK_SUSPENDED)
3096         return 0;
3097
3098     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_REQUESTED_LATENCY, &usec, 0, NULL) == 0);
3099
3100     return usec;
3101 }
3102
3103 /* Called from IO as well as the main thread -- the latter only before the IO thread started up */
3104 void pa_sink_set_max_rewind_within_thread(pa_sink *s, size_t max_rewind) {
3105     pa_sink_input *i;
3106     void *state = NULL;
3107
3108     pa_sink_assert_ref(s);
3109     pa_sink_assert_io_context(s);
3110
3111     if (max_rewind == s->thread_info.max_rewind)
3112         return;
3113
3114     s->thread_info.max_rewind = max_rewind;
3115
3116     if (PA_SINK_IS_LINKED(s->thread_info.state))
3117         PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3118             pa_sink_input_update_max_rewind(i, s->thread_info.max_rewind);
3119
3120     if (s->monitor_source)
3121         pa_source_set_max_rewind_within_thread(s->monitor_source, s->thread_info.max_rewind);
3122 }
3123
3124 /* Called from main thread */
3125 void pa_sink_set_max_rewind(pa_sink *s, size_t max_rewind) {
3126     pa_sink_assert_ref(s);
3127     pa_assert_ctl_context();
3128
3129     if (PA_SINK_IS_LINKED(s->state))
3130         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_MAX_REWIND, NULL, max_rewind, NULL) == 0);
3131     else
3132         pa_sink_set_max_rewind_within_thread(s, max_rewind);
3133 }
3134
3135 /* Called from IO as well as the main thread -- the latter only before the IO thread started up */
3136 void pa_sink_set_max_request_within_thread(pa_sink *s, size_t max_request) {
3137     void *state = NULL;
3138
3139     pa_sink_assert_ref(s);
3140     pa_sink_assert_io_context(s);
3141
3142     if (max_request == s->thread_info.max_request)
3143         return;
3144
3145     s->thread_info.max_request = max_request;
3146
3147     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
3148         pa_sink_input *i;
3149
3150         PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3151             pa_sink_input_update_max_request(i, s->thread_info.max_request);
3152     }
3153 }
3154
3155 /* Called from main thread */
3156 void pa_sink_set_max_request(pa_sink *s, size_t max_request) {
3157     pa_sink_assert_ref(s);
3158     pa_assert_ctl_context();
3159
3160     if (PA_SINK_IS_LINKED(s->state))
3161         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_MAX_REQUEST, NULL, max_request, NULL) == 0);
3162     else
3163         pa_sink_set_max_request_within_thread(s, max_request);
3164 }
3165
3166 /* Called from IO thread */
3167 void pa_sink_invalidate_requested_latency(pa_sink *s, bool dynamic) {
3168     pa_sink_input *i;
3169     void *state = NULL;
3170
3171     pa_sink_assert_ref(s);
3172     pa_sink_assert_io_context(s);
3173
3174     if ((s->flags & PA_SINK_DYNAMIC_LATENCY))
3175         s->thread_info.requested_latency_valid = false;
3176     else if (dynamic)
3177         return;
3178
3179     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
3180
3181         if (s->update_requested_latency)
3182             s->update_requested_latency(s);
3183
3184         PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3185             if (i->update_sink_requested_latency)
3186                 i->update_sink_requested_latency(i);
3187     }
3188 }
3189
3190 /* Called from main thread */
3191 void pa_sink_set_latency_range(pa_sink *s, pa_usec_t min_latency, pa_usec_t max_latency) {
3192     pa_sink_assert_ref(s);
3193     pa_assert_ctl_context();
3194
3195     /* min_latency == 0:           no limit
3196      * min_latency anything else:  specified limit
3197      *
3198      * Similar for max_latency */
3199
3200     if (min_latency < ABSOLUTE_MIN_LATENCY)
3201         min_latency = ABSOLUTE_MIN_LATENCY;
3202
3203     if (max_latency <= 0 ||
3204         max_latency > ABSOLUTE_MAX_LATENCY)
3205         max_latency = ABSOLUTE_MAX_LATENCY;
3206
3207     pa_assert(min_latency <= max_latency);
3208
3209     /* Hmm, let's see if someone forgot to set PA_SINK_DYNAMIC_LATENCY here... */
3210     pa_assert((min_latency == ABSOLUTE_MIN_LATENCY &&
3211                max_latency == ABSOLUTE_MAX_LATENCY) ||
3212               (s->flags & PA_SINK_DYNAMIC_LATENCY));
3213
3214     if (PA_SINK_IS_LINKED(s->state)) {
3215         pa_usec_t r[2];
3216
3217         r[0] = min_latency;
3218         r[1] = max_latency;
3219
3220         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_LATENCY_RANGE, r, 0, NULL) == 0);
3221     } else
3222         pa_sink_set_latency_range_within_thread(s, min_latency, max_latency);
3223 }
3224
3225 /* Called from main thread */
3226 void pa_sink_get_latency_range(pa_sink *s, pa_usec_t *min_latency, pa_usec_t *max_latency) {
3227     pa_sink_assert_ref(s);
3228     pa_assert_ctl_context();
3229     pa_assert(min_latency);
3230     pa_assert(max_latency);
3231
3232     if (PA_SINK_IS_LINKED(s->state)) {
3233         pa_usec_t r[2] = { 0, 0 };
3234
3235         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_LATENCY_RANGE, r, 0, NULL) == 0);
3236
3237         *min_latency = r[0];
3238         *max_latency = r[1];
3239     } else {
3240         *min_latency = s->thread_info.min_latency;
3241         *max_latency = s->thread_info.max_latency;
3242     }
3243 }
3244
3245 /* Called from IO thread */
3246 void pa_sink_set_latency_range_within_thread(pa_sink *s, pa_usec_t min_latency, pa_usec_t max_latency) {
3247     pa_sink_assert_ref(s);
3248     pa_sink_assert_io_context(s);
3249
3250     pa_assert(min_latency >= ABSOLUTE_MIN_LATENCY);
3251     pa_assert(max_latency <= ABSOLUTE_MAX_LATENCY);
3252     pa_assert(min_latency <= max_latency);
3253
3254     /* Hmm, let's see if someone forgot to set PA_SINK_DYNAMIC_LATENCY here... */
3255     pa_assert((min_latency == ABSOLUTE_MIN_LATENCY &&
3256                max_latency == ABSOLUTE_MAX_LATENCY) ||
3257               (s->flags & PA_SINK_DYNAMIC_LATENCY));
3258
3259     if (s->thread_info.min_latency == min_latency &&
3260         s->thread_info.max_latency == max_latency)
3261         return;
3262
3263     s->thread_info.min_latency = min_latency;
3264     s->thread_info.max_latency = max_latency;
3265
3266     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
3267         pa_sink_input *i;
3268         void *state = NULL;
3269
3270         PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3271             if (i->update_sink_latency_range)
3272                 i->update_sink_latency_range(i);
3273     }
3274
3275     pa_sink_invalidate_requested_latency(s, false);
3276
3277     pa_source_set_latency_range_within_thread(s->monitor_source, min_latency, max_latency);
3278 }
3279
3280 /* Called from main thread */
3281 void pa_sink_set_fixed_latency(pa_sink *s, pa_usec_t latency) {
3282     pa_sink_assert_ref(s);
3283     pa_assert_ctl_context();
3284
3285     if (s->flags & PA_SINK_DYNAMIC_LATENCY) {
3286         pa_assert(latency == 0);
3287         return;
3288     }
3289
3290     if (latency < ABSOLUTE_MIN_LATENCY)
3291         latency = ABSOLUTE_MIN_LATENCY;
3292
3293     if (latency > ABSOLUTE_MAX_LATENCY)
3294         latency = ABSOLUTE_MAX_LATENCY;
3295
3296     if (PA_SINK_IS_LINKED(s->state))
3297         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_FIXED_LATENCY, NULL, (int64_t) latency, NULL) == 0);
3298     else
3299         s->thread_info.fixed_latency = latency;
3300
3301     pa_source_set_fixed_latency(s->monitor_source, latency);
3302 }
3303
3304 /* Called from main thread */
3305 pa_usec_t pa_sink_get_fixed_latency(pa_sink *s) {
3306     pa_usec_t latency;
3307
3308     pa_sink_assert_ref(s);
3309     pa_assert_ctl_context();
3310
3311     if (s->flags & PA_SINK_DYNAMIC_LATENCY)
3312         return 0;
3313
3314     if (PA_SINK_IS_LINKED(s->state))
3315         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_FIXED_LATENCY, &latency, 0, NULL) == 0);
3316     else
3317         latency = s->thread_info.fixed_latency;
3318
3319     return latency;
3320 }
3321
3322 /* Called from IO thread */
3323 void pa_sink_set_fixed_latency_within_thread(pa_sink *s, pa_usec_t latency) {
3324     pa_sink_assert_ref(s);
3325     pa_sink_assert_io_context(s);
3326
3327     if (s->flags & PA_SINK_DYNAMIC_LATENCY) {
3328         pa_assert(latency == 0);
3329         s->thread_info.fixed_latency = 0;
3330
3331         if (s->monitor_source)
3332             pa_source_set_fixed_latency_within_thread(s->monitor_source, 0);
3333
3334         return;
3335     }
3336
3337     pa_assert(latency >= ABSOLUTE_MIN_LATENCY);
3338     pa_assert(latency <= ABSOLUTE_MAX_LATENCY);
3339
3340     if (s->thread_info.fixed_latency == latency)
3341         return;
3342
3343     s->thread_info.fixed_latency = latency;
3344
3345     if (PA_SINK_IS_LINKED(s->thread_info.state)) {
3346         pa_sink_input *i;
3347         void *state = NULL;
3348
3349         PA_HASHMAP_FOREACH(i, s->thread_info.inputs, state)
3350             if (i->update_sink_fixed_latency)
3351                 i->update_sink_fixed_latency(i);
3352     }
3353
3354     pa_sink_invalidate_requested_latency(s, false);
3355
3356     pa_source_set_fixed_latency_within_thread(s->monitor_source, latency);
3357 }
3358
3359 /* Called from main context */
3360 void pa_sink_set_port_latency_offset(pa_sink *s, int64_t offset) {
3361     pa_sink_assert_ref(s);
3362
3363     s->port_latency_offset = offset;
3364
3365     if (PA_SINK_IS_LINKED(s->state))
3366         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_PORT_LATENCY_OFFSET, NULL, offset, NULL) == 0);
3367     else
3368         s->thread_info.port_latency_offset = offset;
3369
3370     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PORT_LATENCY_OFFSET_CHANGED], s);
3371 }
3372
3373 /* Called from main context */
3374 size_t pa_sink_get_max_rewind(pa_sink *s) {
3375     size_t r;
3376     pa_assert_ctl_context();
3377     pa_sink_assert_ref(s);
3378
3379     if (!PA_SINK_IS_LINKED(s->state))
3380         return s->thread_info.max_rewind;
3381
3382     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_MAX_REWIND, &r, 0, NULL) == 0);
3383
3384     return r;
3385 }
3386
3387 /* Called from main context */
3388 size_t pa_sink_get_max_request(pa_sink *s) {
3389     size_t r;
3390     pa_sink_assert_ref(s);
3391     pa_assert_ctl_context();
3392
3393     if (!PA_SINK_IS_LINKED(s->state))
3394         return s->thread_info.max_request;
3395
3396     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_GET_MAX_REQUEST, &r, 0, NULL) == 0);
3397
3398     return r;
3399 }
3400
3401 /* Called from main context */
3402 int pa_sink_set_port(pa_sink *s, const char *name, bool save) {
3403     pa_device_port *port;
3404     int ret;
3405
3406     pa_sink_assert_ref(s);
3407     pa_assert_ctl_context();
3408
3409     if (!s->set_port) {
3410         pa_log_debug("set_port() operation not implemented for sink %u \"%s\"", s->index, s->name);
3411         return -PA_ERR_NOTIMPLEMENTED;
3412     }
3413
3414     if (!name)
3415         return -PA_ERR_NOENTITY;
3416
3417     if (!(port = pa_hashmap_get(s->ports, name)))
3418         return -PA_ERR_NOENTITY;
3419
3420     if (s->active_port == port) {
3421         s->save_port = s->save_port || save;
3422         return 0;
3423     }
3424
3425     if (s->flags & PA_SINK_DEFERRED_VOLUME) {
3426         struct sink_message_set_port msg = { .port = port, .ret = 0 };
3427         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SINK_MESSAGE_SET_PORT, &msg, 0, NULL) == 0);
3428         ret = msg.ret;
3429     }
3430     else
3431         ret = s->set_port(s, port);
3432
3433     if (ret < 0)
3434         return -PA_ERR_NOENTITY;
3435
3436     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
3437
3438     pa_log_info("Changed port of sink %u \"%s\" to %s", s->index, s->name, port->name);
3439
3440     s->active_port = port;
3441     s->save_port = save;
3442
3443     pa_sink_set_port_latency_offset(s, s->active_port->latency_offset);
3444
3445     /* The active port affects the default sink selection. */
3446     pa_core_update_default_sink(s->core);
3447
3448     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_PORT_CHANGED], s);
3449
3450     return 0;
3451 }
3452
3453 bool pa_device_init_icon(pa_proplist *p, bool is_sink) {
3454     const char *ff, *c, *t = NULL, *s = "", *profile, *bus;
3455
3456     pa_assert(p);
3457
3458     if (pa_proplist_contains(p, PA_PROP_DEVICE_ICON_NAME))
3459         return true;
3460
3461     if ((ff = pa_proplist_gets(p, PA_PROP_DEVICE_FORM_FACTOR))) {
3462
3463         if (pa_streq(ff, "microphone"))
3464             t = "audio-input-microphone";
3465         else if (pa_streq(ff, "webcam"))
3466             t = "camera-web";
3467         else if (pa_streq(ff, "computer"))
3468             t = "computer";
3469         else if (pa_streq(ff, "handset"))
3470             t = "phone";
3471         else if (pa_streq(ff, "portable"))
3472             t = "multimedia-player";
3473         else if (pa_streq(ff, "tv"))
3474             t = "video-display";
3475
3476         /*
3477          * The following icons are not part of the icon naming spec,
3478          * because Rodney Dawes sucks as the maintainer of that spec.
3479          *
3480          * http://lists.freedesktop.org/archives/xdg/2009-May/010397.html
3481          */
3482         else if (pa_streq(ff, "headset"))
3483             t = "audio-headset";
3484         else if (pa_streq(ff, "headphone"))
3485             t = "audio-headphones";
3486         else if (pa_streq(ff, "speaker"))
3487             t = "audio-speakers";
3488         else if (pa_streq(ff, "hands-free"))
3489             t = "audio-handsfree";
3490     }
3491
3492     if (!t)
3493         if ((c = pa_proplist_gets(p, PA_PROP_DEVICE_CLASS)))
3494             if (pa_streq(c, "modem"))
3495                 t = "modem";
3496
3497     if (!t) {
3498         if (is_sink)
3499             t = "audio-card";
3500         else
3501             t = "audio-input-microphone";
3502     }
3503
3504     if ((profile = pa_proplist_gets(p, PA_PROP_DEVICE_PROFILE_NAME))) {
3505         if (strstr(profile, "analog"))
3506             s = "-analog";
3507         else if (strstr(profile, "iec958"))
3508             s = "-iec958";
3509         else if (strstr(profile, "hdmi"))
3510             s = "-hdmi";
3511     }
3512
3513     bus = pa_proplist_gets(p, PA_PROP_DEVICE_BUS);
3514
3515     pa_proplist_setf(p, PA_PROP_DEVICE_ICON_NAME, "%s%s%s%s", t, pa_strempty(s), bus ? "-" : "", pa_strempty(bus));
3516
3517     return true;
3518 }
3519
3520 bool pa_device_init_description(pa_proplist *p, pa_card *card) {
3521     const char *s, *d = NULL, *k;
3522     pa_assert(p);
3523
3524     if (pa_proplist_contains(p, PA_PROP_DEVICE_DESCRIPTION))
3525         return true;
3526
3527     if (card)
3528         if ((s = pa_proplist_gets(card->proplist, PA_PROP_DEVICE_DESCRIPTION)))
3529             d = s;
3530
3531     if (!d)
3532         if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_FORM_FACTOR)))
3533             if (pa_streq(s, "internal"))
3534                 d = _("Built-in Audio");
3535
3536     if (!d)
3537         if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_CLASS)))
3538             if (pa_streq(s, "modem"))
3539                 d = _("Modem");
3540
3541     if (!d)
3542         d = pa_proplist_gets(p, PA_PROP_DEVICE_PRODUCT_NAME);
3543
3544     if (!d)
3545         return false;
3546
3547     k = pa_proplist_gets(p, PA_PROP_DEVICE_PROFILE_DESCRIPTION);
3548
3549     if (d && k)
3550         pa_proplist_setf(p, PA_PROP_DEVICE_DESCRIPTION, "%s %s", d, k);
3551     else if (d)
3552         pa_proplist_sets(p, PA_PROP_DEVICE_DESCRIPTION, d);
3553
3554     return true;
3555 }
3556
3557 bool pa_device_init_intended_roles(pa_proplist *p) {
3558     const char *s;
3559     pa_assert(p);
3560
3561     if (pa_proplist_contains(p, PA_PROP_DEVICE_INTENDED_ROLES))
3562         return true;
3563
3564     if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_FORM_FACTOR)))
3565         if (pa_streq(s, "handset") || pa_streq(s, "hands-free")
3566             || pa_streq(s, "headset")) {
3567             pa_proplist_sets(p, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
3568             return true;
3569         }
3570
3571     return false;
3572 }
3573
3574 unsigned pa_device_init_priority(pa_proplist *p) {
3575     const char *s;
3576     unsigned priority = 0;
3577
3578     pa_assert(p);
3579
3580     if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_CLASS))) {
3581
3582         if (pa_streq(s, "sound"))
3583             priority += 9000;
3584         else if (!pa_streq(s, "modem"))
3585             priority += 1000;
3586     }
3587
3588     if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_FORM_FACTOR))) {
3589
3590         if (pa_streq(s, "headphone"))
3591             priority += 900;
3592         else if (pa_streq(s, "hifi"))
3593             priority += 600;
3594         else if (pa_streq(s, "speaker"))
3595             priority += 500;
3596         else if (pa_streq(s, "portable"))
3597             priority += 450;
3598     }
3599
3600     if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_BUS))) {
3601
3602         if (pa_streq(s, "bluetooth"))
3603             priority += 50;
3604         else if (pa_streq(s, "usb"))
3605             priority += 40;
3606         else if (pa_streq(s, "pci"))
3607             priority += 30;
3608     }
3609
3610     if ((s = pa_proplist_gets(p, PA_PROP_DEVICE_PROFILE_NAME))) {
3611
3612         if (pa_startswith(s, "analog-"))
3613             priority += 9;
3614         else if (pa_startswith(s, "iec958-"))
3615             priority += 8;
3616     }
3617
3618     return priority;
3619 }
3620
3621 PA_STATIC_FLIST_DECLARE(pa_sink_volume_change, 0, pa_xfree);
3622
3623 /* Called from the IO thread. */
3624 static pa_sink_volume_change *pa_sink_volume_change_new(pa_sink *s) {
3625     pa_sink_volume_change *c;
3626     if (!(c = pa_flist_pop(PA_STATIC_FLIST_GET(pa_sink_volume_change))))
3627         c = pa_xnew(pa_sink_volume_change, 1);
3628
3629     PA_LLIST_INIT(pa_sink_volume_change, c);
3630     c->at = 0;
3631     pa_cvolume_reset(&c->hw_volume, s->sample_spec.channels);
3632     return c;
3633 }
3634
3635 /* Called from the IO thread. */
3636 static void pa_sink_volume_change_free(pa_sink_volume_change *c) {
3637     pa_assert(c);
3638     if (pa_flist_push(PA_STATIC_FLIST_GET(pa_sink_volume_change), c) < 0)
3639         pa_xfree(c);
3640 }
3641
3642 /* Called from the IO thread. */
3643 void pa_sink_volume_change_push(pa_sink *s) {
3644     pa_sink_volume_change *c = NULL;
3645     pa_sink_volume_change *nc = NULL;
3646     pa_sink_volume_change *pc = NULL;
3647     uint32_t safety_margin = s->thread_info.volume_change_safety_margin;
3648
3649     const char *direction = NULL;
3650
3651     pa_assert(s);
3652     nc = pa_sink_volume_change_new(s);
3653
3654     /* NOTE: There is already more different volumes in pa_sink that I can remember.
3655      *       Adding one more volume for HW would get us rid of this, but I am trying
3656      *       to survive with the ones we already have. */
3657     pa_sw_cvolume_divide(&nc->hw_volume, &s->real_volume, &s->soft_volume);
3658
3659     if (!s->thread_info.volume_changes && pa_cvolume_equal(&nc->hw_volume, &s->thread_info.current_hw_volume)) {
3660         pa_log_debug("Volume not changing");
3661         pa_sink_volume_change_free(nc);
3662         return;
3663     }
3664
3665     nc->at = pa_sink_get_latency_within_thread(s, false);
3666     nc->at += pa_rtclock_now() + s->thread_info.volume_change_extra_delay;
3667
3668     if (s->thread_info.volume_changes_tail) {
3669         for (c = s->thread_info.volume_changes_tail; c; c = c->prev) {
3670             /* If volume is going up let's do it a bit late. If it is going
3671              * down let's do it a bit early. */
3672             if (pa_cvolume_avg(&nc->hw_volume) > pa_cvolume_avg(&c->hw_volume)) {
3673                 if (nc->at + safety_margin > c->at) {
3674                     nc->at += safety_margin;
3675                     direction = "up";
3676                     break;
3677                 }
3678             }
3679             else if (nc->at - safety_margin > c->at) {
3680                     nc->at -= safety_margin;
3681                     direction = "down";
3682                     break;
3683             }
3684         }
3685     }
3686
3687     if (c == NULL) {
3688         if (pa_cvolume_avg(&nc->hw_volume) > pa_cvolume_avg(&s->thread_info.current_hw_volume)) {
3689             nc->at += safety_margin;
3690             direction = "up";
3691         } else {
3692             nc->at -= safety_margin;
3693             direction = "down";
3694         }
3695         PA_LLIST_PREPEND(pa_sink_volume_change, s->thread_info.volume_changes, nc);
3696     }
3697     else {
3698         PA_LLIST_INSERT_AFTER(pa_sink_volume_change, s->thread_info.volume_changes, c, nc);
3699     }
3700
3701     pa_log_debug("Volume going %s to %d at %llu", direction, pa_cvolume_avg(&nc->hw_volume), (long long unsigned) nc->at);
3702
3703     /* We can ignore volume events that came earlier but should happen later than this. */
3704     PA_LLIST_FOREACH_SAFE(c, pc, nc->next) {
3705         pa_log_debug("Volume change to %d at %llu was dropped", pa_cvolume_avg(&c->hw_volume), (long long unsigned) c->at);
3706         pa_sink_volume_change_free(c);
3707     }
3708     nc->next = NULL;
3709     s->thread_info.volume_changes_tail = nc;
3710 }
3711
3712 /* Called from the IO thread. */
3713 static void pa_sink_volume_change_flush(pa_sink *s) {
3714     pa_sink_volume_change *c = s->thread_info.volume_changes;
3715     pa_assert(s);
3716     s->thread_info.volume_changes = NULL;
3717     s->thread_info.volume_changes_tail = NULL;
3718     while (c) {
3719         pa_sink_volume_change *next = c->next;
3720         pa_sink_volume_change_free(c);
3721         c = next;
3722     }
3723 }
3724
3725 /* Called from the IO thread. */
3726 bool pa_sink_volume_change_apply(pa_sink *s, pa_usec_t *usec_to_next) {
3727     pa_usec_t now;
3728     bool ret = false;
3729
3730     pa_assert(s);
3731
3732     if (!s->thread_info.volume_changes || !PA_SINK_IS_LINKED(s->state)) {
3733         if (usec_to_next)
3734             *usec_to_next = 0;
3735         return ret;
3736     }
3737
3738     pa_assert(s->write_volume);
3739
3740     now = pa_rtclock_now();
3741
3742     while (s->thread_info.volume_changes && now >= s->thread_info.volume_changes->at) {
3743         pa_sink_volume_change *c = s->thread_info.volume_changes;
3744         PA_LLIST_REMOVE(pa_sink_volume_change, s->thread_info.volume_changes, c);
3745         pa_log_debug("Volume change to %d at %llu was written %llu usec late",
3746                      pa_cvolume_avg(&c->hw_volume), (long long unsigned) c->at, (long long unsigned) (now - c->at));
3747         ret = true;
3748         s->thread_info.current_hw_volume = c->hw_volume;
3749         pa_sink_volume_change_free(c);
3750     }
3751
3752     if (ret)
3753         s->write_volume(s);
3754
3755     if (s->thread_info.volume_changes) {
3756         if (usec_to_next)
3757             *usec_to_next = s->thread_info.volume_changes->at - now;
3758         if (pa_log_ratelimit(PA_LOG_DEBUG))
3759             pa_log_debug("Next volume change in %lld usec", (long long) (s->thread_info.volume_changes->at - now));
3760     }
3761     else {
3762         if (usec_to_next)
3763             *usec_to_next = 0;
3764         s->thread_info.volume_changes_tail = NULL;
3765     }
3766     return ret;
3767 }
3768
3769 /* Called from the IO thread. */
3770 static void pa_sink_volume_change_rewind(pa_sink *s, size_t nbytes) {
3771     /* All the queued volume events later than current latency are shifted to happen earlier. */
3772     pa_sink_volume_change *c;
3773     pa_volume_t prev_vol = pa_cvolume_avg(&s->thread_info.current_hw_volume);
3774     pa_usec_t rewound = pa_bytes_to_usec(nbytes, &s->sample_spec);
3775     pa_usec_t limit = pa_sink_get_latency_within_thread(s, false);
3776
3777     pa_log_debug("latency = %lld", (long long) limit);
3778     limit += pa_rtclock_now() + s->thread_info.volume_change_extra_delay;
3779
3780     PA_LLIST_FOREACH(c, s->thread_info.volume_changes) {
3781         pa_usec_t modified_limit = limit;
3782         if (prev_vol > pa_cvolume_avg(&c->hw_volume))
3783             modified_limit -= s->thread_info.volume_change_safety_margin;
3784         else
3785             modified_limit += s->thread_info.volume_change_safety_margin;
3786         if (c->at > modified_limit) {
3787             c->at -= rewound;
3788             if (c->at < modified_limit)
3789                 c->at = modified_limit;
3790         }
3791         prev_vol = pa_cvolume_avg(&c->hw_volume);
3792     }
3793     pa_sink_volume_change_apply(s, NULL);
3794 }
3795
3796 /* Called from the main thread */
3797 /* Gets the list of formats supported by the sink. The members and idxset must
3798  * be freed by the caller. */
3799 pa_idxset* pa_sink_get_formats(pa_sink *s) {
3800     pa_idxset *ret;
3801
3802     pa_assert(s);
3803
3804     if (s->get_formats) {
3805         /* Sink supports format query, all is good */
3806         ret = s->get_formats(s);
3807     } else {
3808         /* Sink doesn't support format query, so assume it does PCM */
3809         pa_format_info *f = pa_format_info_new();
3810         f->encoding = PA_ENCODING_PCM;
3811
3812         ret = pa_idxset_new(NULL, NULL);
3813         pa_idxset_put(ret, f, NULL);
3814     }
3815
3816     return ret;
3817 }
3818
3819 /* Called from the main thread */
3820 /* Allows an external source to set what formats a sink supports if the sink
3821  * permits this. The function makes a copy of the formats on success. */
3822 bool pa_sink_set_formats(pa_sink *s, pa_idxset *formats) {
3823     pa_assert(s);
3824     pa_assert(formats);
3825
3826     if (s->set_formats)
3827         /* Sink supports setting formats -- let's give it a shot */
3828         return s->set_formats(s, formats);
3829     else
3830         /* Sink doesn't support setting this -- bail out */
3831         return false;
3832 }
3833
3834 /* Called from the main thread */
3835 /* Checks if the sink can accept this format */
3836 bool pa_sink_check_format(pa_sink *s, pa_format_info *f) {
3837     pa_idxset *formats = NULL;
3838     bool ret = false;
3839
3840     pa_assert(s);
3841     pa_assert(f);
3842
3843     formats = pa_sink_get_formats(s);
3844
3845     if (formats) {
3846         pa_format_info *finfo_device;
3847         uint32_t i;
3848
3849         PA_IDXSET_FOREACH(finfo_device, formats, i) {
3850             if (pa_format_info_is_compatible(finfo_device, f)) {
3851                 ret = true;
3852                 break;
3853             }
3854         }
3855
3856         pa_idxset_free(formats, (pa_free_cb_t) pa_format_info_free);
3857     }
3858
3859     return ret;
3860 }
3861
3862 /* Called from the main thread */
3863 /* Calculates the intersection between formats supported by the sink and
3864  * in_formats, and returns these, in the order of the sink's formats. */
3865 pa_idxset* pa_sink_check_formats(pa_sink *s, pa_idxset *in_formats) {
3866     pa_idxset *out_formats = pa_idxset_new(NULL, NULL), *sink_formats = NULL;
3867     pa_format_info *f_sink, *f_in;
3868     uint32_t i, j;
3869
3870     pa_assert(s);
3871
3872     if (!in_formats || pa_idxset_isempty(in_formats))
3873         goto done;
3874
3875     sink_formats = pa_sink_get_formats(s);
3876
3877     PA_IDXSET_FOREACH(f_sink, sink_formats, i) {
3878         PA_IDXSET_FOREACH(f_in, in_formats, j) {
3879             if (pa_format_info_is_compatible(f_sink, f_in))
3880                 pa_idxset_put(out_formats, pa_format_info_copy(f_in), NULL);
3881         }
3882     }
3883
3884 done:
3885     if (sink_formats)
3886         pa_idxset_free(sink_formats, (pa_free_cb_t) pa_format_info_free);
3887
3888     return out_formats;
3889 }
3890
3891 /* Called from the main thread. */
3892 void pa_sink_set_reference_volume_direct(pa_sink *s, const pa_cvolume *volume) {
3893     pa_cvolume old_volume;
3894     char old_volume_str[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
3895     char new_volume_str[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
3896
3897     pa_assert(s);
3898     pa_assert(volume);
3899
3900     old_volume = s->reference_volume;
3901
3902     if (pa_cvolume_equal(volume, &old_volume))
3903         return;
3904
3905     s->reference_volume = *volume;
3906     pa_log_debug("The reference volume of sink %s changed from %s to %s.", s->name,
3907                  pa_cvolume_snprint_verbose(old_volume_str, sizeof(old_volume_str), &old_volume, &s->channel_map,
3908                                             s->flags & PA_SINK_DECIBEL_VOLUME),
3909                  pa_cvolume_snprint_verbose(new_volume_str, sizeof(new_volume_str), volume, &s->channel_map,
3910                                             s->flags & PA_SINK_DECIBEL_VOLUME));
3911
3912     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SINK|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
3913     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SINK_VOLUME_CHANGED], s);
3914 }