Home | History | Annotate | Download | only in audio
      1 /*
      2  *
      3  *  BlueZ - Bluetooth protocol stack for Linux
      4  *
      5  *  Copyright (C) 2006-2010  Nokia Corporation
      6  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel (at) holtmann.org>
      7  *
      8  *
      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.
     13  *
     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.
     18  *
     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
     22  *
     23  */
     24 
     25 #ifdef HAVE_CONFIG_H
     26 #include <config.h>
     27 #endif
     28 
     29 #include <stdint.h>
     30 #include <sys/socket.h>
     31 #include <sys/un.h>
     32 #include <time.h>
     33 #include <sys/time.h>
     34 #include <pthread.h>
     35 #include <signal.h>
     36 #include <limits.h>
     37 
     38 #include <netinet/in.h>
     39 
     40 #include <alsa/asoundlib.h>
     41 #include <alsa/pcm_external.h>
     42 
     43 #include "ipc.h"
     44 #include "sbc.h"
     45 #include "rtp.h"
     46 
     47 /* #define ENABLE_DEBUG */
     48 
     49 #define UINT_SECS_MAX (UINT_MAX / 1000000 - 1)
     50 
     51 #define MIN_PERIOD_TIME 1
     52 
     53 #define BUFFER_SIZE 2048
     54 
     55 #ifdef ENABLE_DEBUG
     56 #define DBG(fmt, arg...)  printf("DEBUG: %s: " fmt "\n" , __FUNCTION__ , ## arg)
     57 #else
     58 #define DBG(fmt, arg...)
     59 #endif
     60 
     61 #ifndef SOL_SCO
     62 #define SOL_SCO 17
     63 #endif
     64 
     65 #ifndef SCO_TXBUFS
     66 #define SCO_TXBUFS 0x03
     67 #endif
     68 
     69 #ifndef SCO_RXBUFS
     70 #define SCO_RXBUFS 0x04
     71 #endif
     72 
     73 #ifndef MIN
     74 # define MIN(x, y) ((x) < (y) ? (x) : (y))
     75 #endif
     76 
     77 #ifndef MAX
     78 # define MAX(x, y) ((x) > (y) ? (x) : (y))
     79 #endif
     80 
     81 #define MAX_BITPOOL 64
     82 #define MIN_BITPOOL 2
     83 
     84 /* adapted from glibc sys/time.h timersub() macro */
     85 #define priv_timespecsub(a, b, result)					\
     86 	do {								\
     87 		(result)->tv_sec = (a)->tv_sec - (b)->tv_sec;		\
     88 		(result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec;	\
     89 		if ((result)->tv_nsec < 0) {				\
     90 			--(result)->tv_sec;				\
     91 			(result)->tv_nsec += 1000000000;		\
     92 		}							\
     93 	} while (0)
     94 
     95 struct bluetooth_a2dp {
     96 	sbc_capabilities_t sbc_capabilities;
     97 	sbc_t sbc;				/* Codec data */
     98 	int sbc_initialized;			/* Keep track if the encoder is initialized */
     99 	unsigned int codesize;			/* SBC codesize */
    100 	int samples;				/* Number of encoded samples */
    101 	uint8_t buffer[BUFFER_SIZE];		/* Codec transfer buffer */
    102 	unsigned int count;			/* Codec transfer buffer counter */
    103 
    104 	int nsamples;				/* Cumulative number of codec samples */
    105 	uint16_t seq_num;			/* Cumulative packet sequence */
    106 	int frame_count;			/* Current frames in buffer*/
    107 };
    108 
    109 struct bluetooth_alsa_config {
    110 	char device[18];		/* Address of the remote Device */
    111 	int has_device;
    112 	uint8_t transport;		/* Requested transport */
    113 	int has_transport;
    114 	uint16_t rate;
    115 	int has_rate;
    116 	uint8_t channel_mode;		/* A2DP only */
    117 	int has_channel_mode;
    118 	uint8_t allocation_method;	/* A2DP only */
    119 	int has_allocation_method;
    120 	uint8_t subbands;		/* A2DP only */
    121 	int has_subbands;
    122 	uint8_t block_length;		/* A2DP only */
    123 	int has_block_length;
    124 	uint8_t bitpool;		/* A2DP only */
    125 	int has_bitpool;
    126 	int autoconnect;
    127 };
    128 
    129 struct bluetooth_data {
    130 	snd_pcm_ioplug_t io;
    131 	struct bluetooth_alsa_config alsa_config;	/* ALSA resource file parameters */
    132 	volatile snd_pcm_sframes_t hw_ptr;
    133 	int transport;					/* chosen transport SCO or AD2P */
    134 	unsigned int link_mtu;				/* MTU for selected transport channel */
    135 	volatile struct pollfd stream;			/* Audio stream filedescriptor */
    136 	struct pollfd server;				/* Audio daemon filedescriptor */
    137 	uint8_t buffer[BUFFER_SIZE];		/* Encoded transfer buffer */
    138 	unsigned int count;				/* Transfer buffer counter */
    139 	struct bluetooth_a2dp a2dp;			/* A2DP data */
    140 
    141 	pthread_t hw_thread;				/* Makes virtual hw pointer move */
    142 	int pipefd[2];					/* Inter thread communication */
    143 	int stopped;
    144 	sig_atomic_t reset;				/* Request XRUN handling */
    145 };
    146 
    147 static int audioservice_send(int sk, const bt_audio_msg_header_t *msg);
    148 static int audioservice_expect(int sk, bt_audio_msg_header_t *outmsg,
    149 							int expected_type);
    150 
    151 static int bluetooth_start(snd_pcm_ioplug_t *io)
    152 {
    153 	DBG("bluetooth_start %p", io);
    154 
    155 	return 0;
    156 }
    157 
    158 static int bluetooth_stop(snd_pcm_ioplug_t *io)
    159 {
    160 	DBG("bluetooth_stop %p", io);
    161 
    162 	return 0;
    163 }
    164 
    165 static void *playback_hw_thread(void *param)
    166 {
    167 	struct bluetooth_data *data = param;
    168 	unsigned int prev_periods;
    169 	double period_time;
    170 	struct timespec start;
    171 	struct pollfd fds[2];
    172 	int poll_timeout;
    173 
    174 	data->server.events = POLLIN;
    175 	/* note: only errors for data->stream.events */
    176 
    177 	fds[0] = data->server;
    178 	fds[1] = data->stream;
    179 
    180 	prev_periods = 0;
    181 	period_time = 1000000.0 * data->io.period_size / data->io.rate;
    182 	if (period_time > (int) (MIN_PERIOD_TIME * 1000))
    183 		poll_timeout = (int) (period_time / 1000.0f);
    184 	else
    185 		poll_timeout = MIN_PERIOD_TIME;
    186 
    187 	clock_gettime(CLOCK_MONOTONIC, &start);
    188 
    189 	while (1) {
    190 		unsigned int dtime, periods;
    191 		struct timespec cur, delta;
    192 		int ret;
    193 
    194 		if (data->stopped)
    195 			goto iter_sleep;
    196 
    197 		if (data->reset) {
    198 			DBG("Handle XRUN in hw-thread.");
    199 			data->reset = 0;
    200 			clock_gettime(CLOCK_MONOTONIC, &start);
    201 			prev_periods = 0;
    202 		}
    203 
    204 		clock_gettime(CLOCK_MONOTONIC, &cur);
    205 
    206 		priv_timespecsub(&cur, &start, &delta);
    207 
    208 		dtime = delta.tv_sec * 1000000 + delta.tv_nsec / 1000;
    209 		periods = 1.0 * dtime / period_time;
    210 
    211 		if (periods > prev_periods) {
    212 			char c = 'w';
    213 			int frags = periods - prev_periods, n;
    214 
    215 			data->hw_ptr += frags *	data->io.period_size;
    216 			data->hw_ptr %= data->io.buffer_size;
    217 
    218 			for (n = 0; n < frags; n++) {
    219 				/* Notify user that hardware pointer
    220 				 * has moved * */
    221 				if (write(data->pipefd[1], &c, 1) < 0)
    222 					pthread_testcancel();
    223 			}
    224 
    225 			/* Reset point of reference to avoid too big values
    226 			 * that wont fit an unsigned int */
    227 			if ((unsigned int) delta.tv_sec < UINT_SECS_MAX)
    228 				prev_periods = periods;
    229 			else {
    230 				prev_periods = 0;
    231 				clock_gettime(CLOCK_MONOTONIC, &start);
    232 			}
    233 		}
    234 
    235 iter_sleep:
    236 		/* sleep up to one period interval */
    237 		ret = poll(fds, 2, poll_timeout);
    238 
    239 		if (ret < 0) {
    240 			if (errno != EINTR) {
    241 				SNDERR("poll error: %s (%d)", strerror(errno),
    242 								errno);
    243 				break;
    244 			}
    245 		} else if (ret > 0) {
    246 			ret = (fds[0].revents) ? 0 : 1;
    247 			SNDERR("poll fd %d revents %d", ret, fds[ret].revents);
    248 			if (fds[ret].revents & (POLLERR | POLLHUP | POLLNVAL))
    249 				break;
    250 		}
    251 
    252 		/* Offer opportunity to be canceled by main thread */
    253 		pthread_testcancel();
    254 	}
    255 
    256 	data->hw_thread = 0;
    257 	pthread_exit(NULL);
    258 }
    259 
    260 static int bluetooth_playback_start(snd_pcm_ioplug_t *io)
    261 {
    262 	struct bluetooth_data *data = io->private_data;
    263 	int err;
    264 
    265 	DBG("%p", io);
    266 
    267 	data->stopped = 0;
    268 
    269 	if (data->hw_thread)
    270 		return 0;
    271 
    272 	err = pthread_create(&data->hw_thread, 0, playback_hw_thread, data);
    273 
    274 	return -err;
    275 }
    276 
    277 static int bluetooth_playback_stop(snd_pcm_ioplug_t *io)
    278 {
    279 	struct bluetooth_data *data = io->private_data;
    280 
    281 	DBG("%p", io);
    282 
    283 	data->stopped = 1;
    284 
    285 	return 0;
    286 }
    287 
    288 static snd_pcm_sframes_t bluetooth_pointer(snd_pcm_ioplug_t *io)
    289 {
    290 	struct bluetooth_data *data = io->private_data;
    291 
    292 	return data->hw_ptr;
    293 }
    294 
    295 static void bluetooth_exit(struct bluetooth_data *data)
    296 {
    297 	struct bluetooth_a2dp *a2dp = &data->a2dp;
    298 
    299 	if (data->server.fd >= 0)
    300 		bt_audio_service_close(data->server.fd);
    301 
    302 	if (data->stream.fd >= 0)
    303 		close(data->stream.fd);
    304 
    305 	if (data->hw_thread) {
    306 		pthread_cancel(data->hw_thread);
    307 		pthread_join(data->hw_thread, 0);
    308 	}
    309 
    310 	if (a2dp->sbc_initialized)
    311 		sbc_finish(&a2dp->sbc);
    312 
    313 	if (data->pipefd[0] > 0)
    314 		close(data->pipefd[0]);
    315 
    316 	if (data->pipefd[1] > 0)
    317 		close(data->pipefd[1]);
    318 
    319 	free(data);
    320 }
    321 
    322 static int bluetooth_close(snd_pcm_ioplug_t *io)
    323 {
    324 	struct bluetooth_data *data = io->private_data;
    325 
    326 	DBG("%p", io);
    327 
    328 	bluetooth_exit(data);
    329 
    330 	return 0;
    331 }
    332 
    333 static int bluetooth_prepare(snd_pcm_ioplug_t *io)
    334 {
    335 	struct bluetooth_data *data = io->private_data;
    336 	char c = 'w';
    337 	char buf[BT_SUGGESTED_BUFFER_SIZE];
    338 	struct bt_start_stream_req *req = (void *) buf;
    339 	struct bt_start_stream_rsp *rsp = (void *) buf;
    340 	struct bt_new_stream_ind *ind = (void *) buf;
    341 	uint32_t period_count = io->buffer_size / io->period_size;
    342 	int opt_name, err;
    343 	struct timeval t = { 0, period_count };
    344 
    345 	DBG("Preparing with io->period_size=%lu io->buffer_size=%lu",
    346 					io->period_size, io->buffer_size);
    347 
    348 	data->reset = 0;
    349 
    350 	/* As we're gonna receive messages on the server socket, we have to stop the
    351 	   hw thread that is polling on it, if any */
    352 	if (data->hw_thread) {
    353 		pthread_cancel(data->hw_thread);
    354 		pthread_join(data->hw_thread, 0);
    355 		data->hw_thread = 0;
    356 	}
    357 
    358 	if (io->stream == SND_PCM_STREAM_PLAYBACK)
    359 		/* If not null for playback, xmms doesn't display time
    360 		 * correctly */
    361 		data->hw_ptr = 0;
    362 	else
    363 		/* ALSA library is really picky on the fact hw_ptr is not null.
    364 		 * If it is, capture won't start */
    365 		data->hw_ptr = io->period_size;
    366 
    367 	/* send start */
    368 	memset(req, 0, BT_SUGGESTED_BUFFER_SIZE);
    369 	req->h.type = BT_REQUEST;
    370 	req->h.name = BT_START_STREAM;
    371 	req->h.length = sizeof(*req);
    372 
    373 	err = audioservice_send(data->server.fd, &req->h);
    374 	if (err < 0)
    375 		return err;
    376 
    377 	rsp->h.length = sizeof(*rsp);
    378 	err = audioservice_expect(data->server.fd, &rsp->h,
    379 					BT_START_STREAM);
    380 	if (err < 0)
    381 		return err;
    382 
    383 	ind->h.length = sizeof(*ind);
    384 	err = audioservice_expect(data->server.fd, &ind->h,
    385 					BT_NEW_STREAM);
    386 	if (err < 0)
    387 		return err;
    388 
    389 	if (data->stream.fd >= 0)
    390 		close(data->stream.fd);
    391 
    392 	data->stream.fd = bt_audio_service_get_data_fd(data->server.fd);
    393 	if (data->stream.fd < 0) {
    394 		return -errno;
    395 	}
    396 
    397 	if (data->transport == BT_CAPABILITIES_TRANSPORT_A2DP) {
    398 		opt_name = (io->stream == SND_PCM_STREAM_PLAYBACK) ?
    399 						SO_SNDTIMEO : SO_RCVTIMEO;
    400 
    401 		if (setsockopt(data->stream.fd, SOL_SOCKET, opt_name, &t,
    402 							sizeof(t)) < 0)
    403 			return -errno;
    404 	} else {
    405 		opt_name = (io->stream == SND_PCM_STREAM_PLAYBACK) ?
    406 						SCO_TXBUFS : SCO_RXBUFS;
    407 
    408 		if (setsockopt(data->stream.fd, SOL_SCO, opt_name, &period_count,
    409 						sizeof(period_count)) == 0)
    410 			return 0;
    411 
    412 		opt_name = (io->stream == SND_PCM_STREAM_PLAYBACK) ?
    413 						SO_SNDBUF : SO_RCVBUF;
    414 
    415 		if (setsockopt(data->stream.fd, SOL_SCO, opt_name, &period_count,
    416 						sizeof(period_count)) == 0)
    417 			return 0;
    418 
    419 		/* FIXME : handle error codes */
    420 	}
    421 
    422 	/* wake up any client polling at us */
    423 	err = write(data->pipefd[1], &c, 1);
    424 	if (err < 0)
    425 		return err;
    426 
    427 	return 0;
    428 }
    429 
    430 static int bluetooth_hsp_hw_params(snd_pcm_ioplug_t *io,
    431 					snd_pcm_hw_params_t *params)
    432 {
    433 	struct bluetooth_data *data = io->private_data;
    434 	char buf[BT_SUGGESTED_BUFFER_SIZE];
    435 	struct bt_open_req *open_req = (void *) buf;
    436 	struct bt_open_rsp *open_rsp = (void *) buf;
    437 	struct bt_set_configuration_req *req = (void *) buf;
    438 	struct bt_set_configuration_rsp *rsp = (void *) buf;
    439 	int err;
    440 
    441 	DBG("Preparing with io->period_size=%lu io->buffer_size=%lu",
    442 					io->period_size, io->buffer_size);
    443 
    444 	memset(req, 0, BT_SUGGESTED_BUFFER_SIZE);
    445 	open_req->h.type = BT_REQUEST;
    446 	open_req->h.name = BT_OPEN;
    447 	open_req->h.length = sizeof(*open_req);
    448 
    449 	strncpy(open_req->destination, data->alsa_config.device, 18);
    450 	open_req->seid = BT_A2DP_SEID_RANGE + 1;
    451 	open_req->lock = (io->stream == SND_PCM_STREAM_PLAYBACK ?
    452 			BT_WRITE_LOCK : BT_READ_LOCK);
    453 
    454 	err = audioservice_send(data->server.fd, &open_req->h);
    455 	if (err < 0)
    456 		return err;
    457 
    458 	open_rsp->h.length = sizeof(*open_rsp);
    459 	err = audioservice_expect(data->server.fd, &open_rsp->h,
    460 					BT_OPEN);
    461 	if (err < 0)
    462 		return err;
    463 
    464 	memset(req, 0, BT_SUGGESTED_BUFFER_SIZE);
    465 	req->h.type = BT_REQUEST;
    466 	req->h.name = BT_SET_CONFIGURATION;
    467 	req->h.length = sizeof(*req);
    468 
    469 	req->codec.transport = BT_CAPABILITIES_TRANSPORT_SCO;
    470 	req->codec.seid = BT_A2DP_SEID_RANGE + 1;
    471 	req->codec.length = sizeof(pcm_capabilities_t);
    472 
    473 	req->h.length += req->codec.length - sizeof(req->codec);
    474 	err = audioservice_send(data->server.fd, &req->h);
    475 	if (err < 0)
    476 		return err;
    477 
    478 	rsp->h.length = sizeof(*rsp);
    479 	err = audioservice_expect(data->server.fd, &rsp->h,
    480 					BT_SET_CONFIGURATION);
    481 	if (err < 0)
    482 		return err;
    483 
    484 	data->transport = BT_CAPABILITIES_TRANSPORT_SCO;
    485 	data->link_mtu = rsp->link_mtu;
    486 
    487 	return 0;
    488 }
    489 
    490 static uint8_t default_bitpool(uint8_t freq, uint8_t mode)
    491 {
    492 	switch (freq) {
    493 	case BT_SBC_SAMPLING_FREQ_16000:
    494 	case BT_SBC_SAMPLING_FREQ_32000:
    495 		return 53;
    496 	case BT_SBC_SAMPLING_FREQ_44100:
    497 		switch (mode) {
    498 		case BT_A2DP_CHANNEL_MODE_MONO:
    499 		case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
    500 			return 31;
    501 		case BT_A2DP_CHANNEL_MODE_STEREO:
    502 		case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
    503 			return 53;
    504 		default:
    505 			DBG("Invalid channel mode %u", mode);
    506 			return 53;
    507 		}
    508 	case BT_SBC_SAMPLING_FREQ_48000:
    509 		switch (mode) {
    510 		case BT_A2DP_CHANNEL_MODE_MONO:
    511 		case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
    512 			return 29;
    513 		case BT_A2DP_CHANNEL_MODE_STEREO:
    514 		case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
    515 			return 51;
    516 		default:
    517 			DBG("Invalid channel mode %u", mode);
    518 			return 51;
    519 		}
    520 	default:
    521 		DBG("Invalid sampling freq %u", freq);
    522 		return 53;
    523 	}
    524 }
    525 
    526 static int bluetooth_a2dp_init(struct bluetooth_data *data,
    527 					snd_pcm_hw_params_t *params)
    528 {
    529 	struct bluetooth_alsa_config *cfg = &data->alsa_config;
    530 	sbc_capabilities_t *cap = &data->a2dp.sbc_capabilities;
    531 	unsigned int max_bitpool, min_bitpool, rate, channels;
    532 	int dir;
    533 
    534 	snd_pcm_hw_params_get_rate(params, &rate, &dir);
    535 	snd_pcm_hw_params_get_channels(params, &channels);
    536 
    537 	switch (rate) {
    538 	case 48000:
    539 		cap->frequency = BT_SBC_SAMPLING_FREQ_48000;
    540 		break;
    541 	case 44100:
    542 		cap->frequency = BT_SBC_SAMPLING_FREQ_44100;
    543 		break;
    544 	case 32000:
    545 		cap->frequency = BT_SBC_SAMPLING_FREQ_32000;
    546 		break;
    547 	case 16000:
    548 		cap->frequency = BT_SBC_SAMPLING_FREQ_16000;
    549 		break;
    550 	default:
    551 		DBG("Rate %d not supported", rate);
    552 		return -1;
    553 	}
    554 
    555 	if (cfg->has_channel_mode)
    556 		cap->channel_mode = cfg->channel_mode;
    557 	else if (channels == 2) {
    558 		if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
    559 			cap->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
    560 		else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
    561 			cap->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
    562 		else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
    563 			cap->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
    564 	} else {
    565 		if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
    566 			cap->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
    567 	}
    568 
    569 	if (!cap->channel_mode) {
    570 		DBG("No supported channel modes");
    571 		return -1;
    572 	}
    573 
    574 	if (cfg->has_block_length)
    575 		cap->block_length = cfg->block_length;
    576 	else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
    577 		cap->block_length = BT_A2DP_BLOCK_LENGTH_16;
    578 	else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
    579 		cap->block_length = BT_A2DP_BLOCK_LENGTH_12;
    580 	else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
    581 		cap->block_length = BT_A2DP_BLOCK_LENGTH_8;
    582 	else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
    583 		cap->block_length = BT_A2DP_BLOCK_LENGTH_4;
    584 	else {
    585 		DBG("No supported block lengths");
    586 		return -1;
    587 	}
    588 
    589 	if (cfg->has_subbands)
    590 		cap->subbands = cfg->subbands;
    591 	if (cap->subbands & BT_A2DP_SUBBANDS_8)
    592 		cap->subbands = BT_A2DP_SUBBANDS_8;
    593 	else if (cap->subbands & BT_A2DP_SUBBANDS_4)
    594 		cap->subbands = BT_A2DP_SUBBANDS_4;
    595 	else {
    596 		DBG("No supported subbands");
    597 		return -1;
    598 	}
    599 
    600 	if (cfg->has_allocation_method)
    601 		cap->allocation_method = cfg->allocation_method;
    602 	if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
    603 		cap->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
    604 	else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
    605 		cap->allocation_method = BT_A2DP_ALLOCATION_SNR;
    606 
    607 	if (cfg->has_bitpool)
    608 		min_bitpool = max_bitpool = cfg->bitpool;
    609 	else {
    610 		min_bitpool = MAX(MIN_BITPOOL, cap->min_bitpool);
    611 		max_bitpool = MIN(default_bitpool(cap->frequency,
    612 					cap->channel_mode),
    613 					cap->max_bitpool);
    614 	}
    615 
    616 	cap->min_bitpool = min_bitpool;
    617 	cap->max_bitpool = max_bitpool;
    618 
    619 	return 0;
    620 }
    621 
    622 static void bluetooth_a2dp_setup(struct bluetooth_a2dp *a2dp)
    623 {
    624 	sbc_capabilities_t active_capabilities = a2dp->sbc_capabilities;
    625 
    626 	if (a2dp->sbc_initialized)
    627 		sbc_reinit(&a2dp->sbc, 0);
    628 	else
    629 		sbc_init(&a2dp->sbc, 0);
    630 	a2dp->sbc_initialized = 1;
    631 
    632 	if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_16000)
    633 		a2dp->sbc.frequency = SBC_FREQ_16000;
    634 
    635 	if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_32000)
    636 		a2dp->sbc.frequency = SBC_FREQ_32000;
    637 
    638 	if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_44100)
    639 		a2dp->sbc.frequency = SBC_FREQ_44100;
    640 
    641 	if (active_capabilities.frequency & BT_SBC_SAMPLING_FREQ_48000)
    642 		a2dp->sbc.frequency = SBC_FREQ_48000;
    643 
    644 	if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_MONO)
    645 		a2dp->sbc.mode = SBC_MODE_MONO;
    646 
    647 	if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
    648 		a2dp->sbc.mode = SBC_MODE_DUAL_CHANNEL;
    649 
    650 	if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
    651 		a2dp->sbc.mode = SBC_MODE_STEREO;
    652 
    653 	if (active_capabilities.channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
    654 		a2dp->sbc.mode = SBC_MODE_JOINT_STEREO;
    655 
    656 	a2dp->sbc.allocation = active_capabilities.allocation_method
    657 				== BT_A2DP_ALLOCATION_SNR ? SBC_AM_SNR
    658 				: SBC_AM_LOUDNESS;
    659 
    660 	switch (active_capabilities.subbands) {
    661 	case BT_A2DP_SUBBANDS_4:
    662 		a2dp->sbc.subbands = SBC_SB_4;
    663 		break;
    664 	case BT_A2DP_SUBBANDS_8:
    665 		a2dp->sbc.subbands = SBC_SB_8;
    666 		break;
    667 	}
    668 
    669 	switch (active_capabilities.block_length) {
    670 	case BT_A2DP_BLOCK_LENGTH_4:
    671 		a2dp->sbc.blocks = SBC_BLK_4;
    672 		break;
    673 	case BT_A2DP_BLOCK_LENGTH_8:
    674 		a2dp->sbc.blocks = SBC_BLK_8;
    675 		break;
    676 	case BT_A2DP_BLOCK_LENGTH_12:
    677 		a2dp->sbc.blocks = SBC_BLK_12;
    678 		break;
    679 	case BT_A2DP_BLOCK_LENGTH_16:
    680 		a2dp->sbc.blocks = SBC_BLK_16;
    681 		break;
    682 	}
    683 
    684 	a2dp->sbc.bitpool = active_capabilities.max_bitpool;
    685 	a2dp->codesize = sbc_get_codesize(&a2dp->sbc);
    686 	a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
    687 }
    688 
    689 static int bluetooth_a2dp_hw_params(snd_pcm_ioplug_t *io,
    690 					snd_pcm_hw_params_t *params)
    691 {
    692 	struct bluetooth_data *data = io->private_data;
    693 	struct bluetooth_a2dp *a2dp = &data->a2dp;
    694 	char buf[BT_SUGGESTED_BUFFER_SIZE];
    695 	struct bt_open_req *open_req = (void *) buf;
    696 	struct bt_open_rsp *open_rsp = (void *) buf;
    697 	struct bt_set_configuration_req *req = (void *) buf;
    698 	struct bt_set_configuration_rsp *rsp = (void *) buf;
    699 	int err;
    700 
    701 	DBG("Preparing with io->period_size=%lu io->buffer_size=%lu",
    702 					io->period_size, io->buffer_size);
    703 
    704 	memset(req, 0, BT_SUGGESTED_BUFFER_SIZE);
    705 	open_req->h.type = BT_REQUEST;
    706 	open_req->h.name = BT_OPEN;
    707 	open_req->h.length = sizeof(*open_req);
    708 
    709 	strncpy(open_req->destination, data->alsa_config.device, 18);
    710 	open_req->seid = a2dp->sbc_capabilities.capability.seid;
    711 	open_req->lock = (io->stream == SND_PCM_STREAM_PLAYBACK ?
    712 			BT_WRITE_LOCK : BT_READ_LOCK);
    713 
    714 	err = audioservice_send(data->server.fd, &open_req->h);
    715 	if (err < 0)
    716 		return err;
    717 
    718 	open_rsp->h.length = sizeof(*open_rsp);
    719 	err = audioservice_expect(data->server.fd, &open_rsp->h,
    720 					BT_OPEN);
    721 	if (err < 0)
    722 		return err;
    723 
    724 	err = bluetooth_a2dp_init(data, params);
    725 	if (err < 0)
    726 		return err;
    727 
    728 	memset(req, 0, BT_SUGGESTED_BUFFER_SIZE);
    729 	req->h.type = BT_REQUEST;
    730 	req->h.name = BT_SET_CONFIGURATION;
    731 	req->h.length = sizeof(*req);
    732 
    733 	memcpy(&req->codec, &a2dp->sbc_capabilities,
    734 			sizeof(a2dp->sbc_capabilities));
    735 
    736 	req->codec.transport = BT_CAPABILITIES_TRANSPORT_A2DP;
    737 	req->codec.length = sizeof(a2dp->sbc_capabilities);
    738 	req->h.length += req->codec.length - sizeof(req->codec);
    739 
    740 	err = audioservice_send(data->server.fd, &req->h);
    741 	if (err < 0)
    742 		return err;
    743 
    744 	rsp->h.length = sizeof(*rsp);
    745 	err = audioservice_expect(data->server.fd, &rsp->h,
    746 					BT_SET_CONFIGURATION);
    747 	if (err < 0)
    748 		return err;
    749 
    750 	data->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
    751 	data->link_mtu = rsp->link_mtu;
    752 
    753 	/* Setup SBC encoder now we agree on parameters */
    754 	bluetooth_a2dp_setup(a2dp);
    755 
    756 	DBG("\tallocation=%u\n\tsubbands=%u\n\tblocks=%u\n\tbitpool=%u\n",
    757 		a2dp->sbc.allocation, a2dp->sbc.subbands, a2dp->sbc.blocks,
    758 		a2dp->sbc.bitpool);
    759 
    760 	return 0;
    761 }
    762 
    763 static int bluetooth_poll_descriptors(snd_pcm_ioplug_t *io,
    764 					struct pollfd *pfd, unsigned int space)
    765 {
    766 	struct bluetooth_data *data = io->private_data;
    767 
    768 	assert(io);
    769 
    770 	if (space < 1)
    771 		return 0;
    772 
    773 	pfd[0].fd = data->stream.fd;
    774 	pfd[0].events = POLLIN;
    775 	pfd[0].revents = 0;
    776 
    777 	return 1;
    778 }
    779 
    780 static int bluetooth_poll_revents(snd_pcm_ioplug_t *io ATTRIBUTE_UNUSED,
    781 					struct pollfd *pfds, unsigned int nfds,
    782 					unsigned short *revents)
    783 {
    784 	assert(pfds && nfds == 1 && revents);
    785 
    786 	*revents = pfds[0].revents;
    787 
    788 	return 0;
    789 }
    790 
    791 static int bluetooth_playback_poll_descriptors_count(snd_pcm_ioplug_t *io)
    792 {
    793 	return 2;
    794 }
    795 
    796 static int bluetooth_playback_poll_descriptors(snd_pcm_ioplug_t *io,
    797 					struct pollfd *pfd, unsigned int space)
    798 {
    799 	struct bluetooth_data *data = io->private_data;
    800 
    801 	DBG("");
    802 
    803 	assert(data->pipefd[0] >= 0);
    804 
    805 	if (space < 2)
    806 		return 0;
    807 
    808 	pfd[0].fd = data->pipefd[0];
    809 	pfd[0].events = POLLIN;
    810 	pfd[0].revents = 0;
    811 	pfd[1].fd = data->stream.fd;
    812 	pfd[1].events = POLLERR | POLLHUP | POLLNVAL;
    813 	pfd[1].revents = 0;
    814 
    815 	return 2;
    816 }
    817 
    818 static int bluetooth_playback_poll_revents(snd_pcm_ioplug_t *io,
    819 					struct pollfd *pfds, unsigned int nfds,
    820 					unsigned short *revents)
    821 {
    822 	static char buf[1];
    823 
    824 	DBG("");
    825 
    826 	assert(pfds);
    827 	assert(nfds == 2);
    828 	assert(revents);
    829 	assert(pfds[0].fd >= 0);
    830 	assert(pfds[1].fd >= 0);
    831 
    832 	if (io->state != SND_PCM_STATE_PREPARED)
    833 		if (read(pfds[0].fd, buf, 1) < 0)
    834 			SYSERR("read error: %s (%d)", strerror(errno), errno);
    835 
    836 	if (pfds[1].revents & (POLLERR | POLLHUP | POLLNVAL))
    837 		io->state = SND_PCM_STATE_DISCONNECTED;
    838 
    839 	*revents = (pfds[0].revents & POLLIN) ? POLLOUT : 0;
    840 
    841 	return 0;
    842 }
    843 
    844 
    845 static snd_pcm_sframes_t bluetooth_hsp_read(snd_pcm_ioplug_t *io,
    846 				const snd_pcm_channel_area_t *areas,
    847 				snd_pcm_uframes_t offset,
    848 				snd_pcm_uframes_t size)
    849 {
    850 	struct bluetooth_data *data = io->private_data;
    851 	snd_pcm_uframes_t frames_to_write, ret;
    852 	unsigned char *buff;
    853 	unsigned int frame_size = 0;
    854 	int nrecv;
    855 
    856 	DBG("areas->step=%u areas->first=%u offset=%lu size=%lu io->nonblock=%u",
    857 			areas->step, areas->first, offset, size, io->nonblock);
    858 
    859 	frame_size = areas->step / 8;
    860 
    861 	if (data->count > 0)
    862 		goto proceed;
    863 
    864 	nrecv = recv(data->stream.fd, data->buffer, data->link_mtu,
    865 					io->nonblock ? MSG_DONTWAIT : 0);
    866 
    867 	if (nrecv < 0) {
    868 		ret = (errno == EPIPE) ? -EIO : -errno;
    869 		goto done;
    870 	}
    871 
    872 	if ((unsigned int) nrecv != data->link_mtu) {
    873 		ret = -EIO;
    874 		SNDERR(strerror(-ret));
    875 		goto done;
    876 	}
    877 
    878 	/* Increment hardware transmition pointer */
    879 	data->hw_ptr = (data->hw_ptr + data->link_mtu / frame_size) %
    880 				io->buffer_size;
    881 
    882 proceed:
    883 	buff = (unsigned char *) areas->addr +
    884 			(areas->first + areas->step * offset) / 8;
    885 
    886 	if ((data->count + size * frame_size) <= data->link_mtu)
    887 		frames_to_write = size;
    888 	else
    889 		frames_to_write = (data->link_mtu - data->count) / frame_size;
    890 
    891 	memcpy(buff, data->buffer + data->count, frame_size * frames_to_write);
    892 	data->count += (frame_size * frames_to_write);
    893 	data->count %= data->link_mtu;
    894 
    895 	/* Return written frames count */
    896 	ret = frames_to_write;
    897 
    898 done:
    899 	DBG("returning %lu", ret);
    900 	return ret;
    901 }
    902 
    903 static snd_pcm_sframes_t bluetooth_hsp_write(snd_pcm_ioplug_t *io,
    904 				const snd_pcm_channel_area_t *areas,
    905 				snd_pcm_uframes_t offset,
    906 				snd_pcm_uframes_t size)
    907 {
    908 	struct bluetooth_data *data = io->private_data;
    909 	snd_pcm_sframes_t ret = 0;
    910 	snd_pcm_uframes_t frames_to_read;
    911 	uint8_t *buff;
    912 	int rsend, frame_size;
    913 
    914 	DBG("areas->step=%u areas->first=%u offset=%lu, size=%lu io->nonblock=%u",
    915 			areas->step, areas->first, offset, size, io->nonblock);
    916 
    917 	if (io->hw_ptr > io->appl_ptr) {
    918 		ret = bluetooth_playback_stop(io);
    919 		if (ret == 0)
    920 			ret = -EPIPE;
    921 		goto done;
    922 	}
    923 
    924 	frame_size = areas->step / 8;
    925 	if ((data->count + size * frame_size) <= data->link_mtu)
    926 		frames_to_read = size;
    927 	else
    928 		frames_to_read = (data->link_mtu - data->count) / frame_size;
    929 
    930 	DBG("count=%d frames_to_read=%lu", data->count, frames_to_read);
    931 
    932 	/* Ready for more data */
    933 	buff = (uint8_t *) areas->addr +
    934 			(areas->first + areas->step * offset) / 8;
    935 	memcpy(data->buffer + data->count, buff, frame_size * frames_to_read);
    936 
    937 	/* Remember we have some frames in the pipe now */
    938 	data->count += frames_to_read * frame_size;
    939 	if (data->count != data->link_mtu) {
    940 		ret = frames_to_read;
    941 		goto done;
    942 	}
    943 
    944 	rsend = send(data->stream.fd, data->buffer, data->link_mtu,
    945 			io->nonblock ? MSG_DONTWAIT : 0);
    946 	if (rsend > 0) {
    947 		/* Reset count pointer */
    948 		data->count = 0;
    949 
    950 		ret = frames_to_read;
    951 	} else if (rsend < 0)
    952 		ret = (errno == EPIPE) ? -EIO : -errno;
    953 	else
    954 		ret = -EIO;
    955 
    956 done:
    957 	DBG("returning %ld", ret);
    958 	return ret;
    959 }
    960 
    961 static snd_pcm_sframes_t bluetooth_a2dp_read(snd_pcm_ioplug_t *io,
    962 				const snd_pcm_channel_area_t *areas,
    963 				snd_pcm_uframes_t offset, snd_pcm_uframes_t size)
    964 {
    965 	snd_pcm_uframes_t ret = 0;
    966 	return ret;
    967 }
    968 
    969 static int avdtp_write(struct bluetooth_data *data)
    970 {
    971 	int ret = 0;
    972 	struct rtp_header *header;
    973 	struct rtp_payload *payload;
    974 	struct bluetooth_a2dp *a2dp = &data->a2dp;
    975 
    976 	header = (void *) a2dp->buffer;
    977 	payload = (void *) (a2dp->buffer + sizeof(*header));
    978 
    979 	memset(a2dp->buffer, 0, sizeof(*header) + sizeof(*payload));
    980 
    981 	payload->frame_count = a2dp->frame_count;
    982 	header->v = 2;
    983 	header->pt = 1;
    984 	header->sequence_number = htons(a2dp->seq_num);
    985 	header->timestamp = htonl(a2dp->nsamples);
    986 	header->ssrc = htonl(1);
    987 
    988 	ret = send(data->stream.fd, a2dp->buffer, a2dp->count, MSG_DONTWAIT);
    989 	if (ret < 0) {
    990 		DBG("send returned %d errno %s.", ret, strerror(errno));
    991 		ret = -errno;
    992 	}
    993 
    994 	/* Reset buffer of data to send */
    995 	a2dp->count = sizeof(struct rtp_header) + sizeof(struct rtp_payload);
    996 	a2dp->frame_count = 0;
    997 	a2dp->samples = 0;
    998 	a2dp->seq_num++;
    999 
   1000 	return ret;
   1001 }
   1002 
   1003 static snd_pcm_sframes_t bluetooth_a2dp_write(snd_pcm_ioplug_t *io,
   1004 				const snd_pcm_channel_area_t *areas,
   1005 				snd_pcm_uframes_t offset, snd_pcm_uframes_t size)
   1006 {
   1007 	struct bluetooth_data *data = io->private_data;
   1008 	struct bluetooth_a2dp *a2dp = &data->a2dp;
   1009 	snd_pcm_sframes_t ret = 0;
   1010 	unsigned int bytes_left;
   1011 	int frame_size, encoded;
   1012 	ssize_t written;
   1013 	uint8_t *buff;
   1014 
   1015 	DBG("areas->step=%u areas->first=%u offset=%lu size=%lu",
   1016 				areas->step, areas->first, offset, size);
   1017 	DBG("hw_ptr=%lu appl_ptr=%lu diff=%lu", io->hw_ptr, io->appl_ptr,
   1018 			io->appl_ptr - io->hw_ptr);
   1019 
   1020 	/* Calutate starting pointers */
   1021 	frame_size = areas->step / 8;
   1022 	bytes_left = size * frame_size;
   1023 	buff = (uint8_t *) areas->addr +
   1024 				(areas->first + areas->step * (offset)) / 8;
   1025 
   1026 	/* Check for underrun */
   1027 	if (io->hw_ptr > io->appl_ptr) {
   1028 		ret = bluetooth_playback_stop(io);
   1029 		if (ret == 0)
   1030 			ret = -EPIPE;
   1031 		data->reset = 1;
   1032 		return ret;
   1033 	}
   1034 
   1035 	/* Check if we should autostart */
   1036 	if (io->state == SND_PCM_STATE_PREPARED) {
   1037 		snd_pcm_sw_params_t *swparams;
   1038 		snd_pcm_uframes_t threshold;
   1039 
   1040 		snd_pcm_sw_params_malloc(&swparams);
   1041 		if (!snd_pcm_sw_params_current(io->pcm, swparams) &&
   1042 				!snd_pcm_sw_params_get_start_threshold(swparams,
   1043 								&threshold)) {
   1044 			if (io->appl_ptr >= threshold) {
   1045 				ret = snd_pcm_start(io->pcm);
   1046 				if (ret != 0)
   1047 					return ret;
   1048 			}
   1049 		}
   1050 
   1051 		snd_pcm_sw_params_free(swparams);
   1052 	}
   1053 
   1054 	/* Check if we have any left over data from the last write */
   1055 	if (data->count > 0) {
   1056 		unsigned int additional_bytes_needed =
   1057 						a2dp->codesize - data->count;
   1058 		if (additional_bytes_needed > bytes_left)
   1059 			goto out;
   1060 
   1061 		memcpy(data->buffer + data->count, buff,
   1062 						additional_bytes_needed);
   1063 
   1064 		/* Enough data to encode (sbc wants 1k blocks) */
   1065 		encoded = sbc_encode(&a2dp->sbc, data->buffer, a2dp->codesize,
   1066 					a2dp->buffer + a2dp->count,
   1067 					sizeof(a2dp->buffer) - a2dp->count,
   1068 								&written);
   1069 		if (encoded <= 0) {
   1070 			DBG("Encoding error %d", encoded);
   1071 			goto done;
   1072 		}
   1073 
   1074 		/* Increment a2dp buffers */
   1075 		a2dp->count += written;
   1076 		a2dp->frame_count++;
   1077 		a2dp->samples += encoded / frame_size;
   1078 		a2dp->nsamples += encoded / frame_size;
   1079 
   1080 		/* No space left for another frame then send */
   1081 		if (a2dp->count + written >= data->link_mtu) {
   1082 			avdtp_write(data);
   1083 			DBG("sending packet %d, count %d, link_mtu %u",
   1084 					a2dp->seq_num, a2dp->count,
   1085 							data->link_mtu);
   1086 		}
   1087 
   1088 		/* Increment up buff pointer to take into account
   1089 		 * the data processed */
   1090 		buff += additional_bytes_needed;
   1091 		bytes_left -= additional_bytes_needed;
   1092 
   1093 		/* Since data has been process mark it as zero */
   1094 		data->count = 0;
   1095 	}
   1096 
   1097 
   1098 	/* Process this buffer in full chunks */
   1099 	while (bytes_left >= a2dp->codesize) {
   1100 		/* Enough data to encode (sbc wants 1k blocks) */
   1101 		encoded = sbc_encode(&a2dp->sbc, buff, a2dp->codesize,
   1102 					a2dp->buffer + a2dp->count,
   1103 					sizeof(a2dp->buffer) - a2dp->count,
   1104 								&written);
   1105 		if (encoded <= 0) {
   1106 			DBG("Encoding error %d", encoded);
   1107 			goto done;
   1108 		}
   1109 
   1110 		/* Increment up buff pointer to take into account
   1111 		 * the data processed */
   1112 		buff += a2dp->codesize;
   1113 		bytes_left -= a2dp->codesize;
   1114 
   1115 		/* Increment a2dp buffers */
   1116 		a2dp->count += written;
   1117 		a2dp->frame_count++;
   1118 		a2dp->samples += encoded / frame_size;
   1119 		a2dp->nsamples += encoded / frame_size;
   1120 
   1121 		/* No space left for another frame then send */
   1122 		if (a2dp->count + written >= data->link_mtu) {
   1123 			avdtp_write(data);
   1124 			DBG("sending packet %d, count %d, link_mtu %u",
   1125 						a2dp->seq_num, a2dp->count,
   1126 							data->link_mtu);
   1127 		}
   1128 	}
   1129 
   1130 out:
   1131 	/* Copy the extra to our temp buffer for the next write */
   1132 	if (bytes_left > 0) {
   1133 		memcpy(data->buffer + data->count, buff, bytes_left);
   1134 		data->count += bytes_left;
   1135 		bytes_left = 0;
   1136 	}
   1137 
   1138 done:
   1139 	DBG("returning %ld", size - bytes_left / frame_size);
   1140 
   1141 	return size - bytes_left / frame_size;
   1142 }
   1143 
   1144 static int bluetooth_playback_delay(snd_pcm_ioplug_t *io,
   1145 					snd_pcm_sframes_t *delayp)
   1146 {
   1147 	DBG("");
   1148 
   1149 	/* This updates io->hw_ptr value using pointer() function */
   1150 	snd_pcm_hwsync(io->pcm);
   1151 
   1152 	*delayp = io->appl_ptr - io->hw_ptr;
   1153 	if ((io->state == SND_PCM_STATE_RUNNING) && (*delayp < 0)) {
   1154 		io->callback->stop(io);
   1155 		io->state = SND_PCM_STATE_XRUN;
   1156 		*delayp = 0;
   1157 	}
   1158 
   1159 	/* This should never fail, ALSA API is really not
   1160 	prepared to handle a non zero return value */
   1161 	return 0;
   1162 }
   1163 
   1164 static snd_pcm_ioplug_callback_t bluetooth_hsp_playback = {
   1165 	.start			= bluetooth_playback_start,
   1166 	.stop			= bluetooth_playback_stop,
   1167 	.pointer		= bluetooth_pointer,
   1168 	.close			= bluetooth_close,
   1169 	.hw_params		= bluetooth_hsp_hw_params,
   1170 	.prepare		= bluetooth_prepare,
   1171 	.transfer		= bluetooth_hsp_write,
   1172 	.poll_descriptors_count	= bluetooth_playback_poll_descriptors_count,
   1173 	.poll_descriptors	= bluetooth_playback_poll_descriptors,
   1174 	.poll_revents		= bluetooth_playback_poll_revents,
   1175 	.delay			= bluetooth_playback_delay,
   1176 };
   1177 
   1178 static snd_pcm_ioplug_callback_t bluetooth_hsp_capture = {
   1179 	.start			= bluetooth_start,
   1180 	.stop			= bluetooth_stop,
   1181 	.pointer		= bluetooth_pointer,
   1182 	.close			= bluetooth_close,
   1183 	.hw_params		= bluetooth_hsp_hw_params,
   1184 	.prepare		= bluetooth_prepare,
   1185 	.transfer		= bluetooth_hsp_read,
   1186 	.poll_descriptors	= bluetooth_poll_descriptors,
   1187 	.poll_revents		= bluetooth_poll_revents,
   1188 };
   1189 
   1190 static snd_pcm_ioplug_callback_t bluetooth_a2dp_playback = {
   1191 	.start			= bluetooth_playback_start,
   1192 	.stop			= bluetooth_playback_stop,
   1193 	.pointer		= bluetooth_pointer,
   1194 	.close			= bluetooth_close,
   1195 	.hw_params		= bluetooth_a2dp_hw_params,
   1196 	.prepare		= bluetooth_prepare,
   1197 	.transfer		= bluetooth_a2dp_write,
   1198 	.poll_descriptors_count	= bluetooth_playback_poll_descriptors_count,
   1199 	.poll_descriptors	= bluetooth_playback_poll_descriptors,
   1200 	.poll_revents		= bluetooth_playback_poll_revents,
   1201 	.delay			= bluetooth_playback_delay,
   1202 };
   1203 
   1204 static snd_pcm_ioplug_callback_t bluetooth_a2dp_capture = {
   1205 	.start			= bluetooth_start,
   1206 	.stop			= bluetooth_stop,
   1207 	.pointer		= bluetooth_pointer,
   1208 	.close			= bluetooth_close,
   1209 	.hw_params		= bluetooth_a2dp_hw_params,
   1210 	.prepare		= bluetooth_prepare,
   1211 	.transfer		= bluetooth_a2dp_read,
   1212 	.poll_descriptors	= bluetooth_poll_descriptors,
   1213 	.poll_revents		= bluetooth_poll_revents,
   1214 };
   1215 
   1216 #define ARRAY_NELEMS(a) (sizeof((a)) / sizeof((a)[0]))
   1217 
   1218 static int bluetooth_hsp_hw_constraint(snd_pcm_ioplug_t *io)
   1219 {
   1220 	struct bluetooth_data *data = io->private_data;
   1221 	snd_pcm_access_t access_list[] = {
   1222 		SND_PCM_ACCESS_RW_INTERLEAVED,
   1223 		/* Mmap access is really useless fo this driver, but we
   1224 		 * support it because some pieces of software out there
   1225 		 * insist on using it */
   1226 		SND_PCM_ACCESS_MMAP_INTERLEAVED
   1227 	};
   1228 	unsigned int format_list[] = {
   1229 		SND_PCM_FORMAT_S16
   1230 	};
   1231 	int err;
   1232 
   1233 	/* access type */
   1234 	err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_ACCESS,
   1235 					ARRAY_NELEMS(access_list), access_list);
   1236 	if (err < 0)
   1237 		return err;
   1238 
   1239 	/* supported formats */
   1240 	err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_FORMAT,
   1241 					ARRAY_NELEMS(format_list), format_list);
   1242 	if (err < 0)
   1243 		return err;
   1244 
   1245 	/* supported channels */
   1246 	err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_CHANNELS,
   1247 							1, 1);
   1248 	if (err < 0)
   1249 		return err;
   1250 
   1251 	/* supported rate */
   1252 	err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_RATE,
   1253 							8000, 8000);
   1254 	if (err < 0)
   1255 		return err;
   1256 
   1257 	/* supported block size */
   1258 	err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_PERIOD_BYTES,
   1259 						data->link_mtu, data->link_mtu);
   1260 	if (err < 0)
   1261 		return err;
   1262 
   1263 	err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_PERIODS,
   1264 									2, 200);
   1265 	if (err < 0)
   1266 		return err;
   1267 
   1268 	return 0;
   1269 }
   1270 
   1271 static int bluetooth_a2dp_hw_constraint(snd_pcm_ioplug_t *io)
   1272 {
   1273 	struct bluetooth_data *data = io->private_data;
   1274 	struct bluetooth_a2dp *a2dp = &data->a2dp;
   1275 	struct bluetooth_alsa_config *cfg = &data->alsa_config;
   1276 	snd_pcm_access_t access_list[] = {
   1277 		SND_PCM_ACCESS_RW_INTERLEAVED,
   1278 		/* Mmap access is really useless fo this driver, but we
   1279 		 * support it because some pieces of software out there
   1280 		 * insist on using it */
   1281 		SND_PCM_ACCESS_MMAP_INTERLEAVED
   1282 	};
   1283 	unsigned int format_list[] = {
   1284 		SND_PCM_FORMAT_S16
   1285 	};
   1286 	unsigned int rate_list[4];
   1287 	unsigned int rate_count;
   1288 	int err, min_channels, max_channels;
   1289 	unsigned int period_list[] = {
   1290 		2048,
   1291 		4096, /* e.g. 23.2msec/period (stereo 16bit at 44.1kHz) */
   1292 		8192
   1293 	};
   1294 
   1295 	/* access type */
   1296 	err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_ACCESS,
   1297 					ARRAY_NELEMS(access_list), access_list);
   1298 	if (err < 0)
   1299 		return err;
   1300 
   1301 	/* supported formats */
   1302 	err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_FORMAT,
   1303 					ARRAY_NELEMS(format_list), format_list);
   1304 	if (err < 0)
   1305 		return err;
   1306 
   1307 	/* supported channels */
   1308 	if (cfg->has_channel_mode)
   1309 		a2dp->sbc_capabilities.channel_mode = cfg->channel_mode;
   1310 
   1311 	if (a2dp->sbc_capabilities.channel_mode &
   1312 			BT_A2DP_CHANNEL_MODE_MONO)
   1313 		min_channels = 1;
   1314 	else
   1315 		min_channels = 2;
   1316 
   1317 	if (a2dp->sbc_capabilities.channel_mode &
   1318 			(~BT_A2DP_CHANNEL_MODE_MONO))
   1319 		max_channels = 2;
   1320 	else
   1321 		max_channels = 1;
   1322 
   1323 	err = snd_pcm_ioplug_set_param_minmax(io, SND_PCM_IOPLUG_HW_CHANNELS,
   1324 							min_channels, max_channels);
   1325 	if (err < 0)
   1326 		return err;
   1327 
   1328 	/* supported buffer sizes
   1329 	 * (can be used as 3*8192, 6*4096, 12*2048, ...) */
   1330 	err = snd_pcm_ioplug_set_param_minmax(io,
   1331 						SND_PCM_IOPLUG_HW_BUFFER_BYTES,
   1332 						8192*3, 8192*3);
   1333 	if (err < 0)
   1334 		return err;
   1335 
   1336 	/* supported block sizes: */
   1337 	err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_PERIOD_BYTES,
   1338 				ARRAY_NELEMS(period_list), period_list);
   1339 	if (err < 0)
   1340 		return err;
   1341 
   1342 	/* supported rates */
   1343 	rate_count = 0;
   1344 	if (cfg->has_rate) {
   1345 		rate_list[rate_count] = cfg->rate;
   1346 		rate_count++;
   1347 	} else {
   1348 		if (a2dp->sbc_capabilities.frequency &
   1349 				BT_SBC_SAMPLING_FREQ_16000) {
   1350 			rate_list[rate_count] = 16000;
   1351 			rate_count++;
   1352 		}
   1353 
   1354 		if (a2dp->sbc_capabilities.frequency &
   1355 				BT_SBC_SAMPLING_FREQ_32000) {
   1356 			rate_list[rate_count] = 32000;
   1357 			rate_count++;
   1358 		}
   1359 
   1360 		if (a2dp->sbc_capabilities.frequency &
   1361 				BT_SBC_SAMPLING_FREQ_44100) {
   1362 			rate_list[rate_count] = 44100;
   1363 			rate_count++;
   1364 		}
   1365 
   1366 		if (a2dp->sbc_capabilities.frequency &
   1367 				BT_SBC_SAMPLING_FREQ_48000) {
   1368 			rate_list[rate_count] = 48000;
   1369 			rate_count++;
   1370 		}
   1371 	}
   1372 
   1373 	err = snd_pcm_ioplug_set_param_list(io, SND_PCM_IOPLUG_HW_RATE,
   1374 						rate_count, rate_list);
   1375 	if (err < 0)
   1376 		return err;
   1377 
   1378 	return 0;
   1379 }
   1380 
   1381 static int bluetooth_parse_config(snd_config_t *conf,
   1382 				struct bluetooth_alsa_config *bt_config)
   1383 {
   1384 	snd_config_iterator_t i, next;
   1385 
   1386 	memset(bt_config, 0, sizeof(struct bluetooth_alsa_config));
   1387 
   1388 	/* Set defaults */
   1389 	bt_config->autoconnect = 1;
   1390 
   1391 	snd_config_for_each(i, next, conf) {
   1392 		snd_config_t *n = snd_config_iterator_entry(i);
   1393 		const char *id, *value;
   1394 
   1395 		if (snd_config_get_id(n, &id) < 0)
   1396 			continue;
   1397 
   1398 		if (strcmp(id, "comment") == 0 || strcmp(id, "type") == 0)
   1399 			continue;
   1400 
   1401 		if (strcmp(id, "autoconnect") == 0) {
   1402 			int b;
   1403 
   1404 			b = snd_config_get_bool(n);
   1405 			if (b < 0) {
   1406 				SNDERR("Invalid type for %s", id);
   1407 				return -EINVAL;
   1408 			}
   1409 
   1410 			bt_config->autoconnect = b;
   1411 			continue;
   1412 		}
   1413 
   1414 		if (strcmp(id, "device") == 0 || strcmp(id, "bdaddr") == 0) {
   1415 			if (snd_config_get_string(n, &value) < 0) {
   1416 				SNDERR("Invalid type for %s", id);
   1417 				return -EINVAL;
   1418 			}
   1419 
   1420 			bt_config->has_device = 1;
   1421 			strncpy(bt_config->device, value, 18);
   1422 			continue;
   1423 		}
   1424 
   1425 		if (strcmp(id, "profile") == 0) {
   1426 			if (snd_config_get_string(n, &value) < 0) {
   1427 				SNDERR("Invalid type for %s", id);
   1428 				return -EINVAL;
   1429 			}
   1430 
   1431 			if (strcmp(value, "auto") == 0) {
   1432 				bt_config->transport = BT_CAPABILITIES_TRANSPORT_ANY;
   1433 				bt_config->has_transport = 1;
   1434 			} else if (strcmp(value, "voice") == 0 ||
   1435 						strcmp(value, "hfp") == 0) {
   1436 				bt_config->transport = BT_CAPABILITIES_TRANSPORT_SCO;
   1437 				bt_config->has_transport = 1;
   1438 			} else if (strcmp(value, "hifi") == 0 ||
   1439 						strcmp(value, "a2dp") == 0) {
   1440 				bt_config->transport = BT_CAPABILITIES_TRANSPORT_A2DP;
   1441 				bt_config->has_transport = 1;
   1442 			}
   1443 			continue;
   1444 		}
   1445 
   1446 		if (strcmp(id, "rate") == 0) {
   1447 			if (snd_config_get_string(n, &value) < 0) {
   1448 				SNDERR("Invalid type for %s", id);
   1449 				return -EINVAL;
   1450 			}
   1451 
   1452 			bt_config->rate = atoi(value);
   1453 			bt_config->has_rate = 1;
   1454 			continue;
   1455 		}
   1456 
   1457 		if (strcmp(id, "mode") == 0) {
   1458 			if (snd_config_get_string(n, &value) < 0) {
   1459 				SNDERR("Invalid type for %s", id);
   1460 				return -EINVAL;
   1461 			}
   1462 
   1463 			if (strcmp(value, "mono") == 0) {
   1464 				bt_config->channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
   1465 				bt_config->has_channel_mode = 1;
   1466 			} else if (strcmp(value, "dual") == 0) {
   1467 				bt_config->channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
   1468 				bt_config->has_channel_mode = 1;
   1469 			} else if (strcmp(value, "stereo") == 0) {
   1470 				bt_config->channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
   1471 				bt_config->has_channel_mode = 1;
   1472 			} else if (strcmp(value, "joint") == 0) {
   1473 				bt_config->channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
   1474 				bt_config->has_channel_mode = 1;
   1475 			}
   1476 			continue;
   1477 		}
   1478 
   1479 		if (strcmp(id, "allocation") == 0) {
   1480 			if (snd_config_get_string(n, &value) < 0) {
   1481 				SNDERR("Invalid type for %s", id);
   1482 				return -EINVAL;
   1483 			}
   1484 
   1485 			if (strcmp(value, "loudness") == 0) {
   1486 				bt_config->allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
   1487 				bt_config->has_allocation_method = 1;
   1488 			} else if (strcmp(value, "snr") == 0) {
   1489 				bt_config->allocation_method = BT_A2DP_ALLOCATION_SNR;
   1490 				bt_config->has_allocation_method = 1;
   1491 			}
   1492 			continue;
   1493 		}
   1494 
   1495 		if (strcmp(id, "subbands") == 0) {
   1496 			if (snd_config_get_string(n, &value) < 0) {
   1497 				SNDERR("Invalid type for %s", id);
   1498 				return -EINVAL;
   1499 			}
   1500 
   1501 			bt_config->subbands = atoi(value);
   1502 			bt_config->has_subbands = 1;
   1503 			continue;
   1504 		}
   1505 
   1506 		if (strcmp(id, "blocks") == 0) {
   1507 			if (snd_config_get_string(n, &value) < 0) {
   1508 				SNDERR("Invalid type for %s", id);
   1509 				return -EINVAL;
   1510 			}
   1511 
   1512 			bt_config->block_length = atoi(value);
   1513 			bt_config->has_block_length = 1;
   1514 			continue;
   1515 		}
   1516 
   1517 		if (strcmp(id, "bitpool") == 0) {
   1518 			if (snd_config_get_string(n, &value) < 0) {
   1519 				SNDERR("Invalid type for %s", id);
   1520 				return -EINVAL;
   1521 			}
   1522 
   1523 			bt_config->bitpool = atoi(value);
   1524 			bt_config->has_bitpool = 1;
   1525 			continue;
   1526 		}
   1527 
   1528 		SNDERR("Unknown field %s", id);
   1529 		return -EINVAL;
   1530 	}
   1531 
   1532 	return 0;
   1533 }
   1534 
   1535 static int audioservice_send(int sk, const bt_audio_msg_header_t *msg)
   1536 {
   1537 	int err;
   1538 	uint16_t length;
   1539 
   1540 	length = msg->length ? msg->length : BT_SUGGESTED_BUFFER_SIZE;
   1541 
   1542 	DBG("sending %s:%s", bt_audio_strtype(msg->type),
   1543 		bt_audio_strname(msg->name));
   1544 	if (send(sk, msg, length, 0) > 0)
   1545 		err = 0;
   1546 	else {
   1547 		err = -errno;
   1548 		SNDERR("Error sending data to audio service: %s(%d)",
   1549 			strerror(errno), errno);
   1550 	}
   1551 
   1552 	return err;
   1553 }
   1554 
   1555 static int audioservice_recv(int sk, bt_audio_msg_header_t *inmsg)
   1556 {
   1557 	int err;
   1558 	ssize_t ret;
   1559 	const char *type, *name;
   1560 	uint16_t length;
   1561 
   1562 	length = inmsg->length ? inmsg->length : BT_SUGGESTED_BUFFER_SIZE;
   1563 
   1564 	DBG("trying to receive msg from audio service...");
   1565 
   1566 	ret = recv(sk, inmsg, length, 0);
   1567 	if (ret < 0) {
   1568 		err = -errno;
   1569 		SNDERR("Error receiving IPC data from bluetoothd: %s (%d)",
   1570 						strerror(errno), errno);
   1571 	} else if ((size_t) ret < sizeof(bt_audio_msg_header_t)) {
   1572 		SNDERR("Too short (%d bytes) IPC packet from bluetoothd", ret);
   1573 		err = -EINVAL;
   1574 	} else {
   1575 		type = bt_audio_strtype(inmsg->type);
   1576 		name = bt_audio_strname(inmsg->name);
   1577 		if (type && name) {
   1578 			DBG("Received %s - %s", type, name);
   1579 			err = 0;
   1580 		} else {
   1581 			err = -EINVAL;
   1582 			SNDERR("Bogus message type %d - name %d"
   1583 					" received from audio service",
   1584 					inmsg->type, inmsg->name);
   1585 		}
   1586 
   1587 	}
   1588 
   1589 	return err;
   1590 }
   1591 
   1592 static int audioservice_expect(int sk, bt_audio_msg_header_t *rsp,
   1593 							int expected_name)
   1594 {
   1595 	bt_audio_error_t *error;
   1596 	int err = audioservice_recv(sk, rsp);
   1597 
   1598 	if (err != 0)
   1599 		return err;
   1600 
   1601 	if (rsp->name != expected_name) {
   1602 		err = -EINVAL;
   1603 		SNDERR("Bogus message %s received while %s was expected",
   1604 				bt_audio_strname(rsp->name),
   1605 				bt_audio_strname(expected_name));
   1606 	}
   1607 
   1608 	if (rsp->type == BT_ERROR) {
   1609 		error = (void *) rsp;
   1610 		SNDERR("%s failed : %s(%d)",
   1611 					bt_audio_strname(rsp->name),
   1612 					strerror(error->posix_errno),
   1613 					error->posix_errno);
   1614 		return -error->posix_errno;
   1615 	}
   1616 
   1617 	return err;
   1618 }
   1619 
   1620 static int bluetooth_parse_capabilities(struct bluetooth_data *data,
   1621 					struct bt_get_capabilities_rsp *rsp)
   1622 {
   1623 	int bytes_left = rsp->h.length - sizeof(*rsp);
   1624 	codec_capabilities_t *codec = (void *) rsp->data;
   1625 
   1626 	data->transport = codec->transport;
   1627 
   1628 	if (codec->transport != BT_CAPABILITIES_TRANSPORT_A2DP)
   1629 		return 0;
   1630 
   1631 	while (bytes_left > 0) {
   1632 		if ((codec->type == BT_A2DP_SBC_SINK) &&
   1633 				!(codec->lock & BT_WRITE_LOCK))
   1634 			break;
   1635 
   1636 		bytes_left -= codec->length;
   1637 		codec = (void *) codec + codec->length;
   1638 	}
   1639 
   1640 	if (bytes_left <= 0 ||
   1641 			codec->length != sizeof(data->a2dp.sbc_capabilities))
   1642 		return -EINVAL;
   1643 
   1644 	memcpy(&data->a2dp.sbc_capabilities, codec, codec->length);
   1645 
   1646 	return 0;
   1647 }
   1648 
   1649 static int bluetooth_init(struct bluetooth_data *data,
   1650 				snd_pcm_stream_t stream, snd_config_t *conf)
   1651 {
   1652 	int sk, err;
   1653 	struct bluetooth_alsa_config *alsa_conf = &data->alsa_config;
   1654 	char buf[BT_SUGGESTED_BUFFER_SIZE];
   1655 	struct bt_get_capabilities_req *req = (void *) buf;
   1656 	struct bt_get_capabilities_rsp *rsp = (void *) buf;
   1657 
   1658 	memset(data, 0, sizeof(struct bluetooth_data));
   1659 
   1660 	err = bluetooth_parse_config(conf, alsa_conf);
   1661 	if (err < 0)
   1662 		return err;
   1663 
   1664 	data->server.fd = -1;
   1665 	data->stream.fd = -1;
   1666 
   1667 	sk = bt_audio_service_open();
   1668 	if (sk <= 0) {
   1669 		err = -errno;
   1670 		goto failed;
   1671 	}
   1672 
   1673 	data->server.fd = sk;
   1674 	data->server.events = POLLIN;
   1675 
   1676 	data->pipefd[0] = -1;
   1677 	data->pipefd[1] = -1;
   1678 
   1679 	if (pipe(data->pipefd) < 0) {
   1680 		err = -errno;
   1681 		goto failed;
   1682 	}
   1683 	if (fcntl(data->pipefd[0], F_SETFL, O_NONBLOCK) < 0) {
   1684 		err = -errno;
   1685 		goto failed;
   1686 	}
   1687 	if (fcntl(data->pipefd[1], F_SETFL, O_NONBLOCK) < 0) {
   1688 		err = -errno;
   1689 		goto failed;
   1690 	}
   1691 
   1692 	memset(req, 0, BT_SUGGESTED_BUFFER_SIZE);
   1693 	req->h.type = BT_REQUEST;
   1694 	req->h.name = BT_GET_CAPABILITIES;
   1695 	req->h.length = sizeof(*req);
   1696 
   1697 	if (alsa_conf->autoconnect)
   1698 		req->flags |= BT_FLAG_AUTOCONNECT;
   1699 	strncpy(req->destination, alsa_conf->device, 18);
   1700 	if (alsa_conf->has_transport)
   1701 		req->transport = alsa_conf->transport;
   1702 	else
   1703 		req->transport = BT_CAPABILITIES_TRANSPORT_ANY;
   1704 
   1705 	err = audioservice_send(data->server.fd, &req->h);
   1706 	if (err < 0)
   1707 		goto failed;
   1708 
   1709 	rsp->h.length = 0;
   1710 	err = audioservice_expect(data->server.fd, &rsp->h,
   1711 					BT_GET_CAPABILITIES);
   1712 	if (err < 0)
   1713 		goto failed;
   1714 
   1715 	bluetooth_parse_capabilities(data, rsp);
   1716 
   1717 	return 0;
   1718 
   1719 failed:
   1720 	if (sk >= 0)
   1721 		bt_audio_service_close(sk);
   1722 	return err;
   1723 }
   1724 
   1725 SND_PCM_PLUGIN_DEFINE_FUNC(bluetooth);
   1726 
   1727 SND_PCM_PLUGIN_DEFINE_FUNC(bluetooth)
   1728 {
   1729 	struct bluetooth_data *data;
   1730 	int err;
   1731 
   1732 	DBG("Bluetooth PCM plugin (%s)",
   1733 		stream == SND_PCM_STREAM_PLAYBACK ? "Playback" : "Capture");
   1734 
   1735 	data = malloc(sizeof(struct bluetooth_data));
   1736 	if (!data) {
   1737 		err = -ENOMEM;
   1738 		goto error;
   1739 	}
   1740 
   1741 	err = bluetooth_init(data, stream, conf);
   1742 	if (err < 0)
   1743 		goto error;
   1744 
   1745 	data->io.version = SND_PCM_IOPLUG_VERSION;
   1746 	data->io.name = "Bluetooth Audio Device";
   1747 	data->io.mmap_rw = 0; /* No direct mmap communication */
   1748 	data->io.private_data = data;
   1749 
   1750 	if (data->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
   1751 		data->io.callback = stream == SND_PCM_STREAM_PLAYBACK ?
   1752 			&bluetooth_a2dp_playback :
   1753 			&bluetooth_a2dp_capture;
   1754 	else
   1755 		data->io.callback = stream == SND_PCM_STREAM_PLAYBACK ?
   1756 			&bluetooth_hsp_playback :
   1757 			&bluetooth_hsp_capture;
   1758 
   1759 	err = snd_pcm_ioplug_create(&data->io, name, stream, mode);
   1760 	if (err < 0)
   1761 		goto error;
   1762 
   1763 	if (data->transport == BT_CAPABILITIES_TRANSPORT_A2DP)
   1764 		err = bluetooth_a2dp_hw_constraint(&data->io);
   1765 	else
   1766 		err = bluetooth_hsp_hw_constraint(&data->io);
   1767 
   1768 	if (err < 0) {
   1769 		snd_pcm_ioplug_delete(&data->io);
   1770 		goto error;
   1771 	}
   1772 
   1773 	*pcmp = data->io.pcm;
   1774 
   1775 	return 0;
   1776 
   1777 error:
   1778 	if (data)
   1779 		bluetooth_exit(data);
   1780 
   1781 	return err;
   1782 }
   1783 
   1784 SND_PCM_PLUGIN_SYMBOL(bluetooth);
   1785