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