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