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