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