sink, source: Do not dereference freed memory when freeing the next events
[platform/upstream/pulseaudio.git] / src / pulsecore / source.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
6
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as published
9   by the Free Software Foundation; either version 2.1 of the License,
10   or (at your option) any later version.
11
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <stdio.h>
26 #include <stdlib.h>
27
28 #include <pulse/format.h>
29 #include <pulse/utf8.h>
30 #include <pulse/xmalloc.h>
31 #include <pulse/timeval.h>
32 #include <pulse/util.h>
33 #include <pulse/rtclock.h>
34 #include <pulse/internal.h>
35
36 #include <pulsecore/core-util.h>
37 #include <pulsecore/source-output.h>
38 #include <pulsecore/namereg.h>
39 #include <pulsecore/core-subscribe.h>
40 #include <pulsecore/log.h>
41 #include <pulsecore/mix.h>
42 #include <pulsecore/flist.h>
43
44 #include "source.h"
45
46 #define ABSOLUTE_MIN_LATENCY (500)
47 #define ABSOLUTE_MAX_LATENCY (10*PA_USEC_PER_SEC)
48 #define DEFAULT_FIXED_LATENCY (250*PA_USEC_PER_MSEC)
49
50 PA_DEFINE_PUBLIC_CLASS(pa_source, pa_msgobject);
51
52 struct pa_source_volume_change {
53     pa_usec_t at;
54     pa_cvolume hw_volume;
55
56     PA_LLIST_FIELDS(pa_source_volume_change);
57 };
58
59 struct source_message_set_port {
60     pa_device_port *port;
61     int ret;
62 };
63
64 static void source_free(pa_object *o);
65
66 static void pa_source_volume_change_push(pa_source *s);
67 static void pa_source_volume_change_flush(pa_source *s);
68
69 pa_source_new_data* pa_source_new_data_init(pa_source_new_data *data) {
70     pa_assert(data);
71
72     pa_zero(*data);
73     data->proplist = pa_proplist_new();
74     data->ports = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) pa_device_port_unref);
75
76     return data;
77 }
78
79 void pa_source_new_data_set_name(pa_source_new_data *data, const char *name) {
80     pa_assert(data);
81
82     pa_xfree(data->name);
83     data->name = pa_xstrdup(name);
84 }
85
86 void pa_source_new_data_set_sample_spec(pa_source_new_data *data, const pa_sample_spec *spec) {
87     pa_assert(data);
88
89     if ((data->sample_spec_is_set = !!spec))
90         data->sample_spec = *spec;
91 }
92
93 void pa_source_new_data_set_channel_map(pa_source_new_data *data, const pa_channel_map *map) {
94     pa_assert(data);
95
96     if ((data->channel_map_is_set = !!map))
97         data->channel_map = *map;
98 }
99
100 void pa_source_new_data_set_alternate_sample_rate(pa_source_new_data *data, const uint32_t alternate_sample_rate) {
101     pa_assert(data);
102
103     data->alternate_sample_rate_is_set = true;
104     data->alternate_sample_rate = alternate_sample_rate;
105 }
106
107 void pa_source_new_data_set_volume(pa_source_new_data *data, const pa_cvolume *volume) {
108     pa_assert(data);
109
110     if ((data->volume_is_set = !!volume))
111         data->volume = *volume;
112 }
113
114 void pa_source_new_data_set_muted(pa_source_new_data *data, bool mute) {
115     pa_assert(data);
116
117     data->muted_is_set = true;
118     data->muted = mute;
119 }
120
121 void pa_source_new_data_set_port(pa_source_new_data *data, const char *port) {
122     pa_assert(data);
123
124     pa_xfree(data->active_port);
125     data->active_port = pa_xstrdup(port);
126 }
127
128 void pa_source_new_data_done(pa_source_new_data *data) {
129     pa_assert(data);
130
131     pa_proplist_free(data->proplist);
132
133     if (data->ports)
134         pa_hashmap_free(data->ports);
135
136     pa_xfree(data->name);
137     pa_xfree(data->active_port);
138 }
139
140 /* Called from main context */
141 static void reset_callbacks(pa_source *s) {
142     pa_assert(s);
143
144     s->set_state = NULL;
145     s->get_volume = NULL;
146     s->set_volume = NULL;
147     s->write_volume = NULL;
148     s->get_mute = NULL;
149     s->set_mute = NULL;
150     s->update_requested_latency = NULL;
151     s->set_port = NULL;
152     s->get_formats = NULL;
153     s->update_rate = NULL;
154 }
155
156 /* Called from main context */
157 pa_source* pa_source_new(
158         pa_core *core,
159         pa_source_new_data *data,
160         pa_source_flags_t flags) {
161
162     pa_source *s;
163     const char *name;
164     char st[PA_SAMPLE_SPEC_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX];
165     char *pt;
166
167     pa_assert(core);
168     pa_assert(data);
169     pa_assert(data->name);
170     pa_assert_ctl_context();
171
172     s = pa_msgobject_new(pa_source);
173
174     if (!(name = pa_namereg_register(core, data->name, PA_NAMEREG_SOURCE, s, data->namereg_fail))) {
175         pa_log_debug("Failed to register name %s.", data->name);
176         pa_xfree(s);
177         return NULL;
178     }
179
180     pa_source_new_data_set_name(data, name);
181
182     if (pa_hook_fire(&core->hooks[PA_CORE_HOOK_SOURCE_NEW], data) < 0) {
183         pa_xfree(s);
184         pa_namereg_unregister(core, name);
185         return NULL;
186     }
187
188     /* FIXME, need to free s here on failure */
189
190     pa_return_null_if_fail(!data->driver || pa_utf8_valid(data->driver));
191     pa_return_null_if_fail(data->name && pa_utf8_valid(data->name) && data->name[0]);
192
193     pa_return_null_if_fail(data->sample_spec_is_set && pa_sample_spec_valid(&data->sample_spec));
194
195     if (!data->channel_map_is_set)
196         pa_return_null_if_fail(pa_channel_map_init_auto(&data->channel_map, data->sample_spec.channels, PA_CHANNEL_MAP_DEFAULT));
197
198     pa_return_null_if_fail(pa_channel_map_valid(&data->channel_map));
199     pa_return_null_if_fail(data->channel_map.channels == data->sample_spec.channels);
200
201     /* FIXME: There should probably be a general function for checking whether
202      * the source volume is allowed to be set, like there is for source outputs. */
203     pa_assert(!data->volume_is_set || !(flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER));
204
205     if (!data->volume_is_set) {
206         pa_cvolume_reset(&data->volume, data->sample_spec.channels);
207         data->save_volume = false;
208     }
209
210     pa_return_null_if_fail(pa_cvolume_valid(&data->volume));
211     pa_return_null_if_fail(pa_cvolume_compatible(&data->volume, &data->sample_spec));
212
213     if (!data->muted_is_set)
214         data->muted = false;
215
216     if (data->card)
217         pa_proplist_update(data->proplist, PA_UPDATE_MERGE, data->card->proplist);
218
219     pa_device_init_description(data->proplist, data->card);
220     pa_device_init_icon(data->proplist, false);
221     pa_device_init_intended_roles(data->proplist);
222
223     if (!data->active_port) {
224         pa_device_port *p = pa_device_port_find_best(data->ports);
225         if (p)
226             pa_source_new_data_set_port(data, p->name);
227     }
228
229     if (pa_hook_fire(&core->hooks[PA_CORE_HOOK_SOURCE_FIXATE], data) < 0) {
230         pa_xfree(s);
231         pa_namereg_unregister(core, name);
232         return NULL;
233     }
234
235     s->parent.parent.free = source_free;
236     s->parent.process_msg = pa_source_process_msg;
237
238     s->core = core;
239     s->state = PA_SOURCE_INIT;
240     s->flags = flags;
241     s->priority = 0;
242     s->suspend_cause = data->suspend_cause;
243     pa_source_set_mixer_dirty(s, false);
244     s->name = pa_xstrdup(name);
245     s->proplist = pa_proplist_copy(data->proplist);
246     s->driver = pa_xstrdup(pa_path_get_filename(data->driver));
247     s->module = data->module;
248     s->card = data->card;
249
250     s->priority = pa_device_init_priority(s->proplist);
251
252     s->sample_spec = data->sample_spec;
253     s->channel_map = data->channel_map;
254     s->default_sample_rate = s->sample_spec.rate;
255
256     if (data->alternate_sample_rate_is_set)
257         s->alternate_sample_rate = data->alternate_sample_rate;
258     else
259         s->alternate_sample_rate = s->core->alternate_sample_rate;
260
261     if (s->sample_spec.rate == s->alternate_sample_rate) {
262         pa_log_warn("Default and alternate sample rates are the same.");
263         s->alternate_sample_rate = 0;
264     }
265
266     s->outputs = pa_idxset_new(NULL, NULL);
267     s->n_corked = 0;
268     s->monitor_of = NULL;
269     s->output_from_master = NULL;
270
271     s->reference_volume = s->real_volume = data->volume;
272     pa_cvolume_reset(&s->soft_volume, s->sample_spec.channels);
273     s->base_volume = PA_VOLUME_NORM;
274     s->n_volume_steps = PA_VOLUME_NORM+1;
275     s->muted = data->muted;
276     s->refresh_volume = s->refresh_muted = false;
277
278     reset_callbacks(s);
279     s->userdata = NULL;
280
281     s->asyncmsgq = NULL;
282
283     /* As a minor optimization we just steal the list instead of
284      * copying it here */
285     s->ports = data->ports;
286     data->ports = NULL;
287
288     s->active_port = NULL;
289     s->save_port = false;
290
291     if (data->active_port)
292         if ((s->active_port = pa_hashmap_get(s->ports, data->active_port)))
293             s->save_port = data->save_port;
294
295     /* Hopefully the active port has already been assigned in the previous call
296        to pa_device_port_find_best, but better safe than sorry */
297     if (!s->active_port)
298         s->active_port = pa_device_port_find_best(s->ports);
299
300     if (s->active_port)
301         s->latency_offset = s->active_port->latency_offset;
302     else
303         s->latency_offset = 0;
304
305     s->save_volume = data->save_volume;
306     s->save_muted = data->save_muted;
307
308     pa_silence_memchunk_get(
309             &core->silence_cache,
310             core->mempool,
311             &s->silence,
312             &s->sample_spec,
313             0);
314
315     s->thread_info.rtpoll = NULL;
316     s->thread_info.outputs = pa_hashmap_new_full(pa_idxset_trivial_hash_func, pa_idxset_trivial_compare_func, NULL,
317                                                  (pa_free_cb_t) pa_source_output_unref);
318     s->thread_info.soft_volume = s->soft_volume;
319     s->thread_info.soft_muted = s->muted;
320     s->thread_info.state = s->state;
321     s->thread_info.max_rewind = 0;
322     s->thread_info.requested_latency_valid = false;
323     s->thread_info.requested_latency = 0;
324     s->thread_info.min_latency = ABSOLUTE_MIN_LATENCY;
325     s->thread_info.max_latency = ABSOLUTE_MAX_LATENCY;
326     s->thread_info.fixed_latency = flags & PA_SOURCE_DYNAMIC_LATENCY ? 0 : DEFAULT_FIXED_LATENCY;
327
328     PA_LLIST_HEAD_INIT(pa_source_volume_change, s->thread_info.volume_changes);
329     s->thread_info.volume_changes_tail = NULL;
330     pa_sw_cvolume_multiply(&s->thread_info.current_hw_volume, &s->soft_volume, &s->real_volume);
331     s->thread_info.volume_change_safety_margin = core->deferred_volume_safety_margin_usec;
332     s->thread_info.volume_change_extra_delay = core->deferred_volume_extra_delay_usec;
333     s->thread_info.latency_offset = s->latency_offset;
334
335     /* FIXME: This should probably be moved to pa_source_put() */
336     pa_assert_se(pa_idxset_put(core->sources, s, &s->index) >= 0);
337
338     if (s->card)
339         pa_assert_se(pa_idxset_put(s->card->sources, s, NULL) >= 0);
340
341     pt = pa_proplist_to_string_sep(s->proplist, "\n    ");
342     pa_log_info("Created source %u \"%s\" with sample spec %s and channel map %s\n    %s",
343                 s->index,
344                 s->name,
345                 pa_sample_spec_snprint(st, sizeof(st), &s->sample_spec),
346                 pa_channel_map_snprint(cm, sizeof(cm), &s->channel_map),
347                 pt);
348     pa_xfree(pt);
349
350     return s;
351 }
352
353 /* Called from main context */
354 static int source_set_state(pa_source *s, pa_source_state_t state) {
355     int ret;
356     bool suspend_change;
357     pa_source_state_t original_state;
358
359     pa_assert(s);
360     pa_assert_ctl_context();
361
362     if (s->state == state)
363         return 0;
364
365     original_state = s->state;
366
367     suspend_change =
368         (original_state == PA_SOURCE_SUSPENDED && PA_SOURCE_IS_OPENED(state)) ||
369         (PA_SOURCE_IS_OPENED(original_state) && state == PA_SOURCE_SUSPENDED);
370
371     if (s->set_state)
372         if ((ret = s->set_state(s, state)) < 0)
373             return ret;
374
375     if (s->asyncmsgq)
376         if ((ret = pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_STATE, PA_UINT_TO_PTR(state), 0, NULL)) < 0) {
377
378             if (s->set_state)
379                 s->set_state(s, original_state);
380
381             return ret;
382         }
383
384     s->state = state;
385
386     if (state != PA_SOURCE_UNLINKED) { /* if we enter UNLINKED state pa_source_unlink() will fire the appropriate events */
387         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_STATE_CHANGED], s);
388         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE | PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
389     }
390
391     if (suspend_change) {
392         pa_source_output *o;
393         uint32_t idx;
394
395         /* We're suspending or resuming, tell everyone about it */
396
397         PA_IDXSET_FOREACH(o, s->outputs, idx)
398             if (s->state == PA_SOURCE_SUSPENDED &&
399                 (o->flags & PA_SOURCE_OUTPUT_KILL_ON_SUSPEND))
400                 pa_source_output_kill(o);
401             else if (o->suspend)
402                 o->suspend(o, state == PA_SOURCE_SUSPENDED);
403     }
404
405     return 0;
406 }
407
408 void pa_source_set_get_volume_callback(pa_source *s, pa_source_cb_t cb) {
409     pa_assert(s);
410
411     s->get_volume = cb;
412 }
413
414 void pa_source_set_set_volume_callback(pa_source *s, pa_source_cb_t cb) {
415     pa_source_flags_t flags;
416
417     pa_assert(s);
418     pa_assert(!s->write_volume || cb);
419
420     s->set_volume = cb;
421
422     /* Save the current flags so we can tell if they've changed */
423     flags = s->flags;
424
425     if (cb) {
426         /* The source implementor is responsible for setting decibel volume support */
427         s->flags |= PA_SOURCE_HW_VOLUME_CTRL;
428     } else {
429         s->flags &= ~PA_SOURCE_HW_VOLUME_CTRL;
430         /* See note below in pa_source_put() about volume sharing and decibel volumes */
431         pa_source_enable_decibel_volume(s, !(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER));
432     }
433
434     /* If the flags have changed after init, let any clients know via a change event */
435     if (s->state != PA_SOURCE_INIT && flags != s->flags)
436         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
437 }
438
439 void pa_source_set_write_volume_callback(pa_source *s, pa_source_cb_t cb) {
440     pa_source_flags_t flags;
441
442     pa_assert(s);
443     pa_assert(!cb || s->set_volume);
444
445     s->write_volume = cb;
446
447     /* Save the current flags so we can tell if they've changed */
448     flags = s->flags;
449
450     if (cb)
451         s->flags |= PA_SOURCE_DEFERRED_VOLUME;
452     else
453         s->flags &= ~PA_SOURCE_DEFERRED_VOLUME;
454
455     /* If the flags have changed after init, let any clients know via a change event */
456     if (s->state != PA_SOURCE_INIT && flags != s->flags)
457         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
458 }
459
460 void pa_source_set_get_mute_callback(pa_source *s, pa_source_get_mute_cb_t cb) {
461     pa_assert(s);
462
463     s->get_mute = cb;
464 }
465
466 void pa_source_set_set_mute_callback(pa_source *s, pa_source_cb_t cb) {
467     pa_source_flags_t flags;
468
469     pa_assert(s);
470
471     s->set_mute = cb;
472
473     /* Save the current flags so we can tell if they've changed */
474     flags = s->flags;
475
476     if (cb)
477         s->flags |= PA_SOURCE_HW_MUTE_CTRL;
478     else
479         s->flags &= ~PA_SOURCE_HW_MUTE_CTRL;
480
481     /* If the flags have changed after init, let any clients know via a change event */
482     if (s->state != PA_SOURCE_INIT && flags != s->flags)
483         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
484 }
485
486 static void enable_flat_volume(pa_source *s, bool enable) {
487     pa_source_flags_t flags;
488
489     pa_assert(s);
490
491     /* Always follow the overall user preference here */
492     enable = enable && s->core->flat_volumes;
493
494     /* Save the current flags so we can tell if they've changed */
495     flags = s->flags;
496
497     if (enable)
498         s->flags |= PA_SOURCE_FLAT_VOLUME;
499     else
500         s->flags &= ~PA_SOURCE_FLAT_VOLUME;
501
502     /* If the flags have changed after init, let any clients know via a change event */
503     if (s->state != PA_SOURCE_INIT && flags != s->flags)
504         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
505 }
506
507 void pa_source_enable_decibel_volume(pa_source *s, bool enable) {
508     pa_source_flags_t flags;
509
510     pa_assert(s);
511
512     /* Save the current flags so we can tell if they've changed */
513     flags = s->flags;
514
515     if (enable) {
516         s->flags |= PA_SOURCE_DECIBEL_VOLUME;
517         enable_flat_volume(s, true);
518     } else {
519         s->flags &= ~PA_SOURCE_DECIBEL_VOLUME;
520         enable_flat_volume(s, false);
521     }
522
523     /* If the flags have changed after init, let any clients know via a change event */
524     if (s->state != PA_SOURCE_INIT && flags != s->flags)
525         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
526 }
527
528 /* Called from main context */
529 void pa_source_put(pa_source *s) {
530     pa_source_assert_ref(s);
531     pa_assert_ctl_context();
532
533     pa_assert(s->state == PA_SOURCE_INIT);
534     pa_assert(!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER) || pa_source_is_filter(s));
535
536     /* The following fields must be initialized properly when calling _put() */
537     pa_assert(s->asyncmsgq);
538     pa_assert(s->thread_info.min_latency <= s->thread_info.max_latency);
539
540     /* Generally, flags should be initialized via pa_source_new(). As a
541      * special exception we allow some volume related flags to be set
542      * between _new() and _put() by the callback setter functions above.
543      *
544      * Thus we implement a couple safeguards here which ensure the above
545      * setters were used (or at least the implementor made manual changes
546      * in a compatible way).
547      *
548      * Note: All of these flags set here can change over the life time
549      * of the source. */
550     pa_assert(!(s->flags & PA_SOURCE_HW_VOLUME_CTRL) || s->set_volume);
551     pa_assert(!(s->flags & PA_SOURCE_DEFERRED_VOLUME) || s->write_volume);
552     pa_assert(!(s->flags & PA_SOURCE_HW_MUTE_CTRL) || s->set_mute);
553
554     /* XXX: Currently decibel volume is disabled for all sources that use volume
555      * sharing. When the master source supports decibel volume, it would be good
556      * to have the flag also in the filter source, but currently we don't do that
557      * so that the flags of the filter source never change when it's moved from
558      * a master source to another. One solution for this problem would be to
559      * remove user-visible volume altogether from filter sources when volume
560      * sharing is used, but the current approach was easier to implement... */
561     /* We always support decibel volumes in software, otherwise we leave it to
562      * the source implementor to set this flag as needed.
563      *
564      * Note: This flag can also change over the life time of the source. */
565     if (!(s->flags & PA_SOURCE_HW_VOLUME_CTRL) && !(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
566         pa_source_enable_decibel_volume(s, true);
567         s->soft_volume = s->reference_volume;
568     }
569
570     /* If the source implementor support DB volumes by itself, we should always
571      * try and enable flat volumes too */
572     if ((s->flags & PA_SOURCE_DECIBEL_VOLUME))
573         enable_flat_volume(s, true);
574
575     if (s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER) {
576         pa_source *root_source = pa_source_get_master(s);
577
578         pa_assert(PA_LIKELY(root_source));
579
580         s->reference_volume = root_source->reference_volume;
581         pa_cvolume_remap(&s->reference_volume, &root_source->channel_map, &s->channel_map);
582
583         s->real_volume = root_source->real_volume;
584         pa_cvolume_remap(&s->real_volume, &root_source->channel_map, &s->channel_map);
585     } else
586         /* We assume that if the sink implementor changed the default
587          * volume he did so in real_volume, because that is the usual
588          * place where he is supposed to place his changes.  */
589         s->reference_volume = s->real_volume;
590
591     s->thread_info.soft_volume = s->soft_volume;
592     s->thread_info.soft_muted = s->muted;
593     pa_sw_cvolume_multiply(&s->thread_info.current_hw_volume, &s->soft_volume, &s->real_volume);
594
595     pa_assert((s->flags & PA_SOURCE_HW_VOLUME_CTRL)
596               || (s->base_volume == PA_VOLUME_NORM
597                   && ((s->flags & PA_SOURCE_DECIBEL_VOLUME || (s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)))));
598     pa_assert(!(s->flags & PA_SOURCE_DECIBEL_VOLUME) || s->n_volume_steps == PA_VOLUME_NORM+1);
599     pa_assert(!(s->flags & PA_SOURCE_DYNAMIC_LATENCY) == !(s->thread_info.fixed_latency == 0));
600
601     if (s->suspend_cause)
602         pa_assert_se(source_set_state(s, PA_SOURCE_SUSPENDED) == 0);
603     else
604         pa_assert_se(source_set_state(s, PA_SOURCE_IDLE) == 0);
605
606     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE | PA_SUBSCRIPTION_EVENT_NEW, s->index);
607     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_PUT], s);
608 }
609
610 /* Called from main context */
611 void pa_source_unlink(pa_source *s) {
612     bool linked;
613     pa_source_output *o, PA_UNUSED *j = NULL;
614
615     pa_assert(s);
616     pa_assert_ctl_context();
617
618     /* See pa_sink_unlink() for a couple of comments how this function
619      * works. */
620
621     linked = PA_SOURCE_IS_LINKED(s->state);
622
623     if (linked)
624         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_UNLINK], s);
625
626     if (s->state != PA_SOURCE_UNLINKED)
627         pa_namereg_unregister(s->core, s->name);
628     pa_idxset_remove_by_data(s->core->sources, s, NULL);
629
630     if (s->card)
631         pa_idxset_remove_by_data(s->card->sources, s, NULL);
632
633     while ((o = pa_idxset_first(s->outputs, NULL))) {
634         pa_assert(o != j);
635         pa_source_output_kill(o);
636         j = o;
637     }
638
639     if (linked)
640         source_set_state(s, PA_SOURCE_UNLINKED);
641     else
642         s->state = PA_SOURCE_UNLINKED;
643
644     reset_callbacks(s);
645
646     if (linked) {
647         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE | PA_SUBSCRIPTION_EVENT_REMOVE, s->index);
648         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_UNLINK_POST], s);
649     }
650 }
651
652 /* Called from main context */
653 static void source_free(pa_object *o) {
654     pa_source *s = PA_SOURCE(o);
655
656     pa_assert(s);
657     pa_assert_ctl_context();
658     pa_assert(pa_source_refcnt(s) == 0);
659
660     if (PA_SOURCE_IS_LINKED(s->state))
661         pa_source_unlink(s);
662
663     pa_log_info("Freeing source %u \"%s\"", s->index, s->name);
664
665     pa_source_volume_change_flush(s);
666
667     pa_idxset_free(s->outputs, NULL);
668     pa_hashmap_free(s->thread_info.outputs);
669
670     if (s->silence.memblock)
671         pa_memblock_unref(s->silence.memblock);
672
673     pa_xfree(s->name);
674     pa_xfree(s->driver);
675
676     if (s->proplist)
677         pa_proplist_free(s->proplist);
678
679     if (s->ports)
680         pa_hashmap_free(s->ports);
681
682     pa_xfree(s);
683 }
684
685 /* Called from main context, and not while the IO thread is active, please */
686 void pa_source_set_asyncmsgq(pa_source *s, pa_asyncmsgq *q) {
687     pa_source_assert_ref(s);
688     pa_assert_ctl_context();
689
690     s->asyncmsgq = q;
691 }
692
693 /* Called from main context, and not while the IO thread is active, please */
694 void pa_source_update_flags(pa_source *s, pa_source_flags_t mask, pa_source_flags_t value) {
695     pa_source_flags_t old_flags;
696     pa_source_output *output;
697     uint32_t idx;
698
699     pa_source_assert_ref(s);
700     pa_assert_ctl_context();
701
702     /* For now, allow only a minimal set of flags to be changed. */
703     pa_assert((mask & ~(PA_SOURCE_DYNAMIC_LATENCY|PA_SOURCE_LATENCY)) == 0);
704
705     old_flags = s->flags;
706     s->flags = (s->flags & ~mask) | (value & mask);
707
708     if (s->flags == old_flags)
709         return;
710
711     if ((s->flags & PA_SOURCE_LATENCY) != (old_flags & PA_SOURCE_LATENCY))
712         pa_log_debug("Source %s: LATENCY flag %s.", s->name, (s->flags & PA_SOURCE_LATENCY) ? "enabled" : "disabled");
713
714     if ((s->flags & PA_SOURCE_DYNAMIC_LATENCY) != (old_flags & PA_SOURCE_DYNAMIC_LATENCY))
715         pa_log_debug("Source %s: DYNAMIC_LATENCY flag %s.",
716                      s->name, (s->flags & PA_SOURCE_DYNAMIC_LATENCY) ? "enabled" : "disabled");
717
718     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE | PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
719     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_FLAGS_CHANGED], s);
720
721     PA_IDXSET_FOREACH(output, s->outputs, idx) {
722         if (output->destination_source)
723             pa_source_update_flags(output->destination_source, mask, value);
724     }
725 }
726
727 /* Called from IO context, or before _put() from main context */
728 void pa_source_set_rtpoll(pa_source *s, pa_rtpoll *p) {
729     pa_source_assert_ref(s);
730     pa_source_assert_io_context(s);
731
732     s->thread_info.rtpoll = p;
733 }
734
735 /* Called from main context */
736 int pa_source_update_status(pa_source*s) {
737     pa_source_assert_ref(s);
738     pa_assert_ctl_context();
739     pa_assert(PA_SOURCE_IS_LINKED(s->state));
740
741     if (s->state == PA_SOURCE_SUSPENDED)
742         return 0;
743
744     return source_set_state(s, pa_source_used_by(s) ? PA_SOURCE_RUNNING : PA_SOURCE_IDLE);
745 }
746
747 /* Called from any context - must be threadsafe */
748 void pa_source_set_mixer_dirty(pa_source *s, bool is_dirty) {
749     pa_atomic_store(&s->mixer_dirty, is_dirty ? 1 : 0);
750 }
751
752 /* Called from main context */
753 int pa_source_suspend(pa_source *s, bool suspend, pa_suspend_cause_t cause) {
754     pa_source_assert_ref(s);
755     pa_assert_ctl_context();
756     pa_assert(PA_SOURCE_IS_LINKED(s->state));
757     pa_assert(cause != 0);
758
759     if (s->monitor_of && cause != PA_SUSPEND_PASSTHROUGH)
760         return -PA_ERR_NOTSUPPORTED;
761
762     if (suspend)
763         s->suspend_cause |= cause;
764     else
765         s->suspend_cause &= ~cause;
766
767     if (!(s->suspend_cause & PA_SUSPEND_SESSION) && (pa_atomic_load(&s->mixer_dirty) != 0)) {
768         /* This might look racy but isn't: If somebody sets mixer_dirty exactly here,
769            it'll be handled just fine. */
770         pa_source_set_mixer_dirty(s, false);
771         pa_log_debug("Mixer is now accessible. Updating alsa mixer settings.");
772         if (s->active_port && s->set_port) {
773             if (s->flags & PA_SOURCE_DEFERRED_VOLUME) {
774                 struct source_message_set_port msg = { .port = s->active_port, .ret = 0 };
775                 pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_PORT, &msg, 0, NULL) == 0);
776             }
777             else
778                 s->set_port(s, s->active_port);
779         }
780         else {
781             if (s->set_mute)
782                 s->set_mute(s);
783             if (s->set_volume)
784                 s->set_volume(s);
785         }
786     }
787
788     if ((pa_source_get_state(s) == PA_SOURCE_SUSPENDED) == !!s->suspend_cause)
789         return 0;
790
791     pa_log_debug("Suspend cause of source %s is 0x%04x, %s", s->name, s->suspend_cause, s->suspend_cause ? "suspending" : "resuming");
792
793     if (s->suspend_cause)
794         return source_set_state(s, PA_SOURCE_SUSPENDED);
795     else
796         return source_set_state(s, pa_source_used_by(s) ? PA_SOURCE_RUNNING : PA_SOURCE_IDLE);
797 }
798
799 /* Called from main context */
800 int pa_source_sync_suspend(pa_source *s) {
801     pa_sink_state_t state;
802
803     pa_source_assert_ref(s);
804     pa_assert_ctl_context();
805     pa_assert(PA_SOURCE_IS_LINKED(s->state));
806     pa_assert(s->monitor_of);
807
808     state = pa_sink_get_state(s->monitor_of);
809
810     if (state == PA_SINK_SUSPENDED)
811         return source_set_state(s, PA_SOURCE_SUSPENDED);
812
813     pa_assert(PA_SINK_IS_OPENED(state));
814
815     return source_set_state(s, pa_source_used_by(s) ? PA_SOURCE_RUNNING : PA_SOURCE_IDLE);
816 }
817
818 /* Called from main context */
819 pa_queue *pa_source_move_all_start(pa_source *s, pa_queue *q) {
820     pa_source_output *o, *n;
821     uint32_t idx;
822
823     pa_source_assert_ref(s);
824     pa_assert_ctl_context();
825     pa_assert(PA_SOURCE_IS_LINKED(s->state));
826
827     if (!q)
828         q = pa_queue_new();
829
830     for (o = PA_SOURCE_OUTPUT(pa_idxset_first(s->outputs, &idx)); o; o = n) {
831         n = PA_SOURCE_OUTPUT(pa_idxset_next(s->outputs, &idx));
832
833         pa_source_output_ref(o);
834
835         if (pa_source_output_start_move(o) >= 0)
836             pa_queue_push(q, o);
837         else
838             pa_source_output_unref(o);
839     }
840
841     return q;
842 }
843
844 /* Called from main context */
845 void pa_source_move_all_finish(pa_source *s, pa_queue *q, bool save) {
846     pa_source_output *o;
847
848     pa_source_assert_ref(s);
849     pa_assert_ctl_context();
850     pa_assert(PA_SOURCE_IS_LINKED(s->state));
851     pa_assert(q);
852
853     while ((o = PA_SOURCE_OUTPUT(pa_queue_pop(q)))) {
854         if (pa_source_output_finish_move(o, s, save) < 0)
855             pa_source_output_fail_move(o);
856
857         pa_source_output_unref(o);
858     }
859
860     pa_queue_free(q, NULL);
861 }
862
863 /* Called from main context */
864 void pa_source_move_all_fail(pa_queue *q) {
865     pa_source_output *o;
866
867     pa_assert_ctl_context();
868     pa_assert(q);
869
870     while ((o = PA_SOURCE_OUTPUT(pa_queue_pop(q)))) {
871         pa_source_output_fail_move(o);
872         pa_source_output_unref(o);
873     }
874
875     pa_queue_free(q, NULL);
876 }
877
878 /* Called from IO thread context */
879 void pa_source_process_rewind(pa_source *s, size_t nbytes) {
880     pa_source_output *o;
881     void *state = NULL;
882
883     pa_source_assert_ref(s);
884     pa_source_assert_io_context(s);
885     pa_assert(PA_SOURCE_IS_LINKED(s->thread_info.state));
886
887     if (nbytes <= 0)
888         return;
889
890     if (s->thread_info.state == PA_SOURCE_SUSPENDED)
891         return;
892
893     pa_log_debug("Processing rewind...");
894
895     PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state) {
896         pa_source_output_assert_ref(o);
897         pa_source_output_process_rewind(o, nbytes);
898     }
899 }
900
901 /* Called from IO thread context */
902 void pa_source_post(pa_source*s, const pa_memchunk *chunk) {
903     pa_source_output *o;
904     void *state = NULL;
905
906     pa_source_assert_ref(s);
907     pa_source_assert_io_context(s);
908     pa_assert(PA_SOURCE_IS_LINKED(s->thread_info.state));
909     pa_assert(chunk);
910
911     if (s->thread_info.state == PA_SOURCE_SUSPENDED)
912         return;
913
914     if (s->thread_info.soft_muted || !pa_cvolume_is_norm(&s->thread_info.soft_volume)) {
915         pa_memchunk vchunk = *chunk;
916
917         pa_memblock_ref(vchunk.memblock);
918         pa_memchunk_make_writable(&vchunk, 0);
919
920         if (s->thread_info.soft_muted || pa_cvolume_is_muted(&s->thread_info.soft_volume))
921             pa_silence_memchunk(&vchunk, &s->sample_spec);
922         else
923             pa_volume_memchunk(&vchunk, &s->sample_spec, &s->thread_info.soft_volume);
924
925         while ((o = pa_hashmap_iterate(s->thread_info.outputs, &state, NULL))) {
926             pa_source_output_assert_ref(o);
927
928             if (!o->thread_info.direct_on_input)
929                 pa_source_output_push(o, &vchunk);
930         }
931
932         pa_memblock_unref(vchunk.memblock);
933     } else {
934
935         while ((o = pa_hashmap_iterate(s->thread_info.outputs, &state, NULL))) {
936             pa_source_output_assert_ref(o);
937
938             if (!o->thread_info.direct_on_input)
939                 pa_source_output_push(o, chunk);
940         }
941     }
942 }
943
944 /* Called from IO thread context */
945 void pa_source_post_direct(pa_source*s, pa_source_output *o, const pa_memchunk *chunk) {
946     pa_source_assert_ref(s);
947     pa_source_assert_io_context(s);
948     pa_assert(PA_SOURCE_IS_LINKED(s->thread_info.state));
949     pa_source_output_assert_ref(o);
950     pa_assert(o->thread_info.direct_on_input);
951     pa_assert(chunk);
952
953     if (s->thread_info.state == PA_SOURCE_SUSPENDED)
954         return;
955
956     if (s->thread_info.soft_muted || !pa_cvolume_is_norm(&s->thread_info.soft_volume)) {
957         pa_memchunk vchunk = *chunk;
958
959         pa_memblock_ref(vchunk.memblock);
960         pa_memchunk_make_writable(&vchunk, 0);
961
962         if (s->thread_info.soft_muted || pa_cvolume_is_muted(&s->thread_info.soft_volume))
963             pa_silence_memchunk(&vchunk, &s->sample_spec);
964         else
965             pa_volume_memchunk(&vchunk, &s->sample_spec, &s->thread_info.soft_volume);
966
967         pa_source_output_push(o, &vchunk);
968
969         pa_memblock_unref(vchunk.memblock);
970     } else
971         pa_source_output_push(o, chunk);
972 }
973
974 /* Called from main thread */
975 int pa_source_update_rate(pa_source *s, uint32_t rate, bool passthrough) {
976     int ret;
977     uint32_t desired_rate = rate;
978     uint32_t default_rate = s->default_sample_rate;
979     uint32_t alternate_rate = s->alternate_sample_rate;
980     bool default_rate_is_usable = false;
981     bool alternate_rate_is_usable = false;
982
983     if (rate == s->sample_spec.rate)
984         return 0;
985
986     if (!s->update_rate && !s->monitor_of)
987         return -1;
988
989     if (PA_UNLIKELY(default_rate == alternate_rate && !passthrough)) {
990         pa_log_debug("Default and alternate sample rates are the same, so there is no point in switching.");
991         return -1;
992     }
993
994     if (PA_SOURCE_IS_RUNNING(s->state)) {
995         pa_log_info("Cannot update rate, SOURCE_IS_RUNNING, will keep using %u Hz",
996                     s->sample_spec.rate);
997         return -1;
998     }
999
1000     if (s->monitor_of) {
1001         if (PA_SINK_IS_RUNNING(s->monitor_of->state)) {
1002             pa_log_info("Cannot update rate, this is a monitor source and the sink is running.");
1003             return -1;
1004         }
1005     }
1006
1007     if (PA_UNLIKELY(!pa_sample_rate_valid(desired_rate)))
1008         return -1;
1009
1010     if (!passthrough && default_rate != desired_rate && alternate_rate != desired_rate) {
1011         if (default_rate % 11025 == 0 && desired_rate % 11025 == 0)
1012             default_rate_is_usable = true;
1013         if (default_rate % 4000 == 0 && desired_rate % 4000 == 0)
1014             default_rate_is_usable = true;
1015         if (alternate_rate && alternate_rate % 11025 == 0 && desired_rate % 11025 == 0)
1016             alternate_rate_is_usable = true;
1017         if (alternate_rate && alternate_rate % 4000 == 0 && desired_rate % 4000 == 0)
1018             alternate_rate_is_usable = true;
1019
1020         if (alternate_rate_is_usable && !default_rate_is_usable)
1021             desired_rate = alternate_rate;
1022         else
1023             desired_rate = default_rate;
1024     }
1025
1026     if (desired_rate == s->sample_spec.rate)
1027         return -1;
1028
1029     if (!passthrough && pa_source_used_by(s) > 0)
1030         return -1;
1031
1032     pa_log_debug("Suspending source %s due to changing the sample rate.", s->name);
1033     pa_source_suspend(s, true, PA_SUSPEND_INTERNAL);
1034
1035     if (s->update_rate)
1036         ret = s->update_rate(s, desired_rate);
1037     else {
1038         /* This is a monitor source. */
1039
1040         /* XXX: This code is written with non-passthrough streams in mind. I
1041          * have no idea whether the behaviour with passthrough streams is
1042          * sensible. */
1043         if (!passthrough) {
1044             uint32_t old_rate = s->sample_spec.rate;
1045
1046             s->sample_spec.rate = desired_rate;
1047             ret = pa_sink_update_rate(s->monitor_of, desired_rate, false);
1048
1049             if (ret < 0) {
1050                 /* Changing the sink rate failed, roll back the old rate for
1051                  * the monitor source. Why did we set the source rate before
1052                  * calling pa_sink_update_rate(), you may ask. The reason is
1053                  * that pa_sink_update_rate() tries to update the monitor
1054                  * source rate, but we are already in the process of updating
1055                  * the monitor source rate, so there's a risk of entering an
1056                  * infinite loop. Setting the source rate before calling
1057                  * pa_sink_update_rate() makes the rate == s->sample_spec.rate
1058                  * check in the beginning of this function return early, so we
1059                  * avoid looping. */
1060                 s->sample_spec.rate = old_rate;
1061             }
1062         } else
1063             ret = -1;
1064     }
1065
1066     if (ret >= 0) {
1067         uint32_t idx;
1068         pa_source_output *o;
1069
1070         PA_IDXSET_FOREACH(o, s->outputs, idx) {
1071             if (o->state == PA_SOURCE_OUTPUT_CORKED)
1072                 pa_source_output_update_rate(o);
1073         }
1074
1075         pa_log_info("Changed sampling rate successfully");
1076     }
1077
1078     pa_source_suspend(s, false, PA_SUSPEND_INTERNAL);
1079
1080     return ret;
1081 }
1082
1083 /* Called from main thread */
1084 pa_usec_t pa_source_get_latency(pa_source *s) {
1085     pa_usec_t usec;
1086
1087     pa_source_assert_ref(s);
1088     pa_assert_ctl_context();
1089     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1090
1091     if (s->state == PA_SOURCE_SUSPENDED)
1092         return 0;
1093
1094     if (!(s->flags & PA_SOURCE_LATENCY))
1095         return 0;
1096
1097     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_LATENCY, &usec, 0, NULL) == 0);
1098
1099     /* usec is unsigned, so check that the offset can be added to usec without
1100      * underflowing. */
1101     if (-s->latency_offset <= (int64_t) usec)
1102         usec += s->latency_offset;
1103     else
1104         usec = 0;
1105
1106     return usec;
1107 }
1108
1109 /* Called from IO thread */
1110 pa_usec_t pa_source_get_latency_within_thread(pa_source *s) {
1111     pa_usec_t usec = 0;
1112     pa_msgobject *o;
1113
1114     pa_source_assert_ref(s);
1115     pa_source_assert_io_context(s);
1116     pa_assert(PA_SOURCE_IS_LINKED(s->thread_info.state));
1117
1118     /* The returned value is supposed to be in the time domain of the sound card! */
1119
1120     if (s->thread_info.state == PA_SOURCE_SUSPENDED)
1121         return 0;
1122
1123     if (!(s->flags & PA_SOURCE_LATENCY))
1124         return 0;
1125
1126     o = PA_MSGOBJECT(s);
1127
1128     /* FIXME: We probably should make this a proper vtable callback instead of going through process_msg() */
1129
1130     if (o->process_msg(o, PA_SOURCE_MESSAGE_GET_LATENCY, &usec, 0, NULL) < 0)
1131         return -1;
1132
1133     /* usec is unsigned, so check that the offset can be added to usec without
1134      * underflowing. */
1135     if (-s->thread_info.latency_offset <= (int64_t) usec)
1136         usec += s->thread_info.latency_offset;
1137     else
1138         usec = 0;
1139
1140     return usec;
1141 }
1142
1143 /* Called from the main thread (and also from the IO thread while the main
1144  * thread is waiting).
1145  *
1146  * When a source uses volume sharing, it never has the PA_SOURCE_FLAT_VOLUME flag
1147  * set. Instead, flat volume mode is detected by checking whether the root source
1148  * has the flag set. */
1149 bool pa_source_flat_volume_enabled(pa_source *s) {
1150     pa_source_assert_ref(s);
1151
1152     s = pa_source_get_master(s);
1153
1154     if (PA_LIKELY(s))
1155         return (s->flags & PA_SOURCE_FLAT_VOLUME);
1156     else
1157         return false;
1158 }
1159
1160 /* Called from the main thread (and also from the IO thread while the main
1161  * thread is waiting). */
1162 pa_source *pa_source_get_master(pa_source *s) {
1163     pa_source_assert_ref(s);
1164
1165     while (s && (s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
1166         if (PA_UNLIKELY(!s->output_from_master))
1167             return NULL;
1168
1169         s = s->output_from_master->source;
1170     }
1171
1172     return s;
1173 }
1174
1175 /* Called from main context */
1176 bool pa_source_is_filter(pa_source *s) {
1177     pa_source_assert_ref(s);
1178
1179     return (s->output_from_master != NULL);
1180 }
1181
1182 /* Called from main context */
1183 bool pa_source_is_passthrough(pa_source *s) {
1184
1185     pa_source_assert_ref(s);
1186
1187     /* NB Currently only monitor sources support passthrough mode */
1188     return (s->monitor_of && pa_sink_is_passthrough(s->monitor_of));
1189 }
1190
1191 /* Called from main context */
1192 void pa_source_enter_passthrough(pa_source *s) {
1193     pa_cvolume volume;
1194
1195     /* set the volume to NORM */
1196     s->saved_volume = *pa_source_get_volume(s, true);
1197     s->saved_save_volume = s->save_volume;
1198
1199     pa_cvolume_set(&volume, s->sample_spec.channels, PA_MIN(s->base_volume, PA_VOLUME_NORM));
1200     pa_source_set_volume(s, &volume, true, false);
1201 }
1202
1203 /* Called from main context */
1204 void pa_source_leave_passthrough(pa_source *s) {
1205     /* Restore source volume to what it was before we entered passthrough mode */
1206     pa_source_set_volume(s, &s->saved_volume, true, s->saved_save_volume);
1207
1208     pa_cvolume_init(&s->saved_volume);
1209     s->saved_save_volume = false;
1210 }
1211
1212 /* Called from main context. */
1213 static void compute_reference_ratio(pa_source_output *o) {
1214     unsigned c = 0;
1215     pa_cvolume remapped;
1216     pa_cvolume ratio;
1217
1218     pa_assert(o);
1219     pa_assert(pa_source_flat_volume_enabled(o->source));
1220
1221     /*
1222      * Calculates the reference ratio from the source's reference
1223      * volume. This basically calculates:
1224      *
1225      * o->reference_ratio = o->volume / o->source->reference_volume
1226      */
1227
1228     remapped = o->source->reference_volume;
1229     pa_cvolume_remap(&remapped, &o->source->channel_map, &o->channel_map);
1230
1231     ratio = o->reference_ratio;
1232
1233     for (c = 0; c < o->sample_spec.channels; c++) {
1234
1235         /* We don't update when the source volume is 0 anyway */
1236         if (remapped.values[c] <= PA_VOLUME_MUTED)
1237             continue;
1238
1239         /* Don't update the reference ratio unless necessary */
1240         if (pa_sw_volume_multiply(
1241                     ratio.values[c],
1242                     remapped.values[c]) == o->volume.values[c])
1243             continue;
1244
1245         ratio.values[c] = pa_sw_volume_divide(
1246                 o->volume.values[c],
1247                 remapped.values[c]);
1248     }
1249
1250     pa_source_output_set_reference_ratio(o, &ratio);
1251 }
1252
1253 /* Called from main context. Only called for the root source in volume sharing
1254  * cases, except for internal recursive calls. */
1255 static void compute_reference_ratios(pa_source *s) {
1256     uint32_t idx;
1257     pa_source_output *o;
1258
1259     pa_source_assert_ref(s);
1260     pa_assert_ctl_context();
1261     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1262     pa_assert(pa_source_flat_volume_enabled(s));
1263
1264     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1265         compute_reference_ratio(o);
1266
1267         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER))
1268             compute_reference_ratios(o->destination_source);
1269     }
1270 }
1271
1272 /* Called from main context. Only called for the root source in volume sharing
1273  * cases, except for internal recursive calls. */
1274 static void compute_real_ratios(pa_source *s) {
1275     pa_source_output *o;
1276     uint32_t idx;
1277
1278     pa_source_assert_ref(s);
1279     pa_assert_ctl_context();
1280     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1281     pa_assert(pa_source_flat_volume_enabled(s));
1282
1283     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1284         unsigned c;
1285         pa_cvolume remapped;
1286
1287         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
1288             /* The origin source uses volume sharing, so this input's real ratio
1289              * is handled as a special case - the real ratio must be 0 dB, and
1290              * as a result i->soft_volume must equal i->volume_factor. */
1291             pa_cvolume_reset(&o->real_ratio, o->real_ratio.channels);
1292             o->soft_volume = o->volume_factor;
1293
1294             compute_real_ratios(o->destination_source);
1295
1296             continue;
1297         }
1298
1299         /*
1300          * This basically calculates:
1301          *
1302          * i->real_ratio := i->volume / s->real_volume
1303          * i->soft_volume := i->real_ratio * i->volume_factor
1304          */
1305
1306         remapped = s->real_volume;
1307         pa_cvolume_remap(&remapped, &s->channel_map, &o->channel_map);
1308
1309         o->real_ratio.channels = o->sample_spec.channels;
1310         o->soft_volume.channels = o->sample_spec.channels;
1311
1312         for (c = 0; c < o->sample_spec.channels; c++) {
1313
1314             if (remapped.values[c] <= PA_VOLUME_MUTED) {
1315                 /* We leave o->real_ratio untouched */
1316                 o->soft_volume.values[c] = PA_VOLUME_MUTED;
1317                 continue;
1318             }
1319
1320             /* Don't lose accuracy unless necessary */
1321             if (pa_sw_volume_multiply(
1322                         o->real_ratio.values[c],
1323                         remapped.values[c]) != o->volume.values[c])
1324
1325                 o->real_ratio.values[c] = pa_sw_volume_divide(
1326                         o->volume.values[c],
1327                         remapped.values[c]);
1328
1329             o->soft_volume.values[c] = pa_sw_volume_multiply(
1330                     o->real_ratio.values[c],
1331                     o->volume_factor.values[c]);
1332         }
1333
1334         /* We don't copy the soft_volume to the thread_info data
1335          * here. That must be done by the caller */
1336     }
1337 }
1338
1339 static pa_cvolume *cvolume_remap_minimal_impact(
1340         pa_cvolume *v,
1341         const pa_cvolume *template,
1342         const pa_channel_map *from,
1343         const pa_channel_map *to) {
1344
1345     pa_cvolume t;
1346
1347     pa_assert(v);
1348     pa_assert(template);
1349     pa_assert(from);
1350     pa_assert(to);
1351     pa_assert(pa_cvolume_compatible_with_channel_map(v, from));
1352     pa_assert(pa_cvolume_compatible_with_channel_map(template, to));
1353
1354     /* Much like pa_cvolume_remap(), but tries to minimize impact when
1355      * mapping from source output to source volumes:
1356      *
1357      * If template is a possible remapping from v it is used instead
1358      * of remapping anew.
1359      *
1360      * If the channel maps don't match we set an all-channel volume on
1361      * the source to ensure that changing a volume on one stream has no
1362      * effect that cannot be compensated for in another stream that
1363      * does not have the same channel map as the source. */
1364
1365     if (pa_channel_map_equal(from, to))
1366         return v;
1367
1368     t = *template;
1369     if (pa_cvolume_equal(pa_cvolume_remap(&t, to, from), v)) {
1370         *v = *template;
1371         return v;
1372     }
1373
1374     pa_cvolume_set(v, to->channels, pa_cvolume_max(v));
1375     return v;
1376 }
1377
1378 /* Called from main thread. Only called for the root source in volume sharing
1379  * cases, except for internal recursive calls. */
1380 static void get_maximum_output_volume(pa_source *s, pa_cvolume *max_volume, const pa_channel_map *channel_map) {
1381     pa_source_output *o;
1382     uint32_t idx;
1383
1384     pa_source_assert_ref(s);
1385     pa_assert(max_volume);
1386     pa_assert(channel_map);
1387     pa_assert(pa_source_flat_volume_enabled(s));
1388
1389     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1390         pa_cvolume remapped;
1391
1392         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
1393             get_maximum_output_volume(o->destination_source, max_volume, channel_map);
1394
1395             /* Ignore this output. The origin source uses volume sharing, so this
1396              * output's volume will be set to be equal to the root source's real
1397              * volume. Obviously this output's current volume must not then
1398              * affect what the root source's real volume will be. */
1399             continue;
1400         }
1401
1402         remapped = o->volume;
1403         cvolume_remap_minimal_impact(&remapped, max_volume, &o->channel_map, channel_map);
1404         pa_cvolume_merge(max_volume, max_volume, &remapped);
1405     }
1406 }
1407
1408 /* Called from main thread. Only called for the root source in volume sharing
1409  * cases, except for internal recursive calls. */
1410 static bool has_outputs(pa_source *s) {
1411     pa_source_output *o;
1412     uint32_t idx;
1413
1414     pa_source_assert_ref(s);
1415
1416     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1417         if (!o->destination_source || !(o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER) || has_outputs(o->destination_source))
1418             return true;
1419     }
1420
1421     return false;
1422 }
1423
1424 /* Called from main thread. Only called for the root source in volume sharing
1425  * cases, except for internal recursive calls. */
1426 static void update_real_volume(pa_source *s, const pa_cvolume *new_volume, pa_channel_map *channel_map) {
1427     pa_source_output *o;
1428     uint32_t idx;
1429
1430     pa_source_assert_ref(s);
1431     pa_assert(new_volume);
1432     pa_assert(channel_map);
1433
1434     s->real_volume = *new_volume;
1435     pa_cvolume_remap(&s->real_volume, channel_map, &s->channel_map);
1436
1437     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1438         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
1439             if (pa_source_flat_volume_enabled(s)) {
1440                 pa_cvolume new_output_volume;
1441
1442                 /* Follow the root source's real volume. */
1443                 new_output_volume = *new_volume;
1444                 pa_cvolume_remap(&new_output_volume, channel_map, &o->channel_map);
1445                 pa_source_output_set_volume_direct(o, &new_output_volume);
1446                 compute_reference_ratio(o);
1447             }
1448
1449             update_real_volume(o->destination_source, new_volume, channel_map);
1450         }
1451     }
1452 }
1453
1454 /* Called from main thread. Only called for the root source in shared volume
1455  * cases. */
1456 static void compute_real_volume(pa_source *s) {
1457     pa_source_assert_ref(s);
1458     pa_assert_ctl_context();
1459     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1460     pa_assert(pa_source_flat_volume_enabled(s));
1461     pa_assert(!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER));
1462
1463     /* This determines the maximum volume of all streams and sets
1464      * s->real_volume accordingly. */
1465
1466     if (!has_outputs(s)) {
1467         /* In the special case that we have no source outputs we leave the
1468          * volume unmodified. */
1469         update_real_volume(s, &s->reference_volume, &s->channel_map);
1470         return;
1471     }
1472
1473     pa_cvolume_mute(&s->real_volume, s->channel_map.channels);
1474
1475     /* First let's determine the new maximum volume of all outputs
1476      * connected to this source */
1477     get_maximum_output_volume(s, &s->real_volume, &s->channel_map);
1478     update_real_volume(s, &s->real_volume, &s->channel_map);
1479
1480     /* Then, let's update the real ratios/soft volumes of all outputs
1481      * connected to this source */
1482     compute_real_ratios(s);
1483 }
1484
1485 /* Called from main thread. Only called for the root source in shared volume
1486  * cases, except for internal recursive calls. */
1487 static void propagate_reference_volume(pa_source *s) {
1488     pa_source_output *o;
1489     uint32_t idx;
1490
1491     pa_source_assert_ref(s);
1492     pa_assert_ctl_context();
1493     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1494     pa_assert(pa_source_flat_volume_enabled(s));
1495
1496     /* This is called whenever the source volume changes that is not
1497      * caused by a source output volume change. We need to fix up the
1498      * source output volumes accordingly */
1499
1500     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1501         pa_cvolume new_volume;
1502
1503         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
1504             propagate_reference_volume(o->destination_source);
1505
1506             /* Since the origin source uses volume sharing, this output's volume
1507              * needs to be updated to match the root source's real volume, but
1508              * that will be done later in update_shared_real_volume(). */
1509             continue;
1510         }
1511
1512         /* This basically calculates:
1513          *
1514          * o->volume := o->reference_volume * o->reference_ratio  */
1515
1516         new_volume = s->reference_volume;
1517         pa_cvolume_remap(&new_volume, &s->channel_map, &o->channel_map);
1518         pa_sw_cvolume_multiply(&new_volume, &new_volume, &o->reference_ratio);
1519         pa_source_output_set_volume_direct(o, &new_volume);
1520     }
1521 }
1522
1523 /* Called from main thread. Only called for the root source in volume sharing
1524  * cases, except for internal recursive calls. The return value indicates
1525  * whether any reference volume actually changed. */
1526 static bool update_reference_volume(pa_source *s, const pa_cvolume *v, const pa_channel_map *channel_map, bool save) {
1527     pa_cvolume volume;
1528     bool reference_volume_changed;
1529     pa_source_output *o;
1530     uint32_t idx;
1531
1532     pa_source_assert_ref(s);
1533     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1534     pa_assert(v);
1535     pa_assert(channel_map);
1536     pa_assert(pa_cvolume_valid(v));
1537
1538     volume = *v;
1539     pa_cvolume_remap(&volume, channel_map, &s->channel_map);
1540
1541     reference_volume_changed = !pa_cvolume_equal(&volume, &s->reference_volume);
1542     pa_source_set_reference_volume_direct(s, &volume);
1543
1544     s->save_volume = (!reference_volume_changed && s->save_volume) || save;
1545
1546     if (!reference_volume_changed && !(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER))
1547         /* If the root source's volume doesn't change, then there can't be any
1548          * changes in the other source in the source tree either.
1549          *
1550          * It's probably theoretically possible that even if the root source's
1551          * volume changes slightly, some filter source doesn't change its volume
1552          * due to rounding errors. If that happens, we still want to propagate
1553          * the changed root source volume to the sources connected to the
1554          * intermediate source that didn't change its volume. This theoretical
1555          * possibility is the reason why we have that !(s->flags &
1556          * PA_SOURCE_SHARE_VOLUME_WITH_MASTER) condition. Probably nobody would
1557          * notice even if we returned here false always if
1558          * reference_volume_changed is false. */
1559         return false;
1560
1561     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1562         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER))
1563             update_reference_volume(o->destination_source, v, channel_map, false);
1564     }
1565
1566     return true;
1567 }
1568
1569 /* Called from main thread */
1570 void pa_source_set_volume(
1571         pa_source *s,
1572         const pa_cvolume *volume,
1573         bool send_msg,
1574         bool save) {
1575
1576     pa_cvolume new_reference_volume;
1577     pa_source *root_source;
1578
1579     pa_source_assert_ref(s);
1580     pa_assert_ctl_context();
1581     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1582     pa_assert(!volume || pa_cvolume_valid(volume));
1583     pa_assert(volume || pa_source_flat_volume_enabled(s));
1584     pa_assert(!volume || volume->channels == 1 || pa_cvolume_compatible(volume, &s->sample_spec));
1585
1586     /* make sure we don't change the volume in PASSTHROUGH mode ...
1587      * ... *except* if we're being invoked to reset the volume to ensure 0 dB gain */
1588     if (pa_source_is_passthrough(s) && (!volume || !pa_cvolume_is_norm(volume))) {
1589         pa_log_warn("Cannot change volume, source is monitor of a PASSTHROUGH sink");
1590         return;
1591     }
1592
1593     /* In case of volume sharing, the volume is set for the root source first,
1594      * from which it's then propagated to the sharing sources. */
1595     root_source = pa_source_get_master(s);
1596
1597     if (PA_UNLIKELY(!root_source))
1598         return;
1599
1600     /* As a special exception we accept mono volumes on all sources --
1601      * even on those with more complex channel maps */
1602
1603     if (volume) {
1604         if (pa_cvolume_compatible(volume, &s->sample_spec))
1605             new_reference_volume = *volume;
1606         else {
1607             new_reference_volume = s->reference_volume;
1608             pa_cvolume_scale(&new_reference_volume, pa_cvolume_max(volume));
1609         }
1610
1611         pa_cvolume_remap(&new_reference_volume, &s->channel_map, &root_source->channel_map);
1612
1613         if (update_reference_volume(root_source, &new_reference_volume, &root_source->channel_map, save)) {
1614             if (pa_source_flat_volume_enabled(root_source)) {
1615                 /* OK, propagate this volume change back to the outputs */
1616                 propagate_reference_volume(root_source);
1617
1618                 /* And now recalculate the real volume */
1619                 compute_real_volume(root_source);
1620             } else
1621                 update_real_volume(root_source, &root_source->reference_volume, &root_source->channel_map);
1622         }
1623
1624     } else {
1625         /* If volume is NULL we synchronize the source's real and
1626          * reference volumes with the stream volumes. */
1627
1628         pa_assert(pa_source_flat_volume_enabled(root_source));
1629
1630         /* Ok, let's determine the new real volume */
1631         compute_real_volume(root_source);
1632
1633         /* Let's 'push' the reference volume if necessary */
1634         pa_cvolume_merge(&new_reference_volume, &s->reference_volume, &root_source->real_volume);
1635         /* If the source and its root don't have the same number of channels, we need to remap */
1636         if (s != root_source && !pa_channel_map_equal(&s->channel_map, &root_source->channel_map))
1637             pa_cvolume_remap(&new_reference_volume, &s->channel_map, &root_source->channel_map);
1638         update_reference_volume(root_source, &new_reference_volume, &root_source->channel_map, save);
1639
1640         /* Now that the reference volume is updated, we can update the streams'
1641          * reference ratios. */
1642         compute_reference_ratios(root_source);
1643     }
1644
1645     if (root_source->set_volume) {
1646         /* If we have a function set_volume(), then we do not apply a
1647          * soft volume by default. However, set_volume() is free to
1648          * apply one to root_source->soft_volume */
1649
1650         pa_cvolume_reset(&root_source->soft_volume, root_source->sample_spec.channels);
1651         if (!(root_source->flags & PA_SOURCE_DEFERRED_VOLUME))
1652             root_source->set_volume(root_source);
1653
1654     } else
1655         /* If we have no function set_volume(), then the soft volume
1656          * becomes the real volume */
1657         root_source->soft_volume = root_source->real_volume;
1658
1659     /* This tells the source that soft volume and/or real volume changed */
1660     if (send_msg)
1661         pa_assert_se(pa_asyncmsgq_send(root_source->asyncmsgq, PA_MSGOBJECT(root_source), PA_SOURCE_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL) == 0);
1662 }
1663
1664 /* Called from the io thread if sync volume is used, otherwise from the main thread.
1665  * Only to be called by source implementor */
1666 void pa_source_set_soft_volume(pa_source *s, const pa_cvolume *volume) {
1667
1668     pa_source_assert_ref(s);
1669     pa_assert(!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER));
1670
1671     if (s->flags & PA_SOURCE_DEFERRED_VOLUME)
1672         pa_source_assert_io_context(s);
1673     else
1674         pa_assert_ctl_context();
1675
1676     if (!volume)
1677         pa_cvolume_reset(&s->soft_volume, s->sample_spec.channels);
1678     else
1679         s->soft_volume = *volume;
1680
1681     if (PA_SOURCE_IS_LINKED(s->state) && !(s->flags & PA_SOURCE_DEFERRED_VOLUME))
1682         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_VOLUME, NULL, 0, NULL) == 0);
1683     else
1684         s->thread_info.soft_volume = s->soft_volume;
1685 }
1686
1687 /* Called from the main thread. Only called for the root source in volume sharing
1688  * cases, except for internal recursive calls. */
1689 static void propagate_real_volume(pa_source *s, const pa_cvolume *old_real_volume) {
1690     pa_source_output *o;
1691     uint32_t idx;
1692
1693     pa_source_assert_ref(s);
1694     pa_assert(old_real_volume);
1695     pa_assert_ctl_context();
1696     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1697
1698     /* This is called when the hardware's real volume changes due to
1699      * some external event. We copy the real volume into our
1700      * reference volume and then rebuild the stream volumes based on
1701      * i->real_ratio which should stay fixed. */
1702
1703     if (!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER)) {
1704         if (pa_cvolume_equal(old_real_volume, &s->real_volume))
1705             return;
1706
1707         /* 1. Make the real volume the reference volume */
1708         update_reference_volume(s, &s->real_volume, &s->channel_map, true);
1709     }
1710
1711     if (pa_source_flat_volume_enabled(s)) {
1712         PA_IDXSET_FOREACH(o, s->outputs, idx) {
1713             pa_cvolume new_volume;
1714
1715             /* 2. Since the source's reference and real volumes are equal
1716              * now our ratios should be too. */
1717             pa_source_output_set_reference_ratio(o, &o->real_ratio);
1718
1719             /* 3. Recalculate the new stream reference volume based on the
1720              * reference ratio and the sink's reference volume.
1721              *
1722              * This basically calculates:
1723              *
1724              * o->volume = s->reference_volume * o->reference_ratio
1725              *
1726              * This is identical to propagate_reference_volume() */
1727             new_volume = s->reference_volume;
1728             pa_cvolume_remap(&new_volume, &s->channel_map, &o->channel_map);
1729             pa_sw_cvolume_multiply(&new_volume, &new_volume, &o->reference_ratio);
1730             pa_source_output_set_volume_direct(o, &new_volume);
1731
1732             if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER))
1733                 propagate_real_volume(o->destination_source, old_real_volume);
1734         }
1735     }
1736
1737     /* Something got changed in the hardware. It probably makes sense
1738      * to save changed hw settings given that hw volume changes not
1739      * triggered by PA are almost certainly done by the user. */
1740     if (!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER))
1741         s->save_volume = true;
1742 }
1743
1744 /* Called from io thread */
1745 void pa_source_update_volume_and_mute(pa_source *s) {
1746     pa_assert(s);
1747     pa_source_assert_io_context(s);
1748
1749     pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_UPDATE_VOLUME_AND_MUTE, NULL, 0, NULL, NULL);
1750 }
1751
1752 /* Called from main thread */
1753 const pa_cvolume *pa_source_get_volume(pa_source *s, bool force_refresh) {
1754     pa_source_assert_ref(s);
1755     pa_assert_ctl_context();
1756     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1757
1758     if (s->refresh_volume || force_refresh) {
1759         struct pa_cvolume old_real_volume;
1760
1761         pa_assert(!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER));
1762
1763         old_real_volume = s->real_volume;
1764
1765         if (!(s->flags & PA_SOURCE_DEFERRED_VOLUME) && s->get_volume)
1766             s->get_volume(s);
1767
1768         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_VOLUME, NULL, 0, NULL) == 0);
1769
1770         update_real_volume(s, &s->real_volume, &s->channel_map);
1771         propagate_real_volume(s, &old_real_volume);
1772     }
1773
1774     return &s->reference_volume;
1775 }
1776
1777 /* Called from main thread. In volume sharing cases, only the root source may
1778  * call this. */
1779 void pa_source_volume_changed(pa_source *s, const pa_cvolume *new_real_volume) {
1780     pa_cvolume old_real_volume;
1781
1782     pa_source_assert_ref(s);
1783     pa_assert_ctl_context();
1784     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1785     pa_assert(!(s->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER));
1786
1787     /* The source implementor may call this if the volume changed to make sure everyone is notified */
1788
1789     old_real_volume = s->real_volume;
1790     update_real_volume(s, new_real_volume, &s->channel_map);
1791     propagate_real_volume(s, &old_real_volume);
1792 }
1793
1794 /* Called from main thread */
1795 void pa_source_set_mute(pa_source *s, bool mute, bool save) {
1796     bool old_muted;
1797
1798     pa_source_assert_ref(s);
1799     pa_assert_ctl_context();
1800
1801     old_muted = s->muted;
1802
1803     if (mute == old_muted) {
1804         s->save_muted |= save;
1805         return;
1806     }
1807
1808     s->muted = mute;
1809     s->save_muted = save;
1810
1811     if (!(s->flags & PA_SOURCE_DEFERRED_VOLUME) && s->set_mute) {
1812         s->set_mute_in_progress = true;
1813         s->set_mute(s);
1814         s->set_mute_in_progress = false;
1815     }
1816
1817     if (!PA_SOURCE_IS_LINKED(s->state))
1818         return;
1819
1820     pa_log_debug("The mute of source %s changed from %s to %s.", s->name, pa_yes_no(old_muted), pa_yes_no(mute));
1821     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_MUTE, NULL, 0, NULL) == 0);
1822     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1823     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_MUTE_CHANGED], s);
1824 }
1825
1826 /* Called from main thread */
1827 bool pa_source_get_mute(pa_source *s, bool force_refresh) {
1828
1829     pa_source_assert_ref(s);
1830     pa_assert_ctl_context();
1831     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1832
1833     if ((s->refresh_muted || force_refresh) && s->get_mute) {
1834         bool mute;
1835
1836         if (s->flags & PA_SOURCE_DEFERRED_VOLUME) {
1837             if (pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_MUTE, &mute, 0, NULL) >= 0)
1838                 pa_source_mute_changed(s, mute);
1839         } else {
1840             if (s->get_mute(s, &mute) >= 0)
1841                 pa_source_mute_changed(s, mute);
1842         }
1843     }
1844
1845     return s->muted;
1846 }
1847
1848 /* Called from main thread */
1849 void pa_source_mute_changed(pa_source *s, bool new_muted) {
1850     pa_source_assert_ref(s);
1851     pa_assert_ctl_context();
1852     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1853
1854     if (s->set_mute_in_progress)
1855         return;
1856
1857     /* pa_source_set_mute() does this same check, so this may appear redundant,
1858      * but we must have this here also, because the save parameter of
1859      * pa_source_set_mute() would otherwise have unintended side effects
1860      * (saving the mute state when it shouldn't be saved). */
1861     if (new_muted == s->muted)
1862         return;
1863
1864     pa_source_set_mute(s, new_muted, true);
1865 }
1866
1867 /* Called from main thread */
1868 bool pa_source_update_proplist(pa_source *s, pa_update_mode_t mode, pa_proplist *p) {
1869     pa_source_assert_ref(s);
1870     pa_assert_ctl_context();
1871
1872     if (p)
1873         pa_proplist_update(s->proplist, mode, p);
1874
1875     if (PA_SOURCE_IS_LINKED(s->state)) {
1876         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_PROPLIST_CHANGED], s);
1877         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1878     }
1879
1880     return true;
1881 }
1882
1883 /* Called from main thread */
1884 /* FIXME -- this should be dropped and be merged into pa_source_update_proplist() */
1885 void pa_source_set_description(pa_source *s, const char *description) {
1886     const char *old;
1887     pa_source_assert_ref(s);
1888     pa_assert_ctl_context();
1889
1890     if (!description && !pa_proplist_contains(s->proplist, PA_PROP_DEVICE_DESCRIPTION))
1891         return;
1892
1893     old = pa_proplist_gets(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
1894
1895     if (old && description && pa_streq(old, description))
1896         return;
1897
1898     if (description)
1899         pa_proplist_sets(s->proplist, PA_PROP_DEVICE_DESCRIPTION, description);
1900     else
1901         pa_proplist_unset(s->proplist, PA_PROP_DEVICE_DESCRIPTION);
1902
1903     if (PA_SOURCE_IS_LINKED(s->state)) {
1904         pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
1905         pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_PROPLIST_CHANGED], s);
1906     }
1907 }
1908
1909 /* Called from main thread */
1910 unsigned pa_source_linked_by(pa_source *s) {
1911     pa_source_assert_ref(s);
1912     pa_assert_ctl_context();
1913     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1914
1915     return pa_idxset_size(s->outputs);
1916 }
1917
1918 /* Called from main thread */
1919 unsigned pa_source_used_by(pa_source *s) {
1920     unsigned ret;
1921
1922     pa_source_assert_ref(s);
1923     pa_assert_ctl_context();
1924     pa_assert(PA_SOURCE_IS_LINKED(s->state));
1925
1926     ret = pa_idxset_size(s->outputs);
1927     pa_assert(ret >= s->n_corked);
1928
1929     return ret - s->n_corked;
1930 }
1931
1932 /* Called from main thread */
1933 unsigned pa_source_check_suspend(pa_source *s) {
1934     unsigned ret;
1935     pa_source_output *o;
1936     uint32_t idx;
1937
1938     pa_source_assert_ref(s);
1939     pa_assert_ctl_context();
1940
1941     if (!PA_SOURCE_IS_LINKED(s->state))
1942         return 0;
1943
1944     ret = 0;
1945
1946     PA_IDXSET_FOREACH(o, s->outputs, idx) {
1947         pa_source_output_state_t st;
1948
1949         st = pa_source_output_get_state(o);
1950
1951         /* We do not assert here. It is perfectly valid for a source output to
1952          * be in the INIT state (i.e. created, marked done but not yet put)
1953          * and we should not care if it's unlinked as it won't contribute
1954          * towards our busy status.
1955          */
1956         if (!PA_SOURCE_OUTPUT_IS_LINKED(st))
1957             continue;
1958
1959         if (st == PA_SOURCE_OUTPUT_CORKED)
1960             continue;
1961
1962         if (o->flags & PA_SOURCE_OUTPUT_DONT_INHIBIT_AUTO_SUSPEND)
1963             continue;
1964
1965         ret ++;
1966     }
1967
1968     return ret;
1969 }
1970
1971 /* Called from the IO thread */
1972 static void sync_output_volumes_within_thread(pa_source *s) {
1973     pa_source_output *o;
1974     void *state = NULL;
1975
1976     pa_source_assert_ref(s);
1977     pa_source_assert_io_context(s);
1978
1979     PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state) {
1980         if (pa_cvolume_equal(&o->thread_info.soft_volume, &o->soft_volume))
1981             continue;
1982
1983         o->thread_info.soft_volume = o->soft_volume;
1984         //pa_source_output_request_rewind(o, 0, true, false, false);
1985     }
1986 }
1987
1988 /* Called from the IO thread. Only called for the root source in volume sharing
1989  * cases, except for internal recursive calls. */
1990 static void set_shared_volume_within_thread(pa_source *s) {
1991     pa_source_output *o;
1992     void *state = NULL;
1993
1994     pa_source_assert_ref(s);
1995
1996     PA_MSGOBJECT(s)->process_msg(PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_VOLUME_SYNCED, NULL, 0, NULL);
1997
1998     PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state) {
1999         if (o->destination_source && (o->destination_source->flags & PA_SOURCE_SHARE_VOLUME_WITH_MASTER))
2000             set_shared_volume_within_thread(o->destination_source);
2001     }
2002 }
2003
2004 /* Called from IO thread, except when it is not */
2005 int pa_source_process_msg(pa_msgobject *object, int code, void *userdata, int64_t offset, pa_memchunk *chunk) {
2006     pa_source *s = PA_SOURCE(object);
2007     pa_source_assert_ref(s);
2008
2009     switch ((pa_source_message_t) code) {
2010
2011         case PA_SOURCE_MESSAGE_ADD_OUTPUT: {
2012             pa_source_output *o = PA_SOURCE_OUTPUT(userdata);
2013
2014             pa_hashmap_put(s->thread_info.outputs, PA_UINT32_TO_PTR(o->index), pa_source_output_ref(o));
2015
2016             if (o->direct_on_input) {
2017                 o->thread_info.direct_on_input = o->direct_on_input;
2018                 pa_hashmap_put(o->thread_info.direct_on_input->thread_info.direct_outputs, PA_UINT32_TO_PTR(o->index), o);
2019             }
2020
2021             pa_assert(!o->thread_info.attached);
2022             o->thread_info.attached = true;
2023
2024             if (o->attach)
2025                 o->attach(o);
2026
2027             pa_source_output_set_state_within_thread(o, o->state);
2028
2029             if (o->thread_info.requested_source_latency != (pa_usec_t) -1)
2030                 pa_source_output_set_requested_latency_within_thread(o, o->thread_info.requested_source_latency);
2031
2032             pa_source_output_update_max_rewind(o, s->thread_info.max_rewind);
2033
2034             /* We don't just invalidate the requested latency here,
2035              * because if we are in a move we might need to fix up the
2036              * requested latency. */
2037             pa_source_output_set_requested_latency_within_thread(o, o->thread_info.requested_source_latency);
2038
2039             /* In flat volume mode we need to update the volume as
2040              * well */
2041             return object->process_msg(object, PA_SOURCE_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL);
2042         }
2043
2044         case PA_SOURCE_MESSAGE_REMOVE_OUTPUT: {
2045             pa_source_output *o = PA_SOURCE_OUTPUT(userdata);
2046
2047             pa_source_output_set_state_within_thread(o, o->state);
2048
2049             if (o->detach)
2050                 o->detach(o);
2051
2052             pa_assert(o->thread_info.attached);
2053             o->thread_info.attached = false;
2054
2055             if (o->thread_info.direct_on_input) {
2056                 pa_hashmap_remove(o->thread_info.direct_on_input->thread_info.direct_outputs, PA_UINT32_TO_PTR(o->index));
2057                 o->thread_info.direct_on_input = NULL;
2058             }
2059
2060             pa_hashmap_remove_and_free(s->thread_info.outputs, PA_UINT32_TO_PTR(o->index));
2061             pa_source_invalidate_requested_latency(s, true);
2062
2063             /* In flat volume mode we need to update the volume as
2064              * well */
2065             return object->process_msg(object, PA_SOURCE_MESSAGE_SET_SHARED_VOLUME, NULL, 0, NULL);
2066         }
2067
2068         case PA_SOURCE_MESSAGE_SET_SHARED_VOLUME: {
2069             pa_source *root_source = pa_source_get_master(s);
2070
2071             if (PA_LIKELY(root_source))
2072                 set_shared_volume_within_thread(root_source);
2073
2074             return 0;
2075         }
2076
2077         case PA_SOURCE_MESSAGE_SET_VOLUME_SYNCED:
2078
2079             if (s->flags & PA_SOURCE_DEFERRED_VOLUME) {
2080                 s->set_volume(s);
2081                 pa_source_volume_change_push(s);
2082             }
2083             /* Fall through ... */
2084
2085         case PA_SOURCE_MESSAGE_SET_VOLUME:
2086
2087             if (!pa_cvolume_equal(&s->thread_info.soft_volume, &s->soft_volume)) {
2088                 s->thread_info.soft_volume = s->soft_volume;
2089             }
2090
2091             /* Fall through ... */
2092
2093         case PA_SOURCE_MESSAGE_SYNC_VOLUMES:
2094             sync_output_volumes_within_thread(s);
2095             return 0;
2096
2097         case PA_SOURCE_MESSAGE_GET_VOLUME:
2098
2099             if ((s->flags & PA_SOURCE_DEFERRED_VOLUME) && s->get_volume) {
2100                 s->get_volume(s);
2101                 pa_source_volume_change_flush(s);
2102                 pa_sw_cvolume_divide(&s->thread_info.current_hw_volume, &s->real_volume, &s->soft_volume);
2103             }
2104
2105             /* In case source implementor reset SW volume. */
2106             if (!pa_cvolume_equal(&s->thread_info.soft_volume, &s->soft_volume)) {
2107                 s->thread_info.soft_volume = s->soft_volume;
2108             }
2109
2110             return 0;
2111
2112         case PA_SOURCE_MESSAGE_SET_MUTE:
2113
2114             if (s->thread_info.soft_muted != s->muted) {
2115                 s->thread_info.soft_muted = s->muted;
2116             }
2117
2118             if (s->flags & PA_SOURCE_DEFERRED_VOLUME && s->set_mute)
2119                 s->set_mute(s);
2120
2121             return 0;
2122
2123         case PA_SOURCE_MESSAGE_GET_MUTE:
2124
2125             if (s->flags & PA_SOURCE_DEFERRED_VOLUME && s->get_mute)
2126                 return s->get_mute(s, userdata);
2127
2128             return 0;
2129
2130         case PA_SOURCE_MESSAGE_SET_STATE: {
2131
2132             bool suspend_change =
2133                 (s->thread_info.state == PA_SOURCE_SUSPENDED && PA_SOURCE_IS_OPENED(PA_PTR_TO_UINT(userdata))) ||
2134                 (PA_SOURCE_IS_OPENED(s->thread_info.state) && PA_PTR_TO_UINT(userdata) == PA_SOURCE_SUSPENDED);
2135
2136             s->thread_info.state = PA_PTR_TO_UINT(userdata);
2137
2138             if (suspend_change) {
2139                 pa_source_output *o;
2140                 void *state = NULL;
2141
2142                 while ((o = pa_hashmap_iterate(s->thread_info.outputs, &state, NULL)))
2143                     if (o->suspend_within_thread)
2144                         o->suspend_within_thread(o, s->thread_info.state == PA_SOURCE_SUSPENDED);
2145             }
2146
2147             return 0;
2148         }
2149
2150         case PA_SOURCE_MESSAGE_GET_REQUESTED_LATENCY: {
2151
2152             pa_usec_t *usec = userdata;
2153             *usec = pa_source_get_requested_latency_within_thread(s);
2154
2155             /* Yes, that's right, the IO thread will see -1 when no
2156              * explicit requested latency is configured, the main
2157              * thread will see max_latency */
2158             if (*usec == (pa_usec_t) -1)
2159                 *usec = s->thread_info.max_latency;
2160
2161             return 0;
2162         }
2163
2164         case PA_SOURCE_MESSAGE_SET_LATENCY_RANGE: {
2165             pa_usec_t *r = userdata;
2166
2167             pa_source_set_latency_range_within_thread(s, r[0], r[1]);
2168
2169             return 0;
2170         }
2171
2172         case PA_SOURCE_MESSAGE_GET_LATENCY_RANGE: {
2173             pa_usec_t *r = userdata;
2174
2175             r[0] = s->thread_info.min_latency;
2176             r[1] = s->thread_info.max_latency;
2177
2178             return 0;
2179         }
2180
2181         case PA_SOURCE_MESSAGE_GET_FIXED_LATENCY:
2182
2183             *((pa_usec_t*) userdata) = s->thread_info.fixed_latency;
2184             return 0;
2185
2186         case PA_SOURCE_MESSAGE_SET_FIXED_LATENCY:
2187
2188             pa_source_set_fixed_latency_within_thread(s, (pa_usec_t) offset);
2189             return 0;
2190
2191         case PA_SOURCE_MESSAGE_GET_MAX_REWIND:
2192
2193             *((size_t*) userdata) = s->thread_info.max_rewind;
2194             return 0;
2195
2196         case PA_SOURCE_MESSAGE_SET_MAX_REWIND:
2197
2198             pa_source_set_max_rewind_within_thread(s, (size_t) offset);
2199             return 0;
2200
2201         case PA_SOURCE_MESSAGE_GET_LATENCY:
2202
2203             if (s->monitor_of) {
2204                 *((pa_usec_t*) userdata) = 0;
2205                 return 0;
2206             }
2207
2208             /* Implementors need to overwrite this implementation! */
2209             return -1;
2210
2211         case PA_SOURCE_MESSAGE_SET_PORT:
2212
2213             pa_assert(userdata);
2214             if (s->set_port) {
2215                 struct source_message_set_port *msg_data = userdata;
2216                 msg_data->ret = s->set_port(s, msg_data->port);
2217             }
2218             return 0;
2219
2220         case PA_SOURCE_MESSAGE_UPDATE_VOLUME_AND_MUTE:
2221             /* This message is sent from IO-thread and handled in main thread. */
2222             pa_assert_ctl_context();
2223
2224             /* Make sure we're not messing with main thread when no longer linked */
2225             if (!PA_SOURCE_IS_LINKED(s->state))
2226                 return 0;
2227
2228             pa_source_get_volume(s, true);
2229             pa_source_get_mute(s, true);
2230             return 0;
2231
2232         case PA_SOURCE_MESSAGE_SET_LATENCY_OFFSET:
2233             s->thread_info.latency_offset = offset;
2234             return 0;
2235
2236         case PA_SOURCE_MESSAGE_MAX:
2237             ;
2238     }
2239
2240     return -1;
2241 }
2242
2243 /* Called from main thread */
2244 int pa_source_suspend_all(pa_core *c, bool suspend, pa_suspend_cause_t cause) {
2245     pa_source *source;
2246     uint32_t idx;
2247     int ret = 0;
2248
2249     pa_core_assert_ref(c);
2250     pa_assert_ctl_context();
2251     pa_assert(cause != 0);
2252
2253     for (source = PA_SOURCE(pa_idxset_first(c->sources, &idx)); source; source = PA_SOURCE(pa_idxset_next(c->sources, &idx))) {
2254         int r;
2255
2256         if (source->monitor_of)
2257             continue;
2258
2259         if ((r = pa_source_suspend(source, suspend, cause)) < 0)
2260             ret = r;
2261     }
2262
2263     return ret;
2264 }
2265
2266 /* Called from IO thread */
2267 void pa_source_detach_within_thread(pa_source *s) {
2268     pa_source_output *o;
2269     void *state = NULL;
2270
2271     pa_source_assert_ref(s);
2272     pa_source_assert_io_context(s);
2273     pa_assert(PA_SOURCE_IS_LINKED(s->thread_info.state));
2274
2275     PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state)
2276         if (o->detach)
2277             o->detach(o);
2278 }
2279
2280 /* Called from IO thread */
2281 void pa_source_attach_within_thread(pa_source *s) {
2282     pa_source_output *o;
2283     void *state = NULL;
2284
2285     pa_source_assert_ref(s);
2286     pa_source_assert_io_context(s);
2287     pa_assert(PA_SOURCE_IS_LINKED(s->thread_info.state));
2288
2289     PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state)
2290         if (o->attach)
2291             o->attach(o);
2292 }
2293
2294 /* Called from IO thread */
2295 pa_usec_t pa_source_get_requested_latency_within_thread(pa_source *s) {
2296     pa_usec_t result = (pa_usec_t) -1;
2297     pa_source_output *o;
2298     void *state = NULL;
2299
2300     pa_source_assert_ref(s);
2301     pa_source_assert_io_context(s);
2302
2303     if (!(s->flags & PA_SOURCE_DYNAMIC_LATENCY))
2304         return PA_CLAMP(s->thread_info.fixed_latency, s->thread_info.min_latency, s->thread_info.max_latency);
2305
2306     if (s->thread_info.requested_latency_valid)
2307         return s->thread_info.requested_latency;
2308
2309     PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state)
2310         if (o->thread_info.requested_source_latency != (pa_usec_t) -1 &&
2311             (result == (pa_usec_t) -1 || result > o->thread_info.requested_source_latency))
2312             result = o->thread_info.requested_source_latency;
2313
2314     if (result != (pa_usec_t) -1)
2315         result = PA_CLAMP(result, s->thread_info.min_latency, s->thread_info.max_latency);
2316
2317     if (PA_SOURCE_IS_LINKED(s->thread_info.state)) {
2318         /* Only cache this if we are fully set up */
2319         s->thread_info.requested_latency = result;
2320         s->thread_info.requested_latency_valid = true;
2321     }
2322
2323     return result;
2324 }
2325
2326 /* Called from main thread */
2327 pa_usec_t pa_source_get_requested_latency(pa_source *s) {
2328     pa_usec_t usec = 0;
2329
2330     pa_source_assert_ref(s);
2331     pa_assert_ctl_context();
2332     pa_assert(PA_SOURCE_IS_LINKED(s->state));
2333
2334     if (s->state == PA_SOURCE_SUSPENDED)
2335         return 0;
2336
2337     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_REQUESTED_LATENCY, &usec, 0, NULL) == 0);
2338
2339     return usec;
2340 }
2341
2342 /* Called from IO thread */
2343 void pa_source_set_max_rewind_within_thread(pa_source *s, size_t max_rewind) {
2344     pa_source_output *o;
2345     void *state = NULL;
2346
2347     pa_source_assert_ref(s);
2348     pa_source_assert_io_context(s);
2349
2350     if (max_rewind == s->thread_info.max_rewind)
2351         return;
2352
2353     s->thread_info.max_rewind = max_rewind;
2354
2355     if (PA_SOURCE_IS_LINKED(s->thread_info.state))
2356         PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state)
2357             pa_source_output_update_max_rewind(o, s->thread_info.max_rewind);
2358 }
2359
2360 /* Called from main thread */
2361 void pa_source_set_max_rewind(pa_source *s, size_t max_rewind) {
2362     pa_source_assert_ref(s);
2363     pa_assert_ctl_context();
2364
2365     if (PA_SOURCE_IS_LINKED(s->state))
2366         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_MAX_REWIND, NULL, max_rewind, NULL) == 0);
2367     else
2368         pa_source_set_max_rewind_within_thread(s, max_rewind);
2369 }
2370
2371 /* Called from IO thread */
2372 void pa_source_invalidate_requested_latency(pa_source *s, bool dynamic) {
2373     pa_source_output *o;
2374     void *state = NULL;
2375
2376     pa_source_assert_ref(s);
2377     pa_source_assert_io_context(s);
2378
2379     if ((s->flags & PA_SOURCE_DYNAMIC_LATENCY))
2380         s->thread_info.requested_latency_valid = false;
2381     else if (dynamic)
2382         return;
2383
2384     if (PA_SOURCE_IS_LINKED(s->thread_info.state)) {
2385
2386         if (s->update_requested_latency)
2387             s->update_requested_latency(s);
2388
2389         while ((o = pa_hashmap_iterate(s->thread_info.outputs, &state, NULL)))
2390             if (o->update_source_requested_latency)
2391                 o->update_source_requested_latency(o);
2392     }
2393
2394     if (s->monitor_of)
2395         pa_sink_invalidate_requested_latency(s->monitor_of, dynamic);
2396 }
2397
2398 /* Called from main thread */
2399 void pa_source_set_latency_range(pa_source *s, pa_usec_t min_latency, pa_usec_t max_latency) {
2400     pa_source_assert_ref(s);
2401     pa_assert_ctl_context();
2402
2403     /* min_latency == 0:           no limit
2404      * min_latency anything else:  specified limit
2405      *
2406      * Similar for max_latency */
2407
2408     if (min_latency < ABSOLUTE_MIN_LATENCY)
2409         min_latency = ABSOLUTE_MIN_LATENCY;
2410
2411     if (max_latency <= 0 ||
2412         max_latency > ABSOLUTE_MAX_LATENCY)
2413         max_latency = ABSOLUTE_MAX_LATENCY;
2414
2415     pa_assert(min_latency <= max_latency);
2416
2417     /* Hmm, let's see if someone forgot to set PA_SOURCE_DYNAMIC_LATENCY here... */
2418     pa_assert((min_latency == ABSOLUTE_MIN_LATENCY &&
2419                max_latency == ABSOLUTE_MAX_LATENCY) ||
2420               (s->flags & PA_SOURCE_DYNAMIC_LATENCY));
2421
2422     if (PA_SOURCE_IS_LINKED(s->state)) {
2423         pa_usec_t r[2];
2424
2425         r[0] = min_latency;
2426         r[1] = max_latency;
2427
2428         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_LATENCY_RANGE, r, 0, NULL) == 0);
2429     } else
2430         pa_source_set_latency_range_within_thread(s, min_latency, max_latency);
2431 }
2432
2433 /* Called from main thread */
2434 void pa_source_get_latency_range(pa_source *s, pa_usec_t *min_latency, pa_usec_t *max_latency) {
2435     pa_source_assert_ref(s);
2436     pa_assert_ctl_context();
2437     pa_assert(min_latency);
2438     pa_assert(max_latency);
2439
2440     if (PA_SOURCE_IS_LINKED(s->state)) {
2441         pa_usec_t r[2] = { 0, 0 };
2442
2443         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_LATENCY_RANGE, r, 0, NULL) == 0);
2444
2445         *min_latency = r[0];
2446         *max_latency = r[1];
2447     } else {
2448         *min_latency = s->thread_info.min_latency;
2449         *max_latency = s->thread_info.max_latency;
2450     }
2451 }
2452
2453 /* Called from IO thread, and from main thread before pa_source_put() is called */
2454 void pa_source_set_latency_range_within_thread(pa_source *s, pa_usec_t min_latency, pa_usec_t max_latency) {
2455     pa_source_assert_ref(s);
2456     pa_source_assert_io_context(s);
2457
2458     pa_assert(min_latency >= ABSOLUTE_MIN_LATENCY);
2459     pa_assert(max_latency <= ABSOLUTE_MAX_LATENCY);
2460     pa_assert(min_latency <= max_latency);
2461
2462     /* Hmm, let's see if someone forgot to set PA_SOURCE_DYNAMIC_LATENCY here... */
2463     pa_assert((min_latency == ABSOLUTE_MIN_LATENCY &&
2464                max_latency == ABSOLUTE_MAX_LATENCY) ||
2465               (s->flags & PA_SOURCE_DYNAMIC_LATENCY) ||
2466               s->monitor_of);
2467
2468     if (s->thread_info.min_latency == min_latency &&
2469         s->thread_info.max_latency == max_latency)
2470         return;
2471
2472     s->thread_info.min_latency = min_latency;
2473     s->thread_info.max_latency = max_latency;
2474
2475     if (PA_SOURCE_IS_LINKED(s->thread_info.state)) {
2476         pa_source_output *o;
2477         void *state = NULL;
2478
2479         PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state)
2480             if (o->update_source_latency_range)
2481                 o->update_source_latency_range(o);
2482     }
2483
2484     pa_source_invalidate_requested_latency(s, false);
2485 }
2486
2487 /* Called from main thread, before the source is put */
2488 void pa_source_set_fixed_latency(pa_source *s, pa_usec_t latency) {
2489     pa_source_assert_ref(s);
2490     pa_assert_ctl_context();
2491
2492     if (s->flags & PA_SOURCE_DYNAMIC_LATENCY) {
2493         pa_assert(latency == 0);
2494         return;
2495     }
2496
2497     if (latency < ABSOLUTE_MIN_LATENCY)
2498         latency = ABSOLUTE_MIN_LATENCY;
2499
2500     if (latency > ABSOLUTE_MAX_LATENCY)
2501         latency = ABSOLUTE_MAX_LATENCY;
2502
2503     if (PA_SOURCE_IS_LINKED(s->state))
2504         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_FIXED_LATENCY, NULL, (int64_t) latency, NULL) == 0);
2505     else
2506         s->thread_info.fixed_latency = latency;
2507 }
2508
2509 /* Called from main thread */
2510 pa_usec_t pa_source_get_fixed_latency(pa_source *s) {
2511     pa_usec_t latency;
2512
2513     pa_source_assert_ref(s);
2514     pa_assert_ctl_context();
2515
2516     if (s->flags & PA_SOURCE_DYNAMIC_LATENCY)
2517         return 0;
2518
2519     if (PA_SOURCE_IS_LINKED(s->state))
2520         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_FIXED_LATENCY, &latency, 0, NULL) == 0);
2521     else
2522         latency = s->thread_info.fixed_latency;
2523
2524     return latency;
2525 }
2526
2527 /* Called from IO thread */
2528 void pa_source_set_fixed_latency_within_thread(pa_source *s, pa_usec_t latency) {
2529     pa_source_assert_ref(s);
2530     pa_source_assert_io_context(s);
2531
2532     if (s->flags & PA_SOURCE_DYNAMIC_LATENCY) {
2533         pa_assert(latency == 0);
2534         s->thread_info.fixed_latency = 0;
2535
2536         return;
2537     }
2538
2539     pa_assert(latency >= ABSOLUTE_MIN_LATENCY);
2540     pa_assert(latency <= ABSOLUTE_MAX_LATENCY);
2541
2542     if (s->thread_info.fixed_latency == latency)
2543         return;
2544
2545     s->thread_info.fixed_latency = latency;
2546
2547     if (PA_SOURCE_IS_LINKED(s->thread_info.state)) {
2548         pa_source_output *o;
2549         void *state = NULL;
2550
2551         PA_HASHMAP_FOREACH(o, s->thread_info.outputs, state)
2552             if (o->update_source_fixed_latency)
2553                 o->update_source_fixed_latency(o);
2554     }
2555
2556     pa_source_invalidate_requested_latency(s, false);
2557 }
2558
2559 /* Called from main thread */
2560 void pa_source_set_latency_offset(pa_source *s, int64_t offset) {
2561     pa_source_assert_ref(s);
2562
2563     s->latency_offset = offset;
2564
2565     if (PA_SOURCE_IS_LINKED(s->state))
2566         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_LATENCY_OFFSET, NULL, offset, NULL) == 0);
2567     else
2568         s->thread_info.latency_offset = offset;
2569 }
2570
2571 /* Called from main thread */
2572 size_t pa_source_get_max_rewind(pa_source *s) {
2573     size_t r;
2574     pa_assert_ctl_context();
2575     pa_source_assert_ref(s);
2576
2577     if (!PA_SOURCE_IS_LINKED(s->state))
2578         return s->thread_info.max_rewind;
2579
2580     pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_GET_MAX_REWIND, &r, 0, NULL) == 0);
2581
2582     return r;
2583 }
2584
2585 /* Called from main context */
2586 int pa_source_set_port(pa_source *s, const char *name, bool save) {
2587     pa_device_port *port;
2588     int ret;
2589
2590     pa_source_assert_ref(s);
2591     pa_assert_ctl_context();
2592
2593     if (!s->set_port) {
2594         pa_log_debug("set_port() operation not implemented for source %u \"%s\"", s->index, s->name);
2595         return -PA_ERR_NOTIMPLEMENTED;
2596     }
2597
2598     if (!name)
2599         return -PA_ERR_NOENTITY;
2600
2601     if (!(port = pa_hashmap_get(s->ports, name)))
2602         return -PA_ERR_NOENTITY;
2603
2604     if (s->active_port == port) {
2605         s->save_port = s->save_port || save;
2606         return 0;
2607     }
2608
2609     if (s->flags & PA_SOURCE_DEFERRED_VOLUME) {
2610         struct source_message_set_port msg = { .port = port, .ret = 0 };
2611         pa_assert_se(pa_asyncmsgq_send(s->asyncmsgq, PA_MSGOBJECT(s), PA_SOURCE_MESSAGE_SET_PORT, &msg, 0, NULL) == 0);
2612         ret = msg.ret;
2613     }
2614     else
2615         ret = s->set_port(s, port);
2616
2617     if (ret < 0)
2618         return -PA_ERR_NOENTITY;
2619
2620     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
2621
2622     pa_log_info("Changed port of source %u \"%s\" to %s", s->index, s->name, port->name);
2623
2624     s->active_port = port;
2625     s->save_port = save;
2626
2627     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_PORT_CHANGED], s);
2628
2629     return 0;
2630 }
2631
2632 PA_STATIC_FLIST_DECLARE(pa_source_volume_change, 0, pa_xfree);
2633
2634 /* Called from the IO thread. */
2635 static pa_source_volume_change *pa_source_volume_change_new(pa_source *s) {
2636     pa_source_volume_change *c;
2637     if (!(c = pa_flist_pop(PA_STATIC_FLIST_GET(pa_source_volume_change))))
2638         c = pa_xnew(pa_source_volume_change, 1);
2639
2640     PA_LLIST_INIT(pa_source_volume_change, c);
2641     c->at = 0;
2642     pa_cvolume_reset(&c->hw_volume, s->sample_spec.channels);
2643     return c;
2644 }
2645
2646 /* Called from the IO thread. */
2647 static void pa_source_volume_change_free(pa_source_volume_change *c) {
2648     pa_assert(c);
2649     if (pa_flist_push(PA_STATIC_FLIST_GET(pa_source_volume_change), c) < 0)
2650         pa_xfree(c);
2651 }
2652
2653 /* Called from the IO thread. */
2654 void pa_source_volume_change_push(pa_source *s) {
2655     pa_source_volume_change *c = NULL;
2656     pa_source_volume_change *nc = NULL;
2657     pa_source_volume_change *pc = NULL;
2658     uint32_t safety_margin = s->thread_info.volume_change_safety_margin;
2659
2660     const char *direction = NULL;
2661
2662     pa_assert(s);
2663     nc = pa_source_volume_change_new(s);
2664
2665     /* NOTE: There is already more different volumes in pa_source that I can remember.
2666      *       Adding one more volume for HW would get us rid of this, but I am trying
2667      *       to survive with the ones we already have. */
2668     pa_sw_cvolume_divide(&nc->hw_volume, &s->real_volume, &s->soft_volume);
2669
2670     if (!s->thread_info.volume_changes && pa_cvolume_equal(&nc->hw_volume, &s->thread_info.current_hw_volume)) {
2671         pa_log_debug("Volume not changing");
2672         pa_source_volume_change_free(nc);
2673         return;
2674     }
2675
2676     nc->at = pa_source_get_latency_within_thread(s);
2677     nc->at += pa_rtclock_now() + s->thread_info.volume_change_extra_delay;
2678
2679     if (s->thread_info.volume_changes_tail) {
2680         for (c = s->thread_info.volume_changes_tail; c; c = c->prev) {
2681             /* If volume is going up let's do it a bit late. If it is going
2682              * down let's do it a bit early. */
2683             if (pa_cvolume_avg(&nc->hw_volume) > pa_cvolume_avg(&c->hw_volume)) {
2684                 if (nc->at + safety_margin > c->at) {
2685                     nc->at += safety_margin;
2686                     direction = "up";
2687                     break;
2688                 }
2689             }
2690             else if (nc->at - safety_margin > c->at) {
2691                     nc->at -= safety_margin;
2692                     direction = "down";
2693                     break;
2694             }
2695         }
2696     }
2697
2698     if (c == NULL) {
2699         if (pa_cvolume_avg(&nc->hw_volume) > pa_cvolume_avg(&s->thread_info.current_hw_volume)) {
2700             nc->at += safety_margin;
2701             direction = "up";
2702         } else {
2703             nc->at -= safety_margin;
2704             direction = "down";
2705         }
2706         PA_LLIST_PREPEND(pa_source_volume_change, s->thread_info.volume_changes, nc);
2707     }
2708     else {
2709         PA_LLIST_INSERT_AFTER(pa_source_volume_change, s->thread_info.volume_changes, c, nc);
2710     }
2711
2712     pa_log_debug("Volume going %s to %d at %llu", direction, pa_cvolume_avg(&nc->hw_volume), (long long unsigned) nc->at);
2713
2714     /* We can ignore volume events that came earlier but should happen later than this. */
2715     PA_LLIST_FOREACH_SAFE(c, pc, nc->next) {
2716         pa_log_debug("Volume change to %d at %llu was dropped", pa_cvolume_avg(&c->hw_volume), (long long unsigned) c->at);
2717         pa_source_volume_change_free(c);
2718     }
2719     nc->next = NULL;
2720     s->thread_info.volume_changes_tail = nc;
2721 }
2722
2723 /* Called from the IO thread. */
2724 static void pa_source_volume_change_flush(pa_source *s) {
2725     pa_source_volume_change *c = s->thread_info.volume_changes;
2726     pa_assert(s);
2727     s->thread_info.volume_changes = NULL;
2728     s->thread_info.volume_changes_tail = NULL;
2729     while (c) {
2730         pa_source_volume_change *next = c->next;
2731         pa_source_volume_change_free(c);
2732         c = next;
2733     }
2734 }
2735
2736 /* Called from the IO thread. */
2737 bool pa_source_volume_change_apply(pa_source *s, pa_usec_t *usec_to_next) {
2738     pa_usec_t now;
2739     bool ret = false;
2740
2741     pa_assert(s);
2742
2743     if (!s->thread_info.volume_changes || !PA_SOURCE_IS_LINKED(s->state)) {
2744         if (usec_to_next)
2745             *usec_to_next = 0;
2746         return ret;
2747     }
2748
2749     pa_assert(s->write_volume);
2750
2751     now = pa_rtclock_now();
2752
2753     while (s->thread_info.volume_changes && now >= s->thread_info.volume_changes->at) {
2754         pa_source_volume_change *c = s->thread_info.volume_changes;
2755         PA_LLIST_REMOVE(pa_source_volume_change, s->thread_info.volume_changes, c);
2756         pa_log_debug("Volume change to %d at %llu was written %llu usec late",
2757                      pa_cvolume_avg(&c->hw_volume), (long long unsigned) c->at, (long long unsigned) (now - c->at));
2758         ret = true;
2759         s->thread_info.current_hw_volume = c->hw_volume;
2760         pa_source_volume_change_free(c);
2761     }
2762
2763     if (ret)
2764         s->write_volume(s);
2765
2766     if (s->thread_info.volume_changes) {
2767         if (usec_to_next)
2768             *usec_to_next = s->thread_info.volume_changes->at - now;
2769         if (pa_log_ratelimit(PA_LOG_DEBUG))
2770             pa_log_debug("Next volume change in %lld usec", (long long) (s->thread_info.volume_changes->at - now));
2771     }
2772     else {
2773         if (usec_to_next)
2774             *usec_to_next = 0;
2775         s->thread_info.volume_changes_tail = NULL;
2776     }
2777     return ret;
2778 }
2779
2780 /* Called from the main thread */
2781 /* Gets the list of formats supported by the source. The members and idxset must
2782  * be freed by the caller. */
2783 pa_idxset* pa_source_get_formats(pa_source *s) {
2784     pa_idxset *ret;
2785
2786     pa_assert(s);
2787
2788     if (s->get_formats) {
2789         /* Source supports format query, all is good */
2790         ret = s->get_formats(s);
2791     } else {
2792         /* Source doesn't support format query, so assume it does PCM */
2793         pa_format_info *f = pa_format_info_new();
2794         f->encoding = PA_ENCODING_PCM;
2795
2796         ret = pa_idxset_new(NULL, NULL);
2797         pa_idxset_put(ret, f, NULL);
2798     }
2799
2800     return ret;
2801 }
2802
2803 /* Called from the main thread */
2804 /* Checks if the source can accept this format */
2805 bool pa_source_check_format(pa_source *s, pa_format_info *f) {
2806     pa_idxset *formats = NULL;
2807     bool ret = false;
2808
2809     pa_assert(s);
2810     pa_assert(f);
2811
2812     formats = pa_source_get_formats(s);
2813
2814     if (formats) {
2815         pa_format_info *finfo_device;
2816         uint32_t i;
2817
2818         PA_IDXSET_FOREACH(finfo_device, formats, i) {
2819             if (pa_format_info_is_compatible(finfo_device, f)) {
2820                 ret = true;
2821                 break;
2822             }
2823         }
2824
2825         pa_idxset_free(formats, (pa_free_cb_t) pa_format_info_free);
2826     }
2827
2828     return ret;
2829 }
2830
2831 /* Called from the main thread */
2832 /* Calculates the intersection between formats supported by the source and
2833  * in_formats, and returns these, in the order of the source's formats. */
2834 pa_idxset* pa_source_check_formats(pa_source *s, pa_idxset *in_formats) {
2835     pa_idxset *out_formats = pa_idxset_new(NULL, NULL), *source_formats = NULL;
2836     pa_format_info *f_source, *f_in;
2837     uint32_t i, j;
2838
2839     pa_assert(s);
2840
2841     if (!in_formats || pa_idxset_isempty(in_formats))
2842         goto done;
2843
2844     source_formats = pa_source_get_formats(s);
2845
2846     PA_IDXSET_FOREACH(f_source, source_formats, i) {
2847         PA_IDXSET_FOREACH(f_in, in_formats, j) {
2848             if (pa_format_info_is_compatible(f_source, f_in))
2849                 pa_idxset_put(out_formats, pa_format_info_copy(f_in), NULL);
2850         }
2851     }
2852
2853 done:
2854     if (source_formats)
2855         pa_idxset_free(source_formats, (pa_free_cb_t) pa_format_info_free);
2856
2857     return out_formats;
2858 }
2859
2860 /* Called from the main thread. */
2861 void pa_source_set_reference_volume_direct(pa_source *s, const pa_cvolume *volume) {
2862     pa_cvolume old_volume;
2863     char old_volume_str[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
2864     char new_volume_str[PA_CVOLUME_SNPRINT_VERBOSE_MAX];
2865
2866     pa_assert(s);
2867     pa_assert(volume);
2868
2869     old_volume = s->reference_volume;
2870
2871     if (pa_cvolume_equal(volume, &old_volume))
2872         return;
2873
2874     s->reference_volume = *volume;
2875     pa_log_debug("The reference volume of source %s changed from %s to %s.", s->name,
2876                  pa_cvolume_snprint_verbose(old_volume_str, sizeof(old_volume_str), &old_volume, &s->channel_map,
2877                                             s->flags & PA_SOURCE_DECIBEL_VOLUME),
2878                  pa_cvolume_snprint_verbose(new_volume_str, sizeof(new_volume_str), volume, &s->channel_map,
2879                                             s->flags & PA_SOURCE_DECIBEL_VOLUME));
2880
2881     pa_subscription_post(s->core, PA_SUBSCRIPTION_EVENT_SOURCE|PA_SUBSCRIPTION_EVENT_CHANGE, s->index);
2882     pa_hook_fire(&s->core->hooks[PA_CORE_HOOK_SOURCE_VOLUME_CHANGED], s);
2883 }