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