• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***
2   This file is part of PulseAudio.
3 
4   Copyright 2008-2013 João Paulo Rechi Vita
5   Copyright 2011-2013 BMW Car IT GmbH.
6   Copyright 2018-2019 Pali Rohár <pali.rohar@gmail.com>
7 
8   PulseAudio is free software; you can redistribute it and/or modify
9   it under the terms of the GNU Lesser General Public License as
10   published by the Free Software Foundation; either version 2.1 of the
11   License, or (at your option) any later version.
12 
13   PulseAudio is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17 
18   You should have received a copy of the GNU Lesser General Public
19   License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
20 ***/
21 
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 
26 #include <errno.h>
27 
28 #include <arpa/inet.h>
29 
30 #include <pulse/rtclock.h>
31 #include <pulse/timeval.h>
32 #include <pulse/utf8.h>
33 #include <pulse/util.h>
34 
35 #include <pulsecore/core-error.h>
36 #include <pulsecore/core-rtclock.h>
37 #include <pulsecore/core-util.h>
38 #include <pulsecore/i18n.h>
39 #include <pulsecore/json.h>
40 #include <pulsecore/message-handler.h>
41 #include <pulsecore/module.h>
42 #include <pulsecore/modargs.h>
43 #include <pulsecore/poll.h>
44 #include <pulsecore/rtpoll.h>
45 #include <pulsecore/shared.h>
46 #include <pulsecore/socket-util.h>
47 #include <pulsecore/thread.h>
48 #include <pulsecore/thread-mq.h>
49 
50 #ifdef USE_SMOOTHER_2
51 #include <pulsecore/time-smoother_2.h>
52 #else
53 #include <pulsecore/time-smoother.h>
54 #endif
55 
56 #include "a2dp-codecs.h"
57 #include "a2dp-codec-util.h"
58 #include "bluez5-util.h"
59 
60 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
61 PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
62 PA_MODULE_VERSION(PACKAGE_VERSION);
63 PA_MODULE_LOAD_ONCE(false);
64 PA_MODULE_USAGE(
65     "path=<device object path>"
66     "autodetect_mtu=<boolean>"
67     "output_rate_refresh_interval_ms=<interval between attempts to improve output rate in milliseconds>"
68     "avrcp_absolute_volume=<synchronize volume with peer, true by default>"
69 );
70 
71 #define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
72 #define FIXED_LATENCY_PLAYBACK_SCO  (25 * PA_USEC_PER_MSEC)
73 #define FIXED_LATENCY_RECORD_A2DP   (25 * PA_USEC_PER_MSEC)
74 #define FIXED_LATENCY_RECORD_SCO    (25 * PA_USEC_PER_MSEC)
75 
76 static const char* const valid_modargs[] = {
77     "path",
78     "autodetect_mtu",
79     "output_rate_refresh_interval_ms",
80     "avrcp_absolute_volume",
81     NULL
82 };
83 
84 enum {
85     BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
86     BLUETOOTH_MESSAGE_STREAM_FD_HUP,
87     BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING,
88     BLUETOOTH_MESSAGE_MAX
89 };
90 
91 enum {
92     PA_SOURCE_MESSAGE_SETUP_STREAM = PA_SOURCE_MESSAGE_MAX,
93 };
94 
95 enum {
96     PA_SINK_MESSAGE_SETUP_STREAM = PA_SINK_MESSAGE_MAX,
97 };
98 
99 typedef struct bluetooth_msg {
100     pa_msgobject parent;
101     pa_card *card;
102 } bluetooth_msg;
103 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
104 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
105 
106 struct userdata {
107     pa_module *module;
108     pa_core *core;
109 
110     pa_hook_slot *device_connection_changed_slot;
111     pa_hook_slot *device_battery_level_changed_slot;
112     pa_hook_slot *transport_state_changed_slot;
113     pa_hook_slot *transport_sink_volume_changed_slot;
114     pa_hook_slot *transport_source_volume_changed_slot;
115 
116     pa_hook_slot *sink_volume_changed_slot;
117     pa_hook_slot *source_volume_changed_slot;
118 
119     pa_bluetooth_discovery *discovery;
120     pa_bluetooth_device *device;
121     pa_bluetooth_transport *transport;
122     bool transport_acquired;
123     bool stream_setup_done;
124 
125     pa_card *card;
126     pa_sink *sink;
127     pa_source *source;
128     pa_bluetooth_profile_t profile;
129     char *output_port_name;
130     char *input_port_name;
131 
132     pa_thread *thread;
133     pa_thread_mq thread_mq;
134     pa_rtpoll *rtpoll;
135     pa_rtpoll_item *rtpoll_item;
136     bluetooth_msg *msg;
137 
138     int stream_fd;
139     size_t read_link_mtu;
140     size_t write_link_mtu;
141     size_t read_block_size;
142     size_t write_block_size;
143     uint64_t read_index;
144     uint64_t write_index;
145     pa_usec_t started_at;
146 
147 #ifdef USE_SMOOTHER_2
148     pa_smoother_2 *read_smoother;
149 #else
150     pa_smoother *read_smoother;
151 #endif
152 
153     pa_memchunk write_memchunk;
154 
155     const pa_bt_codec *bt_codec;
156 
157     void *encoder_info;
158     pa_sample_spec encoder_sample_spec;
159     void *encoder_buffer;                        /* Codec transfer buffer */
160     size_t encoder_buffer_size;                  /* Size of the buffer */
161     size_t encoder_buffer_used;                  /* Used space in the buffer */
162 
163     void *decoder_info;
164     pa_sample_spec decoder_sample_spec;
165     void *decoder_buffer;                        /* Codec transfer buffer */
166     size_t decoder_buffer_size;                  /* Size of the buffer */
167 
168     bool message_handler_registered;
169 };
170 
171 typedef enum pa_bluetooth_form_factor {
172     PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
173     PA_BLUETOOTH_FORM_FACTOR_HEADSET,
174     PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
175     PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
176     PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
177     PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
178     PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
179     PA_BLUETOOTH_FORM_FACTOR_CAR,
180     PA_BLUETOOTH_FORM_FACTOR_HIFI,
181     PA_BLUETOOTH_FORM_FACTOR_PHONE,
182 } pa_bluetooth_form_factor_t;
183 
184 /* Run from main thread */
form_factor_from_class(uint32_t class_of_device)185 static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
186     unsigned major, minor;
187     pa_bluetooth_form_factor_t r;
188 
189     static const pa_bluetooth_form_factor_t table[] = {
190         [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
191         [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
192         [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
193         [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
194         [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
195         [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
196         [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
197         [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
198     };
199 
200     /*
201      * See Bluetooth Assigned Numbers for Baseband
202      * https://www.bluetooth.com/specifications/assigned-numbers/baseband/
203      */
204     major = (class_of_device >> 8) & 0x1F;
205     minor = (class_of_device >> 2) & 0x3F;
206 
207     switch (major) {
208         case 2:
209             return PA_BLUETOOTH_FORM_FACTOR_PHONE;
210         case 4:
211             break;
212         default:
213             pa_log_debug("Unknown Bluetooth major device class %u", major);
214             return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
215     }
216 
217     r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
218 
219     if (!r)
220         pa_log_debug("Unknown Bluetooth minor device class %u", minor);
221 
222     return r;
223 }
224 
225 /* Run from main thread */
form_factor_to_string(pa_bluetooth_form_factor_t ff)226 static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
227     switch (ff) {
228         case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
229             return "unknown";
230         case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
231             return "headset";
232         case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
233             return "hands-free";
234         case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
235             return "microphone";
236         case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
237             return "speaker";
238         case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
239             return "headphone";
240         case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
241             return "portable";
242         case PA_BLUETOOTH_FORM_FACTOR_CAR:
243             return "car";
244         case PA_BLUETOOTH_FORM_FACTOR_HIFI:
245             return "hifi";
246         case PA_BLUETOOTH_FORM_FACTOR_PHONE:
247             return "phone";
248     }
249 
250     pa_assert_not_reached();
251 }
252 
253 /* Run from main thread */
connect_ports(struct userdata * u,void * new_data,pa_direction_t direction)254 static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
255     pa_device_port *port;
256 
257     if (direction == PA_DIRECTION_OUTPUT) {
258         pa_sink_new_data *sink_new_data = new_data;
259 
260         pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
261         pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
262         pa_device_port_ref(port);
263     } else {
264         pa_source_new_data *source_new_data = new_data;
265 
266         pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
267         pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
268         pa_device_port_ref(port);
269     }
270 }
271 
bt_prepare_encoder_buffer(struct userdata * u)272 static bool bt_prepare_encoder_buffer(struct userdata *u)
273 {
274     size_t encoded_size, reserved_size, encoded_frames;
275     pa_assert(u);
276     pa_assert(u->bt_codec);
277 
278     /* If socket write MTU is less than encoded frame size, there could be
279      * up to one write MTU of data left in encoder buffer from previous round.
280      *
281      * Reserve space for at least 2 encoded frames to cover that.
282      *
283      * Note for A2DP codecs it is expected that size of encoded frame is less
284      * than write link MTU. Therefore each encoded frame is sent out completely
285      * and there is no used space in encoder buffer before next encoder call.
286      *
287      * For SCO socket all writes will be of MTU size to match payload length
288      * of HCI packet. Depending on selected USB Alternate Setting the payload
289      * length of HCI packet may exceed encoded frame size. For mSBC frame size
290      * is 60 bytes, payload length of HCI packet in USB Alts 3 is 72 byte,
291      * in USB Alts 5 it is 144 bytes.
292      *
293      * Reserve space for up to 1 + MTU / (encoded frame size) encoded frames
294      * to cover that.
295      *
296      * Note for current linux kernel (up to 5.13.x at least) there is no way to
297      * reliably detect socket MTU size. For now we just set SCO socket MTU to be
298      * large enough to cover all known sizes (largest is USB ALts 5 with 144 bytes)
299      * and adjust SCO write size to be equal to last SCO read size. This makes
300      * write size less or equal to MTU size. Reserving the same number of encoded
301      * frames to cover full MTU is still enough.
302      * See also https://gitlab.freedesktop.org/pulseaudio/pulseaudio/-/merge_requests/254#note_779802
303      */
304 
305     if (u->bt_codec->get_encoded_block_size)
306         encoded_size = u->bt_codec->get_encoded_block_size(u->encoder_info, u->write_block_size);
307     else
308         encoded_size = u->write_block_size;
309 
310     encoded_frames = u->write_link_mtu / u->write_block_size + 1;
311 
312     if (encoded_frames < 2)
313         encoded_frames = 2;
314 
315     reserved_size = encoded_frames * encoded_size;
316 
317     if (u->encoder_buffer_size < reserved_size) {
318         u->encoder_buffer = pa_xrealloc(u->encoder_buffer, reserved_size);
319         u->encoder_buffer_size = reserved_size;
320 
321         if (u->encoder_buffer_used > reserved_size) {
322             u->encoder_buffer_used = 0;
323         }
324     }
325 
326     /* Report if there is still not enough space for new block */
327     if (u->encoder_buffer_size < u->encoder_buffer_used + encoded_size)
328         return false;
329 
330     return true;
331 }
332 
333 /* Run from IO thread */
bt_write_buffer(struct userdata * u)334 static int bt_write_buffer(struct userdata *u) {
335     ssize_t written = 0;
336 
337     pa_assert(u);
338     pa_assert(u->transport);
339     pa_assert(u->bt_codec);
340 
341     written = u->transport->write(u->transport, u->stream_fd, u->encoder_buffer, u->encoder_buffer_used, u->write_link_mtu);
342 
343     if (written > 0) {
344         /* calculate remainder */
345         u->encoder_buffer_used -= written;
346 
347         /* move any remainder back to start of u->encoder_buffer */
348         if (u->encoder_buffer_used)
349             memmove(u->encoder_buffer, u->encoder_buffer + written, u->encoder_buffer_used);
350 
351         return 1;
352     } else if (written == 0) {
353         /* Not enough data in encoder buffer */
354         return 0;
355     } else {
356         /* Reset encoder sequence number and buffer positions */
357         u->bt_codec->reset(u->encoder_info);
358         u->encoder_buffer_used = 0;
359         return -1;
360     }
361 }
362 
363 /* Run from IO thread */
bt_process_render(struct userdata * u)364 static int bt_process_render(struct userdata *u) {
365     int ret;
366 
367     const uint8_t *ptr;
368     size_t processed;
369     size_t length;
370 
371     pa_assert(u);
372     pa_assert(u->sink);
373     pa_assert(u->bt_codec);
374 
375     if (!bt_prepare_encoder_buffer(u))
376         return false;
377 
378     /* First, render some data */
379     if (!u->write_memchunk.memblock)
380         pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
381 
382     pa_assert(u->write_memchunk.length == u->write_block_size);
383 
384     ptr = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
385 
386     length = u->bt_codec->encode_buffer(u->encoder_info, u->write_index / pa_frame_size(&u->encoder_sample_spec),
387             ptr, u->write_memchunk.length,
388             u->encoder_buffer + u->encoder_buffer_used, u->encoder_buffer_size - u->encoder_buffer_used,
389             &processed);
390 
391     pa_memblock_release(u->write_memchunk.memblock);
392 
393     if (processed != u->write_memchunk.length) {
394         pa_log_error("Encoding error");
395         return -1;
396     }
397 
398     /* Encoder function of BT codec may provide empty buffer, in this case do
399      * not post any empty buffer via BT socket. It may be because of codec
400      * internal state, e.g. encoder is waiting for more samples so it can
401      * provide encoded data. */
402 
403     if (PA_LIKELY(length)) {
404         u->encoder_buffer_used += length;
405         ret = 1;
406     } else
407         ret = 0;
408 
409     u->write_index += (uint64_t) u->write_memchunk.length;
410     pa_memblock_unref(u->write_memchunk.memblock);
411     pa_memchunk_reset(&u->write_memchunk);
412 
413     return ret;
414 }
415 
bt_prepare_decoder_buffer(struct userdata * u)416 static void bt_prepare_decoder_buffer(struct userdata *u) {
417     pa_assert(u);
418 
419     if (u->decoder_buffer_size < u->read_link_mtu) {
420         pa_xfree(u->decoder_buffer);
421         u->decoder_buffer = pa_xmalloc(u->read_link_mtu);
422     }
423 
424     /* Decoder buffer cannot be larger then link MTU, otherwise
425      * decode method would produce larger output then read_block_size */
426     u->decoder_buffer_size = u->read_link_mtu;
427 }
428 
429 /* Run from IO thread */
bt_transport_read(pa_bluetooth_transport * t,int fd,void * buffer,size_t size,pa_usec_t * p_timestamp)430 static ssize_t bt_transport_read(pa_bluetooth_transport *t, int fd, void *buffer, size_t size, pa_usec_t *p_timestamp) {
431     ssize_t received = 0;
432 
433     pa_assert(t);
434     for (;;) {
435         uint8_t aux[1024];
436         struct iovec iov;
437         struct cmsghdr *cm;
438         struct msghdr m;
439         bool found_tstamp = false;
440 
441         pa_zero(m);
442         pa_zero(aux);
443         pa_zero(iov);
444 
445         m.msg_iov = &iov;
446         m.msg_iovlen = 1;
447         m.msg_control = aux;
448         m.msg_controllen = sizeof(aux);
449 
450         iov.iov_base = buffer;
451         iov.iov_len = size;
452 
453         received = recvmsg(fd, &m, 0);
454 
455         if (received <= 0) {
456 
457             if (received < 0 && errno == EINTR)
458                 /* Retry right away if we got interrupted */
459                 continue;
460 
461             else if (received < 0 && errno == EAGAIN)
462                 /* Hmm, apparently the socket was not readable, give up for now. */
463                 return 0;
464 
465             pa_log_error("Failed to read data from socket: %s", received < 0 ? pa_cstrerror(errno) : "EOF");
466             return -1;
467         }
468 
469         pa_assert((size_t) received <= size);
470 
471         /* allow write side to find out size of last read packet */
472         t->last_read_size = received;
473 
474         if (p_timestamp) {
475             /* TODO: get timestamp from rtp */
476 
477             for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm)) {
478                 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
479                     struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
480                     pa_rtclock_from_wallclock(tv);
481                     *p_timestamp = pa_timeval_load(tv);
482                     found_tstamp = true;
483                     break;
484                 }
485             }
486 
487             if (!found_tstamp) {
488                 PA_ONCE_BEGIN {
489                     pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
490                 } PA_ONCE_END;
491                 *p_timestamp = pa_rtclock_now();
492             }
493         }
494 
495         break;
496     }
497 
498     return received;
499 }
500 
501 /* Run from IO thread */
502 /* Read incoming data, decode it and post result (if any) to source output.
503  * Returns number of bytes posted to source output. */
bt_process_push(struct userdata * u)504 static int bt_process_push(struct userdata *u) {
505     pa_usec_t tstamp;
506     uint8_t *ptr;
507     ssize_t received;
508     size_t processed = 0;
509 
510     pa_assert(u);
511     pa_assert(u->source);
512     pa_assert(u->read_smoother);
513     pa_assert(u->bt_codec);
514     pa_assert(u->transport);
515 
516     bt_prepare_decoder_buffer(u);
517 
518     received = bt_transport_read(u->transport, u->stream_fd, u->decoder_buffer, u->decoder_buffer_size, &tstamp);
519 
520     if (received <= 0) {
521         return received;
522     }
523 
524     pa_memchunk memchunk;
525 
526     memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
527     memchunk.index = memchunk.length = 0;
528 
529     ptr = pa_memblock_acquire(memchunk.memblock);
530     memchunk.length = pa_memblock_get_length(memchunk.memblock);
531 
532     memchunk.length = u->bt_codec->decode_buffer(u->decoder_info, u->decoder_buffer, received, ptr, memchunk.length, &processed);
533 
534     pa_memblock_release(memchunk.memblock);
535 
536     if (processed != (size_t) received) {
537         pa_log_error("Decoding error");
538         return -1;
539     }
540 
541     u->read_index += (uint64_t) memchunk.length;
542 #ifdef USE_SMOOTHER_2
543         pa_smoother_2_resume(u->read_smoother, tstamp);
544         pa_smoother_2_put(u->read_smoother, tstamp, u->read_index);
545 #else
546         pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec));
547         pa_smoother_resume(u->read_smoother, tstamp, true);
548 #endif
549 
550     /* Decoding of data may result in empty buffer, in this case
551      * do not post empty audio samples. It may happen due to algorithmic
552      * delay of audio codec. */
553     if (PA_LIKELY(memchunk.length))
554         pa_source_post(u->source, &memchunk);
555 
556     /* report decoded size */
557     received = memchunk.length;
558 
559     pa_memblock_unref(memchunk.memblock);
560 
561     return received;
562 }
563 
update_sink_buffer_size(struct userdata * u)564 static void update_sink_buffer_size(struct userdata *u) {
565     int old_bufsize;
566     socklen_t len = sizeof(int);
567     int ret;
568 
569     ret = getsockopt(u->stream_fd, SOL_SOCKET, SO_SNDBUF, &old_bufsize, &len);
570     if (ret == -1) {
571         pa_log_warn("Changing bluetooth buffer size: Failed to getsockopt(SO_SNDBUF): %s", pa_cstrerror(errno));
572     } else {
573         int new_bufsize;
574 
575         /* Set send buffer size as small as possible. The minimum value is 1024 according to the
576          * socket man page. The data is written to the socket in chunks of write_block_size, so
577          * there should at least be room for two chunks in the buffer. Generally, write_block_size
578          * is larger than 512. If not, use the next multiple of write_block_size which is larger
579          * than 1024. */
580         new_bufsize = 2 * u->write_block_size;
581         if (new_bufsize < 1024)
582             new_bufsize = (1024 / u->write_block_size + 1) * u->write_block_size;
583 
584         /* The kernel internally doubles the buffer size that was set by setsockopt and getsockopt
585          * returns the doubled value. */
586         if (new_bufsize != old_bufsize / 2) {
587             ret = setsockopt(u->stream_fd, SOL_SOCKET, SO_SNDBUF, &new_bufsize, len);
588             if (ret == -1)
589                 pa_log_warn("Changing bluetooth buffer size: Failed to change from %d to %d: %s", old_bufsize / 2, new_bufsize, pa_cstrerror(errno));
590             else
591                 pa_log_info("Changing bluetooth buffer size: Changed from %d to %d", old_bufsize / 2, new_bufsize);
592         }
593     }
594 }
595 
teardown_stream(struct userdata * u)596 static void teardown_stream(struct userdata *u) {
597     if (u->rtpoll_item) {
598         pa_rtpoll_item_free(u->rtpoll_item);
599         u->rtpoll_item = NULL;
600     }
601 
602     if (u->stream_fd >= 0) {
603         pa_close(u->stream_fd);
604         u->stream_fd = -1;
605     }
606 
607     if (u->read_smoother) {
608 #ifdef USE_SMOOTHER_2
609         pa_smoother_2_free(u->read_smoother);
610 #else
611         pa_smoother_free(u->read_smoother);
612 #endif
613         u->read_smoother = NULL;
614     }
615 
616     if (u->write_memchunk.memblock) {
617         pa_memblock_unref(u->write_memchunk.memblock);
618         pa_memchunk_reset(&u->write_memchunk);
619     }
620 
621     pa_log_debug("Audio stream torn down");
622     u->stream_setup_done = false;
623 }
624 
transport_acquire(struct userdata * u,bool optional)625 static int transport_acquire(struct userdata *u, bool optional) {
626     pa_assert(u->transport);
627 
628     if (u->transport_acquired)
629         return 0;
630 
631     pa_log_debug("Acquiring transport %s", u->transport->path);
632 
633     u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
634     if (u->stream_fd < 0)
635         return u->stream_fd;
636 
637     /* transport_acquired must be set before calling
638      * pa_bluetooth_transport_set_state() */
639     u->transport_acquired = true;
640     pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
641 
642     if (u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_IDLE) {
643         if (pa_thread_mq_get() != NULL)
644             pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING, NULL, 0, NULL, NULL);
645         else
646             pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
647     }
648 
649     return 0;
650 }
651 
transport_release(struct userdata * u)652 static void transport_release(struct userdata *u) {
653     pa_assert(u->transport);
654 
655     /* Ignore if already released */
656     if (!u->transport_acquired)
657         return;
658 
659     pa_log_debug("Releasing transport %s", u->transport->path);
660 
661     u->transport->release(u->transport);
662 
663     u->transport_acquired = false;
664 
665     teardown_stream(u);
666 
667     /* Set transport state to idle if this was not already done by the remote end closing
668      * the file descriptor. Only do this when called from the I/O thread */
669     if (pa_thread_mq_get() != NULL && u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
670         pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
671 }
672 
673 /* Run from I/O thread */
handle_sink_block_size_change(struct userdata * u)674 static void handle_sink_block_size_change(struct userdata *u) {
675     pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
676     pa_sink_set_fixed_latency_within_thread(u->sink,
677                                             (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
678                                              FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
679                                             pa_bytes_to_usec(u->write_block_size, &u->encoder_sample_spec));
680 
681     /* If there is still data in the memchunk, we have to discard it
682      * because the write_block_size may have changed. */
683     if (u->write_memchunk.memblock) {
684         pa_memblock_unref(u->write_memchunk.memblock);
685         pa_memchunk_reset(&u->write_memchunk);
686     }
687 
688     update_sink_buffer_size(u);
689 }
690 
691 /* Run from I/O thread */
transport_config_mtu(struct userdata * u)692 static void transport_config_mtu(struct userdata *u) {
693     pa_assert(u->bt_codec);
694 
695     if (u->encoder_info) {
696         u->write_block_size = u->bt_codec->get_write_block_size(u->encoder_info, u->write_link_mtu);
697 
698         if (!pa_frame_aligned(u->write_block_size, &u->sink->sample_spec)) {
699             pa_log_debug("Got invalid write MTU: %lu, rounding down", u->write_block_size);
700             u->write_block_size = pa_frame_align(u->write_block_size, &u->sink->sample_spec);
701         }
702     }
703 
704     if (u->decoder_info) {
705         u->read_block_size = u->bt_codec->get_read_block_size(u->decoder_info, u->read_link_mtu);
706 
707         if (!pa_frame_aligned(u->read_block_size, &u->source->sample_spec)) {
708             pa_log_debug("Got invalid read MTU: %lu, rounding down", u->read_block_size);
709             u->read_block_size = pa_frame_align(u->read_block_size, &u->source->sample_spec);
710         }
711     }
712 
713     if (u->sink)
714         handle_sink_block_size_change(u);
715 
716     if (u->source)
717         pa_source_set_fixed_latency_within_thread(u->source,
718                                                   (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
719                                                    FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
720                                                   pa_bytes_to_usec(u->read_block_size, &u->decoder_sample_spec));
721 }
722 
723 /* Run from I/O thread */
setup_stream(struct userdata * u)724 static int setup_stream(struct userdata *u) {
725     struct pollfd *pollfd;
726     int one;
727 
728     pa_assert(u->stream_fd >= 0);
729 
730     /* return if stream is already set up */
731     if (u->stream_setup_done)
732         return 0;
733 
734     pa_log_info("Transport %s resuming", u->transport->path);
735 
736     pa_assert(u->bt_codec);
737 
738     if (u->encoder_info) {
739         if (u->bt_codec->reset(u->encoder_info) < 0)
740             return -1;
741     }
742 
743     if (u->decoder_info) {
744         if (u->bt_codec->reset(u->decoder_info) < 0)
745             return -1;
746     }
747 
748     transport_config_mtu(u);
749 
750     pa_make_fd_nonblock(u->stream_fd);
751     pa_make_socket_low_delay(u->stream_fd);
752 
753     one = 1;
754     if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
755         pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
756 
757     pa_log_debug("Stream properly set up, we're ready to roll!");
758 
759     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
760     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
761     pollfd->fd = u->stream_fd;
762     pollfd->events = pollfd->revents = 0;
763 
764     u->read_index = u->write_index = 0;
765     u->started_at = 0;
766     u->stream_setup_done = true;
767 
768     if (u->source)
769 #ifdef USE_SMOOTHER_2
770         u->read_smoother = pa_smoother_2_new(5*PA_USEC_PER_SEC, pa_rtclock_now(), pa_frame_size(&u->decoder_sample_spec), u->decoder_sample_spec.rate);
771 #else
772         u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
773 #endif
774 
775     return 0;
776 }
777 
778 /* Called from I/O thread, returns true if the transport was acquired or
779  * a connection was requested successfully. */
setup_transport_and_stream(struct userdata * u)780 static bool setup_transport_and_stream(struct userdata *u) {
781     int transport_error;
782 
783     transport_error = transport_acquire(u, false);
784     if (transport_error < 0) {
785         if (transport_error != -EAGAIN)
786             return false;
787     } else {
788         if (setup_stream(u) < 0)
789             return false;
790     }
791     return true;
792 }
793 
794 /* Run from main thread */
sink_source_volume_changed_cb(void * hook_data,void * call_data,void * slot_data)795 static pa_hook_result_t sink_source_volume_changed_cb(void *hook_data, void *call_data, void *slot_data) {
796     struct userdata *u = slot_data;
797     const pa_cvolume *new_volume = NULL;
798     pa_volume_t volume;
799     pa_bluetooth_transport_set_volume_cb notify_volume_change;
800 
801     /* In the HS/HF role, notify the AG of a change in speaker/microphone gain.
802      * In the AG role the command to change HW volume on the remote is already
803      * sent by the hardware callback (if the peer supports it and the sink
804      * or source set_volume callback is attached. Otherwise nothing is sent).
805      */
806     pa_assert(pa_bluetooth_profile_should_attenuate_volume(u->profile));
807 
808     if (u->sink == call_data) {
809         new_volume = pa_sink_get_volume(u->sink, false);
810         notify_volume_change = u->transport->set_sink_volume;
811     } else if (u->source == call_data) {
812         new_volume = pa_source_get_volume(u->source, false);
813         notify_volume_change = u->transport->set_source_volume;
814     } else {
815         return PA_HOOK_OK;
816     }
817 
818     /* Volume control/notifications are optional */
819     if (!notify_volume_change)
820         return PA_HOOK_OK;
821 
822     volume = pa_cvolume_max(new_volume);
823 
824     notify_volume_change(u->transport, volume);
825 
826     return PA_HOOK_OK;
827 }
828 
829 /* Run from IO thread */
source_process_msg(pa_msgobject * o,int code,void * data,int64_t offset,pa_memchunk * chunk)830 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
831     struct userdata *u = PA_SOURCE(o)->userdata;
832 
833     pa_assert(u->source == PA_SOURCE(o));
834     pa_assert(u->transport);
835 
836     switch (code) {
837 
838         case PA_SOURCE_MESSAGE_GET_LATENCY: {
839 #ifndef USE_SMOOTHER_2
840             int64_t wi, ri;
841 #endif
842 
843             if (u->read_smoother) {
844 #ifdef USE_SMOOTHER_2
845                 *((int64_t*) data) = u->source->thread_info.fixed_latency - pa_smoother_2_get_delay(u->read_smoother, pa_rtclock_now(), u->read_index);
846 #else
847                 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
848                 ri = pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec);
849 
850                 *((int64_t*) data) = u->source->thread_info.fixed_latency + wi - ri;
851 #endif
852             } else
853                 *((int64_t*) data) = 0;
854 
855             return 0;
856         }
857 
858         case PA_SOURCE_MESSAGE_SETUP_STREAM:
859             /* Skip stream setup if stream_fd has been invalidated.
860                This can occur if the stream has already been set up and
861                then immediately received POLLHUP. If the stream has
862                already been set up earlier, then this setup_stream()
863                call is redundant anyway, but currently the code
864                is such that this kind of unnecessary setup_stream()
865                calls can happen. */
866             if (u->stream_fd < 0)
867                 pa_log_debug("Skip source stream setup while closing");
868             else
869                 setup_stream(u);
870             return 0;
871 
872     }
873 
874     return pa_source_process_msg(o, code, data, offset, chunk);
875 }
876 
877 /* Called from the IO thread. */
source_set_state_in_io_thread_cb(pa_source * s,pa_source_state_t new_state,pa_suspend_cause_t new_suspend_cause)878 static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
879     struct userdata *u;
880 
881     pa_assert(s);
882     pa_assert_se(u = s->userdata);
883 
884     switch (new_state) {
885 
886         case PA_SOURCE_SUSPENDED:
887             /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
888             if (!PA_SOURCE_IS_OPENED(s->thread_info.state))
889                 break;
890 
891             /* Stop the device if the sink is suspended as well */
892             if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
893                 transport_release(u);
894 
895             if (u->read_smoother)
896 #ifdef USE_SMOOTHER_2
897                 pa_smoother_2_pause(u->read_smoother, pa_rtclock_now());
898 #else
899                 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
900 #endif
901             break;
902 
903         case PA_SOURCE_IDLE:
904         case PA_SOURCE_RUNNING:
905             if (s->thread_info.state != PA_SOURCE_SUSPENDED)
906                 break;
907 
908             /* Resume the device if the sink was suspended as well */
909             if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state))
910                 if (!setup_transport_and_stream(u))
911                     return -1;
912 
913             /* We don't resume the smoother here. Instead we
914              * wait until the first packet arrives */
915 
916             break;
917 
918         case PA_SOURCE_UNLINKED:
919         case PA_SOURCE_INIT:
920         case PA_SOURCE_INVALID_STATE:
921             break;
922     }
923 
924     return 0;
925 }
926 
927 /* Run from main thread */
source_set_volume_cb(pa_source * s)928 static void source_set_volume_cb(pa_source *s) {
929     pa_volume_t volume;
930     struct userdata *u;
931 
932     pa_assert(s);
933     pa_assert(s->core);
934 
935     u = s->userdata;
936 
937     pa_assert(u);
938     pa_assert(u->source == s);
939     pa_assert(!pa_bluetooth_profile_should_attenuate_volume(u->profile));
940     pa_assert(u->transport);
941     pa_assert(u->transport->set_source_volume);
942 
943     /* In the AG role, send a command to change microphone gain on the HS/HF */
944     volume = u->transport->set_source_volume(u->transport, pa_cvolume_max(&s->real_volume));
945 
946     pa_cvolume_set(&s->real_volume, u->decoder_sample_spec.channels, volume);
947 }
948 
949 /* Run from main thread */
source_setup_volume_callback(pa_source * s)950 static void source_setup_volume_callback(pa_source *s) {
951     struct userdata *u;
952 
953     pa_assert(s);
954     pa_assert(s->core);
955 
956     u = s->userdata;
957     pa_assert(u);
958     pa_assert(u->source == s);
959     pa_assert(u->transport);
960 
961     if (pa_bluetooth_profile_is_a2dp(u->profile) && !u->transport->device->avrcp_absolute_volume)
962         return;
963 
964     /* Remote volume control has to be supported for the callback to make sense,
965      * otherwise this source should continue performing attenuation in software
966      * without HW_VOLUME_CTL.
967      * If the peer is an AG however backend-native unconditionally provides this
968      * function, PA in the role of HS/HF is responsible for signalling support
969      * by emitting an initial volume command.
970      * For A2DP bluez-util also unconditionally provides this function to keep
971      * the peer informed about volume changes.
972      */
973     if (!u->transport->set_source_volume)
974         return;
975 
976     if (pa_bluetooth_profile_should_attenuate_volume(u->profile)) {
977         if (u->source_volume_changed_slot)
978             return;
979 
980         pa_log_debug("%s: Attaching volume hook to notify peer of changes", s->name);
981 
982         u->source_volume_changed_slot = pa_hook_connect(&s->core->hooks[PA_CORE_HOOK_SOURCE_VOLUME_CHANGED],
983                                                         PA_HOOK_NORMAL, sink_source_volume_changed_cb, u);
984 
985         /* Send initial volume to peer, signalling support for volume control */
986         u->transport->set_source_volume(u->transport, pa_cvolume_max(&s->real_volume));
987     } else {
988         /* It is yet unknown how (if at all) volume is synchronized for bidirectional
989          * A2DP codecs.  Disallow attaching callbacks (and using HFP n_volume_steps)
990          * below to a pa_source if the peer is in A2DP_SINK role.  This assert should
991          * be replaced with the proper logic when bidirectional codecs are implemented.
992          */
993         pa_assert(u->profile != PA_BLUETOOTH_PROFILE_A2DP_SINK);
994 
995         if (s->set_volume == source_set_volume_cb)
996             return;
997 
998         pa_log_debug("%s: Resetting software volume for hardware attenuation by peer", s->name);
999 
1000         /* Reset local attenuation */
1001         pa_source_set_soft_volume(s, NULL);
1002 
1003         pa_source_set_set_volume_callback(s, source_set_volume_cb);
1004         s->n_volume_steps = HSP_MAX_GAIN + 1;
1005     }
1006 }
1007 
1008 /* Run from main thread */
add_source(struct userdata * u)1009 static int add_source(struct userdata *u) {
1010     pa_source_new_data data;
1011 
1012     pa_assert(u->transport);
1013 
1014     pa_source_new_data_init(&data);
1015     data.module = u->module;
1016     data.card = u->card;
1017     data.driver = __FILE__;
1018     data.name = pa_sprintf_malloc("bluez_source.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1019     data.namereg_fail = false;
1020     pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1021     if (u->bt_codec)
1022         pa_proplist_sets(data.proplist, PA_PROP_BLUETOOTH_CODEC, u->bt_codec->name);
1023     pa_source_new_data_set_sample_spec(&data, &u->decoder_sample_spec);
1024     if (u->profile == PA_BLUETOOTH_PROFILE_HSP_HS
1025         || u->profile == PA_BLUETOOTH_PROFILE_HFP_HF)
1026         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1027 
1028     connect_ports(u, &data, PA_DIRECTION_INPUT);
1029 
1030     if (!u->transport_acquired)
1031         switch (u->profile) {
1032             case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1033             case PA_BLUETOOTH_PROFILE_HFP_AG:
1034             case PA_BLUETOOTH_PROFILE_HSP_AG:
1035                 data.suspend_cause = PA_SUSPEND_USER;
1036                 break;
1037             case PA_BLUETOOTH_PROFILE_HSP_HS:
1038             case PA_BLUETOOTH_PROFILE_HFP_HF:
1039                 /* u->stream_fd contains the error returned by the last transport_acquire()
1040                  * EAGAIN means we are waiting for a NewConnection signal */
1041                 if (u->stream_fd == -EAGAIN)
1042                     data.suspend_cause = PA_SUSPEND_USER;
1043                 else
1044                     pa_assert_not_reached();
1045                 break;
1046             case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1047             case PA_BLUETOOTH_PROFILE_OFF:
1048                 pa_assert_not_reached();
1049                 break;
1050         }
1051 
1052     u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1053     pa_source_new_data_done(&data);
1054     if (!u->source) {
1055         pa_log_error("Failed to create source");
1056         return -1;
1057     }
1058 
1059     u->source->userdata = u;
1060     u->source->parent.process_msg = source_process_msg;
1061     u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
1062 
1063     source_setup_volume_callback(u->source);
1064 
1065     return 0;
1066 }
1067 
1068 /* Run from IO thread */
sink_process_msg(pa_msgobject * o,int code,void * data,int64_t offset,pa_memchunk * chunk)1069 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1070     struct userdata *u = PA_SINK(o)->userdata;
1071 
1072     pa_assert(u->sink == PA_SINK(o));
1073     pa_assert(u->transport);
1074 
1075     switch (code) {
1076 
1077         case PA_SINK_MESSAGE_GET_LATENCY: {
1078             int64_t wi, ri, delay = 0;
1079 
1080             if (u->read_smoother) {
1081 #ifdef USE_SMOOTHER_2
1082                 /* This is only used for SCO where encoder and decoder sample specs are
1083                  * equal and output timing is based on the source. Therefore we can pass
1084                  * the write index without conversion. */
1085                 delay = pa_smoother_2_get_delay(u->read_smoother, pa_rtclock_now(), u->write_index + u->write_block_size);
1086 #else
1087                 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1088                 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->encoder_sample_spec);
1089                 delay = wi - ri;
1090 #endif
1091             } else if (u->started_at) {
1092                 ri = pa_rtclock_now() - u->started_at;
1093                 wi = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1094                 delay = wi - ri;
1095             }
1096 
1097             *((int64_t*) data) = u->sink->thread_info.fixed_latency + delay;
1098 
1099             return 0;
1100         }
1101 
1102         case PA_SINK_MESSAGE_SETUP_STREAM:
1103             /* Skip stream setup if stream_fd has been invalidated.
1104                This can occur if the stream has already been set up and
1105                then immediately received POLLHUP. If the stream has
1106                already been set up earlier, then this setup_stream()
1107                call is redundant anyway, but currently the code
1108                is such that this kind of unnecessary setup_stream()
1109                calls can happen. */
1110             if (u->stream_fd < 0)
1111                 pa_log_debug("Skip sink stream setup while closing");
1112             else
1113                 setup_stream(u);
1114             return 0;
1115     }
1116 
1117     return pa_sink_process_msg(o, code, data, offset, chunk);
1118 }
1119 
1120 /* Called from the IO thread. */
sink_set_state_in_io_thread_cb(pa_sink * s,pa_sink_state_t new_state,pa_suspend_cause_t new_suspend_cause)1121 static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
1122     struct userdata *u;
1123 
1124     pa_assert(s);
1125     pa_assert_se(u = s->userdata);
1126 
1127     switch (new_state) {
1128 
1129         case PA_SINK_SUSPENDED:
1130             /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
1131             if (!PA_SINK_IS_OPENED(s->thread_info.state))
1132                 break;
1133 
1134             /* Stop the device if the source is suspended as well */
1135             if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
1136                 /* We deliberately ignore whether stopping
1137                  * actually worked. Since the stream_fd is
1138                  * closed it doesn't really matter */
1139                 transport_release(u);
1140 
1141             break;
1142 
1143         case PA_SINK_IDLE:
1144         case PA_SINK_RUNNING:
1145             if (s->thread_info.state != PA_SINK_SUSPENDED)
1146                 break;
1147 
1148             /* Resume the device if the source was suspended as well */
1149             if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state))
1150                 if (!setup_transport_and_stream(u))
1151                     return -1;
1152 
1153             break;
1154 
1155         case PA_SINK_UNLINKED:
1156         case PA_SINK_INIT:
1157         case PA_SINK_INVALID_STATE:
1158             break;
1159     }
1160 
1161     return 0;
1162 }
1163 
1164 /* Run from main thread */
sink_set_volume_cb(pa_sink * s)1165 static void sink_set_volume_cb(pa_sink *s) {
1166     pa_volume_t volume;
1167     struct userdata *u;
1168 
1169     pa_assert(s);
1170     pa_assert(s->core);
1171 
1172     u = s->userdata;
1173 
1174     pa_assert(u);
1175     pa_assert(u->sink == s);
1176     pa_assert(!pa_bluetooth_profile_should_attenuate_volume(u->profile));
1177     pa_assert(u->transport);
1178     pa_assert(u->transport->set_sink_volume);
1179 
1180     /* In the AG role, send a command to change speaker gain on the HS/HF */
1181     volume = u->transport->set_sink_volume(u->transport, pa_cvolume_max(&s->real_volume));
1182 
1183     pa_cvolume_set(&s->real_volume, u->encoder_sample_spec.channels, volume);
1184 }
1185 
1186 /* Run from main thread */
sink_setup_volume_callback(pa_sink * s)1187 static void sink_setup_volume_callback(pa_sink *s) {
1188     struct userdata *u;
1189 
1190     pa_assert(s);
1191     pa_assert(s->core);
1192 
1193     u = s->userdata;
1194     pa_assert(u);
1195     pa_assert(u->sink == s);
1196     pa_assert(u->transport);
1197 
1198     if (pa_bluetooth_profile_is_a2dp(u->profile) && !u->transport->device->avrcp_absolute_volume)
1199         return;
1200 
1201     /* Remote volume control has to be supported for the callback to make sense,
1202      * otherwise this sink should continue performing attenuation in software
1203      * without HW_VOLUME_CTL.
1204      * If the peer is an AG however backend-native unconditionally provides this
1205      * function, PA in the role of HS/HF is responsible for signalling support
1206      * by emitting an initial volume command.
1207      */
1208     if (!u->transport->set_sink_volume)
1209         return;
1210 
1211     if (pa_bluetooth_profile_should_attenuate_volume(u->profile)) {
1212         /* It is yet unknown how (if at all) volume is synchronized for bidirectional
1213          * A2DP codecs.  Disallow attaching hooks to a pa_sink if the peer is in
1214          * A2DP_SOURCE role.  This assert should be replaced with the proper logic
1215          * when bidirectional codecs are implemented.
1216          */
1217         pa_assert(u->profile != PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
1218 
1219         if (u->sink_volume_changed_slot)
1220             return;
1221 
1222         pa_log_debug("%s: Attaching volume hook to notify peer of changes", s->name);
1223 
1224         u->sink_volume_changed_slot = pa_hook_connect(&s->core->hooks[PA_CORE_HOOK_SINK_VOLUME_CHANGED],
1225                                                       PA_HOOK_NORMAL, sink_source_volume_changed_cb, u);
1226 
1227         /* Send initial volume to peer, signalling support for volume control */
1228         u->transport->set_sink_volume(u->transport, pa_cvolume_max(&s->real_volume));
1229     } else {
1230         if (s->set_volume == sink_set_volume_cb)
1231             return;
1232 
1233         pa_log_debug("%s: Resetting software volume for hardware attenuation by peer", s->name);
1234 
1235         /* Reset local attenuation */
1236         pa_sink_set_soft_volume(s, NULL);
1237 
1238         pa_sink_set_set_volume_callback(s, sink_set_volume_cb);
1239 
1240         if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK)
1241             s->n_volume_steps = A2DP_MAX_GAIN + 1;
1242         else
1243             s->n_volume_steps = HSP_MAX_GAIN + 1;
1244     }
1245 }
1246 
1247 /* Run from main thread */
add_sink(struct userdata * u)1248 static int add_sink(struct userdata *u) {
1249     pa_sink_new_data data;
1250 
1251     pa_assert(u->transport);
1252 
1253     pa_sink_new_data_init(&data);
1254     data.module = u->module;
1255     data.card = u->card;
1256     data.driver = __FILE__;
1257     data.name = pa_sprintf_malloc("bluez_sink.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1258     data.namereg_fail = false;
1259     pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1260     if (u->bt_codec)
1261         pa_proplist_sets(data.proplist, PA_PROP_BLUETOOTH_CODEC, u->bt_codec->name);
1262     pa_sink_new_data_set_sample_spec(&data, &u->encoder_sample_spec);
1263     if (u->profile == PA_BLUETOOTH_PROFILE_HSP_HS
1264         || u->profile == PA_BLUETOOTH_PROFILE_HFP_HF)
1265         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1266 
1267     connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1268 
1269     if (!u->transport_acquired)
1270         switch (u->profile) {
1271             case PA_BLUETOOTH_PROFILE_HFP_AG:
1272             case PA_BLUETOOTH_PROFILE_HSP_AG:
1273                 data.suspend_cause = PA_SUSPEND_USER;
1274                 break;
1275             case PA_BLUETOOTH_PROFILE_HSP_HS:
1276             case PA_BLUETOOTH_PROFILE_HFP_HF:
1277                 /* u->stream_fd contains the error returned by the last transport_acquire()
1278                  * EAGAIN means we are waiting for a NewConnection signal */
1279                 if (u->stream_fd == -EAGAIN)
1280                     data.suspend_cause = PA_SUSPEND_USER;
1281                 else
1282                     pa_assert_not_reached();
1283                 break;
1284             case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1285                 /* Profile switch should have failed */
1286             case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1287             case PA_BLUETOOTH_PROFILE_OFF:
1288                 pa_assert_not_reached();
1289                 break;
1290         }
1291 
1292     u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1293     pa_sink_new_data_done(&data);
1294     if (!u->sink) {
1295         pa_log_error("Failed to create sink");
1296         return -1;
1297     }
1298 
1299     u->sink->userdata = u;
1300     u->sink->parent.process_msg = sink_process_msg;
1301     u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
1302 
1303     sink_setup_volume_callback(u->sink);
1304 
1305     return 0;
1306 }
1307 
1308 /* Run from main thread */
get_profile_direction(pa_bluetooth_profile_t p)1309 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1310     static const pa_direction_t profile_direction[] = {
1311         [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1312         [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1313         [PA_BLUETOOTH_PROFILE_HSP_HS] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1314         [PA_BLUETOOTH_PROFILE_HSP_AG] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1315         [PA_BLUETOOTH_PROFILE_HFP_HF] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1316         [PA_BLUETOOTH_PROFILE_HFP_AG] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1317         [PA_BLUETOOTH_PROFILE_OFF] = 0
1318     };
1319 
1320     return profile_direction[p];
1321 }
1322 
1323 /* Run from main thread */
transport_config(struct userdata * u)1324 static int transport_config(struct userdata *u) {
1325     pa_assert(u);
1326     pa_assert(u->transport);
1327     pa_assert(!u->bt_codec);
1328     pa_assert(!u->encoder_info);
1329     pa_assert(!u->decoder_info);
1330 
1331     u->bt_codec = u->transport->bt_codec;
1332     pa_assert(u->bt_codec);
1333 
1334     /* reset encoder buffer contents */
1335     u->encoder_buffer_used = 0;
1336 
1337     if (get_profile_direction(u->profile) & PA_DIRECTION_OUTPUT) {
1338         u->encoder_info = u->bt_codec->init(true, false, u->transport->config, u->transport->config_size, &u->encoder_sample_spec, u->core);
1339 
1340         if (!u->encoder_info)
1341             return -1;
1342     }
1343 
1344     if (get_profile_direction(u->profile) & PA_DIRECTION_INPUT) {
1345         u->decoder_info = u->bt_codec->init(false, false, u->transport->config, u->transport->config_size, &u->decoder_sample_spec, u->core);
1346 
1347         if (!u->decoder_info) {
1348             if (u->encoder_info) {
1349                 u->bt_codec->deinit(u->encoder_info);
1350                 u->encoder_info = NULL;
1351             }
1352             return -1;
1353         }
1354     }
1355 
1356     return 0;
1357 }
1358 
1359 /* Run from main thread */
setup_transport(struct userdata * u)1360 static int setup_transport(struct userdata *u) {
1361     pa_bluetooth_transport *t;
1362 
1363     pa_assert(u);
1364     pa_assert(!u->transport);
1365     pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1366 
1367     /* check if profile has a transport */
1368     t = u->device->transports[u->profile];
1369     if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1370         pa_log_warn("Profile %s has no transport", pa_bluetooth_profile_to_string(u->profile));
1371         return -1;
1372     }
1373 
1374     u->transport = t;
1375 
1376     if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HFP_AG || u->profile == PA_BLUETOOTH_PROFILE_HSP_AG)
1377         transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1378     else {
1379         int transport_error;
1380 
1381         transport_error = transport_acquire(u, false);
1382         if (transport_error < 0 && transport_error != -EAGAIN)
1383             return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1384     }
1385 
1386     return transport_config(u);
1387 }
1388 
1389 /* Run from main thread */
init_profile(struct userdata * u)1390 static int init_profile(struct userdata *u) {
1391     int r = 0;
1392     pa_assert(u);
1393     pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1394 
1395     r = setup_transport(u);
1396     if (r == -EINPROGRESS)
1397         return 0;
1398     else if (r < 0)
1399         return -1;
1400 
1401     pa_assert(u->transport);
1402 
1403     if (get_profile_direction (u->profile) & PA_DIRECTION_OUTPUT)
1404         if (add_sink(u) < 0)
1405             r = -1;
1406 
1407     if (get_profile_direction (u->profile) & PA_DIRECTION_INPUT)
1408         if (add_source(u) < 0)
1409             r = -1;
1410 
1411     return r;
1412 }
1413 
bt_render_block(struct userdata * u)1414 static int bt_render_block(struct userdata *u) {
1415     int n_rendered;
1416 
1417     if (u->write_index <= 0)
1418         u->started_at = pa_rtclock_now();
1419 
1420     n_rendered = bt_process_render(u);
1421 
1422     if (n_rendered < 0)
1423         n_rendered = -1;
1424 
1425     return n_rendered;
1426 }
1427 
1428 /* I/O thread function */
thread_func(void * userdata)1429 static void thread_func(void *userdata) {
1430     struct userdata *u = userdata;
1431     unsigned blocks_to_write = 0;
1432     unsigned bytes_to_write = 0;
1433     struct timeval tv_last_output_rate_change;
1434 
1435     pa_assert(u);
1436     pa_assert(u->transport);
1437 
1438     pa_log_debug("IO Thread starting up");
1439 
1440     if (u->core->realtime_scheduling)
1441         pa_thread_make_realtime(u->core->realtime_priority);
1442 
1443     pa_thread_mq_install(&u->thread_mq);
1444 
1445     /* Setup the stream only if the transport was already acquired */
1446     if (u->transport_acquired)
1447         setup_stream(u);
1448 
1449     pa_gettimeofday(&tv_last_output_rate_change);
1450 
1451     for (;;) {
1452         struct pollfd *pollfd;
1453         int ret;
1454         bool disable_timer = true;
1455         bool writable = false;
1456         bool have_source = u->source ? PA_SOURCE_IS_LINKED(u->source->thread_info.state) : false;
1457         bool have_sink = u->sink ? PA_SINK_IS_LINKED(u->sink->thread_info.state) : false;
1458 
1459         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1460 
1461         /* Check for stream error or close */
1462         if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1463             pa_log_info("FD error: %s%s%s%s",
1464                         pollfd->revents & POLLERR ? "POLLERR " :"",
1465                         pollfd->revents & POLLHUP ? "POLLHUP " :"",
1466                         pollfd->revents & POLLPRI ? "POLLPRI " :"",
1467                         pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1468 
1469             if (pollfd->revents & POLLHUP) {
1470                 pollfd = NULL;
1471                 teardown_stream(u);
1472                 blocks_to_write = 0;
1473                 bytes_to_write = 0;
1474                 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
1475             } else
1476                 goto fail;
1477         }
1478 
1479         /* If there is a pollfd, the stream is set up and we need to do something */
1480         if (pollfd) {
1481 
1482             /* Handle source if present */
1483             if (have_source) {
1484 
1485                 /* We should send two blocks to the device before we expect a response. */
1486                 if (have_sink && u->write_index == 0 && u->read_index <= 0)
1487                     blocks_to_write = 2;
1488 
1489                 /* If we got woken up by POLLIN let's do some reading */
1490                 if (pollfd->revents & POLLIN) {
1491                     int n_read;
1492 
1493                     n_read = bt_process_push(u);
1494 
1495                     if (n_read < 0)
1496                         goto fail;
1497 
1498                     if (have_sink && n_read > 0) {
1499                         /* We just read something, so we are supposed to write something, too
1500                          *
1501                          * If source and sink sample specifications are not equal,
1502                          * expected write size needs to be adjusted accordingly.
1503                          */
1504                         if (pa_sample_spec_equal(&u->encoder_sample_spec, &u->decoder_sample_spec))
1505                             bytes_to_write += n_read;
1506                         else
1507                             bytes_to_write += pa_usec_to_bytes(pa_bytes_to_usec(n_read, &u->decoder_sample_spec), &u->encoder_sample_spec);
1508                         blocks_to_write += bytes_to_write / u->write_block_size;
1509                         bytes_to_write = bytes_to_write % u->write_block_size;
1510                     }
1511                 }
1512             }
1513 
1514             /* Handle sink if present */
1515             if (have_sink) {
1516 
1517                 /* Process rewinds */
1518                 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1519                     pa_sink_process_rewind(u->sink, 0);
1520 
1521                 /* Test if the stream is writable */
1522                 if (pollfd->revents & POLLOUT)
1523                     writable = true;
1524 
1525                 /* If we have a source, we let the source determine the timing
1526                  * for the sink */
1527                 if (have_source) {
1528 
1529                     /* If the stream is writable, send some data if necessary */
1530                     if (writable) {
1531                         int result;
1532 
1533                         if (blocks_to_write > 0) {
1534                             result = bt_render_block(u);
1535                             if (result < 0)
1536                                 goto fail;
1537                             blocks_to_write -= result;
1538                         }
1539 
1540                         result = bt_write_buffer(u);
1541 
1542                         if (result < 0)
1543                             goto fail;
1544 
1545                         if (result)
1546                             writable = false;
1547                     }
1548 
1549                     /* writable controls whether we set POLLOUT when polling - we set it to
1550                      * false to enable POLLOUT. If there are more blocks to write, we want to
1551                      * be woken up immediately when the socket becomes writable. If there
1552                      * aren't currently any more blocks to write, then we'll have to wait
1553                      * until we've received more data, so in that case we only want to set
1554                      * POLLIN. Note that when we are woken up the next time, POLLOUT won't be
1555                      * set in revents even if the socket has meanwhile become writable, which
1556                      * may seem bad, but in that case we'll set POLLOUT in the subsequent
1557                      * poll, and the poll will return immediately, so our writes won't be
1558                      * delayed. */
1559                     if (blocks_to_write > 0)
1560                         writable = false;
1561 
1562                 /* There is no source, we have to use the system clock for timing */
1563                 } else {
1564                     bool have_written = false;
1565                     pa_usec_t time_passed = 0;
1566                     pa_usec_t audio_sent = 0;
1567 
1568                     if (u->started_at) {
1569                         time_passed = pa_rtclock_now() - u->started_at;
1570                         audio_sent = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1571                     }
1572 
1573                     /* A new block needs to be sent. */
1574                     if (audio_sent <= time_passed) {
1575                         size_t bytes_to_send = pa_usec_to_bytes(time_passed - audio_sent, &u->encoder_sample_spec);
1576 
1577                         /* There are more than two blocks that need to be written. It seems that
1578                          * the socket has not been accepting data fast enough (could be due to
1579                          * hiccups in the wireless transmission). We need to discard everything
1580                          * older than two block sizes to keep the latency from growing. */
1581                         if (bytes_to_send > 2 * u->write_block_size) {
1582                             uint64_t skip_bytes;
1583                             pa_memchunk tmp;
1584                             size_t max_render_size = pa_frame_align(pa_mempool_block_size_max(u->core->mempool), &u->encoder_sample_spec);
1585                             pa_usec_t skip_usec;
1586 
1587                             skip_bytes = bytes_to_send - 2 * u->write_block_size;
1588                             skip_usec = pa_bytes_to_usec(skip_bytes, &u->encoder_sample_spec);
1589 
1590                             pa_log_debug("Skipping %llu us (= %llu bytes) in audio stream",
1591                                         (unsigned long long) skip_usec,
1592                                         (unsigned long long) skip_bytes);
1593 
1594                             while (skip_bytes > 0) {
1595                                 size_t bytes_to_render;
1596 
1597                                 if (skip_bytes > max_render_size)
1598                                     bytes_to_render = max_render_size;
1599                                 else
1600                                     bytes_to_render = skip_bytes;
1601 
1602                                 pa_sink_render_full(u->sink, bytes_to_render, &tmp);
1603                                 pa_memblock_unref(tmp.memblock);
1604                                 u->write_index += bytes_to_render;
1605                                 skip_bytes -= bytes_to_render;
1606                             }
1607 
1608                             if (u->write_index > 0 && (get_profile_direction(u->profile) & PA_DIRECTION_OUTPUT)) {
1609                                 size_t new_write_block_size = u->bt_codec->reduce_encoder_bitrate(u->encoder_info, u->write_link_mtu);
1610                                 if (new_write_block_size) {
1611                                     u->write_block_size = new_write_block_size;
1612                                     handle_sink_block_size_change(u);
1613                                 }
1614                                 pa_gettimeofday(&tv_last_output_rate_change);
1615                             }
1616                         }
1617 
1618                         blocks_to_write = 1;
1619                     }
1620 
1621                     /* If the stream is writable, send some data if necessary */
1622                     if (writable) {
1623                         int result;
1624 
1625                         if (blocks_to_write > 0) {
1626                             int result = bt_render_block(u);
1627                             if (result < 0)
1628                                 goto fail;
1629                             blocks_to_write -= result;
1630                         }
1631 
1632                         result = bt_write_buffer(u);
1633 
1634                         if (result < 0)
1635                             goto fail;
1636 
1637                         if (result) {
1638                             writable = false;
1639                             have_written = true;
1640                         }
1641                     }
1642 
1643                     /* If nothing was written during this iteration, either the stream
1644                      * is not writable or there was no write pending. Set up a timer that
1645                      * will wake up the thread when the next data needs to be written. */
1646                     if (!have_written) {
1647                         pa_usec_t sleep_for;
1648                         pa_usec_t next_write_at;
1649 
1650                         if (writable) {
1651                             /* There was no write pending on this iteration of the loop.
1652                              * Let's estimate when we need to wake up next */
1653                             next_write_at = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1654                             sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1655                             /* pa_log("Sleeping for %lu; time passed %lu, next write at %lu", (unsigned long) sleep_for, (unsigned long) time_passed, (unsigned long)next_write_at); */
1656 
1657                             if ((get_profile_direction(u->profile) & PA_DIRECTION_OUTPUT) && u->write_memchunk.memblock == NULL) {
1658                                 /* bt_write_buffer() is keeping up with input, try increasing bitrate */
1659                                 if (u->bt_codec->increase_encoder_bitrate
1660                                     && pa_timeval_age(&tv_last_output_rate_change) >= u->device->output_rate_refresh_interval_ms * PA_USEC_PER_MSEC) {
1661                                     size_t new_write_block_size = u->bt_codec->increase_encoder_bitrate(u->encoder_info, u->write_link_mtu);
1662                                     if (new_write_block_size) {
1663                                         u->write_block_size = new_write_block_size;
1664                                         handle_sink_block_size_change(u);
1665                                     }
1666                                     pa_gettimeofday(&tv_last_output_rate_change);
1667                                 }
1668                             }
1669                         } else
1670                             /* We could not write because the stream was not ready. Let's try
1671                              * again in 500 ms and drop audio if we still can't write. The
1672                              * thread will also be woken up when we can write again. */
1673                             sleep_for = PA_USEC_PER_MSEC * 500;
1674 
1675                         pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1676                         disable_timer = false;
1677                     }
1678                 }
1679             }
1680 
1681             /* Set events to wake up the thread */
1682             pollfd->events = (short) (((have_sink && !writable) ? POLLOUT : 0) | (have_source ? POLLIN : 0));
1683 
1684         }
1685 
1686         if (disable_timer)
1687             pa_rtpoll_set_timer_disabled(u->rtpoll);
1688 
1689         if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1690             pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1691             goto fail;
1692         }
1693 
1694         if (ret == 0) {
1695             pa_log_debug("IO thread shutdown requested, stopping cleanly");
1696             transport_release(u);
1697             goto finish;
1698         }
1699     }
1700 
1701 fail:
1702     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1703     pa_log_debug("IO thread failed");
1704     pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1705     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1706 
1707 finish:
1708     pa_log_debug("IO thread shutting down");
1709 }
1710 
1711 /* Run from main thread */
start_thread(struct userdata * u)1712 static int start_thread(struct userdata *u) {
1713     pa_assert(u);
1714     pa_assert(!u->thread);
1715     pa_assert(!u->rtpoll);
1716     pa_assert(!u->rtpoll_item);
1717 
1718     u->rtpoll = pa_rtpoll_new();
1719 
1720     if (pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll) < 0) {
1721         pa_log("pa_thread_mq_init() failed.");
1722         return -1;
1723     }
1724 
1725     if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1726         pa_log_error("Failed to create IO thread");
1727         return -1;
1728     }
1729 
1730     if (u->sink) {
1731         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1732         pa_sink_set_rtpoll(u->sink, u->rtpoll);
1733 
1734         /* If we are in the headset role, the sink should not become default
1735          * unless there is no other sound device available. */
1736         if (u->profile == PA_BLUETOOTH_PROFILE_HFP_AG || u->profile == PA_BLUETOOTH_PROFILE_HSP_AG)
1737             u->sink->priority = 1500;
1738 
1739         pa_sink_put(u->sink);
1740 
1741         if (u->sink->set_volume)
1742             u->sink->set_volume(u->sink);
1743     }
1744 
1745     if (u->source) {
1746         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1747         pa_source_set_rtpoll(u->source, u->rtpoll);
1748 
1749         /* If we are in the headset role or the device is an a2dp source,
1750          * the source should not become default unless there is no other
1751          * sound device available. */
1752         if (u->profile == PA_BLUETOOTH_PROFILE_HFP_AG || u->profile == PA_BLUETOOTH_PROFILE_HSP_AG || u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1753             u->source->priority = 1500;
1754 
1755         pa_source_put(u->source);
1756 
1757         if (u->source->set_volume)
1758             u->source->set_volume(u->source);
1759     }
1760 
1761     if (u->sink || u->source)
1762         if (u->bt_codec)
1763             pa_proplist_sets(u->card->proplist, PA_PROP_BLUETOOTH_CODEC, u->bt_codec->name);
1764 
1765     /* Now that everything is set up we are ready to check for the Volume property.
1766      * Sometimes its initial "change" notification arrives too early when the sink
1767      * is not available or still in UNLINKED state; check it again here to know if
1768      * our sink peer supports Absolute Volume; in that case we should not perform
1769      * any attenuation but delegate all set_volume calls to the peer through this
1770      * Volume property.
1771      *
1772      * Note that this works the other way around if the peer is in source profile:
1773      * we are rendering audio and hence responsible for applying attenuation.  The
1774      * set_volume callback is always registered, and Volume is always passed to
1775      * BlueZ unconditionally.  BlueZ only sends a notification to the peer if it
1776      * registered a notification request for absolute volume previously.
1777      */
1778     if (u->transport && u->sink)
1779         pa_bluetooth_transport_load_a2dp_sink_volume(u->transport);
1780 
1781     return 0;
1782 }
1783 
1784 /* Run from main thread */
stop_thread(struct userdata * u)1785 static void stop_thread(struct userdata *u) {
1786     pa_assert(u);
1787 
1788     if (u->sink || u->source)
1789         pa_proplist_unset(u->card->proplist, PA_PROP_BLUETOOTH_CODEC);
1790 
1791     if (u->sink)
1792         pa_sink_unlink(u->sink);
1793 
1794     if (u->source)
1795         pa_source_unlink(u->source);
1796 
1797     if (u->thread) {
1798         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1799         pa_thread_free(u->thread);
1800         u->thread = NULL;
1801     }
1802 
1803     if (u->rtpoll_item) {
1804         pa_rtpoll_item_free(u->rtpoll_item);
1805         u->rtpoll_item = NULL;
1806     }
1807 
1808     if (u->rtpoll) {
1809         pa_rtpoll_free(u->rtpoll);
1810         u->rtpoll = NULL;
1811         pa_thread_mq_done(&u->thread_mq);
1812     }
1813 
1814     if (u->transport) {
1815         transport_release(u);
1816         u->transport = NULL;
1817     }
1818 
1819     if (u->sink_volume_changed_slot) {
1820         pa_hook_slot_free(u->sink_volume_changed_slot);
1821         u->sink_volume_changed_slot = NULL;
1822     }
1823 
1824     if (u->source_volume_changed_slot) {
1825         pa_hook_slot_free(u->source_volume_changed_slot);
1826         u->source_volume_changed_slot = NULL;
1827     }
1828 
1829     if (u->sink) {
1830         pa_sink_unref(u->sink);
1831         u->sink = NULL;
1832     }
1833 
1834     if (u->source) {
1835         pa_source_unref(u->source);
1836         u->source = NULL;
1837     }
1838 
1839     if (u->read_smoother) {
1840 #ifdef USE_SMOOTHER_2
1841         pa_smoother_2_free(u->read_smoother);
1842 #else
1843         pa_smoother_free(u->read_smoother);
1844 #endif
1845         u->read_smoother = NULL;
1846     }
1847 
1848     if (u->bt_codec) {
1849         if (u->encoder_info) {
1850             u->bt_codec->deinit(u->encoder_info);
1851             u->encoder_info = NULL;
1852         }
1853 
1854         if (u->decoder_info) {
1855             u->bt_codec->deinit(u->decoder_info);
1856             u->decoder_info = NULL;
1857         }
1858 
1859         u->bt_codec = NULL;
1860     }
1861 
1862     if (u->encoder_buffer) {
1863         pa_xfree(u->encoder_buffer);
1864         u->encoder_buffer = NULL;
1865     }
1866 
1867     u->encoder_buffer_size = 0;
1868     u->encoder_buffer_used = 0;
1869 
1870     if (u->decoder_buffer) {
1871         pa_xfree(u->decoder_buffer);
1872         u->decoder_buffer = NULL;
1873     }
1874 
1875     u->decoder_buffer_size = 0;
1876 }
1877 
1878 /* Run from main thread */
get_port_availability(struct userdata * u,pa_direction_t direction)1879 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1880     pa_available_t result = PA_AVAILABLE_NO;
1881     unsigned i;
1882 
1883     pa_assert(u);
1884     pa_assert(u->device);
1885 
1886     for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1887         pa_bluetooth_transport *transport;
1888 
1889         if (!(get_profile_direction(i) & direction))
1890             continue;
1891 
1892         if (!(transport = u->device->transports[i]))
1893             continue;
1894 
1895         switch(transport->state) {
1896             case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1897                 continue;
1898 
1899             case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1900                 if (result == PA_AVAILABLE_NO)
1901                     result = PA_AVAILABLE_UNKNOWN;
1902 
1903                 break;
1904 
1905             case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1906                 return PA_AVAILABLE_YES;
1907         }
1908     }
1909 
1910     return result;
1911 }
1912 
1913 /* Run from main thread */
transport_state_to_availability(pa_bluetooth_transport_state_t state)1914 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1915     switch (state) {
1916         case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1917             return PA_AVAILABLE_NO;
1918         case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1919             return PA_AVAILABLE_YES;
1920         default:
1921             return PA_AVAILABLE_UNKNOWN;
1922     }
1923 }
1924 
1925 /* Run from main thread */
create_card_ports(struct userdata * u,pa_hashmap * ports)1926 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1927     pa_device_port *port;
1928     pa_device_port_new_data port_data;
1929     pa_device_port_type_t input_type, output_type;
1930     const char *name_prefix, *input_description, *output_description;
1931 
1932     pa_assert(u);
1933     pa_assert(ports);
1934     pa_assert(u->device);
1935 
1936     name_prefix = "unknown";
1937     input_description = _("Bluetooth Input");
1938     output_description = _("Bluetooth Output");
1939     input_type = output_type = PA_DEVICE_PORT_TYPE_BLUETOOTH;
1940 
1941     switch (form_factor_from_class(u->device->class_of_device)) {
1942         case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1943             name_prefix = "headset";
1944             input_description = output_description = _("Headset");
1945             input_type = output_type = PA_DEVICE_PORT_TYPE_HEADSET;
1946             break;
1947 
1948         case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1949             name_prefix = "handsfree";
1950             input_description = output_description = _("Handsfree");
1951             input_type = output_type = PA_DEVICE_PORT_TYPE_HANDSFREE;
1952             break;
1953 
1954         case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1955             name_prefix = "microphone";
1956             input_description = _("Microphone");
1957             output_description = _("Bluetooth Output");
1958             input_type = PA_DEVICE_PORT_TYPE_MIC;
1959             break;
1960 
1961         case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1962             name_prefix = "speaker";
1963             input_description = _("Bluetooth Input");
1964             output_description = _("Speaker");
1965             output_type = PA_DEVICE_PORT_TYPE_SPEAKER;
1966             break;
1967 
1968         case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1969             name_prefix = "headphone";
1970             input_description = _("Bluetooth Input");
1971             output_description = _("Headphone");
1972             output_type = PA_DEVICE_PORT_TYPE_HEADPHONES;
1973             break;
1974 
1975         case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1976             name_prefix = "portable";
1977             input_description = output_description = _("Portable");
1978             input_type = output_type = PA_DEVICE_PORT_TYPE_PORTABLE;
1979             break;
1980 
1981         case PA_BLUETOOTH_FORM_FACTOR_CAR:
1982             name_prefix = "car";
1983             input_description = output_description = _("Car");
1984             input_type = output_type = PA_DEVICE_PORT_TYPE_CAR;
1985             break;
1986 
1987         case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1988             name_prefix = "hifi";
1989             input_description = output_description = _("HiFi");
1990             input_type = output_type = PA_DEVICE_PORT_TYPE_HIFI;
1991             break;
1992 
1993         case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1994             name_prefix = "phone";
1995             input_description = output_description = _("Phone");
1996             input_type = output_type = PA_DEVICE_PORT_TYPE_PHONE;
1997             break;
1998 
1999         case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
2000             break;
2001     }
2002 
2003     u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
2004     pa_device_port_new_data_init(&port_data);
2005     pa_device_port_new_data_set_name(&port_data, u->output_port_name);
2006     pa_device_port_new_data_set_description(&port_data, output_description);
2007     pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
2008     pa_device_port_new_data_set_type(&port_data, output_type);
2009     pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
2010     pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2011     pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2012     pa_device_port_new_data_done(&port_data);
2013 
2014     u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
2015     pa_device_port_new_data_init(&port_data);
2016     pa_device_port_new_data_set_name(&port_data, u->input_port_name);
2017     pa_device_port_new_data_set_description(&port_data, input_description);
2018     pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
2019     pa_device_port_new_data_set_type(&port_data, input_type);
2020     pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
2021     pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
2022     pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
2023     pa_device_port_new_data_done(&port_data);
2024 }
2025 
2026 /* Run from main thread */
create_card_profile(struct userdata * u,pa_bluetooth_profile_t profile,pa_hashmap * ports)2027 static pa_card_profile *create_card_profile(struct userdata *u, pa_bluetooth_profile_t profile, pa_hashmap *ports) {
2028     pa_device_port *input_port, *output_port;
2029     const char *name;
2030     pa_card_profile *cp = NULL;
2031     pa_bluetooth_profile_t *p;
2032 
2033     pa_assert(u->input_port_name);
2034     pa_assert(u->output_port_name);
2035     pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
2036     pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
2037 
2038     name = pa_bluetooth_profile_to_string(profile);
2039 
2040     switch (profile) {
2041     case PA_BLUETOOTH_PROFILE_A2DP_SINK:
2042         cp = pa_card_profile_new(name, _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
2043         cp->priority = 40;
2044         cp->n_sinks = 1;
2045         cp->n_sources = 0;
2046         cp->max_sink_channels = 2;
2047         cp->max_source_channels = 0;
2048         pa_hashmap_put(output_port->profiles, cp->name, cp);
2049 
2050         p = PA_CARD_PROFILE_DATA(cp);
2051         break;
2052 
2053     case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
2054         cp = pa_card_profile_new(name, _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
2055         cp->priority = 20;
2056         cp->n_sinks = 0;
2057         cp->n_sources = 1;
2058         cp->max_sink_channels = 0;
2059         cp->max_source_channels = 2;
2060         pa_hashmap_put(input_port->profiles, cp->name, cp);
2061 
2062         p = PA_CARD_PROFILE_DATA(cp);
2063         break;
2064 
2065     case PA_BLUETOOTH_PROFILE_HSP_HS:
2066         cp = pa_card_profile_new(name, _("Headset Head Unit (HSP)"), sizeof(pa_bluetooth_profile_t));
2067         cp->priority = 30;
2068         cp->n_sinks = 1;
2069         cp->n_sources = 1;
2070         cp->max_sink_channels = 1;
2071         cp->max_source_channels = 1;
2072         pa_hashmap_put(input_port->profiles, cp->name, cp);
2073         pa_hashmap_put(output_port->profiles, cp->name, cp);
2074 
2075         p = PA_CARD_PROFILE_DATA(cp);
2076         break;
2077 
2078     case PA_BLUETOOTH_PROFILE_HSP_AG:
2079         cp = pa_card_profile_new(name, _("Headset Audio Gateway (HSP)"), sizeof(pa_bluetooth_profile_t));
2080         cp->priority = 10;
2081         cp->n_sinks = 1;
2082         cp->n_sources = 1;
2083         cp->max_sink_channels = 1;
2084         cp->max_source_channels = 1;
2085         pa_hashmap_put(input_port->profiles, cp->name, cp);
2086         pa_hashmap_put(output_port->profiles, cp->name, cp);
2087 
2088         p = PA_CARD_PROFILE_DATA(cp);
2089         break;
2090 
2091     case PA_BLUETOOTH_PROFILE_HFP_HF:
2092          cp = pa_card_profile_new(name, _("Handsfree Head Unit (HFP)"), sizeof(pa_bluetooth_profile_t));
2093         cp->priority = 30;
2094         cp->n_sinks = 1;
2095         cp->n_sources = 1;
2096         cp->max_sink_channels = 1;
2097         cp->max_source_channels = 1;
2098         pa_hashmap_put(input_port->profiles, cp->name, cp);
2099         pa_hashmap_put(output_port->profiles, cp->name, cp);
2100 
2101         p = PA_CARD_PROFILE_DATA(cp);
2102         break;
2103 
2104     case PA_BLUETOOTH_PROFILE_HFP_AG:
2105         cp = pa_card_profile_new(name, _("Handsfree Audio Gateway (HFP)"), sizeof(pa_bluetooth_profile_t));
2106         cp->priority = 10;
2107         cp->n_sinks = 1;
2108         cp->n_sources = 1;
2109         cp->max_sink_channels = 1;
2110         cp->max_source_channels = 1;
2111         pa_hashmap_put(input_port->profiles, cp->name, cp);
2112         pa_hashmap_put(output_port->profiles, cp->name, cp);
2113 
2114         p = PA_CARD_PROFILE_DATA(cp);
2115         break;
2116 
2117     case PA_BLUETOOTH_PROFILE_OFF:
2118         pa_assert_not_reached();
2119     }
2120 
2121     *p = profile;
2122 
2123     if (u->device->transports[*p])
2124         cp->available = transport_state_to_availability(u->device->transports[*p]->state);
2125     else
2126         cp->available = PA_AVAILABLE_NO;
2127 
2128     return cp;
2129 }
2130 
2131 /* Run from main thread */
set_profile_cb(pa_card * c,pa_card_profile * new_profile)2132 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
2133     struct userdata *u;
2134     pa_bluetooth_profile_t *p;
2135 
2136     pa_assert(c);
2137     pa_assert(new_profile);
2138     pa_assert_se(u = c->userdata);
2139 
2140     p = PA_CARD_PROFILE_DATA(new_profile);
2141 
2142     if (*p != PA_BLUETOOTH_PROFILE_OFF) {
2143         const pa_bluetooth_device *d = u->device;
2144 
2145         if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
2146             pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
2147             return -PA_ERR_IO;
2148         }
2149     }
2150 
2151     stop_thread(u);
2152 
2153     u->profile = *p;
2154 
2155     if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2156         if (init_profile(u) < 0)
2157             goto off;
2158 
2159     if (u->sink || u->source)
2160         if (start_thread(u) < 0)
2161             goto off;
2162 
2163     return 0;
2164 
2165 off:
2166     stop_thread(u);
2167 
2168     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2169 
2170     return -PA_ERR_IO;
2171 }
2172 
uuid_to_profile(const char * uuid,pa_bluetooth_profile_t * _r)2173 static int uuid_to_profile(const char *uuid, pa_bluetooth_profile_t *_r) {
2174     if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK))
2175         *_r = PA_BLUETOOTH_PROFILE_A2DP_SINK;
2176     else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE))
2177         *_r = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
2178     else if (pa_bluetooth_uuid_is_hsp_hs(uuid))
2179         *_r = PA_BLUETOOTH_PROFILE_HSP_HS;
2180     else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF))
2181         *_r = PA_BLUETOOTH_PROFILE_HFP_HF;
2182     else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG))
2183         *_r = PA_BLUETOOTH_PROFILE_HSP_AG;
2184     else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG))
2185         *_r = PA_BLUETOOTH_PROFILE_HFP_AG;
2186     else
2187         return -PA_ERR_INVALID;
2188 
2189     return 0;
2190 }
2191 
2192 /* Run from main thread */
add_card(struct userdata * u)2193 static int add_card(struct userdata *u) {
2194     const pa_bluetooth_device *d;
2195     pa_card_new_data data;
2196     char *alias;
2197     pa_bluetooth_form_factor_t ff;
2198     pa_card_profile *cp;
2199     pa_bluetooth_profile_t *p;
2200     const char *uuid;
2201     void *state;
2202 
2203     pa_assert(u);
2204     pa_assert(u->device);
2205 
2206     d = u->device;
2207 
2208     pa_card_new_data_init(&data);
2209     data.driver = __FILE__;
2210     data.module = u->module;
2211 
2212     alias = pa_utf8_filter(d->alias);
2213     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
2214     pa_xfree(alias);
2215 
2216     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
2217     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2218     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2219     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2220 
2221     if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
2222         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
2223 
2224     pa_proplist_sets(data.proplist, "bluez.path", d->path);
2225     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
2226     pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
2227     data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
2228     data.namereg_fail = false;
2229 
2230     if (d->has_battery_level) {
2231         // See device_battery_level_changed_cb
2232         uint8_t level = d->battery_level;
2233         pa_proplist_setf(data.proplist, "bluetooth.battery", "%d%%", level);
2234     }
2235 
2236     create_card_ports(u, data.ports);
2237 
2238     PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
2239         pa_bluetooth_profile_t profile;
2240 
2241         if (uuid_to_profile(uuid, &profile) < 0)
2242             continue;
2243 
2244         pa_log_debug("Trying to create profile %s (%s) for device %s (%s)",
2245                      pa_bluetooth_profile_to_string(profile), uuid, d->alias, d->address);
2246 
2247         if (pa_hashmap_get(data.profiles, pa_bluetooth_profile_to_string(profile))) {
2248             pa_log_debug("%s already exists", pa_bluetooth_profile_to_string(profile));
2249             continue;
2250         }
2251 
2252         if (!pa_bluetooth_device_supports_profile(d, profile)) {
2253             pa_log_debug("%s is not supported by the device or adapter", pa_bluetooth_profile_to_string(profile));
2254             continue;
2255         }
2256 
2257         cp = create_card_profile(u, profile, data.ports);
2258         pa_hashmap_put(data.profiles, cp->name, cp);
2259     }
2260 
2261     pa_assert(!pa_hashmap_isempty(data.profiles));
2262 
2263     cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
2264     cp->available = PA_AVAILABLE_YES;
2265     p = PA_CARD_PROFILE_DATA(cp);
2266     *p = PA_BLUETOOTH_PROFILE_OFF;
2267     pa_hashmap_put(data.profiles, cp->name, cp);
2268 
2269     u->card = pa_card_new(u->core, &data);
2270     pa_card_new_data_done(&data);
2271     if (!u->card) {
2272         pa_log("Failed to allocate card.");
2273         return -1;
2274     }
2275 
2276     u->card->userdata = u;
2277     u->card->set_profile = set_profile_cb;
2278     pa_card_choose_initial_profile(u->card);
2279     pa_card_put(u->card);
2280 
2281     p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2282     u->profile = *p;
2283 
2284     return 0;
2285 }
2286 
2287 /* Run from main thread */
handle_transport_state_change(struct userdata * u,struct pa_bluetooth_transport * t)2288 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
2289     bool acquire = false;
2290     bool release = false;
2291     pa_card_profile *cp;
2292     pa_device_port *port;
2293     pa_available_t oldavail;
2294 
2295     pa_assert(u);
2296     pa_assert(t);
2297     pa_assert_se(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile)));
2298 
2299     oldavail = cp->available;
2300     /*
2301      * If codec switching is in progress, transport state change should not
2302      * make profile unavailable.
2303      */
2304     if (!t->device->codec_switching_in_progress)
2305         pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
2306 
2307     /* Update port availability */
2308     pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
2309     pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
2310     pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
2311     pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
2312 
2313     /* Acquire or release transport as needed */
2314     acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2315     release = (oldavail != PA_AVAILABLE_NO && t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2316 
2317     if (acquire && transport_acquire(u, true) >= 0) {
2318         if (u->source) {
2319             pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
2320 
2321             /* When the ofono backend resumes source or sink when in the audio gateway role, the
2322              * state of source or sink may already be RUNNING before the transport is acquired via
2323              * hf_audio_agent_new_connection(), so the pa_source_suspend() call will not lead to a
2324              * state change message. In this case we explicitly need to signal the I/O thread to
2325              * set up the stream. */
2326             if (PA_SOURCE_IS_OPENED(u->source->state))
2327                 pa_asyncmsgq_send(u->source->asyncmsgq, PA_MSGOBJECT(u->source), PA_SOURCE_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2328 
2329             /* We remove the IDLE suspend cause, because otherwise
2330              * module-loopback doesn't uncork its streams. FIXME: Messing with
2331              * the IDLE suspend cause here is wrong, the correct way to handle
2332              * this would probably be to uncork the loopback streams not only
2333              * when the other end is unsuspended, but also when the other end's
2334              * suspend cause changes to IDLE only (currently there's no
2335              * notification mechanism for suspend cause changes, though). */
2336             pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2337         }
2338 
2339         if (u->sink) {
2340             pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
2341 
2342             /* Same comment as above */
2343             if (PA_SINK_IS_OPENED(u->sink->state))
2344                 pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), PA_SINK_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2345 
2346             /* FIXME: See the previous comment. */
2347             pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2348         }
2349     }
2350 
2351     if (release && u->transport_acquired) {
2352         /* FIXME: this release is racy, since the audio stream might have
2353          * been set up again in the meantime (but not processed yet by PA).
2354          * BlueZ should probably release the transport automatically, and in
2355          * that case we would just mark the transport as released */
2356 
2357         /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
2358         if (u->source) {
2359             pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
2360             pa_source_suspend(u->source, true, PA_SUSPEND_USER);
2361         }
2362 
2363         if (u->sink) {
2364             pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
2365             pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
2366         }
2367     }
2368 }
2369 
2370 /* Run from main thread */
device_connection_changed_cb(pa_bluetooth_discovery * y,const pa_bluetooth_device * d,struct userdata * u)2371 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2372     pa_assert(d);
2373     pa_assert(u);
2374 
2375     if (d != u->device || pa_bluetooth_device_any_transport_connected(d) || d->codec_switching_in_progress)
2376         return PA_HOOK_OK;
2377 
2378     pa_log_debug("Unloading module for device %s", d->path);
2379     pa_module_unload(u->module, true);
2380 
2381     return PA_HOOK_OK;
2382 }
2383 
device_battery_level_changed_cb(pa_bluetooth_discovery * y,const pa_bluetooth_device * d,struct userdata * u)2384 static pa_hook_result_t device_battery_level_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2385     uint8_t level;
2386 
2387     pa_assert(d);
2388     pa_assert(u);
2389 
2390     if (d != u->device)
2391         return PA_HOOK_OK;
2392 
2393     if (d->has_battery_level) {
2394         level = d->battery_level;
2395         pa_proplist_setf(u->card->proplist, "bluetooth.battery", "%d%%", level);
2396     } else {
2397         pa_proplist_unset(u->card->proplist, "bluetooth.battery");
2398     }
2399 
2400     return PA_HOOK_OK;
2401 }
2402 
2403 /* Run from main thread */
transport_state_changed_cb(pa_bluetooth_discovery * y,pa_bluetooth_transport * t,struct userdata * u)2404 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2405     pa_assert(t);
2406     pa_assert(u);
2407 
2408     if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
2409         pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2410 
2411     if (t->device == u->device)
2412         handle_transport_state_change(u, t);
2413 
2414     return PA_HOOK_OK;
2415 }
2416 
transport_sink_volume_changed_cb(pa_bluetooth_discovery * y,pa_bluetooth_transport * t,struct userdata * u)2417 static pa_hook_result_t transport_sink_volume_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2418     pa_volume_t volume;
2419     pa_cvolume v;
2420 
2421     pa_assert(t);
2422     pa_assert(u);
2423 
2424     if (t != u->transport)
2425       return PA_HOOK_OK;
2426 
2427     volume = t->sink_volume;
2428 
2429     if (!u->sink) {
2430         pa_log_warn("Received peer transport volume change without connected sink");
2431         return PA_HOOK_OK;
2432     }
2433 
2434     sink_setup_volume_callback(u->sink);
2435 
2436     pa_cvolume_set(&v, u->encoder_sample_spec.channels, volume);
2437     if (pa_bluetooth_profile_should_attenuate_volume(t->profile))
2438         pa_sink_set_volume(u->sink, &v, true, true);
2439     else
2440         pa_sink_volume_changed(u->sink, &v);
2441 
2442     return PA_HOOK_OK;
2443 }
2444 
transport_source_volume_changed_cb(pa_bluetooth_discovery * y,pa_bluetooth_transport * t,struct userdata * u)2445 static pa_hook_result_t transport_source_volume_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2446     pa_volume_t volume;
2447     pa_cvolume v;
2448 
2449     pa_assert(t);
2450     pa_assert(u);
2451 
2452     if (t != u->transport)
2453       return PA_HOOK_OK;
2454 
2455     volume = t->source_volume;
2456 
2457     if (!u->source) {
2458         pa_log_warn("Received peer transport volume change without connected source");
2459         return PA_HOOK_OK;
2460     }
2461 
2462     source_setup_volume_callback(u->source);
2463 
2464     pa_cvolume_set(&v, u->decoder_sample_spec.channels, volume);
2465 
2466     if (pa_bluetooth_profile_should_attenuate_volume(t->profile))
2467         pa_source_set_volume(u->source, &v, true, true);
2468     else
2469         pa_source_volume_changed(u->source, &v);
2470 
2471     return PA_HOOK_OK;
2472 }
2473 
make_message_handler_path(const char * name)2474 static char* make_message_handler_path(const char *name) {
2475     return pa_sprintf_malloc("/card/%s/bluez", name);
2476 }
2477 
switch_codec_cb_handler(bool success,pa_bluetooth_profile_t profile,void * userdata)2478 static void switch_codec_cb_handler(bool success, pa_bluetooth_profile_t profile, void *userdata)
2479 {
2480     struct userdata *u = (struct userdata *) userdata;
2481 
2482     if (!success)
2483         goto off;
2484 
2485     u->profile = profile;
2486 
2487     if (init_profile(u) < 0) {
2488         pa_log_info("Failed to initialise profile after codec switching");
2489         goto off;
2490     }
2491 
2492     if (u->sink || u->source)
2493         if (start_thread(u) < 0) {
2494             pa_log_info("Failed to start thread after codec switching");
2495             goto off;
2496         }
2497 
2498     pa_log_info("Codec successfully switched to %s with profile: %s",
2499             u->bt_codec->name, pa_bluetooth_profile_to_string(u->profile));
2500 
2501     return;
2502 
2503 off:
2504     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2505 }
2506 
list_codecs(struct userdata * u)2507 static char *list_codecs(struct userdata *u) {
2508     const pa_a2dp_codec_capabilities *a2dp_capabilities;
2509     const pa_a2dp_codec_id *key;
2510     pa_hashmap *a2dp_endpoints;
2511     pa_json_encoder *encoder;
2512     unsigned int i;
2513     bool is_a2dp_sink;
2514     void *state;
2515 
2516     encoder = pa_json_encoder_new();
2517 
2518     pa_json_encoder_begin_element_array(encoder);
2519 
2520     if (pa_bluetooth_profile_is_a2dp(u->profile)) {
2521         is_a2dp_sink = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK;
2522 
2523         a2dp_endpoints = is_a2dp_sink ? u->device->a2dp_sink_endpoints : u->device->a2dp_source_endpoints;
2524 
2525         PA_HASHMAP_FOREACH_KV(key, a2dp_capabilities, a2dp_endpoints, state) {
2526             for (i = 0; i < pa_bluetooth_a2dp_endpoint_conf_count(); i++) {
2527                 const pa_a2dp_endpoint_conf *endpoint_conf;
2528 
2529                 endpoint_conf = pa_bluetooth_a2dp_endpoint_conf_iter(i);
2530 
2531                 if (memcmp(key, &endpoint_conf->id, sizeof(pa_a2dp_codec_id)) == 0) {
2532                     if (endpoint_conf->can_be_supported(is_a2dp_sink)) {
2533                         pa_json_encoder_begin_element_object(encoder);
2534 
2535                         pa_json_encoder_add_member_string(encoder, "name", endpoint_conf->bt_codec.name);
2536                         pa_json_encoder_add_member_string(encoder, "description", endpoint_conf->bt_codec.description);
2537 
2538                         pa_json_encoder_end_object(encoder);
2539                     }
2540                 }
2541             }
2542         }
2543     } else {
2544         /* find out active codec selection from device profile */
2545         for (i = 0; i < pa_bluetooth_hf_codec_count(); i++) {
2546             const pa_bt_codec *hf_codec;
2547 
2548             hf_codec = pa_bluetooth_hf_codec_iter(i);
2549 
2550             if (true) {
2551                 pa_json_encoder_begin_element_object(encoder);
2552 
2553                 pa_json_encoder_add_member_string(encoder, "name", hf_codec->name);
2554                 pa_json_encoder_add_member_string(encoder, "description", hf_codec->description);
2555 
2556                 pa_json_encoder_end_object(encoder);
2557             }
2558         }
2559     }
2560 
2561     pa_json_encoder_end_array(encoder);
2562 
2563     return pa_json_encoder_to_string_free(encoder);
2564 }
2565 
bluez5_device_message_handler(const char * object_path,const char * message,const pa_json_object * parameters,char ** response,void * userdata)2566 static int bluez5_device_message_handler(const char *object_path, const char *message, const pa_json_object *parameters, char **response, void *userdata) {
2567     char *message_handler_path;
2568     pa_hashmap *capabilities_hashmap;
2569     pa_bluetooth_profile_t profile;
2570     const pa_a2dp_endpoint_conf *endpoint_conf;
2571     const char *codec_name;
2572     struct userdata *u = userdata;
2573     bool is_a2dp_sink;
2574 
2575     pa_assert(u);
2576     pa_assert(message);
2577     pa_assert(response);
2578 
2579     message_handler_path = make_message_handler_path(u->card->name);
2580 
2581     if (!object_path || !pa_streq(object_path, message_handler_path)) {
2582         pa_xfree(message_handler_path);
2583         return -PA_ERR_NOENTITY;
2584     }
2585 
2586     pa_xfree(message_handler_path);
2587 
2588     if (u->device->codec_switching_in_progress) {
2589         pa_log_info("Codec switching operation already in progress");
2590         return -PA_ERR_INVALID;
2591     }
2592 
2593     if (!u->device->adapter->application_registered) {
2594         pa_log_info("Old BlueZ version was detected, only SBC codec supported.");
2595         return -PA_ERR_NOTIMPLEMENTED;
2596     }
2597 
2598     if (u->profile == PA_BLUETOOTH_PROFILE_OFF) {
2599         pa_log_info("Bluetooth profile is off. Message cannot be handled.");
2600         return -PA_ERR_INVALID;
2601     }
2602 
2603     if (pa_streq(message, "switch-codec")) {
2604         if (u->profile != PA_BLUETOOTH_PROFILE_A2DP_SINK &&
2605             u->profile != PA_BLUETOOTH_PROFILE_A2DP_SOURCE) {
2606             pa_log_info("Switching codecs only allowed for A2DP sink or source");
2607             return -PA_ERR_INVALID;
2608         }
2609 
2610         if (!parameters) {
2611             pa_log_info("Codec switching operation requires codec name string parameter");
2612             return -PA_ERR_INVALID;
2613         }
2614 
2615         if (pa_json_object_get_type(parameters) != PA_JSON_TYPE_STRING) {
2616             pa_log_info("Codec name object parameter must be a string");
2617             return -PA_ERR_INVALID;
2618         }
2619 
2620         codec_name = pa_json_object_get_string(parameters);
2621 
2622         if (u->bt_codec && pa_streq(codec_name, u->bt_codec->name)) {
2623             pa_log_info("Requested codec is currently selected codec");
2624             return -PA_ERR_INVALID;
2625         }
2626 
2627         endpoint_conf = pa_bluetooth_get_a2dp_endpoint_conf(codec_name);
2628         if (endpoint_conf == NULL) {
2629             pa_log_info("Invalid codec %s specified for switching", codec_name);
2630             return -PA_ERR_INVALID;
2631         }
2632 
2633         is_a2dp_sink = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK;
2634 
2635         if (!endpoint_conf->can_be_supported(is_a2dp_sink)) {
2636             pa_log_info("Codec not found on system");
2637             return -PA_ERR_NOTSUPPORTED;
2638         }
2639 
2640         /*
2641          * We need to check if we have valid sink or source endpoints which
2642          * were registered during the negotiation process. If we do, then we
2643          * check if the specified codec is present among the codecs supported
2644          * by the remote endpoint.
2645          */
2646         if (pa_hashmap_isempty(is_a2dp_sink ? u->device->a2dp_sink_endpoints : u->device->a2dp_source_endpoints)) {
2647             pa_log_info("No device endpoints found. Codec switching not allowed.");
2648             return -PA_ERR_INVALID;
2649         }
2650 
2651         capabilities_hashmap = pa_hashmap_get(is_a2dp_sink ? u->device->a2dp_sink_endpoints : u->device->a2dp_source_endpoints, &endpoint_conf->id);
2652         if (!capabilities_hashmap) {
2653             pa_log_info("No remote endpoint found for %s codec. Codec not supported by remote endpoint.",
2654                     endpoint_conf->bt_codec.name);
2655             return -PA_ERR_INVALID;
2656         }
2657 
2658         pa_log_info("Initiating codec switching process to %s", endpoint_conf->bt_codec.name);
2659 
2660         /*
2661          * The current profile needs to be saved before we stop the thread and
2662          * initiate the switch. u->profile will be changed in other places
2663          * depending on the state of transport and port availability.
2664          */
2665         profile = u->profile;
2666 
2667         stop_thread(u);
2668 
2669         if (!pa_bluetooth_device_switch_codec(u->device, profile, capabilities_hashmap, endpoint_conf, switch_codec_cb_handler, userdata)
2670                 && !u->device->codec_switching_in_progress)
2671             goto profile_off;
2672 
2673         return PA_OK;
2674     } else if (pa_streq(message, "list-codecs")) {
2675         *response = list_codecs(u);
2676         return PA_OK;
2677     } else if (pa_streq(message, "get-codec")) {
2678         pa_json_encoder *encoder;
2679         encoder = pa_json_encoder_new();
2680 
2681         if (u->bt_codec)
2682             pa_json_encoder_add_element_string(encoder, u->bt_codec->name);
2683         else
2684             pa_json_encoder_add_element_null(encoder);
2685 
2686         *response = pa_json_encoder_to_string_free(encoder);
2687 
2688         return PA_OK;
2689     }
2690 
2691 
2692     return -PA_ERR_NOTIMPLEMENTED;
2693 
2694 profile_off:
2695     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2696 
2697     return -PA_ERR_IO;
2698 }
2699 
2700 /* Run from main thread context */
device_process_msg(pa_msgobject * obj,int code,void * data,int64_t offset,pa_memchunk * chunk)2701 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
2702     struct bluetooth_msg *m = BLUETOOTH_MSG(obj);
2703     struct userdata *u = m->card->userdata;
2704 
2705     switch (code) {
2706         case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
2707             if (m->card->module->unload_requested)
2708                 break;
2709 
2710             pa_log_debug("Switching the profile to off due to IO thread failure.");
2711             pa_assert_se(pa_card_set_profile(m->card, pa_hashmap_get(m->card->profiles, "off"), false) >= 0);
2712             break;
2713         case BLUETOOTH_MESSAGE_STREAM_FD_HUP:
2714             if (u->transport->state > PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2715                 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
2716             break;
2717         case BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING:
2718             /* transport_acquired needs to be checked here, because a message could have been
2719              * pending when the profile was switched. If the new transport has been acquired
2720              * correctly, the call below will have no effect because the transport state is
2721              * already PLAYING. If transport_acquire() failed for the new profile, the transport
2722              * state should not be changed. If the transport has been released for other reasons
2723              * (I/O thread shutdown), transport_acquired will also be false. */
2724             if (u->transport_acquired)
2725                 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
2726             break;
2727     }
2728 
2729     return 0;
2730 }
2731 
pa__init(pa_module * m)2732 int pa__init(pa_module* m) {
2733     struct userdata *u;
2734     const char *path;
2735     pa_modargs *ma;
2736     bool autodetect_mtu, avrcp_absolute_volume;
2737     char *message_handler_path;
2738     uint32_t output_rate_refresh_interval_ms;
2739 
2740     pa_assert(m);
2741 
2742     m->userdata = u = pa_xnew0(struct userdata, 1);
2743     u->module = m;
2744     u->core = m->core;
2745     u->message_handler_registered = false;
2746 
2747     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2748         pa_log_error("Failed to parse module arguments");
2749         goto fail_free_modargs;
2750     }
2751 
2752     if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
2753         pa_log_error("Failed to get device path from module arguments");
2754         goto fail_free_modargs;
2755     }
2756 
2757     if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
2758         pa_bluetooth_discovery_ref(u->discovery);
2759     else {
2760         pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
2761         goto fail_free_modargs;
2762     }
2763 
2764     if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
2765         pa_log_error("%s is unknown", path);
2766         goto fail_free_modargs;
2767     }
2768 
2769     autodetect_mtu = false;
2770     if (pa_modargs_get_value_boolean(ma, "autodetect_mtu", &autodetect_mtu) < 0) {
2771         pa_log("Invalid boolean value for autodetect_mtu parameter");
2772         goto fail_free_modargs;
2773     }
2774 
2775     u->device->autodetect_mtu = autodetect_mtu;
2776 
2777     output_rate_refresh_interval_ms = DEFAULT_OUTPUT_RATE_REFRESH_INTERVAL_MS;
2778     if (pa_modargs_get_value_u32(ma, "output_rate_refresh_interval_ms", &output_rate_refresh_interval_ms) < 0) {
2779         pa_log("Invalid value for output_rate_refresh_interval parameter.");
2780         goto fail_free_modargs;
2781     }
2782 
2783     u->device->output_rate_refresh_interval_ms = output_rate_refresh_interval_ms;
2784 
2785     avrcp_absolute_volume = true;
2786     if (pa_modargs_get_value_boolean(ma, "avrcp_absolute_volume", &avrcp_absolute_volume) < 0) {
2787         pa_log("Invalid boolean value for avrcp_absolute_volume parameter");
2788         goto fail_free_modargs;
2789     }
2790 
2791     u->device->avrcp_absolute_volume = avrcp_absolute_volume;
2792 
2793     pa_modargs_free(ma);
2794 
2795     u->device_connection_changed_slot =
2796         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2797                         PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
2798 
2799     u->device_battery_level_changed_slot =
2800         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_BATTERY_LEVEL_CHANGED),
2801                         PA_HOOK_NORMAL, (pa_hook_cb_t) device_battery_level_changed_cb, u);
2802 
2803     u->transport_state_changed_slot =
2804         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2805                         PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2806 
2807     u->transport_sink_volume_changed_slot =
2808         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SINK_VOLUME_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_sink_volume_changed_cb, u);
2809 
2810     u->transport_source_volume_changed_slot =
2811         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SOURCE_VOLUME_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_source_volume_changed_cb, u);
2812 
2813     if (add_card(u) < 0)
2814         goto fail;
2815 
2816     if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2817         goto fail;
2818 
2819     u->msg->parent.process_msg = device_process_msg;
2820     u->msg->card = u->card;
2821     u->stream_setup_done = false;
2822 
2823     if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2824         if (init_profile(u) < 0)
2825             goto off;
2826 
2827     if (u->sink || u->source)
2828         if (start_thread(u) < 0)
2829             goto off;
2830 
2831     message_handler_path = make_message_handler_path(u->card->name);
2832     pa_message_handler_register(m->core, message_handler_path, "Bluez5 device message handler",
2833             bluez5_device_message_handler, (void *) u);
2834     pa_log_info("Bluez5 device message handler registered at path: %s", message_handler_path);
2835     pa_xfree(message_handler_path);
2836     u->message_handler_registered = true;
2837 
2838     return 0;
2839 
2840 off:
2841     stop_thread(u);
2842 
2843     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2844 
2845     return 0;
2846 
2847 fail_free_modargs:
2848 
2849     if (ma)
2850         pa_modargs_free(ma);
2851 
2852 fail:
2853 
2854     pa__done(m);
2855 
2856     return -1;
2857 }
2858 
pa__done(pa_module * m)2859 void pa__done(pa_module *m) {
2860     char *message_handler_path;
2861     struct userdata *u;
2862 
2863     pa_assert(m);
2864 
2865     if (!(u = m->userdata))
2866         return;
2867 
2868     if (u->message_handler_registered) {
2869         message_handler_path = make_message_handler_path(u->card->name);
2870         pa_message_handler_unregister(m->core, message_handler_path);
2871         pa_xfree(message_handler_path);
2872     }
2873 
2874     stop_thread(u);
2875 
2876     if (u->device_connection_changed_slot)
2877         pa_hook_slot_free(u->device_connection_changed_slot);
2878 
2879     if (u->device_battery_level_changed_slot)
2880         pa_hook_slot_free(u->device_battery_level_changed_slot);
2881 
2882     if (u->transport_state_changed_slot)
2883         pa_hook_slot_free(u->transport_state_changed_slot);
2884 
2885     if (u->transport_sink_volume_changed_slot)
2886         pa_hook_slot_free(u->transport_sink_volume_changed_slot);
2887 
2888     if (u->transport_source_volume_changed_slot)
2889         pa_hook_slot_free(u->transport_source_volume_changed_slot);
2890 
2891     if (u->encoder_buffer)
2892         pa_xfree(u->encoder_buffer);
2893 
2894     if (u->decoder_buffer)
2895         pa_xfree(u->decoder_buffer);
2896 
2897     if (u->msg)
2898         pa_xfree(u->msg);
2899 
2900     if (u->card)
2901         pa_card_free(u->card);
2902 
2903     if (u->discovery)
2904         pa_bluetooth_discovery_unref(u->discovery);
2905 
2906     pa_xfree(u->output_port_name);
2907     pa_xfree(u->input_port_name);
2908 
2909     pa_xfree(u);
2910 }
2911 
pa__get_n_used(pa_module * m)2912 int pa__get_n_used(pa_module *m) {
2913     struct userdata *u;
2914 
2915     pa_assert(m);
2916     pa_assert_se(u = m->userdata);
2917 
2918     return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);
2919 }
2920