• 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/module.h>
40 #include <pulsecore/modargs.h>
41 #include <pulsecore/poll.h>
42 #include <pulsecore/rtpoll.h>
43 #include <pulsecore/shared.h>
44 #include <pulsecore/socket-util.h>
45 #include <pulsecore/thread.h>
46 #include <pulsecore/thread-mq.h>
47 #include <pulsecore/time-smoother.h>
48 
49 #include "a2dp-codecs.h"
50 #include "a2dp-codec-util.h"
51 #include "bluez5-util.h"
52 
53 PA_MODULE_AUTHOR("João Paulo Rechi Vita");
54 PA_MODULE_DESCRIPTION("BlueZ 5 Bluetooth audio sink and source");
55 PA_MODULE_VERSION(PACKAGE_VERSION);
56 PA_MODULE_LOAD_ONCE(false);
57 PA_MODULE_USAGE("path=<device object path>"
58                 "autodetect_mtu=<boolean>");
59 
60 #define FIXED_LATENCY_PLAYBACK_A2DP (25 * PA_USEC_PER_MSEC)
61 #define FIXED_LATENCY_PLAYBACK_SCO  (25 * PA_USEC_PER_MSEC)
62 #define FIXED_LATENCY_RECORD_A2DP   (25 * PA_USEC_PER_MSEC)
63 #define FIXED_LATENCY_RECORD_SCO    (25 * PA_USEC_PER_MSEC)
64 
65 #define HSP_MAX_GAIN 15
66 
67 static const char* const valid_modargs[] = {
68     "path",
69     "autodetect_mtu",
70     NULL
71 };
72 
73 enum {
74     BLUETOOTH_MESSAGE_IO_THREAD_FAILED,
75     BLUETOOTH_MESSAGE_STREAM_FD_HUP,
76     BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING,
77     BLUETOOTH_MESSAGE_MAX
78 };
79 
80 enum {
81     PA_SOURCE_MESSAGE_SETUP_STREAM = PA_SOURCE_MESSAGE_MAX,
82 };
83 
84 enum {
85     PA_SINK_MESSAGE_SETUP_STREAM = PA_SINK_MESSAGE_MAX,
86 };
87 
88 typedef struct bluetooth_msg {
89     pa_msgobject parent;
90     pa_card *card;
91 } bluetooth_msg;
92 PA_DEFINE_PRIVATE_CLASS(bluetooth_msg, pa_msgobject);
93 #define BLUETOOTH_MSG(o) (bluetooth_msg_cast(o))
94 
95 struct userdata {
96     pa_module *module;
97     pa_core *core;
98 
99     pa_hook_slot *device_connection_changed_slot;
100     pa_hook_slot *transport_state_changed_slot;
101     pa_hook_slot *transport_speaker_gain_changed_slot;
102     pa_hook_slot *transport_microphone_gain_changed_slot;
103 
104     pa_bluetooth_discovery *discovery;
105     pa_bluetooth_device *device;
106     pa_bluetooth_transport *transport;
107     bool transport_acquired;
108     bool stream_setup_done;
109 
110     pa_card *card;
111     pa_sink *sink;
112     pa_source *source;
113     pa_bluetooth_profile_t profile;
114     char *output_port_name;
115     char *input_port_name;
116 
117     pa_thread *thread;
118     pa_thread_mq thread_mq;
119     pa_rtpoll *rtpoll;
120     pa_rtpoll_item *rtpoll_item;
121     bluetooth_msg *msg;
122 
123     int stream_fd;
124     int stream_write_type;
125     size_t read_link_mtu;
126     size_t write_link_mtu;
127     size_t read_block_size;
128     size_t write_block_size;
129     uint64_t read_index;
130     uint64_t write_index;
131     pa_usec_t started_at;
132     pa_smoother *read_smoother;
133     pa_memchunk write_memchunk;
134 
135     const pa_a2dp_codec *a2dp_codec;
136 
137     void *encoder_info;
138     pa_sample_spec encoder_sample_spec;
139     void *encoder_buffer;                        /* Codec transfer buffer */
140     size_t encoder_buffer_size;                  /* Size of the buffer */
141 
142     void *decoder_info;
143     pa_sample_spec decoder_sample_spec;
144     void *decoder_buffer;                        /* Codec transfer buffer */
145     size_t decoder_buffer_size;                  /* Size of the buffer */
146 };
147 
148 typedef enum pa_bluetooth_form_factor {
149     PA_BLUETOOTH_FORM_FACTOR_UNKNOWN,
150     PA_BLUETOOTH_FORM_FACTOR_HEADSET,
151     PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
152     PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
153     PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
154     PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
155     PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
156     PA_BLUETOOTH_FORM_FACTOR_CAR,
157     PA_BLUETOOTH_FORM_FACTOR_HIFI,
158     PA_BLUETOOTH_FORM_FACTOR_PHONE,
159 } pa_bluetooth_form_factor_t;
160 
161 /* Run from main thread */
form_factor_from_class(uint32_t class_of_device)162 static pa_bluetooth_form_factor_t form_factor_from_class(uint32_t class_of_device) {
163     unsigned major, minor;
164     pa_bluetooth_form_factor_t r;
165 
166     static const pa_bluetooth_form_factor_t table[] = {
167         [1] = PA_BLUETOOTH_FORM_FACTOR_HEADSET,
168         [2] = PA_BLUETOOTH_FORM_FACTOR_HANDSFREE,
169         [4] = PA_BLUETOOTH_FORM_FACTOR_MICROPHONE,
170         [5] = PA_BLUETOOTH_FORM_FACTOR_SPEAKER,
171         [6] = PA_BLUETOOTH_FORM_FACTOR_HEADPHONE,
172         [7] = PA_BLUETOOTH_FORM_FACTOR_PORTABLE,
173         [8] = PA_BLUETOOTH_FORM_FACTOR_CAR,
174         [10] = PA_BLUETOOTH_FORM_FACTOR_HIFI
175     };
176 
177     /*
178      * See Bluetooth Assigned Numbers:
179      * https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
180      */
181     major = (class_of_device >> 8) & 0x1F;
182     minor = (class_of_device >> 2) & 0x3F;
183 
184     switch (major) {
185         case 2:
186             return PA_BLUETOOTH_FORM_FACTOR_PHONE;
187         case 4:
188             break;
189         default:
190             pa_log_debug("Unknown Bluetooth major device class %u", major);
191             return PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
192     }
193 
194     r = minor < PA_ELEMENTSOF(table) ? table[minor] : PA_BLUETOOTH_FORM_FACTOR_UNKNOWN;
195 
196     if (!r)
197         pa_log_debug("Unknown Bluetooth minor device class %u", minor);
198 
199     return r;
200 }
201 
202 /* Run from main thread */
form_factor_to_string(pa_bluetooth_form_factor_t ff)203 static const char *form_factor_to_string(pa_bluetooth_form_factor_t ff) {
204     switch (ff) {
205         case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
206             return "unknown";
207         case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
208             return "headset";
209         case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
210             return "hands-free";
211         case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
212             return "microphone";
213         case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
214             return "speaker";
215         case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
216             return "headphone";
217         case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
218             return "portable";
219         case PA_BLUETOOTH_FORM_FACTOR_CAR:
220             return "car";
221         case PA_BLUETOOTH_FORM_FACTOR_HIFI:
222             return "hifi";
223         case PA_BLUETOOTH_FORM_FACTOR_PHONE:
224             return "phone";
225     }
226 
227     pa_assert_not_reached();
228 }
229 
230 /* Run from main thread */
connect_ports(struct userdata * u,void * new_data,pa_direction_t direction)231 static void connect_ports(struct userdata *u, void *new_data, pa_direction_t direction) {
232     pa_device_port *port;
233 
234     if (direction == PA_DIRECTION_OUTPUT) {
235         pa_sink_new_data *sink_new_data = new_data;
236 
237         pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
238         pa_assert_se(pa_hashmap_put(sink_new_data->ports, port->name, port) >= 0);
239         pa_device_port_ref(port);
240     } else {
241         pa_source_new_data *source_new_data = new_data;
242 
243         pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
244         pa_assert_se(pa_hashmap_put(source_new_data->ports, port->name, port) >= 0);
245         pa_device_port_ref(port);
246     }
247 }
248 
249 /* Run from IO thread */
sco_process_render(struct userdata * u)250 static int sco_process_render(struct userdata *u) {
251     ssize_t l;
252     pa_memchunk memchunk;
253     int saved_errno;
254 
255     pa_assert(u);
256     pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
257                 u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
258     pa_assert(u->sink);
259 
260     pa_sink_render_full(u->sink, u->write_block_size, &memchunk);
261 
262     pa_assert(memchunk.length == u->write_block_size);
263 
264     for (;;) {
265         const void *p;
266 
267         /* Now write that data to the socket. The socket is of type
268          * SEQPACKET, and we generated the data of the MTU size, so this
269          * should just work. */
270 
271         p = (const uint8_t *) pa_memblock_acquire_chunk(&memchunk);
272         l = pa_write(u->stream_fd, p, memchunk.length, &u->stream_write_type);
273         pa_memblock_release(memchunk.memblock);
274 
275         pa_assert(l != 0);
276 
277         if (l > 0)
278             break;
279 
280         saved_errno = errno;
281 
282         if (saved_errno == EINTR)
283             /* Retry right away if we got interrupted */
284             continue;
285 
286         pa_memblock_unref(memchunk.memblock);
287 
288         if (saved_errno == EAGAIN) {
289             /* Hmm, apparently the socket was not writable, give up for now.
290              * Because the data was already rendered, let's discard the block. */
291             pa_log_debug("Got EAGAIN on write() after POLLOUT, probably there is a temporary connection loss.");
292             return 1;
293         }
294 
295         pa_log_error("Failed to write data to SCO socket: %s", pa_cstrerror(saved_errno));
296         return -1;
297     }
298 
299     pa_assert((size_t) l <= memchunk.length);
300 
301     if ((size_t) l != memchunk.length) {
302         pa_log_error("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
303                     (unsigned long long) l,
304                     (unsigned long long) memchunk.length);
305 
306         pa_memblock_unref(memchunk.memblock);
307         return -1;
308     }
309 
310     u->write_index += (uint64_t) memchunk.length;
311     pa_memblock_unref(memchunk.memblock);
312 
313     return 1;
314 }
315 
316 /* Run from IO thread */
sco_process_push(struct userdata * u)317 static int sco_process_push(struct userdata *u) {
318     ssize_t l;
319     pa_memchunk memchunk;
320     struct cmsghdr *cm;
321     struct msghdr m;
322     bool found_tstamp = false;
323     pa_usec_t tstamp = 0;
324 
325     pa_assert(u);
326     pa_assert(u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT ||
327                 u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY);
328     pa_assert(u->source);
329     pa_assert(u->read_smoother);
330 
331     memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
332     memchunk.index = memchunk.length = 0;
333 
334     for (;;) {
335         void *p;
336         uint8_t aux[1024];
337         struct iovec iov;
338 
339         pa_zero(m);
340         pa_zero(aux);
341         pa_zero(iov);
342 
343         m.msg_iov = &iov;
344         m.msg_iovlen = 1;
345         m.msg_control = aux;
346         m.msg_controllen = sizeof(aux);
347 
348         p = pa_memblock_acquire(memchunk.memblock);
349         iov.iov_base = p;
350         iov.iov_len = pa_memblock_get_length(memchunk.memblock);
351         l = recvmsg(u->stream_fd, &m, 0);
352         pa_memblock_release(memchunk.memblock);
353 
354         if (l > 0)
355             break;
356 
357         if (l < 0 && errno == EINTR)
358             /* Retry right away if we got interrupted */
359             continue;
360 
361         pa_memblock_unref(memchunk.memblock);
362 
363         if (l < 0 && errno == EAGAIN)
364             /* Hmm, apparently the socket was not readable, give up for now. */
365             return 0;
366 
367         pa_log_error("Failed to read data from SCO socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
368         return -1;
369     }
370 
371     pa_assert((size_t) l <= pa_memblock_get_length(memchunk.memblock));
372 
373     /* In some rare occasions, we might receive packets of a very strange
374      * size. This could potentially be possible if the SCO packet was
375      * received partially over-the-air, or more probably due to hardware
376      * issues in our Bluetooth adapter. In these cases, in order to avoid
377      * an assertion failure due to unaligned data, just discard the whole
378      * packet */
379     if (!pa_frame_aligned(l, &u->decoder_sample_spec)) {
380         pa_log_warn("SCO packet received of unaligned size: %zu", l);
381         pa_memblock_unref(memchunk.memblock);
382         return -1;
383     }
384 
385     memchunk.length = (size_t) l;
386     u->read_index += (uint64_t) l;
387 
388     for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
389         if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
390             struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
391             pa_rtclock_from_wallclock(tv);
392             tstamp = pa_timeval_load(tv);
393             found_tstamp = true;
394             break;
395         }
396 
397     if (!found_tstamp) {
398         PA_ONCE_BEGIN {
399             pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
400         } PA_ONCE_END;
401         tstamp = pa_rtclock_now();
402     }
403 
404     pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec));
405     pa_smoother_resume(u->read_smoother, tstamp, true);
406 
407     pa_source_post(u->source, &memchunk);
408     pa_memblock_unref(memchunk.memblock);
409 
410     return l;
411 }
412 
413 /* Run from IO thread */
a2dp_prepare_encoder_buffer(struct userdata * u)414 static void a2dp_prepare_encoder_buffer(struct userdata *u) {
415     pa_assert(u);
416 
417     if (u->encoder_buffer_size < u->write_link_mtu) {
418         pa_xfree(u->encoder_buffer);
419         u->encoder_buffer = pa_xmalloc(u->write_link_mtu);
420     }
421 
422     /* Encoder buffer cannot be larger then link MTU, otherwise
423      * encode method would produce larger packets then link MTU */
424     u->encoder_buffer_size = u->write_link_mtu;
425 }
426 
427 /* Run from IO thread */
a2dp_prepare_decoder_buffer(struct userdata * u)428 static void a2dp_prepare_decoder_buffer(struct userdata *u) {
429     pa_assert(u);
430 
431     if (u->decoder_buffer_size < u->read_link_mtu) {
432         pa_xfree(u->decoder_buffer);
433         u->decoder_buffer = pa_xmalloc(u->read_link_mtu);
434     }
435 
436     /* Decoder buffer cannot be larger then link MTU, otherwise
437      * decode method would produce larger output then read_block_size */
438     u->decoder_buffer_size = u->read_link_mtu;
439 }
440 
441 /* Run from IO thread */
a2dp_write_buffer(struct userdata * u,size_t nbytes)442 static int a2dp_write_buffer(struct userdata *u, size_t nbytes) {
443     int ret = 0;
444 
445     /* Encoder function of A2DP codec may provide empty buffer, in this case do
446      * not post any empty buffer via A2DP socket. It may be because of codec
447      * internal state, e.g. encoder is waiting for more samples so it can
448      * provide encoded data. */
449     if (PA_UNLIKELY(!nbytes)) {
450         u->write_index += (uint64_t) u->write_memchunk.length;
451         pa_memblock_unref(u->write_memchunk.memblock);
452         pa_memchunk_reset(&u->write_memchunk);
453         return 0;
454     }
455 
456     for (;;) {
457         ssize_t l;
458 
459         l = pa_write(u->stream_fd, u->encoder_buffer, nbytes, &u->stream_write_type);
460 
461         pa_assert(l != 0);
462 
463         if (l < 0) {
464 
465             if (errno == EINTR)
466                 /* Retry right away if we got interrupted */
467                 continue;
468 
469             else if (errno == EAGAIN) {
470                 /* Hmm, apparently the socket was not writable, give up for now */
471                 pa_log_debug("Got EAGAIN on write() after POLLOUT, probably there is a temporary connection loss.");
472                 break;
473             }
474 
475             pa_log_error("Failed to write data to socket: %s", pa_cstrerror(errno));
476             ret = -1;
477             break;
478         }
479 
480         pa_assert((size_t) l <= nbytes);
481 
482         if ((size_t) l != nbytes) {
483             pa_log_warn("Wrote memory block to socket only partially! %llu written, wanted to write %llu.",
484                         (unsigned long long) l,
485                         (unsigned long long) nbytes);
486             ret = -1;
487             break;
488         }
489 
490         u->write_index += (uint64_t) u->write_memchunk.length;
491         pa_memblock_unref(u->write_memchunk.memblock);
492         pa_memchunk_reset(&u->write_memchunk);
493 
494         ret = 1;
495 
496         break;
497     }
498 
499     return ret;
500 }
501 
502 /* Run from IO thread */
a2dp_process_render(struct userdata * u)503 static int a2dp_process_render(struct userdata *u) {
504     const uint8_t *ptr;
505     size_t processed;
506     size_t length;
507 
508     pa_assert(u);
509     pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK);
510     pa_assert(u->sink);
511     pa_assert(u->a2dp_codec);
512 
513     /* First, render some data */
514     if (!u->write_memchunk.memblock)
515         pa_sink_render_full(u->sink, u->write_block_size, &u->write_memchunk);
516 
517     pa_assert(u->write_memchunk.length == u->write_block_size);
518 
519     a2dp_prepare_encoder_buffer(u);
520 
521     /* Try to create a packet of the full MTU */
522     ptr = (const uint8_t *) pa_memblock_acquire_chunk(&u->write_memchunk);
523 
524     length = u->a2dp_codec->encode_buffer(u->encoder_info, u->write_index / pa_frame_size(&u->encoder_sample_spec), ptr, u->write_memchunk.length, u->encoder_buffer, u->encoder_buffer_size, &processed);
525 
526     pa_memblock_release(u->write_memchunk.memblock);
527 
528     if (processed != u->write_memchunk.length) {
529         pa_log_error("Encoding error");
530         return -1;
531     }
532 
533     return a2dp_write_buffer(u, length);
534 }
535 
536 /* Run from IO thread */
a2dp_process_push(struct userdata * u)537 static int a2dp_process_push(struct userdata *u) {
538     int ret = 0;
539     pa_memchunk memchunk;
540 
541     pa_assert(u);
542     pa_assert(u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE);
543     pa_assert(u->source);
544     pa_assert(u->read_smoother);
545     pa_assert(u->a2dp_codec);
546 
547     memchunk.memblock = pa_memblock_new(u->core->mempool, u->read_block_size);
548     memchunk.index = memchunk.length = 0;
549 
550     a2dp_prepare_decoder_buffer(u);
551 
552     for (;;) {
553         uint8_t aux[1024];
554         struct iovec iov;
555         struct cmsghdr *cm;
556         struct msghdr m;
557         bool found_tstamp = false;
558         pa_usec_t tstamp;
559         uint8_t *ptr;
560         ssize_t l;
561         size_t processed;
562 
563         pa_zero(m);
564         pa_zero(aux);
565         pa_zero(iov);
566 
567         m.msg_iov = &iov;
568         m.msg_iovlen = 1;
569         m.msg_control = aux;
570         m.msg_controllen = sizeof(aux);
571 
572         iov.iov_base = u->decoder_buffer;
573         iov.iov_len = u->decoder_buffer_size;
574 
575         l = recvmsg(u->stream_fd, &m, 0);
576 
577         if (l <= 0) {
578 
579             if (l < 0 && errno == EINTR)
580                 /* Retry right away if we got interrupted */
581                 continue;
582 
583             else if (l < 0 && errno == EAGAIN)
584                 /* Hmm, apparently the socket was not readable, give up for now. */
585                 break;
586 
587             pa_log_error("Failed to read data from socket: %s", l < 0 ? pa_cstrerror(errno) : "EOF");
588             ret = -1;
589             break;
590         }
591 
592         pa_assert((size_t) l <= u->decoder_buffer_size);
593 
594         /* TODO: get timestamp from rtp */
595 
596         for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm)) {
597             if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SO_TIMESTAMP) {
598                 struct timeval *tv = (struct timeval*) CMSG_DATA(cm);
599                 pa_rtclock_from_wallclock(tv);
600                 tstamp = pa_timeval_load(tv);
601                 found_tstamp = true;
602                 break;
603             }
604         }
605 
606         if (!found_tstamp) {
607             PA_ONCE_BEGIN {
608                 pa_log_warn("Couldn't find SO_TIMESTAMP data in auxiliary recvmsg() data!");
609             } PA_ONCE_END;
610             tstamp = pa_rtclock_now();
611         }
612 
613         ptr = pa_memblock_acquire(memchunk.memblock);
614         memchunk.length = pa_memblock_get_length(memchunk.memblock);
615 
616         memchunk.length = u->a2dp_codec->decode_buffer(u->decoder_info, u->decoder_buffer, l, ptr, memchunk.length, &processed);
617 
618         pa_memblock_release(memchunk.memblock);
619 
620         if (processed != (size_t) l) {
621             pa_log_error("Decoding error");
622             ret = -1;
623             break;
624         }
625 
626         u->read_index += (uint64_t) memchunk.length;
627         pa_smoother_put(u->read_smoother, tstamp, pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec));
628         pa_smoother_resume(u->read_smoother, tstamp, true);
629 
630         /* Decoding of A2DP codec data may result in empty buffer, in this case
631          * do not post empty audio samples. It may happen due to algorithmic
632          * delay of audio codec. */
633         if (PA_LIKELY(memchunk.length))
634             pa_source_post(u->source, &memchunk);
635 
636         ret = l;
637         break;
638     }
639 
640     pa_memblock_unref(memchunk.memblock);
641 
642     return ret;
643 }
644 
update_sink_buffer_size(struct userdata * u)645 static void update_sink_buffer_size(struct userdata *u) {
646     int old_bufsize;
647     socklen_t len = sizeof(int);
648     int ret;
649 
650     ret = getsockopt(u->stream_fd, SOL_SOCKET, SO_SNDBUF, &old_bufsize, &len);
651     if (ret == -1) {
652         pa_log_warn("Changing bluetooth buffer size: Failed to getsockopt(SO_SNDBUF): %s", pa_cstrerror(errno));
653     } else {
654         int new_bufsize;
655 
656         /* Set send buffer size as small as possible. The minimum value is 1024 according to the
657          * socket man page. The data is written to the socket in chunks of write_block_size, so
658          * there should at least be room for two chunks in the buffer. Generally, write_block_size
659          * is larger than 512. If not, use the next multiple of write_block_size which is larger
660          * than 1024. */
661         new_bufsize = 2 * u->write_block_size;
662         if (new_bufsize < 1024)
663             new_bufsize = (1024 / u->write_block_size + 1) * u->write_block_size;
664 
665         /* The kernel internally doubles the buffer size that was set by setsockopt and getsockopt
666          * returns the doubled value. */
667         if (new_bufsize != old_bufsize / 2) {
668             ret = setsockopt(u->stream_fd, SOL_SOCKET, SO_SNDBUF, &new_bufsize, len);
669             if (ret == -1)
670                 pa_log_warn("Changing bluetooth buffer size: Failed to change from %d to %d: %s", old_bufsize / 2, new_bufsize, pa_cstrerror(errno));
671             else
672                 pa_log_info("Changing bluetooth buffer size: Changed from %d to %d", old_bufsize / 2, new_bufsize);
673         }
674     }
675 }
676 
teardown_stream(struct userdata * u)677 static void teardown_stream(struct userdata *u) {
678     if (u->rtpoll_item) {
679         pa_rtpoll_item_free(u->rtpoll_item);
680         u->rtpoll_item = NULL;
681     }
682 
683     if (u->stream_fd >= 0) {
684         pa_close(u->stream_fd);
685         u->stream_fd = -1;
686     }
687 
688     if (u->read_smoother) {
689         pa_smoother_free(u->read_smoother);
690         u->read_smoother = NULL;
691     }
692 
693     if (u->write_memchunk.memblock) {
694         pa_memblock_unref(u->write_memchunk.memblock);
695         pa_memchunk_reset(&u->write_memchunk);
696     }
697 
698     pa_log_debug("Audio stream torn down");
699     u->stream_setup_done = false;
700 }
701 
transport_acquire(struct userdata * u,bool optional)702 static int transport_acquire(struct userdata *u, bool optional) {
703     pa_assert(u->transport);
704 
705     if (u->transport_acquired)
706         return 0;
707 
708     pa_log_debug("Acquiring transport %s", u->transport->path);
709 
710     u->stream_fd = u->transport->acquire(u->transport, optional, &u->read_link_mtu, &u->write_link_mtu);
711     if (u->stream_fd < 0)
712         return u->stream_fd;
713 
714     /* transport_acquired must be set before calling
715      * pa_bluetooth_transport_set_state() */
716     u->transport_acquired = true;
717     pa_log_info("Transport %s acquired: fd %d", u->transport->path, u->stream_fd);
718 
719     if (u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_IDLE) {
720         if (pa_thread_mq_get() != NULL)
721             pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING, NULL, 0, NULL, NULL);
722         else
723             pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
724     }
725 
726     return 0;
727 }
728 
transport_release(struct userdata * u)729 static void transport_release(struct userdata *u) {
730     pa_assert(u->transport);
731 
732     /* Ignore if already released */
733     if (!u->transport_acquired)
734         return;
735 
736     pa_log_debug("Releasing transport %s", u->transport->path);
737 
738     u->transport->release(u->transport);
739 
740     u->transport_acquired = false;
741 
742     teardown_stream(u);
743 
744     /* Set transport state to idle if this was not already done by the remote end closing
745      * the file descriptor. Only do this when called from the I/O thread */
746     if (pa_thread_mq_get() != NULL && u->transport->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING)
747         pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
748 }
749 
750 /* Run from I/O thread */
handle_sink_block_size_change(struct userdata * u)751 static void handle_sink_block_size_change(struct userdata *u) {
752     pa_sink_set_max_request_within_thread(u->sink, u->write_block_size);
753     pa_sink_set_fixed_latency_within_thread(u->sink,
754                                             (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK ?
755                                              FIXED_LATENCY_PLAYBACK_A2DP : FIXED_LATENCY_PLAYBACK_SCO) +
756                                             pa_bytes_to_usec(u->write_block_size, &u->encoder_sample_spec));
757 
758     /* If there is still data in the memchunk, we have to discard it
759      * because the write_block_size may have changed. */
760     if (u->write_memchunk.memblock) {
761         pa_memblock_unref(u->write_memchunk.memblock);
762         pa_memchunk_reset(&u->write_memchunk);
763     }
764 
765     update_sink_buffer_size(u);
766 }
767 
768 /* Run from I/O thread */
transport_config_mtu(struct userdata * u)769 static void transport_config_mtu(struct userdata *u) {
770     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
771         u->read_block_size = u->read_link_mtu;
772         u->write_block_size = u->write_link_mtu;
773 
774         if (!pa_frame_aligned(u->read_block_size, &u->source->sample_spec)) {
775             pa_log_debug("Got invalid read MTU: %lu, rounding down", u->read_block_size);
776             u->read_block_size = pa_frame_align(u->read_block_size, &u->source->sample_spec);
777         }
778 
779         if (!pa_frame_aligned(u->write_block_size, &u->sink->sample_spec)) {
780             pa_log_debug("Got invalid write MTU: %lu, rounding down", u->write_block_size);
781             u->write_block_size = pa_frame_align(u->write_block_size, &u->sink->sample_spec);
782         }
783     } else {
784         pa_assert(u->a2dp_codec);
785         if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
786             u->write_block_size = u->a2dp_codec->get_write_block_size(u->encoder_info, u->write_link_mtu);
787         } else {
788             u->read_block_size = u->a2dp_codec->get_read_block_size(u->decoder_info, u->read_link_mtu);
789         }
790     }
791 
792     if (u->sink)
793         handle_sink_block_size_change(u);
794 
795     if (u->source)
796         pa_source_set_fixed_latency_within_thread(u->source,
797                                                   (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE ?
798                                                    FIXED_LATENCY_RECORD_A2DP : FIXED_LATENCY_RECORD_SCO) +
799                                                   pa_bytes_to_usec(u->read_block_size, &u->decoder_sample_spec));
800 }
801 
802 /* Run from I/O thread */
setup_stream(struct userdata * u)803 static int setup_stream(struct userdata *u) {
804     struct pollfd *pollfd;
805     int one;
806 
807     pa_assert(u->stream_fd >= 0);
808 
809     /* return if stream is already set up */
810     if (u->stream_setup_done)
811         return 0;
812 
813     pa_log_info("Transport %s resuming", u->transport->path);
814 
815     if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
816         pa_assert(u->a2dp_codec);
817         if (u->a2dp_codec->reset(u->encoder_info) < 0)
818             return -1;
819     } else if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE) {
820         pa_assert(u->a2dp_codec);
821         if (u->a2dp_codec->reset(u->decoder_info) < 0)
822             return -1;
823     }
824 
825     transport_config_mtu(u);
826 
827     pa_make_fd_nonblock(u->stream_fd);
828     pa_make_socket_low_delay(u->stream_fd);
829 
830     one = 1;
831     if (setsockopt(u->stream_fd, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) < 0)
832         pa_log_warn("Failed to enable SO_TIMESTAMP: %s", pa_cstrerror(errno));
833 
834     pa_log_debug("Stream properly set up, we're ready to roll!");
835 
836     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
837     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
838     pollfd->fd = u->stream_fd;
839     pollfd->events = pollfd->revents = 0;
840 
841     u->read_index = u->write_index = 0;
842     u->started_at = 0;
843     u->stream_setup_done = true;
844 
845     if (u->source)
846         u->read_smoother = pa_smoother_new(PA_USEC_PER_SEC, 2*PA_USEC_PER_SEC, true, true, 10, pa_rtclock_now(), true);
847 
848     return 0;
849 }
850 
851 /* Called from I/O thread, returns true if the transport was acquired or
852  * a connection was requested successfully. */
setup_transport_and_stream(struct userdata * u)853 static bool setup_transport_and_stream(struct userdata *u) {
854     int transport_error;
855 
856     transport_error = transport_acquire(u, false);
857     if (transport_error < 0) {
858         if (transport_error != -EAGAIN)
859             return false;
860     } else {
861         if (setup_stream(u) < 0)
862             return false;
863     }
864     return true;
865 }
866 
867 /* Run from IO thread */
source_process_msg(pa_msgobject * o,int code,void * data,int64_t offset,pa_memchunk * chunk)868 static int source_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
869     struct userdata *u = PA_SOURCE(o)->userdata;
870 
871     pa_assert(u->source == PA_SOURCE(o));
872     pa_assert(u->transport);
873 
874     switch (code) {
875 
876         case PA_SOURCE_MESSAGE_GET_LATENCY: {
877             int64_t wi, ri;
878 
879             if (u->read_smoother) {
880                 wi = pa_smoother_get(u->read_smoother, pa_rtclock_now());
881                 ri = pa_bytes_to_usec(u->read_index, &u->decoder_sample_spec);
882 
883                 *((int64_t*) data) = u->source->thread_info.fixed_latency + wi - ri;
884             } else
885                 *((int64_t*) data) = 0;
886 
887             return 0;
888         }
889 
890         case PA_SOURCE_MESSAGE_SETUP_STREAM:
891             /* Skip stream setup if stream_fd has been invalidated.
892                This can occur if the stream has already been set up and
893                then immediately received POLLHUP. If the stream has
894                already been set up earlier, then this setup_stream()
895                call is redundant anyway, but currently the code
896                is such that this kind of unnecessary setup_stream()
897                calls can happen. */
898             if (u->stream_fd < 0)
899                 pa_log_debug("Skip source stream setup while closing");
900             else
901                 setup_stream(u);
902             return 0;
903 
904     }
905 
906     return pa_source_process_msg(o, code, data, offset, chunk);
907 }
908 
909 /* 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)910 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) {
911     struct userdata *u;
912 
913     pa_assert(s);
914     pa_assert_se(u = s->userdata);
915 
916     switch (new_state) {
917 
918         case PA_SOURCE_SUSPENDED:
919             /* Ignore if transition is PA_SOURCE_INIT->PA_SOURCE_SUSPENDED */
920             if (!PA_SOURCE_IS_OPENED(s->thread_info.state))
921                 break;
922 
923             /* Stop the device if the sink is suspended as well */
924             if (!u->sink || u->sink->state == PA_SINK_SUSPENDED)
925                 transport_release(u);
926 
927             if (u->read_smoother)
928                 pa_smoother_pause(u->read_smoother, pa_rtclock_now());
929 
930             break;
931 
932         case PA_SOURCE_IDLE:
933         case PA_SOURCE_RUNNING:
934             if (s->thread_info.state != PA_SOURCE_SUSPENDED)
935                 break;
936 
937             /* Resume the device if the sink was suspended as well */
938             if (!u->sink || !PA_SINK_IS_OPENED(u->sink->thread_info.state))
939                 if (!setup_transport_and_stream(u))
940                     return -1;
941 
942             /* We don't resume the smoother here. Instead we
943              * wait until the first packet arrives */
944 
945             break;
946 
947         case PA_SOURCE_UNLINKED:
948         case PA_SOURCE_INIT:
949         case PA_SOURCE_INVALID_STATE:
950             break;
951     }
952 
953     return 0;
954 }
955 
956 /* Run from main thread */
source_set_volume_cb(pa_source * s)957 static void source_set_volume_cb(pa_source *s) {
958     uint16_t gain;
959     pa_volume_t volume;
960     struct userdata *u;
961 
962     pa_assert(s);
963     pa_assert(s->core);
964 
965     u = s->userdata;
966 
967     pa_assert(u);
968     pa_assert(u->source == s);
969 
970     if (u->transport->set_microphone_gain == NULL)
971       return;
972 
973     gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
974 
975     if (gain > HSP_MAX_GAIN)
976         gain = HSP_MAX_GAIN;
977 
978     volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
979 
980     /* increment volume by one to correct rounding errors */
981     if (volume < PA_VOLUME_NORM)
982         volume++;
983 
984     pa_cvolume_set(&s->real_volume, u->decoder_sample_spec.channels, volume);
985 
986     /* Set soft volume when in headset role */
987     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
988         pa_cvolume_set(&s->soft_volume, u->decoder_sample_spec.channels, volume);
989 
990     /* If we are in the AG role, we send a command to the head set to change
991      * the microphone gain. In the HS role, source and sink are swapped, so
992      * in this case we notify the AG that the speaker gain has changed */
993     u->transport->set_microphone_gain(u->transport, gain);
994 }
995 
996 /* Run from main thread */
add_source(struct userdata * u)997 static int add_source(struct userdata *u) {
998     pa_source_new_data data;
999 
1000     pa_assert(u->transport);
1001 
1002     pa_source_new_data_init(&data);
1003     data.module = u->module;
1004     data.card = u->card;
1005     data.driver = __FILE__;
1006     data.name = pa_sprintf_malloc("bluez_source.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1007     data.namereg_fail = false;
1008     pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1009     pa_source_new_data_set_sample_spec(&data, &u->decoder_sample_spec);
1010     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1011         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1012 
1013     connect_ports(u, &data, PA_DIRECTION_INPUT);
1014 
1015     if (!u->transport_acquired)
1016         switch (u->profile) {
1017             case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1018             case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1019                 data.suspend_cause = PA_SUSPEND_USER;
1020                 break;
1021             case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1022                 /* u->stream_fd contains the error returned by the last transport_acquire()
1023                  * EAGAIN means we are waiting for a NewConnection signal */
1024                 if (u->stream_fd == -EAGAIN)
1025                     data.suspend_cause = PA_SUSPEND_USER;
1026                 else
1027                     pa_assert_not_reached();
1028                 break;
1029             case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1030             case PA_BLUETOOTH_PROFILE_OFF:
1031                 pa_assert_not_reached();
1032                 break;
1033         }
1034 
1035     u->source = pa_source_new(u->core, &data, PA_SOURCE_HARDWARE|PA_SOURCE_LATENCY);
1036     pa_source_new_data_done(&data);
1037     if (!u->source) {
1038         pa_log_error("Failed to create source");
1039         return -1;
1040     }
1041 
1042     u->source->userdata = u;
1043     u->source->parent.process_msg = source_process_msg;
1044     u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
1045 
1046     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1047         pa_source_set_set_volume_callback(u->source, source_set_volume_cb);
1048         u->source->n_volume_steps = 16;
1049     }
1050     return 0;
1051 }
1052 
1053 /* Run from IO thread */
sink_process_msg(pa_msgobject * o,int code,void * data,int64_t offset,pa_memchunk * chunk)1054 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
1055     struct userdata *u = PA_SINK(o)->userdata;
1056 
1057     pa_assert(u->sink == PA_SINK(o));
1058     pa_assert(u->transport);
1059 
1060     switch (code) {
1061 
1062         case PA_SINK_MESSAGE_GET_LATENCY: {
1063             int64_t wi = 0, ri = 0;
1064 
1065             if (u->read_smoother) {
1066                 ri = pa_smoother_get(u->read_smoother, pa_rtclock_now());
1067                 wi = pa_bytes_to_usec(u->write_index + u->write_block_size, &u->encoder_sample_spec);
1068             } else if (u->started_at) {
1069                 ri = pa_rtclock_now() - u->started_at;
1070                 wi = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1071             }
1072 
1073             *((int64_t*) data) = u->sink->thread_info.fixed_latency + wi - ri;
1074 
1075             return 0;
1076         }
1077 
1078         case PA_SINK_MESSAGE_SETUP_STREAM:
1079             /* Skip stream setup if stream_fd has been invalidated.
1080                This can occur if the stream has already been set up and
1081                then immediately received POLLHUP. If the stream has
1082                already been set up earlier, then this setup_stream()
1083                call is redundant anyway, but currently the code
1084                is such that this kind of unnecessary setup_stream()
1085                calls can happen. */
1086             if (u->stream_fd < 0)
1087                 pa_log_debug("Skip sink stream setup while closing");
1088             else
1089                 setup_stream(u);
1090             return 0;
1091     }
1092 
1093     return pa_sink_process_msg(o, code, data, offset, chunk);
1094 }
1095 
1096 /* 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)1097 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) {
1098     struct userdata *u;
1099 
1100     pa_assert(s);
1101     pa_assert_se(u = s->userdata);
1102 
1103     switch (new_state) {
1104 
1105         case PA_SINK_SUSPENDED:
1106             /* Ignore if transition is PA_SINK_INIT->PA_SINK_SUSPENDED */
1107             if (!PA_SINK_IS_OPENED(s->thread_info.state))
1108                 break;
1109 
1110             /* Stop the device if the source is suspended as well */
1111             if (!u->source || u->source->state == PA_SOURCE_SUSPENDED)
1112                 /* We deliberately ignore whether stopping
1113                  * actually worked. Since the stream_fd is
1114                  * closed it doesn't really matter */
1115                 transport_release(u);
1116 
1117             break;
1118 
1119         case PA_SINK_IDLE:
1120         case PA_SINK_RUNNING:
1121             if (s->thread_info.state != PA_SINK_SUSPENDED)
1122                 break;
1123 
1124             /* Resume the device if the source was suspended as well */
1125             if (!u->source || !PA_SOURCE_IS_OPENED(u->source->thread_info.state))
1126                 if (!setup_transport_and_stream(u))
1127                     return -1;
1128 
1129             break;
1130 
1131         case PA_SINK_UNLINKED:
1132         case PA_SINK_INIT:
1133         case PA_SINK_INVALID_STATE:
1134             break;
1135     }
1136 
1137     return 0;
1138 }
1139 
1140 /* Run from main thread */
sink_set_volume_cb(pa_sink * s)1141 static void sink_set_volume_cb(pa_sink *s) {
1142     uint16_t gain;
1143     pa_volume_t volume;
1144     struct userdata *u;
1145 
1146     pa_assert(s);
1147     pa_assert(s->core);
1148 
1149     u = s->userdata;
1150 
1151     pa_assert(u);
1152     pa_assert(u->sink == s);
1153 
1154     if (u->transport->set_speaker_gain == NULL)
1155       return;
1156 
1157     gain = (pa_cvolume_max(&s->real_volume) * HSP_MAX_GAIN) / PA_VOLUME_NORM;
1158 
1159     if (gain > HSP_MAX_GAIN)
1160         gain = HSP_MAX_GAIN;
1161 
1162     volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
1163 
1164     /* increment volume by one to correct rounding errors */
1165     if (volume < PA_VOLUME_NORM)
1166         volume++;
1167 
1168     pa_cvolume_set(&s->real_volume, u->encoder_sample_spec.channels, volume);
1169 
1170     /* Set soft volume when in headset role */
1171     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1172         pa_cvolume_set(&s->soft_volume, u->encoder_sample_spec.channels, volume);
1173 
1174     /* If we are in the AG role, we send a command to the head set to change
1175      * the speaker gain. In the HS role, source and sink are swapped, so
1176      * in this case we notify the AG that the microphone gain has changed */
1177     u->transport->set_speaker_gain(u->transport, gain);
1178 }
1179 
1180 /* Run from main thread */
add_sink(struct userdata * u)1181 static int add_sink(struct userdata *u) {
1182     pa_sink_new_data data;
1183 
1184     pa_assert(u->transport);
1185 
1186     pa_sink_new_data_init(&data);
1187     data.module = u->module;
1188     data.card = u->card;
1189     data.driver = __FILE__;
1190     data.name = pa_sprintf_malloc("bluez_sink.%s.%s", u->device->address, pa_bluetooth_profile_to_string(u->profile));
1191     data.namereg_fail = false;
1192     pa_proplist_sets(data.proplist, "bluetooth.protocol", pa_bluetooth_profile_to_string(u->profile));
1193     pa_sink_new_data_set_sample_spec(&data, &u->encoder_sample_spec);
1194     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
1195         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_INTENDED_ROLES, "phone");
1196 
1197     connect_ports(u, &data, PA_DIRECTION_OUTPUT);
1198 
1199     if (!u->transport_acquired)
1200         switch (u->profile) {
1201             case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1202                 data.suspend_cause = PA_SUSPEND_USER;
1203                 break;
1204             case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1205                 /* u->stream_fd contains the error returned by the last transport_acquire()
1206                  * EAGAIN means we are waiting for a NewConnection signal */
1207                 if (u->stream_fd == -EAGAIN)
1208                     data.suspend_cause = PA_SUSPEND_USER;
1209                 else
1210                     pa_assert_not_reached();
1211                 break;
1212             case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1213                 /* Profile switch should have failed */
1214             case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1215             case PA_BLUETOOTH_PROFILE_OFF:
1216                 pa_assert_not_reached();
1217                 break;
1218         }
1219 
1220     u->sink = pa_sink_new(u->core, &data, PA_SINK_HARDWARE|PA_SINK_LATENCY);
1221     pa_sink_new_data_done(&data);
1222     if (!u->sink) {
1223         pa_log_error("Failed to create sink");
1224         return -1;
1225     }
1226 
1227     u->sink->userdata = u;
1228     u->sink->parent.process_msg = sink_process_msg;
1229     u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
1230 
1231     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1232         pa_sink_set_set_volume_callback(u->sink, sink_set_volume_cb);
1233         u->sink->n_volume_steps = 16;
1234     }
1235     return 0;
1236 }
1237 
1238 /* Run from main thread */
transport_config(struct userdata * u)1239 static int transport_config(struct userdata *u) {
1240     if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY) {
1241         u->encoder_sample_spec.format = PA_SAMPLE_S16LE;
1242         u->encoder_sample_spec.channels = 1;
1243         u->encoder_sample_spec.rate = 8000;
1244         u->decoder_sample_spec.format = PA_SAMPLE_S16LE;
1245         u->decoder_sample_spec.channels = 1;
1246         u->decoder_sample_spec.rate = 8000;
1247         return 0;
1248     } else {
1249         bool is_a2dp_sink = u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK;
1250         void *info;
1251 
1252         pa_assert(u->transport);
1253 
1254         pa_assert(!u->a2dp_codec);
1255         pa_assert(!u->encoder_info);
1256         pa_assert(!u->decoder_info);
1257 
1258         u->a2dp_codec = u->transport->a2dp_codec;
1259         pa_assert(u->a2dp_codec);
1260 
1261         info = u->a2dp_codec->init(is_a2dp_sink, false, u->transport->config, u->transport->config_size, is_a2dp_sink ? &u->encoder_sample_spec : &u->decoder_sample_spec);
1262         if (is_a2dp_sink)
1263             u->encoder_info = info;
1264         else
1265             u->decoder_info = info;
1266 
1267         if (!info)
1268             return -1;
1269 
1270         return 0;
1271     }
1272 }
1273 
1274 /* Run from main thread */
setup_transport(struct userdata * u)1275 static int setup_transport(struct userdata *u) {
1276     pa_bluetooth_transport *t;
1277 
1278     pa_assert(u);
1279     pa_assert(!u->transport);
1280     pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1281 
1282     /* check if profile has a transport */
1283     t = u->device->transports[u->profile];
1284     if (!t || t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1285         pa_log_warn("Profile %s has no transport", pa_bluetooth_profile_to_string(u->profile));
1286         return -1;
1287     }
1288 
1289     u->transport = t;
1290 
1291     if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE || u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1292         transport_acquire(u, true); /* In case of error, the sink/sources will be created suspended */
1293     else {
1294         int transport_error;
1295 
1296         transport_error = transport_acquire(u, false);
1297         if (transport_error < 0 && transport_error != -EAGAIN)
1298             return -1; /* We need to fail here until the interactions with module-suspend-on-idle and alike get improved */
1299     }
1300 
1301     return transport_config(u);
1302 }
1303 
1304 /* Run from main thread */
get_profile_direction(pa_bluetooth_profile_t p)1305 static pa_direction_t get_profile_direction(pa_bluetooth_profile_t p) {
1306     static const pa_direction_t profile_direction[] = {
1307         [PA_BLUETOOTH_PROFILE_A2DP_SINK] = PA_DIRECTION_OUTPUT,
1308         [PA_BLUETOOTH_PROFILE_A2DP_SOURCE] = PA_DIRECTION_INPUT,
1309         [PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1310         [PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY] = PA_DIRECTION_INPUT | PA_DIRECTION_OUTPUT,
1311         [PA_BLUETOOTH_PROFILE_OFF] = 0
1312     };
1313 
1314     return profile_direction[p];
1315 }
1316 
1317 /* Run from main thread */
init_profile(struct userdata * u)1318 static int init_profile(struct userdata *u) {
1319     int r = 0;
1320     pa_assert(u);
1321     pa_assert(u->profile != PA_BLUETOOTH_PROFILE_OFF);
1322 
1323     if (setup_transport(u) < 0)
1324         return -1;
1325 
1326     pa_assert(u->transport);
1327 
1328     if (get_profile_direction (u->profile) & PA_DIRECTION_OUTPUT)
1329         if (add_sink(u) < 0)
1330             r = -1;
1331 
1332     if (get_profile_direction (u->profile) & PA_DIRECTION_INPUT)
1333         if (add_source(u) < 0)
1334             r = -1;
1335 
1336     return r;
1337 }
1338 
write_block(struct userdata * u)1339 static int write_block(struct userdata *u) {
1340     int n_written;
1341 
1342     if (u->write_index <= 0)
1343         u->started_at = pa_rtclock_now();
1344 
1345     if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
1346         if ((n_written = a2dp_process_render(u)) < 0)
1347             return -1;
1348     } else {
1349         if ((n_written = sco_process_render(u)) < 0)
1350             return -1;
1351     }
1352 
1353     return n_written;
1354 }
1355 
1356 
1357 /* I/O thread function */
thread_func(void * userdata)1358 static void thread_func(void *userdata) {
1359     struct userdata *u = userdata;
1360     unsigned blocks_to_write = 0;
1361     unsigned bytes_to_write = 0;
1362 
1363     pa_assert(u);
1364     pa_assert(u->transport);
1365 
1366     pa_log_debug("IO Thread starting up");
1367 
1368     if (u->core->realtime_scheduling)
1369         pa_thread_make_realtime(u->core->realtime_priority);
1370 
1371     pa_thread_mq_install(&u->thread_mq);
1372 
1373     /* Setup the stream only if the transport was already acquired */
1374     if (u->transport_acquired)
1375         setup_stream(u);
1376 
1377     for (;;) {
1378         struct pollfd *pollfd;
1379         int ret;
1380         bool disable_timer = true;
1381         bool writable = false;
1382         bool have_source = u->source ? PA_SOURCE_IS_LINKED(u->source->thread_info.state) : false;
1383         bool have_sink = u->sink ? PA_SINK_IS_LINKED(u->sink->thread_info.state) : false;
1384 
1385         pollfd = u->rtpoll_item ? pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL) : NULL;
1386 
1387         /* Check for stream error or close */
1388         if (pollfd && (pollfd->revents & ~(POLLOUT|POLLIN))) {
1389             pa_log_info("FD error: %s%s%s%s",
1390                         pollfd->revents & POLLERR ? "POLLERR " :"",
1391                         pollfd->revents & POLLHUP ? "POLLHUP " :"",
1392                         pollfd->revents & POLLPRI ? "POLLPRI " :"",
1393                         pollfd->revents & POLLNVAL ? "POLLNVAL " :"");
1394 
1395             if (pollfd->revents & POLLHUP) {
1396                 pollfd = NULL;
1397                 teardown_stream(u);
1398                 blocks_to_write = 0;
1399                 bytes_to_write = 0;
1400                 pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_STREAM_FD_HUP, NULL, 0, NULL, NULL);
1401             } else
1402                 goto fail;
1403         }
1404 
1405         /* If there is a pollfd, the stream is set up and we need to do something */
1406         if (pollfd) {
1407 
1408             /* Handle source if present */
1409             if (have_source) {
1410 
1411                 /* We should send two blocks to the device before we expect a response. */
1412                 if (have_sink && u->write_index == 0 && u->read_index <= 0)
1413                     blocks_to_write = 2;
1414 
1415                 /* If we got woken up by POLLIN let's do some reading */
1416                 if (pollfd->revents & POLLIN) {
1417                     int n_read;
1418 
1419                     if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1420                         n_read = a2dp_process_push(u);
1421                     else
1422                         n_read = sco_process_push(u);
1423 
1424                     if (n_read < 0)
1425                         goto fail;
1426 
1427                     if (have_sink && n_read > 0) {
1428                         /* We just read something, so we are supposed to write something, too */
1429                         bytes_to_write += n_read;
1430                         blocks_to_write += bytes_to_write / u->write_block_size;
1431                         bytes_to_write = bytes_to_write % u->write_block_size;
1432                     }
1433                 }
1434             }
1435 
1436             /* Handle sink if present */
1437             if (have_sink) {
1438 
1439                 /* Process rewinds */
1440                 if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
1441                     pa_sink_process_rewind(u->sink, 0);
1442 
1443                 /* Test if the stream is writable */
1444                 if (pollfd->revents & POLLOUT)
1445                     writable = true;
1446 
1447                 /* If we have a source, we let the source determine the timing
1448                  * for the sink */
1449                 if (have_source) {
1450 
1451                     if (writable && blocks_to_write > 0) {
1452                         int result;
1453 
1454                         if ((result = write_block(u)) < 0)
1455                             goto fail;
1456 
1457                         blocks_to_write -= result;
1458 
1459                         /* writable controls whether we set POLLOUT when polling - we set it to
1460                          * false to enable POLLOUT. If there are more blocks to write, we want to
1461                          * be woken up immediately when the socket becomes writable. If there
1462                          * aren't currently any more blocks to write, then we'll have to wait
1463                          * until we've received more data, so in that case we only want to set
1464                          * POLLIN. Note that when we are woken up the next time, POLLOUT won't be
1465                          * set in revents even if the socket has meanwhile become writable, which
1466                          * may seem bad, but in that case we'll set POLLOUT in the subsequent
1467                          * poll, and the poll will return immediately, so our writes won't be
1468                          * delayed. */
1469                         if (blocks_to_write > 0)
1470                             writable = false;
1471                     }
1472 
1473                 /* There is no source, we have to use the system clock for timing */
1474                 } else {
1475                     bool have_written = false;
1476                     pa_usec_t time_passed = 0;
1477                     pa_usec_t audio_sent = 0;
1478 
1479                     if (u->started_at) {
1480                         time_passed = pa_rtclock_now() - u->started_at;
1481                         audio_sent = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1482                     }
1483 
1484                     /* A new block needs to be sent. */
1485                     if (audio_sent <= time_passed) {
1486                         size_t bytes_to_send = pa_usec_to_bytes(time_passed - audio_sent, &u->encoder_sample_spec);
1487 
1488                         /* There are more than two blocks that need to be written. It seems that
1489                          * the socket has not been accepting data fast enough (could be due to
1490                          * hiccups in the wireless transmission). We need to discard everything
1491                          * older than two block sizes to keep the latency from growing. */
1492                         if (bytes_to_send > 2 * u->write_block_size) {
1493                             uint64_t skip_bytes;
1494                             pa_memchunk tmp;
1495                             size_t mempool_max_block_size = pa_mempool_block_size_max(u->core->mempool);
1496                             pa_usec_t skip_usec;
1497 
1498                             skip_bytes = bytes_to_send - 2 * u->write_block_size;
1499                             skip_usec = pa_bytes_to_usec(skip_bytes, &u->encoder_sample_spec);
1500 
1501                             pa_log_debug("Skipping %llu us (= %llu bytes) in audio stream",
1502                                         (unsigned long long) skip_usec,
1503                                         (unsigned long long) skip_bytes);
1504 
1505                             while (skip_bytes > 0) {
1506                                 size_t bytes_to_render;
1507 
1508                                 if (skip_bytes > mempool_max_block_size)
1509                                     bytes_to_render = mempool_max_block_size;
1510                                 else
1511                                     bytes_to_render = skip_bytes;
1512 
1513                                 pa_sink_render_full(u->sink, bytes_to_render, &tmp);
1514                                 pa_memblock_unref(tmp.memblock);
1515                                 u->write_index += bytes_to_render;
1516                                 skip_bytes -= bytes_to_render;
1517                             }
1518 
1519                             if (u->write_index > 0 && u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK) {
1520                                 size_t new_write_block_size = u->a2dp_codec->reduce_encoder_bitrate(u->encoder_info, u->write_link_mtu);
1521                                 if (new_write_block_size) {
1522                                     u->write_block_size = new_write_block_size;
1523                                     handle_sink_block_size_change(u);
1524                                 }
1525                             }
1526                         }
1527 
1528                         blocks_to_write = 1;
1529                     }
1530 
1531                     /* If the stream is writable, send some data if necessary */
1532                     if (writable && blocks_to_write > 0) {
1533                         int result;
1534 
1535                         if ((result = write_block(u)) < 0)
1536                             goto fail;
1537 
1538                         blocks_to_write -= result;
1539                         writable = false;
1540                         if (result)
1541                             have_written = true;
1542                     }
1543 
1544                     /* If nothing was written during this iteration, either the stream
1545                      * is not writable or there was no write pending. Set up a timer that
1546                      * will wake up the thread when the next data needs to be written. */
1547                     if (!have_written) {
1548                         pa_usec_t sleep_for;
1549                         pa_usec_t next_write_at;
1550 
1551                         if (writable) {
1552                             /* There was no write pending on this iteration of the loop.
1553                              * Let's estimate when we need to wake up next */
1554                             next_write_at = pa_bytes_to_usec(u->write_index, &u->encoder_sample_spec);
1555                             sleep_for = time_passed < next_write_at ? next_write_at - time_passed : 0;
1556                             /* 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); */
1557                         } else
1558                             /* We could not write because the stream was not ready. Let's try
1559                              * again in 500 ms and drop audio if we still can't write. The
1560                              * thread will also be woken up when we can write again. */
1561                             sleep_for = PA_USEC_PER_MSEC * 500;
1562 
1563                         pa_rtpoll_set_timer_relative(u->rtpoll, sleep_for);
1564                         disable_timer = false;
1565                     }
1566                 }
1567             }
1568 
1569             /* Set events to wake up the thread */
1570             pollfd->events = (short) (((have_sink && !writable) ? POLLOUT : 0) | (have_source ? POLLIN : 0));
1571 
1572         }
1573 
1574         if (disable_timer)
1575             pa_rtpoll_set_timer_disabled(u->rtpoll);
1576 
1577         if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) {
1578             pa_log_debug("pa_rtpoll_run failed with: %d", ret);
1579             goto fail;
1580         }
1581 
1582         if (ret == 0) {
1583             pa_log_debug("IO thread shutdown requested, stopping cleanly");
1584             transport_release(u);
1585             goto finish;
1586         }
1587     }
1588 
1589 fail:
1590     /* If this was no regular exit from the loop we have to continue processing messages until we receive PA_MESSAGE_SHUTDOWN */
1591     pa_log_debug("IO thread failed");
1592     pa_asyncmsgq_post(pa_thread_mq_get()->outq, PA_MSGOBJECT(u->msg), BLUETOOTH_MESSAGE_IO_THREAD_FAILED, NULL, 0, NULL, NULL);
1593     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
1594 
1595 finish:
1596     pa_log_debug("IO thread shutting down");
1597 }
1598 
1599 /* Run from main thread */
start_thread(struct userdata * u)1600 static int start_thread(struct userdata *u) {
1601     pa_assert(u);
1602     pa_assert(!u->thread);
1603     pa_assert(!u->rtpoll);
1604     pa_assert(!u->rtpoll_item);
1605 
1606     u->rtpoll = pa_rtpoll_new();
1607 
1608     if (pa_thread_mq_init(&u->thread_mq, u->core->mainloop, u->rtpoll) < 0) {
1609         pa_log("pa_thread_mq_init() failed.");
1610         return -1;
1611     }
1612 
1613     if (!(u->thread = pa_thread_new("bluetooth", thread_func, u))) {
1614         pa_log_error("Failed to create IO thread");
1615         return -1;
1616     }
1617 
1618     if (u->sink) {
1619         pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
1620         pa_sink_set_rtpoll(u->sink, u->rtpoll);
1621 
1622         /* If we are in the headset role, the sink should not become default
1623          * unless there is no other sound device available. */
1624         if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY)
1625             u->sink->priority = 1500;
1626 
1627         pa_sink_put(u->sink);
1628 
1629         if (u->sink->set_volume)
1630             u->sink->set_volume(u->sink);
1631     }
1632 
1633     if (u->source) {
1634         pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
1635         pa_source_set_rtpoll(u->source, u->rtpoll);
1636 
1637         /* If we are in the headset role or the device is an a2dp source,
1638          * the source should not become default unless there is no other
1639          * sound device available. */
1640         if (u->profile == PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY || u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE)
1641             u->source->priority = 1500;
1642 
1643         pa_source_put(u->source);
1644 
1645         if (u->source->set_volume)
1646             u->source->set_volume(u->source);
1647     }
1648 
1649     return 0;
1650 }
1651 
1652 /* Run from main thread */
stop_thread(struct userdata * u)1653 static void stop_thread(struct userdata *u) {
1654     pa_assert(u);
1655 
1656     if (u->sink)
1657         pa_sink_unlink(u->sink);
1658 
1659     if (u->source)
1660         pa_source_unlink(u->source);
1661 
1662     if (u->thread) {
1663         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
1664         pa_thread_free(u->thread);
1665         u->thread = NULL;
1666     }
1667 
1668     if (u->rtpoll_item) {
1669         pa_rtpoll_item_free(u->rtpoll_item);
1670         u->rtpoll_item = NULL;
1671     }
1672 
1673     if (u->rtpoll) {
1674         pa_rtpoll_free(u->rtpoll);
1675         u->rtpoll = NULL;
1676         pa_thread_mq_done(&u->thread_mq);
1677     }
1678 
1679     if (u->transport) {
1680         transport_release(u);
1681         u->transport = NULL;
1682     }
1683 
1684     if (u->sink) {
1685         pa_sink_unref(u->sink);
1686         u->sink = NULL;
1687     }
1688 
1689     if (u->source) {
1690         pa_source_unref(u->source);
1691         u->source = NULL;
1692     }
1693 
1694     if (u->read_smoother) {
1695         pa_smoother_free(u->read_smoother);
1696         u->read_smoother = NULL;
1697     }
1698 
1699     if (u->profile == PA_BLUETOOTH_PROFILE_A2DP_SINK || u->profile == PA_BLUETOOTH_PROFILE_A2DP_SOURCE) {
1700         if (u->encoder_info) {
1701             u->a2dp_codec->deinit(u->encoder_info);
1702             u->encoder_info = NULL;
1703         }
1704 
1705         if (u->decoder_info) {
1706             u->a2dp_codec->deinit(u->decoder_info);
1707             u->decoder_info = NULL;
1708         }
1709 
1710         u->a2dp_codec = NULL;
1711     }
1712 }
1713 
1714 /* Run from main thread */
get_port_availability(struct userdata * u,pa_direction_t direction)1715 static pa_available_t get_port_availability(struct userdata *u, pa_direction_t direction) {
1716     pa_available_t result = PA_AVAILABLE_NO;
1717     unsigned i;
1718 
1719     pa_assert(u);
1720     pa_assert(u->device);
1721 
1722     for (i = 0; i < PA_BLUETOOTH_PROFILE_COUNT; i++) {
1723         pa_bluetooth_transport *transport;
1724 
1725         if (!(get_profile_direction(i) & direction))
1726             continue;
1727 
1728         if (!(transport = u->device->transports[i]))
1729             continue;
1730 
1731         switch(transport->state) {
1732             case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1733                 continue;
1734 
1735             case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
1736                 if (result == PA_AVAILABLE_NO)
1737                     result = PA_AVAILABLE_UNKNOWN;
1738 
1739                 break;
1740 
1741             case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1742                 return PA_AVAILABLE_YES;
1743         }
1744     }
1745 
1746     return result;
1747 }
1748 
1749 /* Run from main thread */
transport_state_to_availability(pa_bluetooth_transport_state_t state)1750 static pa_available_t transport_state_to_availability(pa_bluetooth_transport_state_t state) {
1751     switch (state) {
1752         case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
1753             return PA_AVAILABLE_NO;
1754         case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
1755             return PA_AVAILABLE_YES;
1756         default:
1757             return PA_AVAILABLE_UNKNOWN;
1758     }
1759 }
1760 
1761 /* Run from main thread */
create_card_ports(struct userdata * u,pa_hashmap * ports)1762 static void create_card_ports(struct userdata *u, pa_hashmap *ports) {
1763     pa_device_port *port;
1764     pa_device_port_new_data port_data;
1765     pa_device_port_type_t input_type, output_type;
1766     const char *name_prefix, *input_description, *output_description;
1767 
1768     pa_assert(u);
1769     pa_assert(ports);
1770     pa_assert(u->device);
1771 
1772     name_prefix = "unknown";
1773     input_description = _("Bluetooth Input");
1774     output_description = _("Bluetooth Output");
1775     input_type = output_type = PA_DEVICE_PORT_TYPE_BLUETOOTH;
1776 
1777     switch (form_factor_from_class(u->device->class_of_device)) {
1778         case PA_BLUETOOTH_FORM_FACTOR_HEADSET:
1779             name_prefix = "headset";
1780             input_description = output_description = _("Headset");
1781             input_type = output_type = PA_DEVICE_PORT_TYPE_HEADSET;
1782             break;
1783 
1784         case PA_BLUETOOTH_FORM_FACTOR_HANDSFREE:
1785             name_prefix = "handsfree";
1786             input_description = output_description = _("Handsfree");
1787             input_type = output_type = PA_DEVICE_PORT_TYPE_HANDSFREE;
1788             break;
1789 
1790         case PA_BLUETOOTH_FORM_FACTOR_MICROPHONE:
1791             name_prefix = "microphone";
1792             input_description = _("Microphone");
1793             output_description = _("Bluetooth Output");
1794             input_type = PA_DEVICE_PORT_TYPE_MIC;
1795             break;
1796 
1797         case PA_BLUETOOTH_FORM_FACTOR_SPEAKER:
1798             name_prefix = "speaker";
1799             input_description = _("Bluetooth Input");
1800             output_description = _("Speaker");
1801             output_type = PA_DEVICE_PORT_TYPE_SPEAKER;
1802             break;
1803 
1804         case PA_BLUETOOTH_FORM_FACTOR_HEADPHONE:
1805             name_prefix = "headphone";
1806             input_description = _("Bluetooth Input");
1807             output_description = _("Headphone");
1808             output_type = PA_DEVICE_PORT_TYPE_HEADPHONES;
1809             break;
1810 
1811         case PA_BLUETOOTH_FORM_FACTOR_PORTABLE:
1812             name_prefix = "portable";
1813             input_description = output_description = _("Portable");
1814             input_type = output_type = PA_DEVICE_PORT_TYPE_PORTABLE;
1815             break;
1816 
1817         case PA_BLUETOOTH_FORM_FACTOR_CAR:
1818             name_prefix = "car";
1819             input_description = output_description = _("Car");
1820             input_type = output_type = PA_DEVICE_PORT_TYPE_CAR;
1821             break;
1822 
1823         case PA_BLUETOOTH_FORM_FACTOR_HIFI:
1824             name_prefix = "hifi";
1825             input_description = output_description = _("HiFi");
1826             input_type = output_type = PA_DEVICE_PORT_TYPE_HIFI;
1827             break;
1828 
1829         case PA_BLUETOOTH_FORM_FACTOR_PHONE:
1830             name_prefix = "phone";
1831             input_description = output_description = _("Phone");
1832             input_type = output_type = PA_DEVICE_PORT_TYPE_PHONE;
1833             break;
1834 
1835         case PA_BLUETOOTH_FORM_FACTOR_UNKNOWN:
1836             break;
1837     }
1838 
1839     u->output_port_name = pa_sprintf_malloc("%s-output", name_prefix);
1840     pa_device_port_new_data_init(&port_data);
1841     pa_device_port_new_data_set_name(&port_data, u->output_port_name);
1842     pa_device_port_new_data_set_description(&port_data, output_description);
1843     pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_OUTPUT);
1844     pa_device_port_new_data_set_type(&port_data, output_type);
1845     pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_OUTPUT));
1846     pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1847     pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1848     pa_device_port_new_data_done(&port_data);
1849 
1850     u->input_port_name = pa_sprintf_malloc("%s-input", name_prefix);
1851     pa_device_port_new_data_init(&port_data);
1852     pa_device_port_new_data_set_name(&port_data, u->input_port_name);
1853     pa_device_port_new_data_set_description(&port_data, input_description);
1854     pa_device_port_new_data_set_direction(&port_data, PA_DIRECTION_INPUT);
1855     pa_device_port_new_data_set_type(&port_data, input_type);
1856     pa_device_port_new_data_set_available(&port_data, get_port_availability(u, PA_DIRECTION_INPUT));
1857     pa_assert_se(port = pa_device_port_new(u->core, &port_data, 0));
1858     pa_assert_se(pa_hashmap_put(ports, port->name, port) >= 0);
1859     pa_device_port_new_data_done(&port_data);
1860 }
1861 
1862 /* Run from main thread */
create_card_profile(struct userdata * u,pa_bluetooth_profile_t profile,pa_hashmap * ports)1863 static pa_card_profile *create_card_profile(struct userdata *u, pa_bluetooth_profile_t profile, pa_hashmap *ports) {
1864     pa_device_port *input_port, *output_port;
1865     const char *name;
1866     pa_card_profile *cp = NULL;
1867     pa_bluetooth_profile_t *p;
1868 
1869     pa_assert(u->input_port_name);
1870     pa_assert(u->output_port_name);
1871     pa_assert_se(input_port = pa_hashmap_get(ports, u->input_port_name));
1872     pa_assert_se(output_port = pa_hashmap_get(ports, u->output_port_name));
1873 
1874     name = pa_bluetooth_profile_to_string(profile);
1875 
1876     switch (profile) {
1877     case PA_BLUETOOTH_PROFILE_A2DP_SINK:
1878         cp = pa_card_profile_new(name, _("High Fidelity Playback (A2DP Sink)"), sizeof(pa_bluetooth_profile_t));
1879         cp->priority = 40;
1880         cp->n_sinks = 1;
1881         cp->n_sources = 0;
1882         cp->max_sink_channels = 2;
1883         cp->max_source_channels = 0;
1884         pa_hashmap_put(output_port->profiles, cp->name, cp);
1885 
1886         p = PA_CARD_PROFILE_DATA(cp);
1887         break;
1888 
1889     case PA_BLUETOOTH_PROFILE_A2DP_SOURCE:
1890         cp = pa_card_profile_new(name, _("High Fidelity Capture (A2DP Source)"), sizeof(pa_bluetooth_profile_t));
1891         cp->priority = 20;
1892         cp->n_sinks = 0;
1893         cp->n_sources = 1;
1894         cp->max_sink_channels = 0;
1895         cp->max_source_channels = 2;
1896         pa_hashmap_put(input_port->profiles, cp->name, cp);
1897 
1898         p = PA_CARD_PROFILE_DATA(cp);
1899         break;
1900 
1901     case PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT:
1902         cp = pa_card_profile_new(name, _("Headset Head Unit (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
1903         cp->priority = 30;
1904         cp->n_sinks = 1;
1905         cp->n_sources = 1;
1906         cp->max_sink_channels = 1;
1907         cp->max_source_channels = 1;
1908         pa_hashmap_put(input_port->profiles, cp->name, cp);
1909         pa_hashmap_put(output_port->profiles, cp->name, cp);
1910 
1911         p = PA_CARD_PROFILE_DATA(cp);
1912         break;
1913 
1914     case PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY:
1915         cp = pa_card_profile_new(name, _("Headset Audio Gateway (HSP/HFP)"), sizeof(pa_bluetooth_profile_t));
1916         cp->priority = 10;
1917         cp->n_sinks = 1;
1918         cp->n_sources = 1;
1919         cp->max_sink_channels = 1;
1920         cp->max_source_channels = 1;
1921         pa_hashmap_put(input_port->profiles, cp->name, cp);
1922         pa_hashmap_put(output_port->profiles, cp->name, cp);
1923 
1924         p = PA_CARD_PROFILE_DATA(cp);
1925         break;
1926 
1927     case PA_BLUETOOTH_PROFILE_OFF:
1928         pa_assert_not_reached();
1929     }
1930 
1931     *p = profile;
1932 
1933     if (u->device->transports[*p])
1934         cp->available = transport_state_to_availability(u->device->transports[*p]->state);
1935     else
1936         cp->available = PA_AVAILABLE_NO;
1937 
1938     return cp;
1939 }
1940 
1941 /* Run from main thread */
set_profile_cb(pa_card * c,pa_card_profile * new_profile)1942 static int set_profile_cb(pa_card *c, pa_card_profile *new_profile) {
1943     struct userdata *u;
1944     pa_bluetooth_profile_t *p;
1945 
1946     pa_assert(c);
1947     pa_assert(new_profile);
1948     pa_assert_se(u = c->userdata);
1949 
1950     p = PA_CARD_PROFILE_DATA(new_profile);
1951 
1952     if (*p != PA_BLUETOOTH_PROFILE_OFF) {
1953         const pa_bluetooth_device *d = u->device;
1954 
1955         if (!d->transports[*p] || d->transports[*p]->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
1956             pa_log_warn("Refused to switch profile to %s: Not connected", new_profile->name);
1957             return -PA_ERR_IO;
1958         }
1959     }
1960 
1961     stop_thread(u);
1962 
1963     u->profile = *p;
1964 
1965     if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
1966         if (init_profile(u) < 0)
1967             goto off;
1968 
1969     if (u->sink || u->source)
1970         if (start_thread(u) < 0)
1971             goto off;
1972 
1973     return 0;
1974 
1975 off:
1976     stop_thread(u);
1977 
1978     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
1979 
1980     return -PA_ERR_IO;
1981 }
1982 
uuid_to_profile(const char * uuid,pa_bluetooth_profile_t * _r)1983 static int uuid_to_profile(const char *uuid, pa_bluetooth_profile_t *_r) {
1984     if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK))
1985         *_r = PA_BLUETOOTH_PROFILE_A2DP_SINK;
1986     else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE))
1987         *_r = PA_BLUETOOTH_PROFILE_A2DP_SOURCE;
1988     else if (pa_bluetooth_uuid_is_hsp_hs(uuid) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_HF))
1989         *_r = PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT;
1990     else if (pa_streq(uuid, PA_BLUETOOTH_UUID_HSP_AG) || pa_streq(uuid, PA_BLUETOOTH_UUID_HFP_AG))
1991         *_r = PA_BLUETOOTH_PROFILE_HEADSET_AUDIO_GATEWAY;
1992     else
1993         return -PA_ERR_INVALID;
1994 
1995     return 0;
1996 }
1997 
1998 /* Run from main thread */
add_card(struct userdata * u)1999 static int add_card(struct userdata *u) {
2000     const pa_bluetooth_device *d;
2001     pa_card_new_data data;
2002     char *alias;
2003     pa_bluetooth_form_factor_t ff;
2004     pa_card_profile *cp;
2005     pa_bluetooth_profile_t *p;
2006     const char *uuid;
2007     void *state;
2008 
2009     pa_assert(u);
2010     pa_assert(u->device);
2011 
2012     d = u->device;
2013 
2014     pa_card_new_data_init(&data);
2015     data.driver = __FILE__;
2016     data.module = u->module;
2017 
2018     alias = pa_utf8_filter(d->alias);
2019     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, alias);
2020     pa_xfree(alias);
2021 
2022     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, d->address);
2023     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "bluez");
2024     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
2025     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_BUS, "bluetooth");
2026 
2027     if ((ff = form_factor_from_class(d->class_of_device)) != PA_BLUETOOTH_FORM_FACTOR_UNKNOWN)
2028         pa_proplist_sets(data.proplist, PA_PROP_DEVICE_FORM_FACTOR, form_factor_to_string(ff));
2029 
2030     pa_proplist_sets(data.proplist, "bluez.path", d->path);
2031     pa_proplist_setf(data.proplist, "bluez.class", "0x%06x", d->class_of_device);
2032     pa_proplist_sets(data.proplist, "bluez.alias", d->alias);
2033     data.name = pa_sprintf_malloc("bluez_card.%s", d->address);
2034     data.namereg_fail = false;
2035 
2036     create_card_ports(u, data.ports);
2037 
2038     PA_HASHMAP_FOREACH(uuid, d->uuids, state) {
2039         pa_bluetooth_profile_t profile;
2040 
2041         if (uuid_to_profile(uuid, &profile) < 0)
2042             continue;
2043 
2044         if (pa_hashmap_get(data.profiles, pa_bluetooth_profile_to_string(profile)))
2045             continue;
2046 
2047         cp = create_card_profile(u, profile, data.ports);
2048         pa_hashmap_put(data.profiles, cp->name, cp);
2049     }
2050 
2051     pa_assert(!pa_hashmap_isempty(data.profiles));
2052 
2053     cp = pa_card_profile_new("off", _("Off"), sizeof(pa_bluetooth_profile_t));
2054     cp->available = PA_AVAILABLE_YES;
2055     p = PA_CARD_PROFILE_DATA(cp);
2056     *p = PA_BLUETOOTH_PROFILE_OFF;
2057     pa_hashmap_put(data.profiles, cp->name, cp);
2058 
2059     u->card = pa_card_new(u->core, &data);
2060     pa_card_new_data_done(&data);
2061     if (!u->card) {
2062         pa_log("Failed to allocate card.");
2063         return -1;
2064     }
2065 
2066     u->card->userdata = u;
2067     u->card->set_profile = set_profile_cb;
2068     pa_card_choose_initial_profile(u->card);
2069     pa_card_put(u->card);
2070 
2071     p = PA_CARD_PROFILE_DATA(u->card->active_profile);
2072     u->profile = *p;
2073 
2074     return 0;
2075 }
2076 
2077 /* Run from main thread */
handle_transport_state_change(struct userdata * u,struct pa_bluetooth_transport * t)2078 static void handle_transport_state_change(struct userdata *u, struct pa_bluetooth_transport *t) {
2079     bool acquire = false;
2080     bool release = false;
2081     pa_card_profile *cp;
2082     pa_device_port *port;
2083     pa_available_t oldavail;
2084 
2085     pa_assert(u);
2086     pa_assert(t);
2087     pa_assert_se(cp = pa_hashmap_get(u->card->profiles, pa_bluetooth_profile_to_string(t->profile)));
2088 
2089     oldavail = cp->available;
2090     pa_card_profile_set_available(cp, transport_state_to_availability(t->state));
2091 
2092     /* Update port availability */
2093     pa_assert_se(port = pa_hashmap_get(u->card->ports, u->output_port_name));
2094     pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_OUTPUT));
2095     pa_assert_se(port = pa_hashmap_get(u->card->ports, u->input_port_name));
2096     pa_device_port_set_available(port, get_port_availability(u, PA_DIRECTION_INPUT));
2097 
2098     /* Acquire or release transport as needed */
2099     acquire = (t->state == PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2100     release = (oldavail != PA_AVAILABLE_NO && t->state != PA_BLUETOOTH_TRANSPORT_STATE_PLAYING && u->profile == t->profile);
2101 
2102     if (acquire && transport_acquire(u, true) >= 0) {
2103         if (u->source) {
2104             pa_log_debug("Resuming source %s because its transport state changed to playing", u->source->name);
2105 
2106             /* When the ofono backend resumes source or sink when in the audio gateway role, the
2107              * state of source or sink may already be RUNNING before the transport is acquired via
2108              * hf_audio_agent_new_connection(), so the pa_source_suspend() call will not lead to a
2109              * state change message. In this case we explicitly need to signal the I/O thread to
2110              * set up the stream. */
2111             if (PA_SOURCE_IS_OPENED(u->source->state))
2112                 pa_asyncmsgq_send(u->source->asyncmsgq, PA_MSGOBJECT(u->source), PA_SOURCE_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2113 
2114             /* We remove the IDLE suspend cause, because otherwise
2115              * module-loopback doesn't uncork its streams. FIXME: Messing with
2116              * the IDLE suspend cause here is wrong, the correct way to handle
2117              * this would probably be to uncork the loopback streams not only
2118              * when the other end is unsuspended, but also when the other end's
2119              * suspend cause changes to IDLE only (currently there's no
2120              * notification mechanism for suspend cause changes, though). */
2121             pa_source_suspend(u->source, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2122         }
2123 
2124         if (u->sink) {
2125             pa_log_debug("Resuming sink %s because its transport state changed to playing", u->sink->name);
2126 
2127             /* Same comment as above */
2128             if (PA_SINK_IS_OPENED(u->sink->state))
2129                 pa_asyncmsgq_send(u->sink->asyncmsgq, PA_MSGOBJECT(u->sink), PA_SINK_MESSAGE_SETUP_STREAM, NULL, 0, NULL);
2130 
2131             /* FIXME: See the previous comment. */
2132             pa_sink_suspend(u->sink, false, PA_SUSPEND_IDLE|PA_SUSPEND_USER);
2133         }
2134     }
2135 
2136     if (release && u->transport_acquired) {
2137         /* FIXME: this release is racy, since the audio stream might have
2138          * been set up again in the meantime (but not processed yet by PA).
2139          * BlueZ should probably release the transport automatically, and in
2140          * that case we would just mark the transport as released */
2141 
2142         /* Remote side closed the stream so we consider it PA_SUSPEND_USER */
2143         if (u->source) {
2144             pa_log_debug("Suspending source %s because the remote end closed the stream", u->source->name);
2145             pa_source_suspend(u->source, true, PA_SUSPEND_USER);
2146         }
2147 
2148         if (u->sink) {
2149             pa_log_debug("Suspending sink %s because the remote end closed the stream", u->sink->name);
2150             pa_sink_suspend(u->sink, true, PA_SUSPEND_USER);
2151         }
2152     }
2153 }
2154 
2155 /* Run from main thread */
device_connection_changed_cb(pa_bluetooth_discovery * y,const pa_bluetooth_device * d,struct userdata * u)2156 static pa_hook_result_t device_connection_changed_cb(pa_bluetooth_discovery *y, const pa_bluetooth_device *d, struct userdata *u) {
2157     pa_assert(d);
2158     pa_assert(u);
2159 
2160     if (d != u->device || pa_bluetooth_device_any_transport_connected(d))
2161         return PA_HOOK_OK;
2162 
2163     pa_log_debug("Unloading module for device %s", d->path);
2164     pa_module_unload(u->module, true);
2165 
2166     return PA_HOOK_OK;
2167 }
2168 
2169 /* Run from main thread */
transport_state_changed_cb(pa_bluetooth_discovery * y,pa_bluetooth_transport * t,struct userdata * u)2170 static pa_hook_result_t transport_state_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2171     pa_assert(t);
2172     pa_assert(u);
2173 
2174     if (t == u->transport && t->state <= PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
2175         pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2176 
2177     if (t->device == u->device)
2178         handle_transport_state_change(u, t);
2179 
2180     return PA_HOOK_OK;
2181 }
2182 
transport_speaker_gain_changed_cb(pa_bluetooth_discovery * y,pa_bluetooth_transport * t,struct userdata * u)2183 static pa_hook_result_t transport_speaker_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2184     pa_volume_t volume;
2185     pa_cvolume v;
2186     uint16_t gain;
2187 
2188     pa_assert(t);
2189     pa_assert(u);
2190 
2191     if (t != u->transport)
2192       return PA_HOOK_OK;
2193 
2194     gain = t->speaker_gain;
2195     volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
2196 
2197     /* increment volume by one to correct rounding errors */
2198     if (volume < PA_VOLUME_NORM)
2199         volume++;
2200 
2201     pa_cvolume_set(&v, u->encoder_sample_spec.channels, volume);
2202     if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
2203         pa_sink_volume_changed(u->sink, &v);
2204     else
2205         pa_sink_set_volume(u->sink, &v, true, true);
2206 
2207     return PA_HOOK_OK;
2208 }
2209 
transport_microphone_gain_changed_cb(pa_bluetooth_discovery * y,pa_bluetooth_transport * t,struct userdata * u)2210 static pa_hook_result_t transport_microphone_gain_changed_cb(pa_bluetooth_discovery *y, pa_bluetooth_transport *t, struct userdata *u) {
2211     pa_volume_t volume;
2212     pa_cvolume v;
2213     uint16_t gain;
2214 
2215     pa_assert(t);
2216     pa_assert(u);
2217 
2218     if (t != u->transport)
2219       return PA_HOOK_OK;
2220 
2221     gain = t->microphone_gain;
2222     volume = (pa_volume_t) (gain * PA_VOLUME_NORM / HSP_MAX_GAIN);
2223 
2224     /* increment volume by one to correct rounding errors */
2225     if (volume < PA_VOLUME_NORM)
2226         volume++;
2227 
2228     pa_cvolume_set(&v, u->decoder_sample_spec.channels, volume);
2229 
2230     if (t->profile == PA_BLUETOOTH_PROFILE_HEADSET_HEAD_UNIT)
2231         pa_source_volume_changed(u->source, &v);
2232     else
2233         pa_source_set_volume(u->source, &v, true, true);
2234 
2235     return PA_HOOK_OK;
2236 }
2237 
2238 /* Run from main thread context */
device_process_msg(pa_msgobject * obj,int code,void * data,int64_t offset,pa_memchunk * chunk)2239 static int device_process_msg(pa_msgobject *obj, int code, void *data, int64_t offset, pa_memchunk *chunk) {
2240     struct bluetooth_msg *m = BLUETOOTH_MSG(obj);
2241     struct userdata *u = m->card->userdata;
2242 
2243     switch (code) {
2244         case BLUETOOTH_MESSAGE_IO_THREAD_FAILED:
2245             if (m->card->module->unload_requested)
2246                 break;
2247 
2248             pa_log_debug("Switching the profile to off due to IO thread failure.");
2249             pa_assert_se(pa_card_set_profile(m->card, pa_hashmap_get(m->card->profiles, "off"), false) >= 0);
2250             break;
2251         case BLUETOOTH_MESSAGE_STREAM_FD_HUP:
2252             if (u->transport->state > PA_BLUETOOTH_TRANSPORT_STATE_IDLE)
2253                 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
2254             break;
2255         case BLUETOOTH_MESSAGE_SET_TRANSPORT_PLAYING:
2256             /* transport_acquired needs to be checked here, because a message could have been
2257              * pending when the profile was switched. If the new transport has been acquired
2258              * correctly, the call below will have no effect because the transport state is
2259              * already PLAYING. If transport_acquire() failed for the new profile, the transport
2260              * state should not be changed. If the transport has been released for other reasons
2261              * (I/O thread shutdown), transport_acquired will also be false. */
2262             if (u->transport_acquired)
2263                 pa_bluetooth_transport_set_state(u->transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);
2264             break;
2265     }
2266 
2267     return 0;
2268 }
2269 
pa__init(pa_module * m)2270 int pa__init(pa_module* m) {
2271     struct userdata *u;
2272     const char *path;
2273     pa_modargs *ma;
2274     bool autodetect_mtu;
2275 
2276     pa_assert(m);
2277 
2278     m->userdata = u = pa_xnew0(struct userdata, 1);
2279     u->module = m;
2280     u->core = m->core;
2281 
2282     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
2283         pa_log_error("Failed to parse module arguments");
2284         goto fail_free_modargs;
2285     }
2286 
2287     if (!(path = pa_modargs_get_value(ma, "path", NULL))) {
2288         pa_log_error("Failed to get device path from module arguments");
2289         goto fail_free_modargs;
2290     }
2291 
2292     if ((u->discovery = pa_shared_get(u->core, "bluetooth-discovery")))
2293         pa_bluetooth_discovery_ref(u->discovery);
2294     else {
2295         pa_log_error("module-bluez5-discover doesn't seem to be loaded, refusing to load module-bluez5-device");
2296         goto fail_free_modargs;
2297     }
2298 
2299     if (!(u->device = pa_bluetooth_discovery_get_device_by_path(u->discovery, path))) {
2300         pa_log_error("%s is unknown", path);
2301         goto fail_free_modargs;
2302     }
2303 
2304     autodetect_mtu = false;
2305     if (pa_modargs_get_value_boolean(ma, "autodetect_mtu", &autodetect_mtu) < 0) {
2306         pa_log("Invalid boolean value for autodetect_mtu parameter");
2307         goto fail_free_modargs;
2308     }
2309 
2310     u->device->autodetect_mtu = autodetect_mtu;
2311 
2312     pa_modargs_free(ma);
2313 
2314     u->device_connection_changed_slot =
2315         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED),
2316                         PA_HOOK_NORMAL, (pa_hook_cb_t) device_connection_changed_cb, u);
2317 
2318     u->transport_state_changed_slot =
2319         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED),
2320                         PA_HOOK_NORMAL, (pa_hook_cb_t) transport_state_changed_cb, u);
2321 
2322     u->transport_speaker_gain_changed_slot =
2323         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_speaker_gain_changed_cb, u);
2324 
2325     u->transport_microphone_gain_changed_slot =
2326         pa_hook_connect(pa_bluetooth_discovery_hook(u->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED), PA_HOOK_NORMAL, (pa_hook_cb_t) transport_microphone_gain_changed_cb, u);
2327 
2328     if (add_card(u) < 0)
2329         goto fail;
2330 
2331     if (!(u->msg = pa_msgobject_new(bluetooth_msg)))
2332         goto fail;
2333 
2334     u->msg->parent.process_msg = device_process_msg;
2335     u->msg->card = u->card;
2336     u->stream_setup_done = false;
2337 
2338     if (u->profile != PA_BLUETOOTH_PROFILE_OFF)
2339         if (init_profile(u) < 0)
2340             goto off;
2341 
2342     if (u->sink || u->source)
2343         if (start_thread(u) < 0)
2344             goto off;
2345 
2346     return 0;
2347 
2348 off:
2349     stop_thread(u);
2350 
2351     pa_assert_se(pa_card_set_profile(u->card, pa_hashmap_get(u->card->profiles, "off"), false) >= 0);
2352 
2353     return 0;
2354 
2355 fail_free_modargs:
2356 
2357     if (ma)
2358         pa_modargs_free(ma);
2359 
2360 fail:
2361 
2362     pa__done(m);
2363 
2364     return -1;
2365 }
2366 
pa__done(pa_module * m)2367 void pa__done(pa_module *m) {
2368     struct userdata *u;
2369 
2370     pa_assert(m);
2371 
2372     if (!(u = m->userdata))
2373         return;
2374 
2375     stop_thread(u);
2376 
2377     if (u->device_connection_changed_slot)
2378         pa_hook_slot_free(u->device_connection_changed_slot);
2379 
2380     if (u->transport_state_changed_slot)
2381         pa_hook_slot_free(u->transport_state_changed_slot);
2382 
2383     if (u->transport_speaker_gain_changed_slot)
2384         pa_hook_slot_free(u->transport_speaker_gain_changed_slot);
2385 
2386     if (u->transport_microphone_gain_changed_slot)
2387         pa_hook_slot_free(u->transport_microphone_gain_changed_slot);
2388 
2389     if (u->encoder_buffer)
2390         pa_xfree(u->encoder_buffer);
2391 
2392     if (u->decoder_buffer)
2393         pa_xfree(u->decoder_buffer);
2394 
2395     if (u->msg)
2396         pa_xfree(u->msg);
2397 
2398     if (u->card)
2399         pa_card_free(u->card);
2400 
2401     if (u->discovery)
2402         pa_bluetooth_discovery_unref(u->discovery);
2403 
2404     pa_xfree(u->output_port_name);
2405     pa_xfree(u->input_port_name);
2406 
2407     pa_xfree(u);
2408 }
2409 
pa__get_n_used(pa_module * m)2410 int pa__get_n_used(pa_module *m) {
2411     struct userdata *u;
2412 
2413     pa_assert(m);
2414     pa_assert_se(u = m->userdata);
2415 
2416     return (u->sink ? pa_sink_linked_by(u->sink) : 0) + (u->source ? pa_source_linked_by(u->source) : 0);
2417 }
2418