2 This file is part of PulseAudio.
4 Copyright 2009 Intel Corporation
5 Contributor: Pierre-Louis Bossart <pierre-louis.bossart@intel.com>
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.
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.
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/>.
27 #include <pulse/xmalloc.h>
29 #include <pulsecore/sink-input.h>
30 #include <pulsecore/module.h>
31 #include <pulsecore/modargs.h>
32 #include <pulsecore/namereg.h>
33 #include <pulsecore/log.h>
34 #include <pulsecore/core-util.h>
36 #include <pulse/rtclock.h>
37 #include <pulse/timeval.h>
39 PA_MODULE_AUTHOR("Pierre-Louis Bossart");
40 PA_MODULE_DESCRIPTION("Loopback from source to sink");
41 PA_MODULE_VERSION(PACKAGE_VERSION);
42 PA_MODULE_LOAD_ONCE(false);
44 "source=<source to connect to> "
45 "sink=<sink to connect to> "
46 "adjust_time=<how often to readjust rates in s> "
47 "latency_msec=<latency in ms> "
48 "max_latency_msec=<maximum latency in ms> "
49 "fast_adjust_threshold_msec=<threshold for fast adjust in ms> "
50 "format=<sample format> "
52 "channels=<number of channels> "
53 "channel_map=<channel map> "
54 "sink_input_properties=<proplist> "
55 "source_output_properties=<proplist> "
56 "source_dont_move=<boolean> "
57 "sink_dont_move=<boolean> "
58 "remix=<remix channels?> ");
60 #define DEFAULT_LATENCY_MSEC 200
62 #define MEMBLOCKQ_MAXLENGTH (1024*1024*32)
64 #define MIN_DEVICE_LATENCY (2.5*PA_USEC_PER_MSEC)
66 #define DEFAULT_ADJUST_TIME_USEC (10*PA_USEC_PER_SEC)
68 typedef struct loopback_msg loopback_msg;
76 pa_sink_input *sink_input;
77 pa_source_output *source_output;
79 pa_asyncmsgq *asyncmsgq;
80 pa_memblockq *memblockq;
82 pa_rtpoll_item *rtpoll_item_read, *rtpoll_item_write;
84 pa_time_event *time_event;
86 /* Variables used to calculate the average time between
87 * subsequent calls of adjust_rates() */
88 pa_usec_t adjust_time_stamp;
89 pa_usec_t real_adjust_time;
90 pa_usec_t real_adjust_time_sum;
92 /* Values from command line configuration */
94 pa_usec_t max_latency;
95 pa_usec_t adjust_time;
96 pa_usec_t fast_adjust_threshold;
98 /* Latency boundaries and current values */
99 pa_usec_t min_source_latency;
100 pa_usec_t max_source_latency;
101 pa_usec_t min_sink_latency;
102 pa_usec_t max_sink_latency;
103 pa_usec_t configured_sink_latency;
104 pa_usec_t configured_source_latency;
105 int64_t source_latency_offset;
106 int64_t sink_latency_offset;
107 pa_usec_t minimum_latency;
109 /* lower latency limit found by underruns */
110 pa_usec_t underrun_latency_limit;
112 /* Various counters */
113 uint32_t iteration_counter;
114 uint32_t underrun_counter;
115 uint32_t adjust_counter;
117 bool fixed_alsa_source;
118 bool source_sink_changed;
120 /* Used for sink input and source output snapshots */
122 int64_t send_counter;
123 int64_t source_latency;
124 pa_usec_t source_timestamp;
126 int64_t recv_counter;
127 size_t loopback_memblockq_length;
128 int64_t sink_latency;
129 pa_usec_t sink_timestamp;
132 /* Input thread variable */
133 int64_t send_counter;
135 /* Output thread variables */
137 int64_t recv_counter;
138 pa_usec_t effective_source_latency;
140 /* Copied from main thread */
141 pa_usec_t minimum_latency;
143 /* Various booleans */
149 } output_thread_info;
152 struct loopback_msg {
154 struct userdata *userdata;
158 PA_DEFINE_PRIVATE_CLASS(loopback_msg, pa_msgobject);
159 #define LOOPBACK_MSG(o) (loopback_msg_cast(o))
161 static const char* const valid_modargs[] = {
167 "fast_adjust_threshold_msec",
172 "sink_input_properties",
173 "source_output_properties",
181 SINK_INPUT_MESSAGE_POST = PA_SINK_INPUT_MESSAGE_MAX,
182 SINK_INPUT_MESSAGE_REWIND,
183 SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT,
184 SINK_INPUT_MESSAGE_SOURCE_CHANGED,
185 SINK_INPUT_MESSAGE_SET_EFFECTIVE_SOURCE_LATENCY,
186 SINK_INPUT_MESSAGE_UPDATE_MIN_LATENCY,
187 SINK_INPUT_MESSAGE_FAST_ADJUST,
191 SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT = PA_SOURCE_OUTPUT_MESSAGE_MAX,
195 LOOPBACK_MESSAGE_SOURCE_LATENCY_RANGE_CHANGED,
196 LOOPBACK_MESSAGE_SINK_LATENCY_RANGE_CHANGED,
197 LOOPBACK_MESSAGE_UNDERRUN,
200 static void enable_adjust_timer(struct userdata *u, bool enable);
202 /* Called from main context */
203 static void teardown(struct userdata *u) {
205 pa_assert_ctl_context();
208 enable_adjust_timer(u, false);
213 /* Handling the asyncmsgq between the source output and the sink input
214 * requires some care. When the source output is unlinked, nothing needs
215 * to be done for the asyncmsgq, because the source output is the sending
216 * end. But when the sink input is unlinked, we should ensure that the
217 * asyncmsgq is emptied, because the messages in the queue hold references
218 * to the sink input. Also, we need to ensure that new messages won't be
219 * written to the queue after we have emptied it.
221 * Emptying the queue can be done in the state_change() callback of the
222 * sink input, when the new state is "unlinked".
224 * Preventing new messages from being written to the queue can be achieved
225 * by unlinking the source output before unlinking the sink input. There
226 * are no other writers for that queue, so this is sufficient. */
228 if (u->source_output) {
229 pa_source_output_unlink(u->source_output);
230 pa_source_output_unref(u->source_output);
231 u->source_output = NULL;
235 pa_sink_input_unlink(u->sink_input);
236 pa_sink_input_unref(u->sink_input);
237 u->sink_input = NULL;
241 /* rate controller, called from main context
242 * - maximum deviation from base rate is less than 1%
243 * - can create audible artifacts by changing the rate too quickly
244 * - exhibits hunting with USB or Bluetooth sources
246 static uint32_t rate_controller(
248 pa_usec_t adjust_time,
249 int32_t latency_difference_usec) {
254 /* Calculate best rate to correct the current latency offset, limit at
255 * slightly below 1% difference from base_rate */
256 min_cycles = (double)abs(latency_difference_usec) / adjust_time / 0.01 + 1;
257 new_rate = base_rate * (1.0 + (double)latency_difference_usec / min_cycles / adjust_time);
262 /* Called from main thread.
263 * It has been a matter of discussion how to correctly calculate the minimum
264 * latency that module-loopback can deliver with a given source and sink.
265 * The calculation has been placed in a separate function so that the definition
266 * can easily be changed. The resulting estimate is not very exact because it
267 * depends on the reported latency ranges. In cases were the lower bounds of
268 * source and sink latency are not reported correctly (USB) the result will
270 static void update_minimum_latency(struct userdata *u, pa_sink *sink, bool print_msg) {
272 if (u->underrun_latency_limit)
273 /* If we already detected a real latency limit because of underruns, use it */
274 u->minimum_latency = u->underrun_latency_limit;
277 /* Calculate latency limit from latency ranges */
279 u->minimum_latency = u->min_sink_latency;
280 if (u->fixed_alsa_source)
281 /* If we are using an alsa source with fixed latency, we will get a wakeup when
282 * one fragment is filled, and then we empty the source buffer, so the source
283 * latency never grows much beyond one fragment (assuming that the CPU doesn't
284 * cause a bottleneck). */
285 u->minimum_latency += u->core->default_fragment_size_msec * PA_USEC_PER_MSEC;
288 /* In all other cases the source will deliver new data at latest after one source latency.
289 * Make sure there is enough data available that the sink can keep on playing until new
291 u->minimum_latency += u->min_source_latency;
293 /* Multiply by 1.1 as a safety margin for delays that are proportional to the buffer sizes */
294 u->minimum_latency *= 1.1;
296 /* Add 1.5 ms as a safety margin for delays not related to the buffer sizes */
297 u->minimum_latency += 1.5 * PA_USEC_PER_MSEC;
300 /* Add the latency offsets */
301 if (-(u->sink_latency_offset + u->source_latency_offset) <= (int64_t)u->minimum_latency)
302 u->minimum_latency += u->sink_latency_offset + u->source_latency_offset;
304 u->minimum_latency = 0;
306 /* If the sink is valid, send a message to update the minimum latency to
307 * the output thread, else set the variable directly */
309 pa_asyncmsgq_send(sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_UPDATE_MIN_LATENCY, NULL, u->minimum_latency, NULL);
311 u->output_thread_info.minimum_latency = u->minimum_latency;
314 pa_log_info("Minimum possible end to end latency: %0.2f ms", (double)u->minimum_latency / PA_USEC_PER_MSEC);
315 if (u->latency < u->minimum_latency)
316 pa_log_warn("Configured latency of %0.2f ms is smaller than minimum latency, using minimum instead", (double)u->latency / PA_USEC_PER_MSEC);
320 /* Called from main context */
321 static void adjust_rates(struct userdata *u) {
323 uint32_t old_rate, base_rate, new_rate, run_hours;
324 int32_t latency_difference;
325 pa_usec_t current_buffer_latency, snapshot_delay;
326 int64_t current_source_sink_latency, current_latency, latency_at_optimum_rate;
327 pa_usec_t final_latency, now, time_passed;
330 pa_assert_ctl_context();
332 /* Runtime and counters since last change of source or sink
333 * or source/sink latency */
334 run_hours = u->iteration_counter * u->real_adjust_time / PA_USEC_PER_SEC / 3600;
335 u->iteration_counter +=1;
337 /* If we are seeing underruns then the latency is too small */
338 if (u->underrun_counter > 2) {
339 pa_usec_t target_latency;
341 target_latency = PA_MAX(u->latency, u->minimum_latency) + 5 * PA_USEC_PER_MSEC;
343 if (u->max_latency == 0 || target_latency < u->max_latency) {
344 u->underrun_latency_limit = PA_CLIP_SUB((int64_t)target_latency, u->sink_latency_offset + u->source_latency_offset);
345 pa_log_warn("Too many underruns, increasing latency to %0.2f ms", (double)target_latency / PA_USEC_PER_MSEC);
347 u->underrun_latency_limit = PA_CLIP_SUB((int64_t)u->max_latency, u->sink_latency_offset + u->source_latency_offset);
348 pa_log_warn("Too many underruns, configured maximum latency of %0.2f ms is reached", (double)u->max_latency / PA_USEC_PER_MSEC);
349 pa_log_warn("Consider increasing the max_latency_msec");
352 update_minimum_latency(u, u->sink_input->sink, false);
353 u->underrun_counter = 0;
356 /* Allow one underrun per hour */
357 if (u->iteration_counter * u->real_adjust_time / PA_USEC_PER_SEC / 3600 > run_hours) {
358 u->underrun_counter = PA_CLIP_SUB(u->underrun_counter, 1u);
359 pa_log_info("Underrun counter: %u", u->underrun_counter);
362 /* Calculate real adjust time if source or sink did not change and if the system has
363 * not been suspended. If the time between two calls is more than 5% longer than the
364 * configured adjust time, we assume that the system has been sleeping and skip the
365 * calculation for this iteration. */
366 now = pa_rtclock_now();
367 time_passed = now - u->adjust_time_stamp;
368 if (!u->source_sink_changed && time_passed < u->adjust_time * 1.05) {
370 u->real_adjust_time_sum += time_passed;
371 u->real_adjust_time = u->real_adjust_time_sum / u->adjust_counter;
373 u->adjust_time_stamp = now;
375 /* Rates and latencies */
376 old_rate = u->sink_input->sample_spec.rate;
377 base_rate = u->source_output->sample_spec.rate;
379 buffer = u->latency_snapshot.loopback_memblockq_length;
380 if (u->latency_snapshot.recv_counter <= u->latency_snapshot.send_counter)
381 buffer += (size_t) (u->latency_snapshot.send_counter - u->latency_snapshot.recv_counter);
383 buffer = PA_CLIP_SUB(buffer, (size_t) (u->latency_snapshot.recv_counter - u->latency_snapshot.send_counter));
385 current_buffer_latency = pa_bytes_to_usec(buffer, &u->sink_input->sample_spec);
386 snapshot_delay = u->latency_snapshot.source_timestamp - u->latency_snapshot.sink_timestamp;
387 current_source_sink_latency = u->latency_snapshot.sink_latency + u->latency_snapshot.source_latency - snapshot_delay;
389 /* Current latency */
390 current_latency = current_source_sink_latency + current_buffer_latency;
392 /* Latency at base rate */
393 latency_at_optimum_rate = current_source_sink_latency + current_buffer_latency * old_rate / base_rate;
395 final_latency = PA_MAX(u->latency, u->minimum_latency);
396 latency_difference = (int32_t)(latency_at_optimum_rate - final_latency);
398 pa_log_debug("Loopback overall latency is %0.2f ms + %0.2f ms + %0.2f ms = %0.2f ms",
399 (double) u->latency_snapshot.sink_latency / PA_USEC_PER_MSEC,
400 (double) current_buffer_latency / PA_USEC_PER_MSEC,
401 (double) u->latency_snapshot.source_latency / PA_USEC_PER_MSEC,
402 (double) current_latency / PA_USEC_PER_MSEC);
404 pa_log_debug("Loopback latency at base rate is %0.2f ms", (double)latency_at_optimum_rate / PA_USEC_PER_MSEC);
406 /* Drop or insert samples if fast_adjust_threshold_msec was specified and the latency difference is too large. */
407 if (u->fast_adjust_threshold > 0 && abs(latency_difference) > u->fast_adjust_threshold) {
408 pa_log_debug ("Latency difference larger than %" PRIu64 " msec, skipping or inserting samples.", u->fast_adjust_threshold / PA_USEC_PER_MSEC);
410 pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_FAST_ADJUST, NULL, current_source_sink_latency, NULL);
412 /* Skip real adjust time calculation on next iteration. */
413 u->source_sink_changed = true;
417 /* Calculate new rate */
418 new_rate = rate_controller(base_rate, u->real_adjust_time, latency_difference);
420 u->source_sink_changed = false;
423 pa_sink_input_set_rate(u->sink_input, new_rate);
424 pa_log_debug("[%s] Updated sampling rate to %lu Hz.", u->sink_input->sink->name, (unsigned long) new_rate);
427 /* Called from main context */
428 static void time_callback(pa_mainloop_api *a, pa_time_event *e, const struct timeval *t, void *userdata) {
429 struct userdata *u = userdata;
433 pa_assert(u->time_event == e);
435 /* Restart timer right away */
436 pa_core_rttime_restart(u->core, u->time_event, pa_rtclock_now() + u->adjust_time);
438 /* Get sink and source latency snapshot */
439 pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT, NULL, 0, NULL);
440 pa_asyncmsgq_send(u->source_output->source->asyncmsgq, PA_MSGOBJECT(u->source_output), SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT, NULL, 0, NULL);
445 /* Called from main context
446 * When source or sink changes, give it a third of a second to settle down, then call adjust_rates for the first time */
447 static void enable_adjust_timer(struct userdata *u, bool enable) {
452 u->core->mainloop->time_free(u->time_event);
454 u->time_event = pa_core_rttime_new(u->core, pa_rtclock_now() + 333 * PA_USEC_PER_MSEC, time_callback, u);
459 u->core->mainloop->time_free(u->time_event);
460 u->time_event = NULL;
464 /* Called from main context */
465 static void update_adjust_timer(struct userdata *u) {
467 if ((u->sink_input && u->sink_input->state == PA_SINK_INPUT_CORKED) ||
468 (u->source_output && u->source_output->state == PA_SOURCE_OUTPUT_CORKED))
470 if (u->sink_input->state == PA_SINK_INPUT_CORKED || u->source_output->state == PA_SOURCE_OUTPUT_CORKED)
472 enable_adjust_timer(u, false);
474 enable_adjust_timer(u, true);
477 /* Called from main thread
478 * Calculates minimum and maximum possible latency for source and sink */
479 static void update_latency_boundaries(struct userdata *u, pa_source *source, pa_sink *sink) {
483 /* Source latencies */
484 u->fixed_alsa_source = false;
485 if (source->flags & PA_SOURCE_DYNAMIC_LATENCY)
486 pa_source_get_latency_range(source, &u->min_source_latency, &u->max_source_latency);
488 u->min_source_latency = pa_source_get_fixed_latency(source);
489 u->max_source_latency = u->min_source_latency;
490 if ((s = pa_proplist_gets(source->proplist, PA_PROP_DEVICE_API))) {
492 if (pa_streq(s, "alsa") || pa_streq(s, "tizen"))
494 if (pa_streq(s, "alsa"))
496 u->fixed_alsa_source = true;
500 u->source_latency_offset = source->port_latency_offset;
502 /* Latencies below 2.5 ms cause problems, limit source latency if possible */
503 if (u->max_source_latency >= MIN_DEVICE_LATENCY)
504 u->min_source_latency = PA_MAX(u->min_source_latency, MIN_DEVICE_LATENCY);
506 u->min_source_latency = u->max_source_latency;
511 if (sink->flags & PA_SINK_DYNAMIC_LATENCY)
512 pa_sink_get_latency_range(sink, &u->min_sink_latency, &u->max_sink_latency);
514 u->min_sink_latency = pa_sink_get_fixed_latency(sink);
515 u->max_sink_latency = u->min_sink_latency;
518 u->sink_latency_offset = sink->port_latency_offset;
520 /* Latencies below 2.5 ms cause problems, limit sink latency if possible */
521 if (u->max_sink_latency >= MIN_DEVICE_LATENCY)
522 u->min_sink_latency = PA_MAX(u->min_sink_latency, MIN_DEVICE_LATENCY);
524 u->min_sink_latency = u->max_sink_latency;
527 update_minimum_latency(u, sink, true);
530 /* Called from output context
531 * Sets the memblockq to the configured latency corrected by latency_offset_usec */
532 static void memblockq_adjust(struct userdata *u, int64_t latency_offset_usec, bool allow_push) {
533 size_t current_memblockq_length, requested_memblockq_length, buffer_correction;
534 int64_t requested_buffer_latency;
536 pa_usec_t final_latency;
538 pa_usec_t final_latency, requested_sink_latency;
541 final_latency = PA_MAX(u->latency, u->output_thread_info.minimum_latency);
544 /* FIXME : rollback upstream code due to bluetooth sync issue */
545 requested_buffer_latency = PA_CLIP_SUB(final_latency, (uint64_t)latency_offset_usec);
547 /* If source or sink have some large negative latency offset, we might want to
548 * hold more than final_latency in the memblockq */
549 requested_buffer_latency = (int64_t)final_latency - latency_offset_usec;
551 /* Keep at least one sink latency in the queue to make sure that the sink
552 * never underruns initially */
553 requested_sink_latency = pa_sink_get_requested_latency_within_thread(u->sink_input->sink);
554 if (requested_buffer_latency < (int64_t)requested_sink_latency)
555 requested_buffer_latency = requested_sink_latency;
558 requested_memblockq_length = pa_usec_to_bytes(requested_buffer_latency, &u->sink_input->sample_spec);
559 current_memblockq_length = pa_memblockq_get_length(u->memblockq);
561 if (current_memblockq_length > requested_memblockq_length) {
562 /* Drop audio from queue */
563 buffer_correction = current_memblockq_length - requested_memblockq_length;
564 pa_log_info("Dropping %" PRIu64 " usec of audio from queue", pa_bytes_to_usec(buffer_correction, &u->sink_input->sample_spec));
565 pa_memblockq_drop(u->memblockq, buffer_correction);
567 } else if (current_memblockq_length < requested_memblockq_length && allow_push) {
568 /* Add silence to queue */
569 buffer_correction = requested_memblockq_length - current_memblockq_length;
570 pa_log_info("Adding %" PRIu64 " usec of silence to queue", pa_bytes_to_usec(buffer_correction, &u->sink_input->sample_spec));
571 pa_memblockq_seek(u->memblockq, (int64_t)buffer_correction, PA_SEEK_RELATIVE, true);
575 /* Called from input thread context */
576 static void source_output_push_cb(pa_source_output *o, const pa_memchunk *chunk) {
579 int64_t current_source_latency;
581 pa_source_output_assert_ref(o);
582 pa_source_output_assert_io_context(o);
583 pa_assert_se(u = o->userdata);
585 /* Send current source latency and timestamp with the message */
586 push_time = pa_rtclock_now();
587 current_source_latency = pa_source_get_latency_within_thread(u->source_output->source, true);
589 pa_asyncmsgq_post(u->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_POST, PA_INT_TO_PTR(current_source_latency), push_time, chunk, NULL);
590 u->send_counter += (int64_t) chunk->length;
593 /* Called from input thread context */
594 static void source_output_process_rewind_cb(pa_source_output *o, size_t nbytes) {
597 pa_source_output_assert_ref(o);
598 pa_source_output_assert_io_context(o);
599 pa_assert_se(u = o->userdata);
601 pa_asyncmsgq_post(u->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_REWIND, NULL, (int64_t) nbytes, NULL, NULL);
602 u->send_counter -= (int64_t) nbytes;
605 /* Called from input thread context */
606 static int source_output_process_msg_cb(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
607 struct userdata *u = PA_SOURCE_OUTPUT(obj)->userdata;
611 case SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT: {
614 length = pa_memblockq_get_length(u->source_output->thread_info.delay_memblockq);
616 u->latency_snapshot.send_counter = u->send_counter;
617 /* Add content of delay memblockq to the source latency */
618 u->latency_snapshot.source_latency = pa_source_get_latency_within_thread(u->source_output->source, true) +
619 pa_bytes_to_usec(length, &u->source_output->source->sample_spec);
620 u->latency_snapshot.source_timestamp = pa_rtclock_now();
626 return pa_source_output_process_msg(obj, code, data, offset, chunk);
629 /* Called from main thread.
630 * Get current effective latency of the source. If the source is in use with
631 * smaller latency than the configured latency, it will continue running with
632 * the smaller value when the source output is switched to the source. */
633 static void update_effective_source_latency(struct userdata *u, pa_source *source, pa_sink *sink) {
634 pa_usec_t effective_source_latency;
636 effective_source_latency = u->configured_source_latency;
639 effective_source_latency = pa_source_get_requested_latency(source);
640 if (effective_source_latency == 0 || effective_source_latency > u->configured_source_latency)
641 effective_source_latency = u->configured_source_latency;
644 /* If the sink is valid, send a message to the output thread, else set the variable directly */
646 pa_asyncmsgq_send(sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_SET_EFFECTIVE_SOURCE_LATENCY, NULL, (int64_t)effective_source_latency, NULL);
648 u->output_thread_info.effective_source_latency = effective_source_latency;
651 /* Called from main thread.
652 * Set source output latency to one third of the overall latency if possible.
653 * The choice of one third is rather arbitrary somewhere between the minimum
654 * possible latency which would cause a lot of CPU load and half the configured
655 * latency which would quickly lead to underruns */
656 static void set_source_output_latency(struct userdata *u, pa_source *source) {
657 pa_usec_t latency, requested_latency;
659 requested_latency = u->latency / 3;
661 /* Normally we try to configure sink and source latency equally. If the
662 * sink latency cannot match the requested source latency try to set the
663 * source latency to a smaller value to avoid underruns */
664 if (u->min_sink_latency > requested_latency) {
665 latency = PA_MAX(u->latency, u->minimum_latency);
666 requested_latency = (latency - u->min_sink_latency) / 2;
669 latency = PA_CLAMP(requested_latency , u->min_source_latency, u->max_source_latency);
670 u->configured_source_latency = pa_source_output_set_requested_latency(u->source_output, latency);
671 if (u->configured_source_latency != requested_latency)
672 pa_log_warn("Cannot set requested source latency of %0.2f ms, adjusting to %0.2f ms", (double)requested_latency / PA_USEC_PER_MSEC, (double)u->configured_source_latency / PA_USEC_PER_MSEC);
675 /* Called from input thread context */
676 static void source_output_attach_cb(pa_source_output *o) {
679 pa_source_output_assert_ref(o);
680 pa_source_output_assert_io_context(o);
681 pa_assert_se(u = o->userdata);
683 u->rtpoll_item_write = pa_rtpoll_item_new_asyncmsgq_write(
684 o->source->thread_info.rtpoll,
689 /* Called from input thread context */
690 static void source_output_detach_cb(pa_source_output *o) {
693 pa_source_output_assert_ref(o);
694 pa_source_output_assert_io_context(o);
695 pa_assert_se(u = o->userdata);
697 if (u->rtpoll_item_write) {
698 pa_rtpoll_item_free(u->rtpoll_item_write);
699 u->rtpoll_item_write = NULL;
703 /* Called from main thread */
704 static void source_output_kill_cb(pa_source_output *o) {
707 pa_source_output_assert_ref(o);
708 pa_assert_ctl_context();
709 pa_assert_se(u = o->userdata);
712 pa_module_unload_request(u->module, true);
715 /* Called from main thread */
716 static bool source_output_may_move_to_cb(pa_source_output *o, pa_source *dest) {
719 pa_source_output_assert_ref(o);
720 pa_assert_ctl_context();
721 pa_assert_se(u = o->userdata);
723 if (!u->sink_input || !u->sink_input->sink)
726 return dest != u->sink_input->sink->monitor_source;
729 /* Called from main thread */
730 static void source_output_moving_cb(pa_source_output *o, pa_source *dest) {
732 char *input_description;
738 pa_source_output_assert_ref(o);
739 pa_assert_ctl_context();
740 pa_assert_se(u = o->userdata);
743 if (!u->sink_input) {
744 pa_log_warn("sink_input is already null now, do nothing");
749 input_description = pa_sprintf_malloc("Loopback of %s",
750 pa_strnull(pa_proplist_gets(dest->proplist, PA_PROP_DEVICE_DESCRIPTION)));
751 pa_sink_input_set_property(u->sink_input, PA_PROP_MEDIA_NAME, input_description);
752 pa_xfree(input_description);
754 if ((n = pa_proplist_gets(dest->proplist, PA_PROP_DEVICE_ICON_NAME)))
755 pa_sink_input_set_property(u->sink_input, PA_PROP_DEVICE_ICON_NAME, n);
757 /* Set latency and calculate latency limits */
758 u->underrun_latency_limit = 0;
759 update_latency_boundaries(u, dest, u->sink_input->sink);
760 set_source_output_latency(u, dest);
761 update_effective_source_latency(u, dest, u->sink_input->sink);
763 /* Uncork the sink input unless the destination is suspended for other
764 * reasons than idle. */
765 if (dest->state == PA_SOURCE_SUSPENDED)
766 pa_sink_input_cork(u->sink_input, (dest->suspend_cause != PA_SUSPEND_IDLE));
768 pa_sink_input_cork(u->sink_input, false);
770 update_adjust_timer(u);
773 u->iteration_counter = 0;
774 u->underrun_counter = 0;
776 u->source_sink_changed = true;
778 /* Send a mesage to the output thread that the source has changed.
779 * If the sink is invalid here during a profile switching situation
780 * we can safely set push_called to false directly. */
781 if (u->sink_input->sink)
782 pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_SOURCE_CHANGED, NULL, 0, NULL);
784 u->output_thread_info.push_called = false;
786 /* The sampling rate may be far away from the default rate if we are still
787 * recovering from a previous source or sink change, so reset rate to
788 * default before moving the source. */
789 pa_sink_input_set_rate(u->sink_input, u->source_output->sample_spec.rate);
792 /* Called from main thread */
793 static void source_output_suspend_cb(pa_source_output *o, pa_source_state_t old_state, pa_suspend_cause_t old_suspend_cause) {
797 pa_source_output_assert_ref(o);
798 pa_assert_ctl_context();
799 pa_assert_se(u = o->userdata);
801 /* State has not changed, nothing to do */
802 if (old_state == o->source->state)
805 suspended = (o->source->state == PA_SOURCE_SUSPENDED);
807 /* If the source has been suspended, we need to handle this like
808 * a source change when the source is resumed */
811 if (u->sink_input && u->sink_input->sink)
813 if (u->sink_input->sink)
815 pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_SOURCE_CHANGED, NULL, 0, NULL);
817 u->output_thread_info.push_called = false;
820 /* Get effective source latency on unsuspend */
824 update_effective_source_latency(u, u->source_output->source, u->sink_input->sink);
829 pa_sink_input_cork(u->sink_input, suspended);
831 update_adjust_timer(u);
834 /* Called from input thread context */
835 static void update_source_latency_range_cb(pa_source_output *i) {
838 pa_source_output_assert_ref(i);
839 pa_source_output_assert_io_context(i);
840 pa_assert_se(u = i->userdata);
842 /* Source latency may have changed */
843 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), LOOPBACK_MESSAGE_SOURCE_LATENCY_RANGE_CHANGED, NULL, 0, NULL, NULL);
846 /* Called from output thread context */
847 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
850 pa_sink_input_assert_ref(i);
851 pa_sink_input_assert_io_context(i);
852 pa_assert_se(u = i->userdata);
855 /* It seems necessary to handle outstanding push messages here, though it is not clear
856 * why. Removing this part leads to underruns when low latencies are configured. */
857 u->output_thread_info.in_pop = true;
858 while (pa_asyncmsgq_process_one(u->asyncmsgq) > 0)
860 u->output_thread_info.in_pop = false;
862 /* While pop has not been called, latency adjustments in SINK_INPUT_MESSAGE_POST are
863 * enabled. Disable them on second pop and enable the final adjustment during the
864 * next push. The adjustment must be done on the next push, because there is no way
865 * to retrieve the source latency here. We are waiting for the second pop, because
866 * the first pop may be called before the sink is actually started. */
867 if (!u->output_thread_info.pop_called && u->output_thread_info.first_pop_done) {
868 u->output_thread_info.pop_adjust = true;
869 u->output_thread_info.pop_called = true;
871 u->output_thread_info.first_pop_done = true;
873 if (pa_memblockq_peek(u->memblockq, chunk) < 0) {
874 pa_log_info("Could not peek into queue");
878 chunk->length = PA_MIN(chunk->length, nbytes);
879 pa_memblockq_drop(u->memblockq, chunk->length);
881 /* Adjust the memblockq to ensure that there is
882 * enough data in the queue to avoid underruns. */
883 if (!u->output_thread_info.push_called)
884 memblockq_adjust(u, 0, true);
889 /* Called from output thread context */
890 static void sink_input_process_rewind_cb(pa_sink_input *i, size_t nbytes) {
893 pa_sink_input_assert_ref(i);
894 pa_sink_input_assert_io_context(i);
895 pa_assert_se(u = i->userdata);
897 pa_memblockq_rewind(u->memblockq, nbytes);
900 /* Called from output thread context */
901 static int sink_input_process_msg_cb(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
902 struct userdata *u = PA_SINK_INPUT(obj)->userdata;
904 pa_sink_input_assert_io_context(u->sink_input);
908 case PA_SINK_INPUT_MESSAGE_GET_LATENCY: {
911 *r = pa_bytes_to_usec(pa_memblockq_get_length(u->memblockq), &u->sink_input->sample_spec);
913 /* Fall through, the default handler will add in the extra
914 * latency added by the resampler */
918 case SINK_INPUT_MESSAGE_POST:
920 pa_memblockq_push_align(u->memblockq, chunk);
922 /* If push has not been called yet, latency adjustments in sink_input_pop_cb()
923 * are enabled. Disable them on first push and correct the memblockq. If pop
924 * has not been called yet, wait until the pop_cb() requests the adjustment */
925 if (u->output_thread_info.pop_called && (!u->output_thread_info.push_called || u->output_thread_info.pop_adjust)) {
928 /* This is the source latency at the time push was called */
929 time_delta = PA_PTR_TO_INT(data);
930 /* Add the time between push and post */
931 time_delta += pa_rtclock_now() - (pa_usec_t) offset;
932 /* Add the sink latency */
933 time_delta += pa_sink_get_latency_within_thread(u->sink_input->sink, true);
935 /* The source latency report includes the audio in the chunk,
936 * but since we already pushed the chunk to the memblockq, we need
937 * to subtract the chunk size from the source latency so that it
938 * won't be counted towards both the memblockq latency and the
941 * Sometimes the alsa source reports way too low latency (might
942 * be a bug in the alsa source code). This seems to happen when
943 * there's an overrun. As an attempt to detect overruns, we
944 * check if the chunk size is larger than the configured source
945 * latency. If so, we assume that the source should have pushed
946 * a chunk whose size equals the configured latency, so we
947 * modify time_delta only by that amount, which makes
948 * memblockq_adjust() drop more data than it would otherwise.
949 * This seems to work quite well, but it's possible that the
950 * next push also contains too much data, and in that case the
951 * resulting latency will be wrong. */
952 if (pa_bytes_to_usec(chunk->length, &u->sink_input->sample_spec) > u->output_thread_info.effective_source_latency)
953 time_delta -= (int64_t)u->output_thread_info.effective_source_latency;
955 time_delta -= (int64_t)pa_bytes_to_usec(chunk->length, &u->sink_input->sample_spec);
957 /* FIXME: We allow pushing silence here to fix up the latency. This
958 * might lead to a gap in the stream */
959 memblockq_adjust(u, time_delta, true);
961 u->output_thread_info.pop_adjust = false;
962 u->output_thread_info.push_called = true;
965 /* If pop has not been called yet, make sure the latency does not grow too much.
966 * Don't push any silence here, because we already have new data in the queue */
967 if (!u->output_thread_info.pop_called)
968 memblockq_adjust(u, 0, false);
970 /* Is this the end of an underrun? Then let's start things
972 if (u->sink_input->sink->thread_info.state != PA_SINK_SUSPENDED &&
973 u->sink_input->thread_info.underrun_for > 0 &&
974 pa_memblockq_is_readable(u->memblockq)) {
976 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), LOOPBACK_MESSAGE_UNDERRUN, NULL, 0, NULL, NULL);
977 /* If called from within the pop callback skip the rewind */
978 if (!u->output_thread_info.in_pop) {
979 pa_log_debug("Requesting rewind due to end of underrun.");
980 pa_sink_input_request_rewind(u->sink_input,
981 (size_t) (u->sink_input->thread_info.underrun_for == (size_t) -1 ? 0 : u->sink_input->thread_info.underrun_for),
986 u->output_thread_info.recv_counter += (int64_t) chunk->length;
990 case SINK_INPUT_MESSAGE_REWIND:
992 /* Do not try to rewind if no data was pushed yet */
993 if (u->output_thread_info.push_called)
994 pa_memblockq_seek(u->memblockq, -offset, PA_SEEK_RELATIVE, true);
996 u->output_thread_info.recv_counter -= offset;
1000 case SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT: {
1003 length = pa_memblockq_get_length(u->sink_input->thread_info.render_memblockq);
1005 u->latency_snapshot.recv_counter = u->output_thread_info.recv_counter;
1006 u->latency_snapshot.loopback_memblockq_length = pa_memblockq_get_length(u->memblockq);
1007 /* Add content of render memblockq to sink latency */
1008 u->latency_snapshot.sink_latency = pa_sink_get_latency_within_thread(u->sink_input->sink, true) +
1009 pa_bytes_to_usec(length, &u->sink_input->sink->sample_spec);
1010 u->latency_snapshot.sink_timestamp = pa_rtclock_now();
1015 case SINK_INPUT_MESSAGE_SOURCE_CHANGED:
1017 u->output_thread_info.push_called = false;
1021 case SINK_INPUT_MESSAGE_SET_EFFECTIVE_SOURCE_LATENCY:
1023 u->output_thread_info.effective_source_latency = (pa_usec_t)offset;
1027 case SINK_INPUT_MESSAGE_UPDATE_MIN_LATENCY:
1029 u->output_thread_info.minimum_latency = (pa_usec_t)offset;
1033 case SINK_INPUT_MESSAGE_FAST_ADJUST:
1035 memblockq_adjust(u, offset, true);
1040 return pa_sink_input_process_msg(obj, code, data, offset, chunk);
1042 /* Called from main thread.
1043 * Set sink input latency to one third of the overall latency if possible.
1044 * The choice of one third is rather arbitrary somewhere between the minimum
1045 * possible latency which would cause a lot of CPU load and half the configured
1046 * latency which would quickly lead to underruns. */
1047 static void set_sink_input_latency(struct userdata *u, pa_sink *sink) {
1048 pa_usec_t latency, requested_latency;
1050 requested_latency = u->latency / 3;
1052 /* Normally we try to configure sink and source latency equally. If the
1053 * source latency cannot match the requested sink latency try to set the
1054 * sink latency to a smaller value to avoid underruns */
1055 if (u->min_source_latency > requested_latency) {
1056 latency = PA_MAX(u->latency, u->minimum_latency);
1057 requested_latency = (latency - u->min_source_latency) / 2;
1058 /* In the case of a fixed alsa source, u->minimum_latency is calculated from
1059 * the default fragment size while u->min_source_latency is the reported minimum
1060 * of the source latency (nr_of_fragments * fragment_size). This can lead to a
1061 * situation where u->minimum_latency < u->min_source_latency. We only fall
1062 * back to use the fragment size instead of min_source_latency if the calculation
1063 * above does not deliver a usable result. */
1064 if (u->fixed_alsa_source && u->min_source_latency >= latency)
1065 requested_latency = (latency - u->core->default_fragment_size_msec * PA_USEC_PER_MSEC) / 2;
1068 latency = PA_CLAMP(requested_latency , u->min_sink_latency, u->max_sink_latency);
1069 u->configured_sink_latency = pa_sink_input_set_requested_latency(u->sink_input, latency);
1070 if (u->configured_sink_latency != requested_latency)
1071 pa_log_warn("Cannot set requested sink latency of %0.2f ms, adjusting to %0.2f ms", (double)requested_latency / PA_USEC_PER_MSEC, (double)u->configured_sink_latency / PA_USEC_PER_MSEC);
1074 /* Called from output thread context */
1075 static void sink_input_attach_cb(pa_sink_input *i) {
1078 pa_sink_input_assert_ref(i);
1079 pa_sink_input_assert_io_context(i);
1080 pa_assert_se(u = i->userdata);
1082 u->rtpoll_item_read = pa_rtpoll_item_new_asyncmsgq_read(
1083 i->sink->thread_info.rtpoll,
1087 pa_memblockq_set_prebuf(u->memblockq, pa_sink_input_get_max_request(i)*2);
1088 pa_memblockq_set_maxrewind(u->memblockq, pa_sink_input_get_max_rewind(i));
1091 /* Called from output thread context */
1092 static void sink_input_detach_cb(pa_sink_input *i) {
1095 pa_sink_input_assert_ref(i);
1096 pa_sink_input_assert_io_context(i);
1097 pa_assert_se(u = i->userdata);
1099 if (u->rtpoll_item_read) {
1100 pa_rtpoll_item_free(u->rtpoll_item_read);
1101 u->rtpoll_item_read = NULL;
1105 /* Called from output thread context */
1106 static void sink_input_update_max_rewind_cb(pa_sink_input *i, size_t nbytes) {
1109 pa_sink_input_assert_ref(i);
1110 pa_sink_input_assert_io_context(i);
1111 pa_assert_se(u = i->userdata);
1113 pa_memblockq_set_maxrewind(u->memblockq, nbytes);
1116 /* Called from output thread context */
1117 static void sink_input_update_max_request_cb(pa_sink_input *i, size_t nbytes) {
1120 pa_sink_input_assert_ref(i);
1121 pa_sink_input_assert_io_context(i);
1122 pa_assert_se(u = i->userdata);
1124 pa_memblockq_set_prebuf(u->memblockq, nbytes*2);
1125 pa_log_info("Max request changed");
1128 /* Called from main thread */
1129 static void sink_input_kill_cb(pa_sink_input *i) {
1132 pa_sink_input_assert_ref(i);
1133 pa_assert_ctl_context();
1134 pa_assert_se(u = i->userdata);
1137 pa_module_unload_request(u->module, true);
1140 /* Called from the output thread context */
1141 static void sink_input_state_change_cb(pa_sink_input *i, pa_sink_input_state_t state) {
1144 pa_sink_input_assert_ref(i);
1145 pa_assert_se(u = i->userdata);
1147 if (state == PA_SINK_INPUT_UNLINKED)
1148 pa_asyncmsgq_flush(u->asyncmsgq, false);
1151 /* Called from main thread */
1152 static void sink_input_moving_cb(pa_sink_input *i, pa_sink *dest) {
1154 char *output_description;
1160 pa_sink_input_assert_ref(i);
1161 pa_assert_ctl_context();
1162 pa_assert_se(u = i->userdata);
1165 if (!u->source_output) {
1166 pa_log_warn("source_output is already null now, do nothing");
1171 output_description = pa_sprintf_malloc("Loopback to %s",
1172 pa_strnull(pa_proplist_gets(dest->proplist, PA_PROP_DEVICE_DESCRIPTION)));
1173 pa_source_output_set_property(u->source_output, PA_PROP_MEDIA_NAME, output_description);
1174 pa_xfree(output_description);
1176 if ((n = pa_proplist_gets(dest->proplist, PA_PROP_DEVICE_ICON_NAME)))
1177 pa_source_output_set_property(u->source_output, PA_PROP_MEDIA_ICON_NAME, n);
1179 /* Set latency and calculate latency limits */
1180 u->underrun_latency_limit = 0;
1181 update_latency_boundaries(u, NULL, dest);
1182 set_sink_input_latency(u, dest);
1183 update_effective_source_latency(u, u->source_output->source, dest);
1185 /* Uncork the source output unless the destination is suspended for other
1186 * reasons than idle */
1187 if (dest->state == PA_SINK_SUSPENDED)
1188 pa_source_output_cork(u->source_output, (dest->suspend_cause != PA_SUSPEND_IDLE));
1190 pa_source_output_cork(u->source_output, false);
1192 update_adjust_timer(u);
1194 /* Reset counters */
1195 u->iteration_counter = 0;
1196 u->underrun_counter = 0;
1198 u->source_sink_changed = true;
1200 u->output_thread_info.pop_called = false;
1201 u->output_thread_info.first_pop_done = false;
1203 /* Sample rate may be far away from the default rate if we are still
1204 * recovering from a previous source or sink change, so reset rate to
1205 * default before moving the sink. */
1206 pa_sink_input_set_rate(u->sink_input, u->source_output->sample_spec.rate);
1209 /* Called from main thread */
1210 static bool sink_input_may_move_to_cb(pa_sink_input *i, pa_sink *dest) {
1213 pa_sink_input_assert_ref(i);
1214 pa_assert_ctl_context();
1215 pa_assert_se(u = i->userdata);
1217 if (!u->source_output || !u->source_output->source)
1220 return dest != u->source_output->source->monitor_of;
1223 /* Called from main thread */
1224 static void sink_input_suspend_cb(pa_sink_input *i, pa_sink_state_t old_state, pa_suspend_cause_t old_suspend_cause) {
1228 pa_sink_input_assert_ref(i);
1229 pa_assert_ctl_context();
1230 pa_assert_se(u = i->userdata);
1232 /* State has not changed, nothing to do */
1233 if (old_state == i->sink->state)
1236 suspended = (i->sink->state == PA_SINK_SUSPENDED);
1238 /* If the sink has been suspended, we need to handle this like
1239 * a sink change when the sink is resumed. Because the sink
1240 * is suspended, we can set the variables directly. */
1242 u->output_thread_info.pop_called = false;
1243 u->output_thread_info.first_pop_done = false;
1246 /* Set effective source latency on unsuspend */
1248 if (u->source_output)
1250 update_effective_source_latency(u, u->source_output->source, u->sink_input->sink);
1253 if (u->source_output)
1255 pa_source_output_cork(u->source_output, suspended);
1257 update_adjust_timer(u);
1260 /* Called from output thread context */
1261 static void update_sink_latency_range_cb(pa_sink_input *i) {
1264 pa_sink_input_assert_ref(i);
1265 pa_sink_input_assert_io_context(i);
1266 pa_assert_se(u = i->userdata);
1268 /* Sink latency may have changed */
1269 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), LOOPBACK_MESSAGE_SINK_LATENCY_RANGE_CHANGED, NULL, 0, NULL, NULL);
1272 /* Called from main context */
1273 static int loopback_process_msg_cb(pa_msgobject *o, int code, void *userdata, int64_t offset, pa_memchunk *chunk) {
1274 struct loopback_msg *msg;
1276 pa_usec_t current_latency;
1279 pa_assert_ctl_context();
1281 msg = LOOPBACK_MSG(o);
1283 /* If messages are processed after a module unload request, they
1284 * must be ignored. */
1288 pa_assert_se(u = msg->userdata);
1292 case LOOPBACK_MESSAGE_SOURCE_LATENCY_RANGE_CHANGED:
1294 update_effective_source_latency(u, u->source_output->source, u->sink_input->sink);
1295 current_latency = pa_source_get_requested_latency(u->source_output->source);
1296 if (current_latency > u->configured_source_latency) {
1297 /* The minimum latency has changed to a value larger than the configured latency, so
1298 * the source latency has been increased. The case that the minimum latency changes
1299 * back to a smaller value is not handled because this never happens with the current
1300 * source implementations. */
1301 pa_log_warn("Source minimum latency increased to %0.2f ms", (double)current_latency / PA_USEC_PER_MSEC);
1302 u->configured_source_latency = current_latency;
1303 update_latency_boundaries(u, u->source_output->source, u->sink_input->sink);
1304 /* We re-start counting when the latency has changed */
1305 u->iteration_counter = 0;
1306 u->underrun_counter = 0;
1311 case LOOPBACK_MESSAGE_SINK_LATENCY_RANGE_CHANGED:
1313 current_latency = pa_sink_get_requested_latency(u->sink_input->sink);
1314 if (current_latency > u->configured_sink_latency) {
1315 /* The minimum latency has changed to a value larger than the configured latency, so
1316 * the sink latency has been increased. The case that the minimum latency changes back
1317 * to a smaller value is not handled because this never happens with the current sink
1318 * implementations. */
1319 pa_log_warn("Sink minimum latency increased to %0.2f ms", (double)current_latency / PA_USEC_PER_MSEC);
1320 u->configured_sink_latency = current_latency;
1321 update_latency_boundaries(u, u->source_output->source, u->sink_input->sink);
1322 /* We re-start counting when the latency has changed */
1323 u->iteration_counter = 0;
1324 u->underrun_counter = 0;
1329 case LOOPBACK_MESSAGE_UNDERRUN:
1331 u->underrun_counter++;
1332 pa_log_debug("Underrun detected, counter incremented to %u", u->underrun_counter);
1341 static pa_hook_result_t sink_port_latency_offset_changed_cb(pa_core *core, pa_sink *sink, struct userdata *u) {
1343 if (sink != u->sink_input->sink)
1346 u->sink_latency_offset = sink->port_latency_offset;
1347 update_minimum_latency(u, sink, true);
1352 static pa_hook_result_t source_port_latency_offset_changed_cb(pa_core *core, pa_source *source, struct userdata *u) {
1354 if (source != u->source_output->source)
1357 u->source_latency_offset = source->port_latency_offset;
1358 update_minimum_latency(u, u->sink_input->sink, true);
1363 int pa__init(pa_module *m) {
1364 pa_modargs *ma = NULL;
1366 pa_sink *sink = NULL;
1367 pa_sink_input_new_data sink_input_data;
1368 bool sink_dont_move;
1369 pa_source *source = NULL;
1370 pa_source_output_new_data source_output_data;
1371 bool source_dont_move;
1372 uint32_t latency_msec;
1373 uint32_t max_latency_msec;
1374 uint32_t fast_adjust_threshold;
1377 bool format_set = false;
1378 bool rate_set = false;
1379 bool channels_set = false;
1380 pa_memchunk silence;
1381 uint32_t adjust_time_sec;
1387 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1388 pa_log("Failed to parse module arguments");
1392 n = pa_modargs_get_value(ma, "source", NULL);
1393 if (n && !(source = pa_namereg_get(m->core, n, PA_NAMEREG_SOURCE))) {
1394 pa_log("No such source.");
1398 n = pa_modargs_get_value(ma, "sink", NULL);
1399 if (n && !(sink = pa_namereg_get(m->core, n, PA_NAMEREG_SINK))) {
1400 pa_log("No such sink.");
1404 if (pa_modargs_get_value_boolean(ma, "remix", &remix) < 0) {
1405 pa_log("Invalid boolean remix parameter");
1410 ss = source->sample_spec;
1411 map = source->channel_map;
1414 channels_set = true;
1416 ss = sink->sample_spec;
1417 map = sink->channel_map;
1420 channels_set = true;
1422 /* FIXME: Dummy stream format, needed because pa_sink_input_new()
1423 * requires valid sample spec and channel map even when all the FIX_*
1424 * stream flags are specified. pa_sink_input_new() should be changed
1425 * to ignore the sample spec and channel map when the FIX_* flags are
1427 ss.format = PA_SAMPLE_U8;
1431 map.map[0] = PA_CHANNEL_POSITION_MONO;
1434 if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
1435 pa_log("Invalid sample format specification or channel map");
1439 if (ss.rate < 4000 || ss.rate > PA_RATE_MAX) {
1440 pa_log("Invalid rate specification, valid range is 4000 Hz to %i Hz", PA_RATE_MAX);
1444 if (pa_modargs_get_value(ma, "format", NULL))
1447 if (pa_modargs_get_value(ma, "rate", NULL))
1450 if (pa_modargs_get_value(ma, "channels", NULL) || pa_modargs_get_value(ma, "channel_map", NULL))
1451 channels_set = true;
1453 latency_msec = DEFAULT_LATENCY_MSEC;
1454 if (pa_modargs_get_value_u32(ma, "latency_msec", &latency_msec) < 0 || latency_msec < 1 || latency_msec > 30000) {
1455 pa_log("Invalid latency specification");
1459 fast_adjust_threshold = 0;
1460 if (pa_modargs_get_value_u32(ma, "fast_adjust_threshold_msec", &fast_adjust_threshold) < 0 || (fast_adjust_threshold != 0 && fast_adjust_threshold < 100)) {
1461 pa_log("Invalid fast adjust threshold specification");
1465 max_latency_msec = 0;
1466 if (pa_modargs_get_value_u32(ma, "max_latency_msec", &max_latency_msec) < 0) {
1467 pa_log("Invalid maximum latency specification");
1471 if (max_latency_msec > 0 && max_latency_msec < latency_msec) {
1472 pa_log_warn("Configured maximum latency is smaller than latency, using latency instead");
1473 max_latency_msec = latency_msec;
1476 m->userdata = u = pa_xnew0(struct userdata, 1);
1479 u->latency = (pa_usec_t) latency_msec * PA_USEC_PER_MSEC;
1480 u->max_latency = (pa_usec_t) max_latency_msec * PA_USEC_PER_MSEC;
1481 u->output_thread_info.pop_called = false;
1482 u->output_thread_info.pop_adjust = false;
1483 u->output_thread_info.push_called = false;
1484 u->iteration_counter = 0;
1485 u->underrun_counter = 0;
1486 u->underrun_latency_limit = 0;
1487 u->source_sink_changed = true;
1488 u->real_adjust_time_sum = 0;
1489 u->adjust_counter = 0;
1490 u->fast_adjust_threshold = fast_adjust_threshold * PA_USEC_PER_MSEC;
1492 adjust_time_sec = DEFAULT_ADJUST_TIME_USEC / PA_USEC_PER_SEC;
1493 if (pa_modargs_get_value_u32(ma, "adjust_time", &adjust_time_sec) < 0) {
1494 pa_log("Failed to parse adjust_time value");
1498 if (adjust_time_sec != DEFAULT_ADJUST_TIME_USEC / PA_USEC_PER_SEC)
1499 u->adjust_time = adjust_time_sec * PA_USEC_PER_SEC;
1501 u->adjust_time = DEFAULT_ADJUST_TIME_USEC;
1503 u->real_adjust_time = u->adjust_time;
1505 pa_source_output_new_data_init(&source_output_data);
1506 source_output_data.driver = __FILE__;
1507 source_output_data.module = m;
1509 pa_source_output_new_data_set_source(&source_output_data, source, false, true);
1511 if (pa_modargs_get_proplist(ma, "source_output_properties", source_output_data.proplist, PA_UPDATE_REPLACE) < 0) {
1512 pa_log("Failed to parse the source_output_properties value.");
1513 pa_source_output_new_data_done(&source_output_data);
1517 if (!pa_proplist_contains(source_output_data.proplist, PA_PROP_MEDIA_ROLE))
1518 pa_proplist_sets(source_output_data.proplist, PA_PROP_MEDIA_ROLE, "abstract");
1520 pa_source_output_new_data_set_sample_spec(&source_output_data, &ss);
1521 pa_source_output_new_data_set_channel_map(&source_output_data, &map);
1522 source_output_data.flags = PA_SOURCE_OUTPUT_START_CORKED;
1525 source_output_data.flags |= PA_SOURCE_OUTPUT_NO_REMIX;
1528 source_output_data.flags |= PA_SOURCE_OUTPUT_FIX_FORMAT;
1531 source_output_data.flags |= PA_SOURCE_OUTPUT_FIX_RATE;
1534 source_output_data.flags |= PA_SOURCE_OUTPUT_FIX_CHANNELS;
1536 source_dont_move = false;
1537 if (pa_modargs_get_value_boolean(ma, "source_dont_move", &source_dont_move) < 0) {
1538 pa_log("source_dont_move= expects a boolean argument.");
1542 if (source_dont_move)
1543 source_output_data.flags |= PA_SOURCE_OUTPUT_DONT_MOVE;
1545 pa_source_output_new(&u->source_output, m->core, &source_output_data);
1546 pa_source_output_new_data_done(&source_output_data);
1548 if (!u->source_output)
1551 u->source_output->parent.process_msg = source_output_process_msg_cb;
1552 u->source_output->push = source_output_push_cb;
1553 u->source_output->process_rewind = source_output_process_rewind_cb;
1554 u->source_output->kill = source_output_kill_cb;
1555 u->source_output->attach = source_output_attach_cb;
1556 u->source_output->detach = source_output_detach_cb;
1557 u->source_output->may_move_to = source_output_may_move_to_cb;
1558 u->source_output->moving = source_output_moving_cb;
1559 u->source_output->suspend = source_output_suspend_cb;
1560 u->source_output->update_source_latency_range = update_source_latency_range_cb;
1561 u->source_output->update_source_fixed_latency = update_source_latency_range_cb;
1562 u->source_output->userdata = u;
1564 /* If format, rate or channels were originally unset, they are set now
1565 * after the pa_source_output_new() call. */
1566 ss = u->source_output->sample_spec;
1567 map = u->source_output->channel_map;
1569 pa_sink_input_new_data_init(&sink_input_data);
1570 sink_input_data.driver = __FILE__;
1571 sink_input_data.module = m;
1574 pa_sink_input_new_data_set_sink(&sink_input_data, sink, false, true);
1576 if (pa_modargs_get_proplist(ma, "sink_input_properties", sink_input_data.proplist, PA_UPDATE_REPLACE) < 0) {
1577 pa_log("Failed to parse the sink_input_properties value.");
1578 pa_sink_input_new_data_done(&sink_input_data);
1582 if (!pa_proplist_contains(sink_input_data.proplist, PA_PROP_MEDIA_ROLE))
1583 pa_proplist_sets(sink_input_data.proplist, PA_PROP_MEDIA_ROLE, "abstract");
1585 pa_sink_input_new_data_set_sample_spec(&sink_input_data, &ss);
1586 pa_sink_input_new_data_set_channel_map(&sink_input_data, &map);
1587 sink_input_data.flags = PA_SINK_INPUT_VARIABLE_RATE | PA_SINK_INPUT_START_CORKED;
1590 sink_input_data.flags |= PA_SINK_INPUT_NO_REMIX;
1592 sink_dont_move = false;
1593 if (pa_modargs_get_value_boolean(ma, "sink_dont_move", &sink_dont_move) < 0) {
1594 pa_log("sink_dont_move= expects a boolean argument.");
1599 sink_input_data.flags |= PA_SINK_INPUT_DONT_MOVE;
1601 pa_sink_input_new(&u->sink_input, m->core, &sink_input_data);
1602 pa_sink_input_new_data_done(&sink_input_data);
1607 u->sink_input->parent.process_msg = sink_input_process_msg_cb;
1608 u->sink_input->pop = sink_input_pop_cb;
1609 u->sink_input->process_rewind = sink_input_process_rewind_cb;
1610 u->sink_input->kill = sink_input_kill_cb;
1611 u->sink_input->state_change = sink_input_state_change_cb;
1612 u->sink_input->attach = sink_input_attach_cb;
1613 u->sink_input->detach = sink_input_detach_cb;
1614 u->sink_input->update_max_rewind = sink_input_update_max_rewind_cb;
1615 u->sink_input->update_max_request = sink_input_update_max_request_cb;
1616 u->sink_input->may_move_to = sink_input_may_move_to_cb;
1617 u->sink_input->moving = sink_input_moving_cb;
1618 u->sink_input->suspend = sink_input_suspend_cb;
1619 u->sink_input->update_sink_latency_range = update_sink_latency_range_cb;
1620 u->sink_input->update_sink_fixed_latency = update_sink_latency_range_cb;
1621 u->sink_input->userdata = u;
1623 update_latency_boundaries(u, u->source_output->source, u->sink_input->sink);
1624 set_sink_input_latency(u, u->sink_input->sink);
1625 set_source_output_latency(u, u->source_output->source);
1627 pa_sink_input_get_silence(u->sink_input, &silence);
1628 u->memblockq = pa_memblockq_new(
1629 "module-loopback memblockq",
1631 MEMBLOCKQ_MAXLENGTH, /* maxlength */
1632 MEMBLOCKQ_MAXLENGTH, /* tlength */
1633 &ss, /* sample_spec */
1637 &silence); /* silence frame */
1638 pa_memblock_unref(silence.memblock);
1639 /* Fill the memblockq with silence */
1640 pa_memblockq_seek(u->memblockq, pa_usec_to_bytes(u->latency, &u->sink_input->sample_spec), PA_SEEK_RELATIVE, true);
1642 u->asyncmsgq = pa_asyncmsgq_new(0);
1643 if (!u->asyncmsgq) {
1644 pa_log("pa_asyncmsgq_new() failed.");
1648 if (!pa_proplist_contains(u->source_output->proplist, PA_PROP_MEDIA_NAME))
1649 pa_proplist_setf(u->source_output->proplist, PA_PROP_MEDIA_NAME, "Loopback to %s",
1650 pa_strnull(pa_proplist_gets(u->sink_input->sink->proplist, PA_PROP_DEVICE_DESCRIPTION)));
1652 if (!pa_proplist_contains(u->source_output->proplist, PA_PROP_MEDIA_ICON_NAME)
1653 && (n = pa_proplist_gets(u->sink_input->sink->proplist, PA_PROP_DEVICE_ICON_NAME)))
1654 pa_proplist_sets(u->source_output->proplist, PA_PROP_MEDIA_ICON_NAME, n);
1656 if (!pa_proplist_contains(u->sink_input->proplist, PA_PROP_MEDIA_NAME))
1657 pa_proplist_setf(u->sink_input->proplist, PA_PROP_MEDIA_NAME, "Loopback from %s",
1658 pa_strnull(pa_proplist_gets(u->source_output->source->proplist, PA_PROP_DEVICE_DESCRIPTION)));
1660 if (source && !pa_proplist_contains(u->sink_input->proplist, PA_PROP_MEDIA_ICON_NAME)
1661 && (n = pa_proplist_gets(u->source_output->source->proplist, PA_PROP_DEVICE_ICON_NAME)))
1662 pa_proplist_sets(u->sink_input->proplist, PA_PROP_MEDIA_ICON_NAME, n);
1664 /* Hooks to track changes of latency offsets */
1665 pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_SINK_PORT_LATENCY_OFFSET_CHANGED],
1666 PA_HOOK_NORMAL, (pa_hook_cb_t) sink_port_latency_offset_changed_cb, u);
1667 pa_module_hook_connect(m, &m->core->hooks[PA_CORE_HOOK_SOURCE_PORT_LATENCY_OFFSET_CHANGED],
1668 PA_HOOK_NORMAL, (pa_hook_cb_t) source_port_latency_offset_changed_cb, u);
1670 /* Setup message handler for main thread */
1671 u->msg = pa_msgobject_new(loopback_msg);
1672 u->msg->parent.process_msg = loopback_process_msg_cb;
1673 u->msg->userdata = u;
1674 u->msg->dead = false;
1676 /* The output thread is not yet running, set effective_source_latency directly */
1677 update_effective_source_latency(u, u->source_output->source, NULL);
1679 pa_sink_input_put(u->sink_input);
1680 pa_source_output_put(u->source_output);
1682 if (u->source_output->source->state != PA_SOURCE_SUSPENDED)
1683 pa_sink_input_cork(u->sink_input, false);
1685 if (u->sink_input->sink->state != PA_SINK_SUSPENDED)
1686 pa_source_output_cork(u->source_output, false);
1688 update_adjust_timer(u);
1690 pa_modargs_free(ma);
1695 pa_modargs_free(ma);
1702 void pa__done(pa_module*m) {
1707 if (!(u = m->userdata))
1713 pa_memblockq_free(u->memblockq);
1716 pa_asyncmsgq_unref(u->asyncmsgq);
1719 loopback_msg_unref(u->msg);