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