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