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>
37 #include <netinet/in.h>
45 #define LOG_TAG "A2DP"
46 #include <utils/Log.h>
48 /* #define ENABLE_DEBUG */
50 #define BUFFER_SIZE 2048
55 #define DBG(fmt, arg...)
60 # define MIN(x, y) ((x) < (y) ? (x) : (y))
64 # define MAX(x, y) ((x) > (y) ? (x) : (y))
67 #define MAX_BITPOOL 64
72 /* Number of milliseconds worth of audio to buffer in our the data->stream.fd socket */
73 #define SOCK_BUFFER_MS 100
75 struct bluetooth_data {
76 int link_mtu; /* MTU for selected transport channel */
77 struct pollfd stream; /* Audio stream filedescriptor */
78 struct pollfd server; /* Audio daemon filedescriptor */
80 sbc_capabilities_t sbc_capabilities;
81 sbc_t sbc; /* Codec data */
82 int sbc_initialized; /* Keep track if the encoder is initialized */
83 int frame_duration; /* length of an SBC frame in microseconds */
84 int codesize; /* SBC codesize */
85 int samples; /* Number of encoded samples */
86 uint8_t buffer[BUFFER_SIZE]; /* Codec transfer buffer */
87 int count; /* Codec transfer buffer counter */
89 int nsamples; /* Cumulative number of codec samples */
90 uint16_t seq_num; /* Cumulative packet sequence */
91 int frame_count; /* Current frames in buffer*/
98 /* used for pacing our writes to the output socket */
99 struct timeval last_write;
100 unsigned long last_duration;
102 /* true if we already set the buffer size on the data->stream.fd socket */
103 int adjusted_sock_buffer;
107 static int audioservice_send(int sk, const bt_audio_msg_header_t *msg);
108 static int audioservice_expect(int sk, bt_audio_msg_header_t *outmsg,
110 static int bluetooth_a2dp_hw_params(struct bluetooth_data *data);
113 static void bluetooth_exit(struct bluetooth_data *data)
115 if (data->server.fd >= 0)
116 bt_audio_service_close(data->server.fd);
118 if (data->stream.fd >= 0)
119 close(data->stream.fd);
121 if (data->sbc_initialized)
122 sbc_finish(&data->sbc);
125 static int bluetooth_start(struct bluetooth_data *data)
128 char buf[BT_AUDIO_IPC_PACKET_SIZE];
129 struct bt_streamstart_req *start_req = (void*) buf;
130 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
131 struct bt_streamfd_ind *streamfd_ind = (void*) buf;
137 memset(start_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
138 start_req->h.msg_type = BT_STREAMSTART_REQ;
140 err = audioservice_send(data->server.fd, &start_req->h);
144 err = audioservice_expect(data->server.fd, &rsp_hdr->msg_h,
149 if (rsp_hdr->posix_errno != 0) {
150 SNDERR("BT_START failed : %s(%d)",
151 strerror(rsp_hdr->posix_errno),
152 rsp_hdr->posix_errno);
154 /* if the connection dropped, we may need to reset the configuration */
157 if (bluetooth_a2dp_hw_params(data) == 0)
161 return -rsp_hdr->posix_errno;
164 err = audioservice_expect(data->server.fd, &streamfd_ind->h,
169 if (data->stream.fd >= 0) {
170 close(data->stream.fd);
171 data->stream.fd = -1;
172 data->adjusted_sock_buffer = 0;
175 data->stream.fd = bt_audio_service_get_data_fd(data->server.fd);
176 if (data->stream.fd < 0) {
179 data->stream.events = POLLOUT;
184 static int bluetooth_stop(struct bluetooth_data *data)
186 char buf[BT_AUDIO_IPC_PACKET_SIZE];
187 struct bt_streamstop_req *stop_req = (void*) buf;
188 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
193 if (data->stream.fd >= 0) {
194 close(data->stream.fd);
198 /* send stop request */
199 memset(stop_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
200 stop_req->h.msg_type = BT_STREAMSTOP_REQ;
202 err = audioservice_send(data->server.fd, &stop_req->h);
206 err = audioservice_expect(data->server.fd, &rsp_hdr->msg_h,
211 if (rsp_hdr->posix_errno != 0) {
212 SNDERR("BT_STREAMSTOP failed : %s(%d)",
213 strerror(rsp_hdr->posix_errno),
214 rsp_hdr->posix_errno);
215 return -rsp_hdr->posix_errno;
221 static uint8_t default_bitpool(uint8_t freq, uint8_t mode)
224 case BT_SBC_SAMPLING_FREQ_16000:
225 case BT_SBC_SAMPLING_FREQ_32000:
227 case BT_SBC_SAMPLING_FREQ_44100:
229 case BT_A2DP_CHANNEL_MODE_MONO:
230 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
232 case BT_A2DP_CHANNEL_MODE_STEREO:
233 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
236 DBG("Invalid channel mode %u", mode);
239 case BT_SBC_SAMPLING_FREQ_48000:
241 case BT_A2DP_CHANNEL_MODE_MONO:
242 case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
244 case BT_A2DP_CHANNEL_MODE_STEREO:
245 case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
248 DBG("Invalid channel mode %u", mode);
252 DBG("Invalid sampling freq %u", freq);
257 static int bluetooth_a2dp_init(struct bluetooth_data *data)
259 sbc_capabilities_t *cap = &data->sbc_capabilities;
260 unsigned int max_bitpool, min_bitpool;
263 switch (data->rate) {
265 cap->frequency = BT_SBC_SAMPLING_FREQ_48000;
268 cap->frequency = BT_SBC_SAMPLING_FREQ_44100;
271 cap->frequency = BT_SBC_SAMPLING_FREQ_32000;
274 cap->frequency = BT_SBC_SAMPLING_FREQ_16000;
277 DBG("Rate %d not supported", data->rate);
281 if (data->channels == 2) {
282 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
283 cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
284 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
285 cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
286 else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
287 cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
289 if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
290 cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
293 if (!cap->channel_mode) {
294 DBG("No supported channel modes");
298 if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
299 cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
300 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
301 cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
302 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
303 cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
304 else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
305 cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
307 DBG("No supported block lengths");
311 if (cap->subbands & BT_A2DP_SUBBANDS_8)
312 cap->subbands = BT_A2DP_SUBBANDS_8;
313 else if (cap->subbands & BT_A2DP_SUBBANDS_4)
314 cap->subbands = BT_A2DP_SUBBANDS_4;
316 DBG("No supported subbands");
320 if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
321 cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
322 else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
323 cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
325 min_bitpool = MAX(MIN_BITPOOL, cap->min_bitpool);
326 max_bitpool = MIN(default_bitpool(cap->frequency,
330 cap->min_bitpool = min_bitpool;
331 cap->max_bitpool = max_bitpool;
333 DBG("bluetooth_a2dp_init bottom:\n channel_mode: %d\n frequency: %d\n allocation_method: %d\n subbands: %d\n block_length: %d\n min_bitpool: %d\n max_bitpool: %d\n ",
334 cap->channel_mode, cap->frequency, cap->allocation_method, cap->subbands,
335 cap->block_length, cap->min_bitpool, cap->max_bitpool);
341 static void bluetooth_a2dp_setup(struct bluetooth_data *data)
343 sbc_capabilities_t active_capabilities = data->sbc_capabilities;
345 if (data->sbc_initialized)
346 sbc_reinit(&data->sbc, 0);
348 sbc_init(&data->sbc, 0);
349 data->sbc_initialized = 1;
351 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
352 data->sbc.frequency = SBC_FREQ_16000;
354 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
355 data->sbc.frequency = SBC_FREQ_32000;
357 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
358 data->sbc.frequency = SBC_FREQ_44100;
360 if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
361 data->sbc.frequency = SBC_FREQ_48000;
363 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
364 data->sbc.mode = SBC_MODE_MONO;
366 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
367 data->sbc.mode = SBC_MODE_DUAL_CHANNEL;
369 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
370 data->sbc.mode = SBC_MODE_STEREO;
372 if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
373 data->sbc.mode = SBC_MODE_JOINT_STEREO;
375 data->sbc.allocation = active_capabilities.allocation_method
376 == BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR
379 switch (active_capabilities.subbands) {
380 case BT_A2DP_SUBBANDS_4:
381 data->sbc.subbands = SBC_SB_4;
383 case BT_A2DP_SUBBANDS_8:
384 data->sbc.subbands = SBC_SB_8;
388 switch (active_capabilities.block_length) {
389 case BT_A2DP_BLOCK_LENGTH_4:
390 data->sbc.blocks = SBC_BLK_4;
392 case BT_A2DP_BLOCK_LENGTH_8:
393 data->sbc.blocks = SBC_BLK_8;
395 case BT_A2DP_BLOCK_LENGTH_12:
396 data->sbc.blocks = SBC_BLK_12;
398 case BT_A2DP_BLOCK_LENGTH_16:
399 data->sbc.blocks = SBC_BLK_16;
403 data->sbc.bitpool = active_capabilities.max_bitpool;
404 data->codesize = sbc_get_codesize(&data->sbc);
405 data->frame_duration = sbc_get_frame_duration(&data->sbc);
406 data->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
409 static int bluetooth_a2dp_hw_params(struct bluetooth_data *data)
411 char buf[BT_AUDIO_IPC_PACKET_SIZE];
412 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
413 struct bt_setconfiguration_req *setconf_req = (void*) buf;
414 struct bt_setconfiguration_rsp *setconf_rsp = (void*) buf;
417 err = bluetooth_a2dp_init(data);
421 memset(setconf_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
422 setconf_req->h.msg_type = BT_SETCONFIGURATION_REQ;
423 strncpy(setconf_req->device, data->address, 18);
424 setconf_req->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
425 setconf_req->sbc_capabilities = data->sbc_capabilities;
426 setconf_req->access_mode = BT_CAPABILITIES_ACCESS_MODE_WRITE;
428 err = audioservice_send(data->server.fd, &setconf_req->h);
432 err = audioservice_expect(data->server.fd, &rsp_hdr->msg_h,
433 BT_SETCONFIGURATION_RSP);
437 if (rsp_hdr->posix_errno != 0) {
438 SNDERR("BT_SETCONFIGURATION failed : %s(%d)",
439 strerror(rsp_hdr->posix_errno),
440 rsp_hdr->posix_errno);
441 return -rsp_hdr->posix_errno;
444 data->link_mtu = setconf_rsp->link_mtu;
446 /* Setup SBC encoder now we agree on parameters */
447 bluetooth_a2dp_setup(data);
449 DBG("\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
450 data->sbc.allocation, data->sbc.subbands, data->sbc.blocks,
456 static int avdtp_write(struct bluetooth_data *data, unsigned long duration)
459 struct rtp_header *header;
460 struct rtp_payload *payload;
463 int microseconds, bytes;
465 header = (struct rtp_header *)data->buffer;
466 payload = (struct rtp_payload *)(data->buffer + sizeof(*header));
468 memset(data->buffer, 0, sizeof(*header) + sizeof(*payload));
470 payload->frame_count = data->frame_count;
473 header->sequence_number = htons(data->seq_num);
474 header->timestamp = htonl(data->nsamples);
475 header->ssrc = htonl(1);
477 data->stream.revents = 0;
478 ret = poll(&data->stream, 1, -1);
479 if (ret == 1 && data->stream.revents == POLLOUT) {
480 gettimeofday(&now, NULL);
481 if (data->last_write.tv_sec || data->last_write.tv_usec) {
482 if (now.tv_usec > data->last_write.tv_usec)
483 delta = now.tv_usec - data->last_write.tv_usec;
485 delta = (1000000 - data->last_write.tv_usec) + now.tv_usec;
487 if (duration > delta) {
488 DBG("duration: %ld delta: %ld, delay %ld us", duration, delta, duration - delta);
489 usleep(duration - delta);
492 data->last_write = now;
494 ret = send(data->stream.fd, data->buffer, data->count, 0);
496 DBG("send returned %d errno %s.", ret, strerror(errno));
503 if (!data->adjusted_sock_buffer) {
504 /* microseconds: number of microseconds of audio for this write */
505 microseconds = data->frame_duration * data->frame_count;
506 /* ret: number of bytes written */
507 /* bytes: number of bytes corresponding to SOCK_BUFFER_MS milliseconds of audio playback */
508 bytes = (ret * 1000 * SOCK_BUFFER_MS) / microseconds;
510 DBG("microseconds: %d, ret: %d, bytes: %d\n", microseconds, ret, bytes);
511 setsockopt(data->stream.fd, SOL_SOCKET, SO_SNDBUF, &bytes, sizeof(bytes));
512 data->adjusted_sock_buffer = 1;
515 /* Reset buffer of data to send */
516 data->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
517 data->frame_count = 0;
524 static int audioservice_send(int sk, const bt_audio_msg_header_t *msg)
528 DBG("sending %s", bt_audio_strmsg(msg->msg_type));
529 if (send(sk, msg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0)
533 SNDERR("Error sending data to audio service: %s(%d)",
534 strerror(errno), errno);
540 static int audioservice_recv(int sk, bt_audio_msg_header_t *inmsg)
545 DBG("trying to receive msg from audio service...");
546 if (recv(sk, inmsg, BT_AUDIO_IPC_PACKET_SIZE, 0) > 0) {
547 type = bt_audio_strmsg(inmsg->msg_type);
549 DBG("Received %s", type);
553 SNDERR("Bogus message type %d "
554 "received from audio service",
559 SNDERR("Error receiving data from audio service: %s(%d)",
560 strerror(errno), errno);
566 static int audioservice_expect(int sk, bt_audio_msg_header_t *rsp_hdr,
569 int err = audioservice_recv(sk, rsp_hdr);
571 if (rsp_hdr->msg_type != expected_type) {
573 SNDERR("Bogus message %s received while "
575 bt_audio_strmsg(rsp_hdr->msg_type),
576 bt_audio_strmsg(expected_type));
582 static int bluetooth_init(struct bluetooth_data *data)
585 char buf[BT_AUDIO_IPC_PACKET_SIZE];
586 bt_audio_rsp_msg_header_t *rsp_hdr = (void*) buf;
587 struct bt_getcapabilities_req *getcaps_req = (void*) buf;
588 struct bt_getcapabilities_rsp *getcaps_rsp = (void*) buf;
590 memset(data, 0, sizeof(struct bluetooth_data));
592 data->server.fd = -1;
593 data->stream.fd = -1;
594 data->adjusted_sock_buffer = 0;
596 sk = bt_audio_service_open();
598 SNDERR("bt_audio_service_open failed\n");
603 data->server.fd = sk;
604 data->server.events = POLLIN;
606 memset(getcaps_req, 0, BT_AUDIO_IPC_PACKET_SIZE);
607 getcaps_req->h.msg_type = BT_GETCAPABILITIES_REQ;
608 getcaps_req->flags = 0;
609 getcaps_req->flags |= BT_FLAG_AUTOCONNECT;
610 strncpy(getcaps_req->device, data->address, 18);
611 getcaps_req->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
613 err = audioservice_send(data->server.fd, &getcaps_req->h);
615 SNDERR("audioservice_send failed for BT_GETCAPABILITIES_REQ\n");
619 err = audioservice_expect(data->server.fd, &rsp_hdr->msg_h, BT_GETCAPABILITIES_RSP);
621 SNDERR("audioservice_expect failed for BT_GETCAPABILITIES_RSP\n");
624 if (rsp_hdr->posix_errno != 0) {
625 SNDERR("BT_GETCAPABILITIES failed : %s(%d)",
626 strerror(rsp_hdr->posix_errno),
627 rsp_hdr->posix_errno);
628 err = -rsp_hdr->posix_errno;
632 if (getcaps_rsp->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
633 data->sbc_capabilities = getcaps_rsp->sbc_capabilities;
638 SNDERR("bluetooth_init failed, err: %d\n", err);
639 bt_audio_service_close(sk);
640 data->server.fd = -1;
644 int a2dp_init(const char* address, int rate, int channels, a2dpData* dataPtr)
650 struct bluetooth_data* data = malloc(sizeof(struct bluetooth_data));
654 strncpy(data->address, address, 18);
656 err = bluetooth_init(data);
661 data->channels = channels;
663 err = bluetooth_a2dp_hw_params(data);
665 SNDERR("bluetooth_a2dp_hw_params failed");
673 bluetooth_exit(data);
679 int a2dp_write(a2dpData d, const void* buffer, int count)
681 struct bluetooth_data* data = (struct bluetooth_data*)d;
682 const uint8_t* src = buffer;
683 int codesize = data->codesize;
685 long frames_left = count;
686 int encoded, written;
688 unsigned long duration = 0;
690 if (!data->started) {
691 ret = bluetooth_start(data);
693 SNDERR("bluetooth_start failed");
699 while (frames_left >= codesize) {
700 /* Enough data to encode (sbc wants 1k blocks) */
701 encoded = sbc_encode(&(data->sbc), src, codesize,
702 data->buffer + data->count,
703 sizeof(data->buffer) - data->count,
706 DBG("Encoding error %d", encoded);
709 DBG("sbc_encode returned %d, codesize: %d, written: %d\n", encoded, codesize, written);
712 data->count += written;
714 data->samples += encoded;
715 data->nsamples += encoded;
716 duration += data->frame_duration;
718 /* No space left for another frame then send */
719 if (data->count + written >= data->link_mtu) {
720 DBG("sending packet %d, count %d, link_mtu %u",
721 data->seq_num, data->count,
723 avdtp_write(data, data->last_duration);
724 data->last_duration = duration;
729 frames_left -= encoded;
733 SNDERR("%ld bytes left at end of a2dp_write\n", frames_left);
736 DBG("returning %ld", ret);
740 int a2dp_stop(a2dpData d)
742 struct bluetooth_data* data = (struct bluetooth_data*)d;
747 return bluetooth_stop(data);
750 void a2dp_cleanup(a2dpData d)
752 struct bluetooth_data* data = (struct bluetooth_data*)d;
753 bluetooth_exit(data);