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