3 * BlueZ - Bluetooth protocol stack for Linux
5 * Copyright (C) 2006-2007 Nokia Corporation
6 * Copyright (C) 2004-2008 Marcel Holtmann <marcel@holtmann.org>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
30 #include <sys/socket.h>
38 #include <netinet/in.h>
40 #include <sys/prctl.h>
48 #define LOG_TAG "A2DP"
49 #include <utils/Log.h>
52 /* #define ENABLE_VERBOSE */
53 /* #define ENABLE_TIMING */
55 #define BUFFER_SIZE 2048
60 #define DBG(fmt, arg...)
66 #define VDBG(fmt, arg...)
70 # define MIN(x, y) ((x) < (y) ? (x) : (y))
74 # define MAX(x, y) ((x) > (y) ? (x) : (y))
77 #define MAX_BITPOOL 64
82 /* Number of packets to buffer in the stream socket */
83 #define PACKET_BUFFER_COUNT 10
85 /* timeout in milliseconds to prevent poll() from hanging indefinitely */
86 #define POLL_TIMEOUT 1000
88 /* timeout in milliseconds for a2dp_write */
89 #define WRITE_TIMEOUT 500
94 A2DP_STATE_INITIALIZED,
95 A2DP_STATE_CONFIGURING,
96 A2DP_STATE_CONFIGURED,
111 struct bluetooth_data {
112 int link_mtu; /* MTU for transport channel */
113 struct pollfd stream; /* Audio stream filedescriptor */
114 struct pollfd server; /* Audio daemon filedescriptor */
115 a2dp_state_t state; /* Current A2DP state */
116 a2dp_command_t command; /* Current command for a2dp_thread */
118 pthread_mutex_t mutex;
120 pthread_cond_t thread_start;
121 pthread_cond_t thread_wait;
122 pthread_cond_t client_wait;
124 sbc_capabilities_t sbc_capabilities;
125 sbc_t sbc; /* Codec data */
126 int frame_duration; /* length of an SBC frame in microseconds */
127 int codesize; /* SBC codesize */
128 int samples; /* Number of encoded samples */
129 uint8_t buffer[BUFFER_SIZE]; /* Codec transfer buffer */
130 int count; /* Codec transfer buffer counter */
132 int nsamples; /* Cumulative number of codec samples */
133 uint16_t seq_num; /* Cumulative packet sequence */
134 int frame_count; /* Current frames in buffer*/
140 /* used for pacing our writes to the output socket */
144 static uint64_t get_microseconds()
147 gettimeofday(&now, NULL);
148 return (now.tv_sec * 1000000UL + now.tv_usec);
152 static void print_time(const char* message, uint64_t then, uint64_t now)
154 DBG("%s: %lld us", message, now - then);
158 static int audioservice_send(struct bluetooth_data *data, const bt_audio_msg_header_t *msg);
159 static int audioservice_expect(struct bluetooth_data *data, bt_audio_msg_header_t *outmsg,
161 static int bluetooth_a2dp_hw_params(struct bluetooth_data *data);
162 static void set_state(struct bluetooth_data *data, a2dp_state_t state);
165 static void bluetooth_close(struct bluetooth_data *data)
167 DBG("bluetooth_close");
168 if (data->server.fd >= 0) {
169 bt_audio_service_close(data->server.fd);
170 data->server.fd = -1;
173 if (data->stream.fd >= 0) {
174 close(data->stream.fd);
175 data->stream.fd = -1;
178 data->state = A2DP_STATE_NONE;
181 static int bluetooth_start(struct bluetooth_data *data)
184 char buf[BT_SUGGESTED_BUFFER_SIZE];
185 struct bt_start_stream_req *start_req = (void*) buf;
186 struct bt_start_stream_rsp *start_rsp = (void*) buf;
187 struct bt_new_stream_ind *streamfd_ind = (void*) buf;
188 int opt_name, err, bytes;
190 DBG("bluetooth_start");
191 data->state = A2DP_STATE_STARTING;
193 memset(start_req, 0, BT_SUGGESTED_BUFFER_SIZE);
194 start_req->h.type = BT_REQUEST;
195 start_req->h.name = BT_START_STREAM;
196 start_req->h.length = sizeof(*start_req);
199 err = audioservice_send(data, &start_req->h);
203 start_rsp->h.length = sizeof(*start_rsp);
204 err = audioservice_expect(data, &start_rsp->h, BT_START_STREAM);
208 streamfd_ind->h.length = sizeof(*streamfd_ind);
209 err = audioservice_expect(data, &streamfd_ind->h, BT_NEW_STREAM);
213 data->stream.fd = bt_audio_service_get_data_fd(data->server.fd);
214 if (data->stream.fd < 0) {
215 ERR("bt_audio_service_get_data_fd failed, errno: %d", errno);
219 data->stream.events = POLLOUT;
221 /* set our socket buffer to the size of PACKET_BUFFER_COUNT packets */
222 bytes = data->link_mtu * PACKET_BUFFER_COUNT;
223 setsockopt(data->stream.fd, SOL_SOCKET, SO_SNDBUF, &bytes,
226 data->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
227 data->frame_count = 0;
231 data->frame_count = 0;
232 data->next_write = 0;
234 set_state(data, A2DP_STATE_STARTED);
238 /* set state to A2DP_STATE_INITIALIZED to force reconfiguration */
239 if (data->state == A2DP_STATE_STARTING)
240 set_state(data, A2DP_STATE_INITIALIZED);
244 static int bluetooth_stop(struct bluetooth_data *data)
246 char buf[BT_SUGGESTED_BUFFER_SIZE];
247 struct bt_stop_stream_req *stop_req = (void*) buf;
248 struct bt_stop_stream_rsp *stop_rsp = (void*) buf;
251 DBG("bluetooth_stop");
253 data->state = A2DP_STATE_STOPPING;
254 if (data->stream.fd >= 0) {
255 close(data->stream.fd);
256 data->stream.fd = -1;
259 /* send stop request */
260 memset(stop_req, 0, BT_SUGGESTED_BUFFER_SIZE);
261 stop_req->h.type = BT_REQUEST;
262 stop_req->h.name = BT_STOP_STREAM;
263 stop_req->h.length = sizeof(*stop_req);
265 err = audioservice_send(data, &stop_req->h);
269 stop_rsp->h.length = sizeof(*stop_rsp);
270 err = audioservice_expect(data, &stop_rsp->h, BT_STOP_STREAM);
275 if (data->state == A2DP_STATE_STOPPING)
276 set_state(data, A2DP_STATE_CONFIGURED);
280 static uint8_t default_bitpool(uint8_t freq, uint8_t mode)
283 case BT_SBC_SAMPLING_FREQ_16000:
284 case BT_SBC_SAMPLING_FREQ_32000:
286 case BT_SBC_SAMPLING_FREQ_44100:
288 case BT_A2DP_CHANNEL_MODE_MONO:
289 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
291 case BT_A2DP_CHANNEL_MODE_STEREO:
292 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
295 ERR("Invalid channel mode %u", mode);
298 case BT_SBC_SAMPLING_FREQ_48000:
300 case BT_A2DP_CHANNEL_MODE_MONO:
301 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
303 case BT_A2DP_CHANNEL_MODE_STEREO:
304 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
307 ERR("Invalid channel mode %u", mode);
311 ERR("Invalid sampling freq %u", freq);
316 static int bluetooth_a2dp_init(struct bluetooth_data *data)
318 sbc_capabilities_t *cap = &data->sbc_capabilities;
319 unsigned int max_bitpool, min_bitpool;
322 switch (data->rate) {
324 cap->frequency = BT_SBC_SAMPLING_FREQ_48000;
327 cap->frequency = BT_SBC_SAMPLING_FREQ_44100;
330 cap->frequency = BT_SBC_SAMPLING_FREQ_32000;
333 cap->frequency = BT_SBC_SAMPLING_FREQ_16000;
336 ERR("Rate %d not supported", data->rate);
340 if (data->channels == 2) {
341 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
342 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
343 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
344 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
345 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
346 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
348 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
349 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
352 if (!cap->channel_mode) {
353 ERR("No supported channel modes");
357 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
358 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
359 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
360 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
361 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
362 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
363 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
364 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
366 ERR("No supported block lengths");
370 if (cap->subbands & BT_A2DP_SUBBANDS_8)
371 cap->subbands = BT_A2DP_SUBBANDS_8;
372 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
373 cap->subbands = BT_A2DP_SUBBANDS_4;
375 ERR("No supported subbands");
379 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
380 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
381 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
382 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
384 min_bitpool = MAX(MIN_BITPOOL, cap->min_bitpool);
385 max_bitpool = MIN(default_bitpool(cap->frequency,
389 cap->min_bitpool = min_bitpool;
390 cap->max_bitpool = max_bitpool;
395 static void bluetooth_a2dp_setup(struct bluetooth_data *data)
397 sbc_capabilities_t active_capabilities = data->sbc_capabilities;
399 sbc_reinit(&data->sbc, 0);
401 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
402 data->sbc.frequency = SBC_FREQ_16000;
404 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
405 data->sbc.frequency = SBC_FREQ_32000;
407 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
408 data->sbc.frequency = SBC_FREQ_44100;
410 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
411 data->sbc.frequency = SBC_FREQ_48000;
413 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
414 data->sbc.mode = SBC_MODE_MONO;
416 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
417 data->sbc.mode = SBC_MODE_DUAL_CHANNEL;
419 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
420 data->sbc.mode = SBC_MODE_STEREO;
422 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
423 data->sbc.mode = SBC_MODE_JOINT_STEREO;
425 data->sbc.allocation = active_capabilities.allocation_method
426 == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR
429 switch (active_capabilities.subbands) {
430 case BT_A2DP_SUBBANDS_4:
431 data->sbc.subbands = SBC_SB_4;
433 case BT_A2DP_SUBBANDS_8:
434 data->sbc.subbands = SBC_SB_8;
438 switch (active_capabilities.block_length) {
439 case BT_A2DP_BLOCK_LENGTH_4:
440 data->sbc.blocks = SBC_BLK_4;
442 case BT_A2DP_BLOCK_LENGTH_8:
443 data->sbc.blocks = SBC_BLK_8;
445 case BT_A2DP_BLOCK_LENGTH_12:
446 data->sbc.blocks = SBC_BLK_12;
448 case BT_A2DP_BLOCK_LENGTH_16:
449 data->sbc.blocks = SBC_BLK_16;
453 data->sbc.bitpool = active_capabilities.max_bitpool;
454 data->codesize = sbc_get_codesize(&data->sbc);
455 data->frame_duration = sbc_get_frame_duration(&data->sbc);
456 DBG("frame_duration: %d us", data->frame_duration);
459 static int bluetooth_a2dp_hw_params(struct bluetooth_data *data)
461 char buf[BT_SUGGESTED_BUFFER_SIZE];
462 struct bt_open_req *open_req = (void *) buf;
463 struct bt_open_rsp *open_rsp = (void *) buf;
464 struct bt_set_configuration_req *setconf_req = (void*) buf;
465 struct bt_set_configuration_rsp *setconf_rsp = (void*) buf;
468 memset(open_req, 0, BT_SUGGESTED_BUFFER_SIZE);
469 open_req->h.type = BT_REQUEST;
470 open_req->h.name = BT_OPEN;
471 open_req->h.length = sizeof(*open_req);
472 strncpy(open_req->destination, data->address, 18);
473 open_req->seid = data->sbc_capabilities.capability.seid;
474 open_req->lock = BT_WRITE_LOCK;
476 err = audioservice_send(data, &open_req->h);
480 open_rsp->h.length = sizeof(*open_rsp);
481 err = audioservice_expect(data, &open_rsp->h, BT_OPEN);
485 err = bluetooth_a2dp_init(data);
490 memset(setconf_req, 0, BT_SUGGESTED_BUFFER_SIZE);
491 setconf_req->h.type = BT_REQUEST;
492 setconf_req->h.name = BT_SET_CONFIGURATION;
493 setconf_req->h.length = sizeof(*setconf_req);
494 memcpy(&setconf_req->codec, &data->sbc_capabilities,
495 sizeof(data->sbc_capabilities));
497 setconf_req->codec.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
498 setconf_req->codec.length = sizeof(data->sbc_capabilities);
499 setconf_req->h.length += setconf_req->codec.length - sizeof(setconf_req->codec);
501 DBG("bluetooth_a2dp_hw_params sending configuration:\n");
502 switch (data->sbc_capabilities.channel_mode) {
503 case BT_A2DP_CHANNEL_MODE_MONO:
504 DBG("\tchannel_mode: MONO\n");
506 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
507 DBG("\tchannel_mode: DUAL CHANNEL\n");
509 case BT_A2DP_CHANNEL_MODE_STEREO:
510 DBG("\tchannel_mode: STEREO\n");
512 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
513 DBG("\tchannel_mode: JOINT STEREO\n");
516 DBG("\tchannel_mode: UNKNOWN (%d)\n",
517 data->sbc_capabilities.channel_mode);
519 switch (data->sbc_capabilities.frequency) {
520 case BT_SBC_SAMPLING_FREQ_16000:
521 DBG("\tfrequency: 16000\n");
523 case BT_SBC_SAMPLING_FREQ_32000:
524 DBG("\tfrequency: 32000\n");
526 case BT_SBC_SAMPLING_FREQ_44100:
527 DBG("\tfrequency: 44100\n");
529 case BT_SBC_SAMPLING_FREQ_48000:
530 DBG("\tfrequency: 48000\n");
533 DBG("\tfrequency: UNKNOWN (%d)\n",
534 data->sbc_capabilities.frequency);
536 switch (data->sbc_capabilities.allocation_method) {
537 case BT_A2DP_ALLOCATION_SNR:
538 DBG("\tallocation_method: SNR\n");
540 case BT_A2DP_ALLOCATION_LOUDNESS:
541 DBG("\tallocation_method: LOUDNESS\n");
544 DBG("\tallocation_method: UNKNOWN (%d)\n",
545 data->sbc_capabilities.allocation_method);
547 switch (data->sbc_capabilities.subbands) {
548 case BT_A2DP_SUBBANDS_4:
549 DBG("\tsubbands: 4\n");
551 case BT_A2DP_SUBBANDS_8:
552 DBG("\tsubbands: 8\n");
555 DBG("\tsubbands: UNKNOWN (%d)\n",
556 data->sbc_capabilities.subbands);
558 switch (data->sbc_capabilities.block_length) {
559 case BT_A2DP_BLOCK_LENGTH_4:
560 DBG("\tblock_length: 4\n");
562 case BT_A2DP_BLOCK_LENGTH_8:
563 DBG("\tblock_length: 8\n");
565 case BT_A2DP_BLOCK_LENGTH_12:
566 DBG("\tblock_length: 12\n");
568 case BT_A2DP_BLOCK_LENGTH_16:
569 DBG("\tblock_length: 16\n");
572 DBG("\tblock_length: UNKNOWN (%d)\n",
573 data->sbc_capabilities.block_length);
575 DBG("\tmin_bitpool: %d\n", data->sbc_capabilities.min_bitpool);
576 DBG("\tmax_bitpool: %d\n", data->sbc_capabilities.max_bitpool);
578 err = audioservice_send(data, &setconf_req->h);
582 err = audioservice_expect(data, &setconf_rsp->h, BT_SET_CONFIGURATION);
586 data->link_mtu = setconf_rsp->link_mtu;
587 DBG("MTU: %d", data->link_mtu);
589 /* Setup SBC encoder now we agree on parameters */
590 bluetooth_a2dp_setup(data);
592 DBG("\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
593 data->sbc.allocation, data->sbc.subbands, data->sbc.blocks,
599 static int avdtp_write(struct bluetooth_data *data)
602 struct rtp_header *header;
603 struct rtp_payload *payload;
606 long duration = data->frame_duration * data->frame_count;
608 uint64_t begin, end, begin2, end2;
609 begin = get_microseconds();
612 header = (struct rtp_header *)data->buffer;
613 payload = (struct rtp_payload *)(data->buffer + sizeof(*header));
615 memset(data->buffer, 0, sizeof(*header) + sizeof(*payload));
617 payload->frame_count = data->frame_count;
620 header->sequence_number = htons(data->seq_num);
621 header->timestamp = htonl(data->nsamples);
622 header->ssrc = htonl(1);
624 data->stream.revents = 0;
626 begin2 = get_microseconds();
628 ret = poll(&data->stream, 1, POLL_TIMEOUT);
630 end2 = get_microseconds();
631 print_time("poll", begin2, end2);
633 if (ret == 1 && data->stream.revents == POLLOUT) {
635 now = get_microseconds();
637 if (data->next_write) {
638 ahead = data->next_write - now;
640 DBG("duration: %ld, ahead: %ld", duration, ahead);
643 /* too fast, need to throttle */
647 data->next_write = now;
650 /* fallen too far behind, don't try to catch up */
651 VDBG("ahead < 0, resetting next_write");
652 data->next_write = 0;
654 /* advance next_write by duration */
655 data->next_write += duration;
659 begin2 = get_microseconds();
661 ret = send(data->stream.fd, data->buffer, data->count, MSG_NOSIGNAL);
663 end2 = get_microseconds();
664 print_time("send", begin2, end2);
667 /* can happen during normal remote disconnect */
668 VDBG("send() failed: %d (errno %s)", ret, strerror(errno));
671 bluetooth_close(data);
674 /* can happen during normal remote disconnect */
675 VDBG("poll() failed: %d (revents = %d, errno %s)",
676 ret, data->stream.revents, strerror(errno));
679 /* Reset buffer of data to send */
680 data->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
681 data->frame_count = 0;
686 end = get_microseconds();
687 print_time("avdtp_write", begin, end);
689 return 0; /* always return success */
692 static int audioservice_send(struct bluetooth_data *data,
693 const bt_audio_msg_header_t *msg)
698 length = msg->length ? msg->length : BT_SUGGESTED_BUFFER_SIZE;
700 VDBG("sending %s", bt_audio_strmsg(msg->msg_type));
701 if (send(data->server.fd, msg, length,
706 ERR("Error sending data to audio service: %s(%d)",
707 strerror(errno), errno);
709 bluetooth_close(data);
715 static int audioservice_recv(struct bluetooth_data *data,
716 bt_audio_msg_header_t *inmsg)
719 const char *type, *name;
722 length = inmsg->length ? inmsg->length : BT_SUGGESTED_BUFFER_SIZE;
724 ret = recv(data->server.fd, inmsg, length, 0);
727 ERR("Error receiving IPC data from bluetoothd: %s (%d)",
728 strerror(errno), errno);
730 bluetooth_close(data);
731 } else if ((size_t) ret < sizeof(bt_audio_msg_header_t)) {
732 ERR("Too short (%d bytes) IPC packet from bluetoothd", ret);
734 } else if (inmsg->type == BT_ERROR) {
735 bt_audio_error_t *error = (bt_audio_error_t *)inmsg;
736 ret = recv(data->server.fd, &error->posix_errno,
737 sizeof(error->posix_errno), 0);
740 ERR("Error receiving error code for BT_ERROR: %s (%d)",
741 strerror(errno), errno);
743 bluetooth_close(data);
745 ERR("%s failed : %s(%d)",
746 bt_audio_strname(error->h.name),
747 strerror(error->posix_errno),
749 err = -error->posix_errno;
752 type = bt_audio_strtype(inmsg->type);
753 name = bt_audio_strname(inmsg->name);
755 DBG("Received %s - %s", type, name);
759 ERR("Bogus message type %d - name %d"
760 " received from audio service",
761 inmsg->type, inmsg->name);
768 static int audioservice_expect(struct bluetooth_data *data,
769 bt_audio_msg_header_t *rsp_hdr, int expected_name)
771 int err = audioservice_recv(data, rsp_hdr);
776 if (rsp_hdr->name != expected_name) {
778 ERR("Bogus message %s received while %s was expected",
779 bt_audio_strname(rsp_hdr->name),
780 bt_audio_strname(expected_name));
786 static int bluetooth_init(struct bluetooth_data *data)
790 DBG("bluetooth_init");
792 sk = bt_audio_service_open();
794 ERR("bt_audio_service_open failed\n");
798 data->server.fd = sk;
799 data->server.events = POLLIN;
800 data->state = A2DP_STATE_INITIALIZED;
805 static int bluetooth_parse_capabilities(struct bluetooth_data *data,
806 struct bt_get_capabilities_rsp *rsp)
808 int bytes_left = rsp->h.length - sizeof(*rsp);
809 codec_capabilities_t *codec = (void *) rsp->data;
811 if (codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP)
814 while (bytes_left > 0) {
815 if ((codec->type == BT_A2DP_SBC_SINK) &&
816 !(codec->lock & BT_WRITE_LOCK))
819 bytes_left -= codec->length;
820 codec = (void *) codec + codec->length;
823 if (bytes_left <= 0 ||
824 codec->length != sizeof(data->sbc_capabilities))
827 memcpy(&data->sbc_capabilities, codec, codec->length);
832 static int bluetooth_configure(struct bluetooth_data *data)
834 char buf[BT_SUGGESTED_BUFFER_SIZE];
835 struct bt_get_capabilities_req *getcaps_req = (void*) buf;
836 struct bt_get_capabilities_rsp *getcaps_rsp = (void*) buf;
839 DBG("bluetooth_configure");
841 data->state = A2DP_STATE_CONFIGURING;
842 memset(getcaps_req, 0, BT_SUGGESTED_BUFFER_SIZE);
843 getcaps_req->h.type = BT_REQUEST;
844 getcaps_req->h.name = BT_GET_CAPABILITIES;
846 getcaps_req->flags = 0;
847 getcaps_req->flags |= BT_FLAG_AUTOCONNECT;
848 strncpy(getcaps_req->destination, data->address, 18);
849 getcaps_req->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
850 getcaps_req->h.length = sizeof(*getcaps_req);
852 err = audioservice_send(data, &getcaps_req->h);
854 ERR("audioservice_send failed for BT_GETCAPABILITIES_REQ\n");
858 getcaps_rsp->h.length = 0;
859 err = audioservice_expect(data, &getcaps_rsp->h, BT_GET_CAPABILITIES);
861 ERR("audioservice_expect failed for BT_GETCAPABILITIES_RSP\n");
865 bluetooth_parse_capabilities(data, getcaps_rsp);
866 err = bluetooth_a2dp_hw_params(data);
868 ERR("bluetooth_a2dp_hw_params failed err: %d", err);
872 set_state(data, A2DP_STATE_CONFIGURED);
876 if (data->state == A2DP_STATE_CONFIGURING)
877 set_state(data, A2DP_STATE_INITIALIZED);
881 static void set_state(struct bluetooth_data *data, a2dp_state_t state)
884 pthread_cond_signal(&data->client_wait);
887 static void set_command(struct bluetooth_data *data, a2dp_command_t command)
889 VDBG("set_command %d\n", command);
890 pthread_mutex_lock(&data->mutex);
891 data->command = command;
892 pthread_cond_signal(&data->thread_wait);
893 pthread_mutex_unlock(&data->mutex);
896 /* timeout is in milliseconds */
897 static int wait_for_start(struct bluetooth_data *data, int timeout)
899 a2dp_state_t state = data->state;
906 begin = get_microseconds();
909 gettimeofday(&tv, (struct timezone *) NULL);
910 ts.tv_sec = tv.tv_sec + (timeout / 1000);
911 ts.tv_nsec = (tv.tv_usec + (timeout % 1000) * 1000L ) * 1000L;
913 while (state != A2DP_STATE_STARTED && !err) {
914 if (state == A2DP_STATE_NONE)
915 set_command(data, A2DP_CMD_INIT);
916 else if (state == A2DP_STATE_INITIALIZED)
917 set_command(data, A2DP_CMD_CONFIGURE);
918 else if (state == A2DP_STATE_CONFIGURED)
919 set_command(data, A2DP_CMD_START);
921 pthread_mutex_lock(&data->mutex);
922 while ((err = pthread_cond_timedwait(&data->client_wait, &data->mutex, &ts))
925 pthread_mutex_unlock(&data->mutex);
929 end = get_microseconds();
930 print_time("wait_for_start", begin, end);
933 /* pthread_cond_timedwait returns positive errors */
937 static void* a2dp_thread(void *d)
939 struct bluetooth_data* data = (struct bluetooth_data*)d;
941 DBG("a2dp_thread started");
942 prctl(PR_SET_NAME, "a2dp_thread", 0, 0, 0);
944 pthread_mutex_lock(&data->mutex);
947 pthread_cond_signal(&data->thread_start);
951 a2dp_command_t command;
953 pthread_cond_wait(&data->thread_wait, &data->mutex);
954 command = data->command;
958 if (data->state != A2DP_STATE_NONE)
960 bluetooth_init(data);
962 case A2DP_CMD_CONFIGURE:
963 if (data->state != A2DP_STATE_INITIALIZED)
965 bluetooth_configure(data);
969 if (data->state != A2DP_STATE_CONFIGURED)
971 bluetooth_start(data);
975 if (data->state != A2DP_STATE_STARTED)
977 bluetooth_stop(data);
981 bluetooth_close(data);
982 sbc_finish(&data->sbc);
992 pthread_mutex_unlock(&data->mutex);
993 DBG("a2dp_thread finished");
997 int a2dp_init(int rate, int channels, a2dpData* dataPtr)
999 struct bluetooth_data* data;
1000 pthread_attr_t attr;
1003 DBG("a2dp_init rate: %d channels: %d", rate, channels);
1005 data = malloc(sizeof(struct bluetooth_data));
1009 memset(data, 0, sizeof(struct bluetooth_data));
1010 data->server.fd = -1;
1011 data->stream.fd = -1;
1012 data->state = A2DP_STATE_NONE;
1014 strncpy(data->address, "00:00:00:00:00:00", 18);
1016 data->channels = channels;
1018 sbc_init(&data->sbc, 0);
1020 pthread_mutex_init(&data->mutex, NULL);
1021 pthread_cond_init(&data->thread_start, NULL);
1022 pthread_cond_init(&data->thread_wait, NULL);
1023 pthread_cond_init(&data->client_wait, NULL);
1025 pthread_mutex_lock(&data->mutex);
1028 pthread_attr_init(&attr);
1029 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1031 err = pthread_create(&data->thread, &attr, a2dp_thread, data);
1033 /* If the thread create fails we must not wait */
1034 pthread_mutex_unlock(&data->mutex);
1039 /* Make sure the state machine is ready and waiting */
1040 while (!data->started) {
1041 pthread_cond_wait(&data->thread_start, &data->mutex);
1044 /* Poke the state machine to get it going */
1045 pthread_cond_signal(&data->thread_wait);
1047 pthread_mutex_unlock(&data->mutex);
1052 bluetooth_close(data);
1053 sbc_finish(&data->sbc);
1059 void a2dp_set_sink(a2dpData d, const char* address)
1061 struct bluetooth_data* data = (struct bluetooth_data*)d;
1062 if (strncmp(data->address, address, 18)) {
1063 strncpy(data->address, address, 18);
1064 set_command(data, A2DP_CMD_INIT);
1068 int a2dp_write(a2dpData d, const void* buffer, int count)
1070 struct bluetooth_data* data = (struct bluetooth_data*)d;
1071 uint8_t* src = (uint8_t *)buffer;
1074 long frames_left = count;
1075 int encoded, written;
1077 int did_configure = 0;
1078 #ifdef ENABLE_TIMING
1079 uint64_t begin, end;
1080 DBG("********** a2dp_write **********");
1081 begin = get_microseconds();
1084 err = wait_for_start(data, WRITE_TIMEOUT);
1088 codesize = data->codesize;
1090 while (frames_left >= codesize) {
1091 /* Enough data to encode (sbc wants 512 byte blocks) */
1092 encoded = sbc_encode(&(data->sbc), src, codesize,
1093 data->buffer + data->count,
1094 sizeof(data->buffer) - data->count,
1097 ERR("Encoding error %d", encoded);
1100 VDBG("sbc_encode returned %d, codesize: %d, written: %d\n",
1101 encoded, codesize, written);
1104 data->count += written;
1105 data->frame_count++;
1106 data->samples += encoded;
1107 data->nsamples += encoded;
1109 /* No space left for another frame then send */
1110 if (data->count + written >= data->link_mtu) {
1111 VDBG("sending packet %d, count %d, link_mtu %u",
1112 data->seq_num, data->count,
1114 err = avdtp_write(data);
1120 frames_left -= encoded;
1123 if (frames_left > 0)
1124 ERR("%ld bytes left at end of a2dp_write\n", frames_left);
1127 #ifdef ENABLE_TIMING
1128 end = get_microseconds();
1129 print_time("a2dp_write total", begin, end);
1134 int a2dp_stop(a2dpData d)
1136 struct bluetooth_data* data = (struct bluetooth_data*)d;
1141 set_command(data, A2DP_CMD_STOP);
1145 void a2dp_cleanup(a2dpData d)
1147 struct bluetooth_data* data = (struct bluetooth_data*)d;
1148 DBG("a2dp_cleanup\n");
1149 set_command(data, A2DP_CMD_QUIT);