Add policy in pulseaudio-system.conf to allow new interface
[platform/upstream/pulseaudio.git] / src / modules / module-loopback.c
1 /***
2     This file is part of PulseAudio.
3
4     Copyright 2009 Intel Corporation
5     Contributor: Pierre-Louis Bossart <pierre-louis.bossart@intel.com>
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
27 #include <pulse/xmalloc.h>
28
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>
35
36 #include <pulse/rtclock.h>
37 #include <pulse/timeval.h>
38
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);
43 PA_MODULE_USAGE(
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> "
51         "rate=<sample rate> "
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?> ");
59
60 #define DEFAULT_LATENCY_MSEC 200
61
62 #define MEMBLOCKQ_MAXLENGTH (1024*1024*32)
63
64 #define MIN_DEVICE_LATENCY (2.5*PA_USEC_PER_MSEC)
65
66 #define DEFAULT_ADJUST_TIME_USEC (10*PA_USEC_PER_SEC)
67
68 typedef struct loopback_msg loopback_msg;
69
70 struct userdata {
71     pa_core *core;
72     pa_module *module;
73
74     loopback_msg *msg;
75
76     pa_sink_input *sink_input;
77     pa_source_output *source_output;
78
79     pa_asyncmsgq *asyncmsgq;
80     pa_memblockq *memblockq;
81
82     pa_rtpoll_item *rtpoll_item_read, *rtpoll_item_write;
83
84     pa_time_event *time_event;
85
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;
91
92     /* Values from command line configuration */
93     pa_usec_t latency;
94     pa_usec_t max_latency;
95     pa_usec_t adjust_time;
96     pa_usec_t fast_adjust_threshold;
97
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;
108
109     /* lower latency limit found by underruns */
110     pa_usec_t underrun_latency_limit;
111
112     /* Various counters */
113     uint32_t iteration_counter;
114     uint32_t underrun_counter;
115     uint32_t adjust_counter;
116
117     bool fixed_alsa_source;
118     bool source_sink_changed;
119
120     /* Used for sink input and source output snapshots */
121     struct {
122         int64_t send_counter;
123         int64_t source_latency;
124         pa_usec_t source_timestamp;
125
126         int64_t recv_counter;
127         size_t loopback_memblockq_length;
128         int64_t sink_latency;
129         pa_usec_t sink_timestamp;
130     } latency_snapshot;
131
132     /* Input thread variable */
133     int64_t send_counter;
134
135     /* Output thread variables */
136     struct {
137         int64_t recv_counter;
138         pa_usec_t effective_source_latency;
139
140         /* Copied from main thread */
141         pa_usec_t minimum_latency;
142
143         /* Various booleans */
144         bool in_pop;
145         bool pop_called;
146         bool pop_adjust;
147         bool first_pop_done;
148         bool push_called;
149     } output_thread_info;
150 };
151
152 struct loopback_msg {
153     pa_msgobject parent;
154     struct userdata *userdata;
155     bool dead;
156 };
157
158 PA_DEFINE_PRIVATE_CLASS(loopback_msg, pa_msgobject);
159 #define LOOPBACK_MSG(o) (loopback_msg_cast(o))
160
161 static const char* const valid_modargs[] = {
162     "source",
163     "sink",
164     "adjust_time",
165     "latency_msec",
166     "max_latency_msec",
167     "fast_adjust_threshold_msec",
168     "format",
169     "rate",
170     "channels",
171     "channel_map",
172     "sink_input_properties",
173     "source_output_properties",
174     "source_dont_move",
175     "sink_dont_move",
176     "remix",
177     NULL,
178 };
179
180 enum {
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,
188 };
189
190 enum {
191     SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT = PA_SOURCE_OUTPUT_MESSAGE_MAX,
192 };
193
194 enum {
195     LOOPBACK_MESSAGE_SOURCE_LATENCY_RANGE_CHANGED,
196     LOOPBACK_MESSAGE_SINK_LATENCY_RANGE_CHANGED,
197     LOOPBACK_MESSAGE_UNDERRUN,
198 };
199
200 static void enable_adjust_timer(struct userdata *u, bool enable);
201
202 /* Called from main context */
203 static void teardown(struct userdata *u) {
204     pa_assert(u);
205     pa_assert_ctl_context();
206
207     u->adjust_time = 0;
208     enable_adjust_timer(u, false);
209
210     if (u->msg)
211         u->msg->dead = true;
212
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.
220      *
221      * Emptying the queue can be done in the state_change() callback of the
222      * sink input, when the new state is "unlinked".
223      *
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. */
227
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;
232     }
233
234     if (u->sink_input) {
235         pa_sink_input_unlink(u->sink_input);
236         pa_sink_input_unref(u->sink_input);
237         u->sink_input = NULL;
238     }
239 }
240
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
245  */
246 static uint32_t rate_controller(
247                 uint32_t base_rate,
248                 pa_usec_t adjust_time,
249                 int32_t latency_difference_usec) {
250
251     uint32_t new_rate;
252     double min_cycles;
253
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);
258
259     return new_rate;
260 }
261
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
269  * be wrong. */
270 static void update_minimum_latency(struct userdata *u, pa_sink *sink, bool print_msg) {
271
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;
275
276     else {
277         /* Calculate latency limit from latency ranges */
278
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;
286
287         else
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
290              * data is pushed. */
291             u->minimum_latency += u->min_source_latency;
292
293         /* Multiply by 1.1 as a safety margin for delays that are proportional to the buffer sizes */
294         u->minimum_latency *= 1.1;
295
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;
298     }
299
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;
303     else
304         u->minimum_latency = 0;
305
306     /* If the sink is valid, send a message to update the minimum latency to
307      * the output thread, else set the variable directly */
308     if (sink)
309         pa_asyncmsgq_send(sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_UPDATE_MIN_LATENCY, NULL, u->minimum_latency, NULL);
310     else
311         u->output_thread_info.minimum_latency = u->minimum_latency;
312
313     if (print_msg) {
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);
317     }
318 }
319
320 /* Called from main context */
321 static void adjust_rates(struct userdata *u) {
322     size_t buffer;
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;
328
329     pa_assert(u);
330     pa_assert_ctl_context();
331
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;
336
337     /* If we are seeing underruns then the latency is too small */
338     if (u->underrun_counter > 2) {
339         pa_usec_t target_latency;
340
341         target_latency = PA_MAX(u->latency, u->minimum_latency) + 5 * PA_USEC_PER_MSEC;
342
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);
346         } else {
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");
350         }
351
352         update_minimum_latency(u, u->sink_input->sink, false);
353         u->underrun_counter = 0;
354     }
355
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);
360     }
361
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) {
369         u->adjust_counter++;
370         u->real_adjust_time_sum += time_passed;
371         u->real_adjust_time = u->real_adjust_time_sum / u->adjust_counter;
372     }
373     u->adjust_time_stamp = now;
374
375     /* Rates and latencies */
376     old_rate = u->sink_input->sample_spec.rate;
377     base_rate = u->source_output->sample_spec.rate;
378
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);
382     else
383         buffer = PA_CLIP_SUB(buffer, (size_t) (u->latency_snapshot.recv_counter - u->latency_snapshot.send_counter));
384
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;
388
389     /* Current latency */
390     current_latency = current_source_sink_latency + current_buffer_latency;
391
392     /* Latency at base rate */
393     latency_at_optimum_rate = current_source_sink_latency + current_buffer_latency * old_rate / base_rate;
394
395     final_latency = PA_MAX(u->latency, u->minimum_latency);
396     latency_difference = (int32_t)(latency_at_optimum_rate - final_latency);
397
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);
403
404     pa_log_debug("Loopback latency at base rate is %0.2f ms", (double)latency_at_optimum_rate / PA_USEC_PER_MSEC);
405
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);
409
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);
411
412         /* Skip real adjust time calculation on next iteration. */
413         u->source_sink_changed = true;
414         return;
415     }
416
417     /* Calculate new rate */
418     new_rate = rate_controller(base_rate, u->real_adjust_time, latency_difference);
419
420     u->source_sink_changed = false;
421
422     /* Set rate */
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);
425 }
426
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;
430
431     pa_assert(u);
432     pa_assert(a);
433     pa_assert(u->time_event == e);
434
435     /* Restart timer right away */
436     pa_core_rttime_restart(u->core, u->time_event, pa_rtclock_now() + u->adjust_time);
437
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);
441
442     adjust_rates(u);
443 }
444
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) {
448     if (enable) {
449         if (!u->adjust_time)
450             return;
451         if (u->time_event)
452             u->core->mainloop->time_free(u->time_event);
453
454         u->time_event = pa_core_rttime_new(u->core, pa_rtclock_now() + 333 * PA_USEC_PER_MSEC, time_callback, u);
455     } else {
456         if (!u->time_event)
457             return;
458
459         u->core->mainloop->time_free(u->time_event);
460         u->time_event = NULL;
461     }
462 }
463
464 /* Called from main context */
465 static void update_adjust_timer(struct userdata *u) {
466 #ifdef __TIZEN__
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))
469 #else
470     if (u->sink_input->state == PA_SINK_INPUT_CORKED || u->source_output->state == PA_SOURCE_OUTPUT_CORKED)
471 #endif
472         enable_adjust_timer(u, false);
473     else
474         enable_adjust_timer(u, true);
475 }
476
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) {
480     const char *s;
481
482     if (source) {
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);
487         else {
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))) {
491 #ifdef __TIZEN__
492                 if (pa_streq(s, "alsa") || pa_streq(s, "tizen"))
493 #else
494                 if (pa_streq(s, "alsa"))
495 #endif
496                     u->fixed_alsa_source = true;
497             }
498         }
499         /* Source offset */
500         u->source_latency_offset = source->port_latency_offset;
501
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);
505         else
506             u->min_source_latency = u->max_source_latency;
507     }
508
509     if (sink) {
510         /* Sink latencies */
511         if (sink->flags & PA_SINK_DYNAMIC_LATENCY)
512             pa_sink_get_latency_range(sink, &u->min_sink_latency, &u->max_sink_latency);
513         else {
514             u->min_sink_latency = pa_sink_get_fixed_latency(sink);
515             u->max_sink_latency = u->min_sink_latency;
516         }
517         /* Sink offset */
518         u->sink_latency_offset = sink->port_latency_offset;
519
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);
523         else
524             u->min_sink_latency = u->max_sink_latency;
525     }
526
527     update_minimum_latency(u, sink, true);
528 }
529
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;
535 #ifdef __TIZEN__
536     pa_usec_t final_latency;
537 #else
538     pa_usec_t final_latency, requested_sink_latency;
539 #endif
540
541     final_latency = PA_MAX(u->latency, u->output_thread_info.minimum_latency);
542
543 #ifdef __TIZEN__
544     /* FIXME : rollback upstream code due to bluetooth sync issue */
545     requested_buffer_latency = PA_CLIP_SUB(final_latency, (uint64_t)latency_offset_usec);
546 #else
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;
550
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;
556 #endif
557
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);
560
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);
566
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);
572     }
573 }
574
575 /* Called from input thread context */
576 static void source_output_push_cb(pa_source_output *o, const pa_memchunk *chunk) {
577     struct userdata *u;
578     pa_usec_t push_time;
579     int64_t current_source_latency;
580
581     pa_source_output_assert_ref(o);
582     pa_source_output_assert_io_context(o);
583     pa_assert_se(u = o->userdata);
584
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);
588
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;
591 }
592
593 /* Called from input thread context */
594 static void source_output_process_rewind_cb(pa_source_output *o, size_t nbytes) {
595     struct userdata *u;
596
597     pa_source_output_assert_ref(o);
598     pa_source_output_assert_io_context(o);
599     pa_assert_se(u = o->userdata);
600
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;
603 }
604
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;
608
609     switch (code) {
610
611         case SOURCE_OUTPUT_MESSAGE_LATENCY_SNAPSHOT: {
612             size_t length;
613
614             length = pa_memblockq_get_length(u->source_output->thread_info.delay_memblockq);
615
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();
621
622             return 0;
623         }
624     }
625
626     return pa_source_output_process_msg(obj, code, data, offset, chunk);
627 }
628
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;
635
636     effective_source_latency = u->configured_source_latency;
637
638     if (source) {
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;
642     }
643
644     /* If the sink is valid, send a message to the output thread, else set the variable directly */
645     if (sink)
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);
647     else
648        u->output_thread_info.effective_source_latency = effective_source_latency;
649 }
650
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;
658
659     requested_latency = u->latency / 3;
660
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;
667     }
668
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);
673 }
674
675 /* Called from input thread context */
676 static void source_output_attach_cb(pa_source_output *o) {
677     struct userdata *u;
678
679     pa_source_output_assert_ref(o);
680     pa_source_output_assert_io_context(o);
681     pa_assert_se(u = o->userdata);
682
683     u->rtpoll_item_write = pa_rtpoll_item_new_asyncmsgq_write(
684             o->source->thread_info.rtpoll,
685             PA_RTPOLL_LATE,
686             u->asyncmsgq);
687 }
688
689 /* Called from input thread context */
690 static void source_output_detach_cb(pa_source_output *o) {
691     struct userdata *u;
692
693     pa_source_output_assert_ref(o);
694     pa_source_output_assert_io_context(o);
695     pa_assert_se(u = o->userdata);
696
697     if (u->rtpoll_item_write) {
698         pa_rtpoll_item_free(u->rtpoll_item_write);
699         u->rtpoll_item_write = NULL;
700     }
701 }
702
703 /* Called from main thread */
704 static void source_output_kill_cb(pa_source_output *o) {
705     struct userdata *u;
706
707     pa_source_output_assert_ref(o);
708     pa_assert_ctl_context();
709     pa_assert_se(u = o->userdata);
710
711     teardown(u);
712     pa_module_unload_request(u->module, true);
713 }
714
715 /* Called from main thread */
716 static bool source_output_may_move_to_cb(pa_source_output *o, pa_source *dest) {
717     struct userdata *u;
718
719     pa_source_output_assert_ref(o);
720     pa_assert_ctl_context();
721     pa_assert_se(u = o->userdata);
722
723     if (!u->sink_input || !u->sink_input->sink)
724         return true;
725
726     return dest != u->sink_input->sink->monitor_source;
727 }
728
729 /* Called from main thread */
730 static void source_output_moving_cb(pa_source_output *o, pa_source *dest) {
731     struct userdata *u;
732     char *input_description;
733     const char *n;
734
735     if (!dest)
736         return;
737
738     pa_source_output_assert_ref(o);
739     pa_assert_ctl_context();
740     pa_assert_se(u = o->userdata);
741
742 #ifdef __TIZEN__
743     if (!u->sink_input) {
744         pa_log_warn("sink_input is already null now, do nothing");
745         return;
746     }
747 #endif
748
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);
753
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);
756
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);
762
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));
767     else
768         pa_sink_input_cork(u->sink_input, false);
769
770     update_adjust_timer(u);
771
772     /* Reset counters */
773     u->iteration_counter = 0;
774     u->underrun_counter = 0;
775
776     u->source_sink_changed = true;
777
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);
783     else
784         u->output_thread_info.push_called = false;
785
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);
790 }
791
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) {
794     struct userdata *u;
795     bool suspended;
796
797     pa_source_output_assert_ref(o);
798     pa_assert_ctl_context();
799     pa_assert_se(u = o->userdata);
800
801     /* State has not changed, nothing to do */
802     if (old_state == o->source->state)
803         return;
804
805     suspended = (o->source->state == PA_SOURCE_SUSPENDED);
806
807     /* If the source has been suspended, we need to handle this like
808      * a source change when the source is resumed */
809     if (suspended) {
810 #ifdef __TIZEN__
811         if (u->sink_input && u->sink_input->sink)
812 #else
813         if (u->sink_input->sink)
814 #endif
815             pa_asyncmsgq_send(u->sink_input->sink->asyncmsgq, PA_MSGOBJECT(u->sink_input), SINK_INPUT_MESSAGE_SOURCE_CHANGED, NULL, 0, NULL);
816         else
817             u->output_thread_info.push_called = false;
818
819     } else
820         /* Get effective source latency on unsuspend */
821 #ifdef __TIZEN__
822         if (u->sink_input)
823 #endif
824         update_effective_source_latency(u, u->source_output->source, u->sink_input->sink);
825
826 #ifdef __TIZEN__
827     if (u->sink_input)
828 #endif
829     pa_sink_input_cork(u->sink_input, suspended);
830
831     update_adjust_timer(u);
832 }
833
834 /* Called from input thread context */
835 static void update_source_latency_range_cb(pa_source_output *i) {
836     struct userdata *u;
837
838     pa_source_output_assert_ref(i);
839     pa_source_output_assert_io_context(i);
840     pa_assert_se(u = i->userdata);
841
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);
844 }
845
846 /* Called from output thread context */
847 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
848     struct userdata *u;
849
850     pa_sink_input_assert_ref(i);
851     pa_sink_input_assert_io_context(i);
852     pa_assert_se(u = i->userdata);
853     pa_assert(chunk);
854
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)
859         ;
860     u->output_thread_info.in_pop = false;
861
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;
870     }
871     u->output_thread_info.first_pop_done = true;
872
873     if (pa_memblockq_peek(u->memblockq, chunk) < 0) {
874         pa_log_info("Could not peek into queue");
875         return -1;
876     }
877
878     chunk->length = PA_MIN(chunk->length, nbytes);
879     pa_memblockq_drop(u->memblockq, chunk->length);
880
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);
885
886     return 0;
887 }
888
889 /* Called from output thread context */
890 static void sink_input_process_rewind_cb(pa_sink_input *i, size_t nbytes) {
891     struct userdata *u;
892
893     pa_sink_input_assert_ref(i);
894     pa_sink_input_assert_io_context(i);
895     pa_assert_se(u = i->userdata);
896
897     pa_memblockq_rewind(u->memblockq, nbytes);
898 }
899
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;
903
904     pa_sink_input_assert_io_context(u->sink_input);
905
906     switch (code) {
907
908         case PA_SINK_INPUT_MESSAGE_GET_LATENCY: {
909             pa_usec_t *r = data;
910
911             *r = pa_bytes_to_usec(pa_memblockq_get_length(u->memblockq), &u->sink_input->sample_spec);
912
913             /* Fall through, the default handler will add in the extra
914              * latency added by the resampler */
915             break;
916         }
917
918         case SINK_INPUT_MESSAGE_POST:
919
920             pa_memblockq_push_align(u->memblockq, chunk);
921
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)) {
926                 int64_t time_delta;
927
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);
934
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
939                  * source latency.
940                  *
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;
954                 else
955                     time_delta -= (int64_t)pa_bytes_to_usec(chunk->length, &u->sink_input->sample_spec);
956
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);
960
961                 u->output_thread_info.pop_adjust = false;
962                 u->output_thread_info.push_called = true;
963             }
964
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);
969
970             /* Is this the end of an underrun? Then let's start things
971              * right-away */
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)) {
975
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),
982                                                  false, true, false);
983                 }
984             }
985
986             u->output_thread_info.recv_counter += (int64_t) chunk->length;
987
988             return 0;
989
990         case SINK_INPUT_MESSAGE_REWIND:
991
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);
995
996             u->output_thread_info.recv_counter -= offset;
997
998             return 0;
999
1000         case SINK_INPUT_MESSAGE_LATENCY_SNAPSHOT: {
1001             size_t length;
1002
1003             length = pa_memblockq_get_length(u->sink_input->thread_info.render_memblockq);
1004
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();
1011
1012             return 0;
1013         }
1014
1015         case SINK_INPUT_MESSAGE_SOURCE_CHANGED:
1016
1017             u->output_thread_info.push_called = false;
1018
1019             return 0;
1020
1021         case SINK_INPUT_MESSAGE_SET_EFFECTIVE_SOURCE_LATENCY:
1022
1023             u->output_thread_info.effective_source_latency = (pa_usec_t)offset;
1024
1025             return 0;
1026
1027         case SINK_INPUT_MESSAGE_UPDATE_MIN_LATENCY:
1028
1029             u->output_thread_info.minimum_latency = (pa_usec_t)offset;
1030
1031             return 0;
1032
1033         case SINK_INPUT_MESSAGE_FAST_ADJUST:
1034
1035             memblockq_adjust(u, offset, true);
1036
1037             return 0;
1038     }
1039
1040     return pa_sink_input_process_msg(obj, code, data, offset, chunk);
1041 }
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;
1049
1050     requested_latency = u->latency / 3;
1051
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;
1066     }
1067
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);
1072 }
1073
1074 /* Called from output thread context */
1075 static void sink_input_attach_cb(pa_sink_input *i) {
1076     struct userdata *u;
1077
1078     pa_sink_input_assert_ref(i);
1079     pa_sink_input_assert_io_context(i);
1080     pa_assert_se(u = i->userdata);
1081
1082     u->rtpoll_item_read = pa_rtpoll_item_new_asyncmsgq_read(
1083             i->sink->thread_info.rtpoll,
1084             PA_RTPOLL_LATE,
1085             u->asyncmsgq);
1086
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));
1089 }
1090
1091 /* Called from output thread context */
1092 static void sink_input_detach_cb(pa_sink_input *i) {
1093     struct userdata *u;
1094
1095     pa_sink_input_assert_ref(i);
1096     pa_sink_input_assert_io_context(i);
1097     pa_assert_se(u = i->userdata);
1098
1099     if (u->rtpoll_item_read) {
1100         pa_rtpoll_item_free(u->rtpoll_item_read);
1101         u->rtpoll_item_read = NULL;
1102     }
1103 }
1104
1105 /* Called from output thread context */
1106 static void sink_input_update_max_rewind_cb(pa_sink_input *i, size_t nbytes) {
1107     struct userdata *u;
1108
1109     pa_sink_input_assert_ref(i);
1110     pa_sink_input_assert_io_context(i);
1111     pa_assert_se(u = i->userdata);
1112
1113     pa_memblockq_set_maxrewind(u->memblockq, nbytes);
1114 }
1115
1116 /* Called from output thread context */
1117 static void sink_input_update_max_request_cb(pa_sink_input *i, size_t nbytes) {
1118     struct userdata *u;
1119
1120     pa_sink_input_assert_ref(i);
1121     pa_sink_input_assert_io_context(i);
1122     pa_assert_se(u = i->userdata);
1123
1124     pa_memblockq_set_prebuf(u->memblockq, nbytes*2);
1125     pa_log_info("Max request changed");
1126 }
1127
1128 /* Called from main thread */
1129 static void sink_input_kill_cb(pa_sink_input *i) {
1130     struct userdata *u;
1131
1132     pa_sink_input_assert_ref(i);
1133     pa_assert_ctl_context();
1134     pa_assert_se(u = i->userdata);
1135
1136     teardown(u);
1137     pa_module_unload_request(u->module, true);
1138 }
1139
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) {
1142     struct userdata *u;
1143
1144     pa_sink_input_assert_ref(i);
1145     pa_assert_se(u = i->userdata);
1146
1147     if (state == PA_SINK_INPUT_UNLINKED)
1148         pa_asyncmsgq_flush(u->asyncmsgq, false);
1149 }
1150
1151 /* Called from main thread */
1152 static void sink_input_moving_cb(pa_sink_input *i, pa_sink *dest) {
1153     struct userdata *u;
1154     char *output_description;
1155     const char *n;
1156
1157     if (!dest)
1158         return;
1159
1160     pa_sink_input_assert_ref(i);
1161     pa_assert_ctl_context();
1162     pa_assert_se(u = i->userdata);
1163
1164 #ifdef __TIZEN__
1165     if (!u->source_output) {
1166         pa_log_warn("source_output is already null now, do nothing");
1167         return;
1168     }
1169 #endif
1170
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);
1175
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);
1178
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);
1184
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));
1189     else
1190         pa_source_output_cork(u->source_output, false);
1191
1192     update_adjust_timer(u);
1193
1194     /* Reset counters */
1195     u->iteration_counter = 0;
1196     u->underrun_counter = 0;
1197
1198     u->source_sink_changed = true;
1199
1200     u->output_thread_info.pop_called = false;
1201     u->output_thread_info.first_pop_done = false;
1202
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);
1207 }
1208
1209 /* Called from main thread */
1210 static bool sink_input_may_move_to_cb(pa_sink_input *i, pa_sink *dest) {
1211     struct userdata *u;
1212
1213     pa_sink_input_assert_ref(i);
1214     pa_assert_ctl_context();
1215     pa_assert_se(u = i->userdata);
1216
1217     if (!u->source_output || !u->source_output->source)
1218         return true;
1219
1220     return dest != u->source_output->source->monitor_of;
1221 }
1222
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) {
1225     struct userdata *u;
1226     bool suspended;
1227
1228     pa_sink_input_assert_ref(i);
1229     pa_assert_ctl_context();
1230     pa_assert_se(u = i->userdata);
1231
1232     /* State has not changed, nothing to do */
1233     if (old_state == i->sink->state)
1234         return;
1235
1236     suspended = (i->sink->state == PA_SINK_SUSPENDED);
1237
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. */
1241     if (suspended) {
1242         u->output_thread_info.pop_called = false;
1243         u->output_thread_info.first_pop_done = false;
1244
1245     } else
1246         /* Set effective source latency on unsuspend */
1247 #ifdef __TIZEN__
1248         if (u->source_output)
1249 #endif
1250         update_effective_source_latency(u, u->source_output->source, u->sink_input->sink);
1251
1252 #ifdef __TIZEN__
1253     if (u->source_output)
1254 #endif
1255     pa_source_output_cork(u->source_output, suspended);
1256
1257     update_adjust_timer(u);
1258 }
1259
1260 /* Called from output thread context */
1261 static void update_sink_latency_range_cb(pa_sink_input *i) {
1262     struct userdata *u;
1263
1264     pa_sink_input_assert_ref(i);
1265     pa_sink_input_assert_io_context(i);
1266     pa_assert_se(u = i->userdata);
1267
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);
1270 }
1271
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;
1275     struct userdata *u;
1276     pa_usec_t current_latency;
1277
1278     pa_assert(o);
1279     pa_assert_ctl_context();
1280
1281     msg = LOOPBACK_MSG(o);
1282
1283     /* If messages are processed after a module unload request, they
1284      * must be ignored. */
1285     if (msg->dead)
1286         return 0;
1287
1288     pa_assert_se(u = msg->userdata);
1289
1290     switch (code) {
1291
1292         case LOOPBACK_MESSAGE_SOURCE_LATENCY_RANGE_CHANGED:
1293
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;
1307             }
1308
1309             return 0;
1310
1311         case LOOPBACK_MESSAGE_SINK_LATENCY_RANGE_CHANGED:
1312
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;
1325             }
1326
1327             return 0;
1328
1329         case LOOPBACK_MESSAGE_UNDERRUN:
1330
1331             u->underrun_counter++;
1332             pa_log_debug("Underrun detected, counter incremented to %u", u->underrun_counter);
1333
1334             return 0;
1335
1336     }
1337
1338     return 0;
1339 }
1340
1341 static pa_hook_result_t sink_port_latency_offset_changed_cb(pa_core *core, pa_sink *sink, struct userdata *u) {
1342
1343     if (sink != u->sink_input->sink)
1344         return PA_HOOK_OK;
1345
1346     u->sink_latency_offset = sink->port_latency_offset;
1347     update_minimum_latency(u, sink, true);
1348
1349     return PA_HOOK_OK;
1350 }
1351
1352 static pa_hook_result_t source_port_latency_offset_changed_cb(pa_core *core, pa_source *source, struct userdata *u) {
1353
1354     if (source != u->source_output->source)
1355         return PA_HOOK_OK;
1356
1357     u->source_latency_offset = source->port_latency_offset;
1358     update_minimum_latency(u, u->sink_input->sink, true);
1359
1360     return PA_HOOK_OK;
1361 }
1362
1363 int pa__init(pa_module *m) {
1364     pa_modargs *ma = NULL;
1365     struct userdata *u;
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;
1375     pa_sample_spec ss;
1376     pa_channel_map map;
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;
1382     const char *n;
1383     bool remix = true;
1384
1385     pa_assert(m);
1386
1387     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1388         pa_log("Failed to parse module arguments");
1389         goto fail;
1390     }
1391
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.");
1395         goto fail;
1396     }
1397
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.");
1401         goto fail;
1402     }
1403
1404     if (pa_modargs_get_value_boolean(ma, "remix", &remix) < 0) {
1405         pa_log("Invalid boolean remix parameter");
1406         goto fail;
1407     }
1408
1409     if (source) {
1410         ss = source->sample_spec;
1411         map = source->channel_map;
1412         format_set = true;
1413         rate_set = true;
1414         channels_set = true;
1415     } else if (sink) {
1416         ss = sink->sample_spec;
1417         map = sink->channel_map;
1418         format_set = true;
1419         rate_set = true;
1420         channels_set = true;
1421     } else {
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
1426          * present. */
1427         ss.format = PA_SAMPLE_U8;
1428         ss.rate = 8000;
1429         ss.channels = 1;
1430         map.channels = 1;
1431         map.map[0] = PA_CHANNEL_POSITION_MONO;
1432     }
1433
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");
1436         goto fail;
1437     }
1438
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);
1441         goto fail;
1442     }
1443
1444     if (pa_modargs_get_value(ma, "format", NULL))
1445         format_set = true;
1446
1447     if (pa_modargs_get_value(ma, "rate", NULL))
1448         rate_set = true;
1449
1450     if (pa_modargs_get_value(ma, "channels", NULL) || pa_modargs_get_value(ma, "channel_map", NULL))
1451         channels_set = true;
1452
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");
1456         goto fail;
1457     }
1458
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");
1462         goto fail;
1463     }
1464
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");
1468         goto fail;
1469     }
1470
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;
1474     }
1475
1476     m->userdata = u = pa_xnew0(struct userdata, 1);
1477     u->core = m->core;
1478     u->module = m;
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;
1491
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");
1495         goto fail;
1496     }
1497
1498     if (adjust_time_sec != DEFAULT_ADJUST_TIME_USEC / PA_USEC_PER_SEC)
1499         u->adjust_time = adjust_time_sec * PA_USEC_PER_SEC;
1500     else
1501         u->adjust_time = DEFAULT_ADJUST_TIME_USEC;
1502
1503     u->real_adjust_time = u->adjust_time;
1504
1505     pa_source_output_new_data_init(&source_output_data);
1506     source_output_data.driver = __FILE__;
1507     source_output_data.module = m;
1508     if (source)
1509         pa_source_output_new_data_set_source(&source_output_data, source, false, true);
1510
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);
1514         goto fail;
1515     }
1516
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");
1519
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;
1523
1524     if (!remix)
1525         source_output_data.flags |= PA_SOURCE_OUTPUT_NO_REMIX;
1526
1527     if (!format_set)
1528         source_output_data.flags |= PA_SOURCE_OUTPUT_FIX_FORMAT;
1529
1530     if (!rate_set)
1531         source_output_data.flags |= PA_SOURCE_OUTPUT_FIX_RATE;
1532
1533     if (!channels_set)
1534         source_output_data.flags |= PA_SOURCE_OUTPUT_FIX_CHANNELS;
1535
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.");
1539         goto fail;
1540     }
1541
1542     if (source_dont_move)
1543         source_output_data.flags |= PA_SOURCE_OUTPUT_DONT_MOVE;
1544
1545     pa_source_output_new(&u->source_output, m->core, &source_output_data);
1546     pa_source_output_new_data_done(&source_output_data);
1547
1548     if (!u->source_output)
1549         goto fail;
1550
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;
1563
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;
1568
1569     pa_sink_input_new_data_init(&sink_input_data);
1570     sink_input_data.driver = __FILE__;
1571     sink_input_data.module = m;
1572
1573     if (sink)
1574         pa_sink_input_new_data_set_sink(&sink_input_data, sink, false, true);
1575
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);
1579         goto fail;
1580     }
1581
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");
1584
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;
1588
1589     if (!remix)
1590         sink_input_data.flags |= PA_SINK_INPUT_NO_REMIX;
1591
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.");
1595         goto fail;
1596     }
1597
1598     if (sink_dont_move)
1599         sink_input_data.flags |= PA_SINK_INPUT_DONT_MOVE;
1600
1601     pa_sink_input_new(&u->sink_input, m->core, &sink_input_data);
1602     pa_sink_input_new_data_done(&sink_input_data);
1603
1604     if (!u->sink_input)
1605         goto fail;
1606
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;
1622
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);
1626
1627     pa_sink_input_get_silence(u->sink_input, &silence);
1628     u->memblockq = pa_memblockq_new(
1629             "module-loopback memblockq",
1630             0,                      /* idx */
1631             MEMBLOCKQ_MAXLENGTH,    /* maxlength */
1632             MEMBLOCKQ_MAXLENGTH,    /* tlength */
1633             &ss,                    /* sample_spec */
1634             0,                      /* prebuf */
1635             0,                      /* minreq */
1636             0,                      /* maxrewind */
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);
1641
1642     u->asyncmsgq = pa_asyncmsgq_new(0);
1643     if (!u->asyncmsgq) {
1644         pa_log("pa_asyncmsgq_new() failed.");
1645         goto fail;
1646     }
1647
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)));
1651
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);
1655
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)));
1659
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);
1663
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);
1669
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;
1675
1676     /* The output thread is not yet running, set effective_source_latency directly */
1677     update_effective_source_latency(u, u->source_output->source, NULL);
1678
1679     pa_sink_input_put(u->sink_input);
1680     pa_source_output_put(u->source_output);
1681
1682     if (u->source_output->source->state != PA_SOURCE_SUSPENDED)
1683         pa_sink_input_cork(u->sink_input, false);
1684
1685     if (u->sink_input->sink->state != PA_SINK_SUSPENDED)
1686         pa_source_output_cork(u->source_output, false);
1687
1688     update_adjust_timer(u);
1689
1690     pa_modargs_free(ma);
1691     return 0;
1692
1693 fail:
1694     if (ma)
1695         pa_modargs_free(ma);
1696
1697     pa__done(m);
1698
1699     return -1;
1700 }
1701
1702 void pa__done(pa_module*m) {
1703     struct userdata *u;
1704
1705     pa_assert(m);
1706
1707     if (!(u = m->userdata))
1708         return;
1709
1710     teardown(u);
1711
1712     if (u->memblockq)
1713         pa_memblockq_free(u->memblockq);
1714
1715     if (u->asyncmsgq)
1716         pa_asyncmsgq_unref(u->asyncmsgq);
1717
1718     if (u->msg)
1719         loopback_msg_unref(u->msg);
1720
1721     pa_xfree(u);
1722 }