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