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 program is free software; you can redistribute it and/or modify
     10  *  it under the terms of the GNU General Public License as published by
     11  *  the Free Software Foundation; either version 2 of the License, or
     12  *  (at your option) any later version.
     13  *
     14  *  This program 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
     17  *  GNU General Public License for more details.
     18  *
     19  *  You should have received a copy of the GNU General Public License
     20  *  along with this program; 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 <stdlib.h>
     30 #include <stdint.h>
     31 #include <errno.h>
     32 #include <unistd.h>
     33 #include <assert.h>
     34 #include <signal.h>
     35 #include <sys/types.h>
     36 #include <sys/stat.h>
     37 #include <fcntl.h>
     38 #include <netinet/in.h>
     39 
     40 #include <bluetooth/bluetooth.h>
     41 #include <bluetooth/sdp.h>
     42 #include <bluetooth/sdp_lib.h>
     43 #include <bluetooth/l2cap.h>
     44 
     45 #include <glib.h>
     46 #include <dbus/dbus.h>
     47 #include <gdbus.h>
     48 
     49 #include "log.h"
     50 #include "error.h"
     51 #include "uinput.h"
     52 #include "adapter.h"
     53 #include "../src/device.h"
     54 #include "device.h"
     55 #include "manager.h"
     56 #include "avdtp.h"
     57 #include "control.h"
     58 #include "sdpd.h"
     59 #include "glib-helper.h"
     60 #include "btio.h"
     61 #include "dbus-common.h"
     62 
     63 #define AVCTP_PSM 23
     64 
     65 /* Message types */
     66 #define AVCTP_COMMAND		0
     67 #define AVCTP_RESPONSE		1
     68 
     69 /* Packet types */
     70 #define AVCTP_PACKET_SINGLE	0
     71 #define AVCTP_PACKET_START	1
     72 #define AVCTP_PACKET_CONTINUE	2
     73 #define AVCTP_PACKET_END	3
     74 
     75 /* ctype entries */
     76 #define CTYPE_CONTROL		0x0
     77 #define CTYPE_STATUS		0x1
     78 #define CTYPE_NOT_IMPLEMENTED	0x8
     79 #define CTYPE_ACCEPTED		0x9
     80 #define CTYPE_REJECTED		0xA
     81 #define CTYPE_STABLE		0xC
     82 
     83 /* opcodes */
     84 #define OP_UNITINFO		0x30
     85 #define OP_SUBUNITINFO		0x31
     86 #define OP_PASSTHROUGH		0x7c
     87 
     88 /* subunits of interest */
     89 #define SUBUNIT_PANEL		0x09
     90 
     91 /* operands in passthrough commands */
     92 #define VOL_UP_OP		0x41
     93 #define VOL_DOWN_OP		0x42
     94 #define MUTE_OP			0x43
     95 #define PLAY_OP			0x44
     96 #define STOP_OP			0x45
     97 #define PAUSE_OP		0x46
     98 #define RECORD_OP		0x47
     99 #define REWIND_OP		0x48
    100 #define FAST_FORWARD_OP		0x49
    101 #define EJECT_OP		0x4a
    102 #define FORWARD_OP		0x4b
    103 #define BACKWARD_OP		0x4c
    104 
    105 #define QUIRK_NO_RELEASE	1 << 0
    106 
    107 static DBusConnection *connection = NULL;
    108 static gchar *input_device_name = NULL;
    109 static GSList *servers = NULL;
    110 
    111 #if __BYTE_ORDER == __LITTLE_ENDIAN
    112 
    113 struct avctp_header {
    114 	uint8_t ipid:1;
    115 	uint8_t cr:1;
    116 	uint8_t packet_type:2;
    117 	uint8_t transaction:4;
    118 	uint16_t pid;
    119 } __attribute__ ((packed));
    120 #define AVCTP_HEADER_LENGTH 3
    121 
    122 struct avrcp_header {
    123 	uint8_t code:4;
    124 	uint8_t _hdr0:4;
    125 	uint8_t subunit_id:3;
    126 	uint8_t subunit_type:5;
    127 	uint8_t opcode;
    128 } __attribute__ ((packed));
    129 #define AVRCP_HEADER_LENGTH 3
    130 
    131 #elif __BYTE_ORDER == __BIG_ENDIAN
    132 
    133 struct avctp_header {
    134 	uint8_t transaction:4;
    135 	uint8_t packet_type:2;
    136 	uint8_t cr:1;
    137 	uint8_t ipid:1;
    138 	uint16_t pid;
    139 } __attribute__ ((packed));
    140 #define AVCTP_HEADER_LENGTH 3
    141 
    142 struct avrcp_header {
    143 	uint8_t _hdr0:4;
    144 	uint8_t code:4;
    145 	uint8_t subunit_type:5;
    146 	uint8_t subunit_id:3;
    147 	uint8_t opcode;
    148 } __attribute__ ((packed));
    149 #define AVRCP_HEADER_LENGTH 3
    150 
    151 #else
    152 #error "Unknown byte order"
    153 #endif
    154 
    155 struct avctp_state_callback {
    156 	avctp_state_cb cb;
    157 	void *user_data;
    158 	unsigned int id;
    159 };
    160 
    161 struct avctp_server {
    162 	bdaddr_t src;
    163 	GIOChannel *io;
    164 	uint32_t tg_record_id;
    165 #ifndef ANDROID
    166 	uint32_t ct_record_id;
    167 #endif
    168 };
    169 
    170 struct control {
    171 	struct audio_device *dev;
    172 
    173 	avctp_state_t state;
    174 
    175 	int uinput;
    176 
    177 	GIOChannel *io;
    178 	guint io_id;
    179 
    180 	uint16_t mtu;
    181 
    182 	gboolean target;
    183 
    184 	uint8_t key_quirks[256];
    185 
    186 	gboolean ignore_pause;
    187 };
    188 
    189 static struct {
    190 	const char *name;
    191 	uint8_t avrcp;
    192 	uint16_t uinput;
    193 } key_map[] = {
    194 	{ "PLAY",		PLAY_OP,		KEY_PLAYCD },
    195 	{ "STOP",		STOP_OP,		KEY_STOPCD },
    196 	{ "PAUSE",		PAUSE_OP,		KEY_PAUSECD },
    197 	{ "FORWARD",		FORWARD_OP,		KEY_NEXTSONG },
    198 	{ "BACKWARD",		BACKWARD_OP,		KEY_PREVIOUSSONG },
    199 	{ "REWIND",		REWIND_OP,		KEY_REWIND },
    200 	{ "FAST FORWARD",	FAST_FORWARD_OP,	KEY_FASTFORWARD },
    201 	{ NULL }
    202 };
    203 
    204 static GSList *avctp_callbacks = NULL;
    205 
    206 static void auth_cb(DBusError *derr, void *user_data);
    207 
    208 static sdp_record_t *avrcp_ct_record()
    209 {
    210 	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
    211 	uuid_t root_uuid, l2cap, avctp, avrct;
    212 	sdp_profile_desc_t profile[1];
    213 	sdp_list_t *aproto, *proto[2];
    214 	sdp_record_t *record;
    215 	sdp_data_t *psm, *version, *features;
    216 	uint16_t lp = AVCTP_PSM;
    217 	uint16_t avrcp_ver = 0x0100, avctp_ver = 0x0103, feat = 0x000f;
    218 
    219 	record = sdp_record_alloc();
    220 	if (!record)
    221 		return NULL;
    222 
    223 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
    224 	root = sdp_list_append(0, &root_uuid);
    225 	sdp_set_browse_groups(record, root);
    226 
    227 	/* Service Class ID List */
    228 	sdp_uuid16_create(&avrct, AV_REMOTE_SVCLASS_ID);
    229 	svclass_id = sdp_list_append(0, &avrct);
    230 	sdp_set_service_classes(record, svclass_id);
    231 
    232 	/* Protocol Descriptor List */
    233 	sdp_uuid16_create(&l2cap, L2CAP_UUID);
    234 	proto[0] = sdp_list_append(0, &l2cap);
    235 	psm = sdp_data_alloc(SDP_UINT16, &lp);
    236 	proto[0] = sdp_list_append(proto[0], psm);
    237 	apseq = sdp_list_append(0, proto[0]);
    238 
    239 	sdp_uuid16_create(&avctp, AVCTP_UUID);
    240 	proto[1] = sdp_list_append(0, &avctp);
    241 	version = sdp_data_alloc(SDP_UINT16, &avctp_ver);
    242 	proto[1] = sdp_list_append(proto[1], version);
    243 	apseq = sdp_list_append(apseq, proto[1]);
    244 
    245 	aproto = sdp_list_append(0, apseq);
    246 	sdp_set_access_protos(record, aproto);
    247 
    248 	/* Bluetooth Profile Descriptor List */
    249 	sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID);
    250 	profile[0].version = avrcp_ver;
    251 	pfseq = sdp_list_append(0, &profile[0]);
    252 	sdp_set_profile_descs(record, pfseq);
    253 
    254 	features = sdp_data_alloc(SDP_UINT16, &feat);
    255 	sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
    256 
    257 	sdp_set_info_attr(record, "AVRCP CT", 0, 0);
    258 
    259 	free(psm);
    260 	free(version);
    261 	sdp_list_free(proto[0], 0);
    262 	sdp_list_free(proto[1], 0);
    263 	sdp_list_free(apseq, 0);
    264 	sdp_list_free(pfseq, 0);
    265 	sdp_list_free(aproto, 0);
    266 	sdp_list_free(root, 0);
    267 	sdp_list_free(svclass_id, 0);
    268 
    269 	return record;
    270 }
    271 
    272 static sdp_record_t *avrcp_tg_record()
    273 {
    274 	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
    275 	uuid_t root_uuid, l2cap, avctp, avrtg;
    276 	sdp_profile_desc_t profile[1];
    277 	sdp_list_t *aproto, *proto[2];
    278 	sdp_record_t *record;
    279 	sdp_data_t *psm, *version, *features;
    280 	uint16_t lp = AVCTP_PSM;
    281 	uint16_t avrcp_ver = 0x0100, avctp_ver = 0x0103, feat = 0x000f;
    282 
    283 #ifdef ANDROID
    284 	feat = 0x0001;
    285 #endif
    286 	record = sdp_record_alloc();
    287 	if (!record)
    288 		return NULL;
    289 
    290 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
    291 	root = sdp_list_append(0, &root_uuid);
    292 	sdp_set_browse_groups(record, root);
    293 
    294 	/* Service Class ID List */
    295 	sdp_uuid16_create(&avrtg, AV_REMOTE_TARGET_SVCLASS_ID);
    296 	svclass_id = sdp_list_append(0, &avrtg);
    297 	sdp_set_service_classes(record, svclass_id);
    298 
    299 	/* Protocol Descriptor List */
    300 	sdp_uuid16_create(&l2cap, L2CAP_UUID);
    301 	proto[0] = sdp_list_append(0, &l2cap);
    302 	psm = sdp_data_alloc(SDP_UINT16, &lp);
    303 	proto[0] = sdp_list_append(proto[0], psm);
    304 	apseq = sdp_list_append(0, proto[0]);
    305 
    306 	sdp_uuid16_create(&avctp, AVCTP_UUID);
    307 	proto[1] = sdp_list_append(0, &avctp);
    308 	version = sdp_data_alloc(SDP_UINT16, &avctp_ver);
    309 	proto[1] = sdp_list_append(proto[1], version);
    310 	apseq = sdp_list_append(apseq, proto[1]);
    311 
    312 	aproto = sdp_list_append(0, apseq);
    313 	sdp_set_access_protos(record, aproto);
    314 
    315 	/* Bluetooth Profile Descriptor List */
    316 	sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID);
    317 	profile[0].version = avrcp_ver;
    318 	pfseq = sdp_list_append(0, &profile[0]);
    319 	sdp_set_profile_descs(record, pfseq);
    320 
    321 	features = sdp_data_alloc(SDP_UINT16, &feat);
    322 	sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
    323 
    324 	sdp_set_info_attr(record, "AVRCP TG", 0, 0);
    325 
    326 	free(psm);
    327 	free(version);
    328 	sdp_list_free(proto[0], 0);
    329 	sdp_list_free(proto[1], 0);
    330 	sdp_list_free(apseq, 0);
    331 	sdp_list_free(aproto, 0);
    332 	sdp_list_free(pfseq, 0);
    333 	sdp_list_free(root, 0);
    334 	sdp_list_free(svclass_id, 0);
    335 
    336 	return record;
    337 }
    338 
    339 static int send_event(int fd, uint16_t type, uint16_t code, int32_t value)
    340 {
    341 	struct uinput_event event;
    342 
    343 	memset(&event, 0, sizeof(event));
    344 	event.type	= type;
    345 	event.code	= code;
    346 	event.value	= value;
    347 
    348 	return write(fd, &event, sizeof(event));
    349 }
    350 
    351 static void send_key(int fd, uint16_t key, int pressed)
    352 {
    353 	if (fd < 0)
    354 		return;
    355 
    356 	send_event(fd, EV_KEY, key, pressed);
    357 	send_event(fd, EV_SYN, SYN_REPORT, 0);
    358 }
    359 
    360 static void handle_panel_passthrough(struct control *control,
    361 					const unsigned char *operands,
    362 					int operand_count)
    363 {
    364 	const char *status;
    365 	int pressed, i;
    366 
    367 	if (operand_count == 0)
    368 		return;
    369 
    370 	if (operands[0] & 0x80) {
    371 		status = "released";
    372 		pressed = 0;
    373 	} else {
    374 		status = "pressed";
    375 		pressed = 1;
    376 	}
    377 
    378 #ifdef ANDROID
    379 	if ((operands[0] & 0x7F) == PAUSE_OP) {
    380 		if (!sink_is_streaming(control->dev)) {
    381 			if (pressed) {
    382 				uint8_t key_quirks =
    383 					control->key_quirks[PAUSE_OP];
    384 				DBG("AVRCP: Ignoring Pause key - pressed");
    385 				if (!(key_quirks & QUIRK_NO_RELEASE))
    386 					control->ignore_pause = TRUE;
    387 				return;
    388 			} else if (!pressed && control->ignore_pause) {
    389 				DBG("AVRCP: Ignoring Pause key - released");
    390 				control->ignore_pause = FALSE;
    391 				return;
    392 			}
    393 		}
    394 	}
    395 #endif
    396 
    397 	for (i = 0; key_map[i].name != NULL; i++) {
    398 		uint8_t key_quirks;
    399 
    400 		if ((operands[0] & 0x7F) != key_map[i].avrcp)
    401 			continue;
    402 
    403 		DBG("AVRCP: %s %s", key_map[i].name, status);
    404 
    405 		key_quirks = control->key_quirks[key_map[i].avrcp];
    406 
    407 		if (key_quirks & QUIRK_NO_RELEASE) {
    408 			if (!pressed) {
    409 				DBG("AVRCP: Ignoring release");
    410 				break;
    411 			}
    412 
    413 			DBG("AVRCP: treating key press as press + release");
    414 			send_key(control->uinput, key_map[i].uinput, 1);
    415 			send_key(control->uinput, key_map[i].uinput, 0);
    416 			break;
    417 		}
    418 
    419 		send_key(control->uinput, key_map[i].uinput, pressed);
    420 		break;
    421 	}
    422 
    423 	if (key_map[i].name == NULL)
    424 		DBG("AVRCP: unknown button 0x%02X %s",
    425 						operands[0] & 0x7F, status);
    426 }
    427 
    428 static void avctp_disconnected(struct audio_device *dev)
    429 {
    430 	struct control *control = dev->control;
    431 
    432 	if (!control)
    433 		return;
    434 
    435 	if (control->io) {
    436 		g_io_channel_shutdown(control->io, TRUE, NULL);
    437 		g_io_channel_unref(control->io);
    438 		control->io = NULL;
    439 	}
    440 
    441 	if (control->io_id) {
    442 		g_source_remove(control->io_id);
    443 		control->io_id = 0;
    444 
    445 		if (control->state == AVCTP_STATE_CONNECTING)
    446 			audio_device_cancel_authorization(dev, auth_cb,
    447 								control);
    448 	}
    449 
    450 	if (control->uinput >= 0) {
    451 		char address[18];
    452 
    453 		ba2str(&dev->dst, address);
    454 		DBG("AVRCP: closing uinput for %s", address);
    455 
    456 		ioctl(control->uinput, UI_DEV_DESTROY);
    457 		close(control->uinput);
    458 		control->uinput = -1;
    459 	}
    460 }
    461 
    462 static void avctp_set_state(struct control *control, avctp_state_t new_state)
    463 {
    464 	GSList *l;
    465 	struct audio_device *dev = control->dev;
    466 	avdtp_session_state_t old_state = control->state;
    467 	gboolean value;
    468 
    469 	switch (new_state) {
    470 	case AVCTP_STATE_DISCONNECTED:
    471 		DBG("AVCTP Disconnected");
    472 
    473 		avctp_disconnected(control->dev);
    474 
    475 		if (old_state != AVCTP_STATE_CONNECTED)
    476 			break;
    477 
    478 		value = FALSE;
    479 		g_dbus_emit_signal(dev->conn, dev->path,
    480 					AUDIO_CONTROL_INTERFACE,
    481 					"Disconnected", DBUS_TYPE_INVALID);
    482 		emit_property_changed(dev->conn, dev->path,
    483 					AUDIO_CONTROL_INTERFACE, "Connected",
    484 					DBUS_TYPE_BOOLEAN, &value);
    485 
    486 		if (!audio_device_is_active(dev, NULL))
    487 			audio_device_set_authorized(dev, FALSE);
    488 
    489 		break;
    490 	case AVCTP_STATE_CONNECTING:
    491 		DBG("AVCTP Connecting");
    492 		break;
    493 	case AVCTP_STATE_CONNECTED:
    494 		DBG("AVCTP Connected");
    495 		value = TRUE;
    496 		g_dbus_emit_signal(control->dev->conn, control->dev->path,
    497 				AUDIO_CONTROL_INTERFACE, "Connected",
    498 				DBUS_TYPE_INVALID);
    499 		emit_property_changed(control->dev->conn, control->dev->path,
    500 				AUDIO_CONTROL_INTERFACE, "Connected",
    501 				DBUS_TYPE_BOOLEAN, &value);
    502 		break;
    503 	default:
    504 		error("Invalid AVCTP state %d", new_state);
    505 		return;
    506 	}
    507 
    508 	control->state = new_state;
    509 
    510 	for (l = avctp_callbacks; l != NULL; l = l->next) {
    511 		struct avctp_state_callback *cb = l->data;
    512 		cb->cb(control->dev, old_state, new_state, cb->user_data);
    513 	}
    514 }
    515 
    516 static gboolean control_cb(GIOChannel *chan, GIOCondition cond,
    517 				gpointer data)
    518 {
    519 	struct control *control = data;
    520 	unsigned char buf[1024], *operands;
    521 	struct avctp_header *avctp;
    522 	struct avrcp_header *avrcp;
    523 	int ret, packet_size, operand_count, sock;
    524 
    525 	if (cond & (G_IO_ERR | G_IO_HUP | G_IO_NVAL))
    526 		goto failed;
    527 
    528 	sock = g_io_channel_unix_get_fd(control->io);
    529 
    530 	ret = read(sock, buf, sizeof(buf));
    531 	if (ret <= 0)
    532 		goto failed;
    533 
    534 	DBG("Got %d bytes of data for AVCTP session %p", ret, control);
    535 
    536 	if ((unsigned int) ret < sizeof(struct avctp_header)) {
    537 		error("Too small AVCTP packet");
    538 		goto failed;
    539 	}
    540 
    541 	packet_size = ret;
    542 
    543 	avctp = (struct avctp_header *) buf;
    544 
    545 	DBG("AVCTP transaction %u, packet type %u, C/R %u, IPID %u, "
    546 			"PID 0x%04X",
    547 			avctp->transaction, avctp->packet_type,
    548 			avctp->cr, avctp->ipid, ntohs(avctp->pid));
    549 
    550 	ret -= sizeof(struct avctp_header);
    551 	if ((unsigned int) ret < sizeof(struct avrcp_header)) {
    552 		error("Too small AVRCP packet");
    553 		goto failed;
    554 	}
    555 
    556 	avrcp = (struct avrcp_header *) (buf + sizeof(struct avctp_header));
    557 
    558 	ret -= sizeof(struct avrcp_header);
    559 
    560 	operands = buf + sizeof(struct avctp_header) + sizeof(struct avrcp_header);
    561 	operand_count = ret;
    562 
    563 	DBG("AVRCP %s 0x%01X, subunit_type 0x%02X, subunit_id 0x%01X, "
    564 			"opcode 0x%02X, %d operands",
    565 			avctp->cr ? "response" : "command",
    566 			avrcp->code, avrcp->subunit_type, avrcp->subunit_id,
    567 			avrcp->opcode, operand_count);
    568 
    569 	if (avctp->packet_type != AVCTP_PACKET_SINGLE) {
    570 		avctp->cr = AVCTP_RESPONSE;
    571 		avrcp->code = CTYPE_NOT_IMPLEMENTED;
    572 	} else if (avctp->pid != htons(AV_REMOTE_SVCLASS_ID)) {
    573 		avctp->ipid = 1;
    574 		avctp->cr = AVCTP_RESPONSE;
    575 		avrcp->code = CTYPE_REJECTED;
    576 	} else if (avctp->cr == AVCTP_COMMAND &&
    577 			avrcp->code == CTYPE_CONTROL &&
    578 			avrcp->subunit_type == SUBUNIT_PANEL &&
    579 			avrcp->opcode == OP_PASSTHROUGH) {
    580 		handle_panel_passthrough(control, operands, operand_count);
    581 		avctp->cr = AVCTP_RESPONSE;
    582 		avrcp->code = CTYPE_ACCEPTED;
    583 	} else if (avctp->cr == AVCTP_COMMAND &&
    584 			avrcp->code == CTYPE_STATUS &&
    585 			(avrcp->opcode == OP_UNITINFO
    586 			|| avrcp->opcode == OP_SUBUNITINFO)) {
    587 		avctp->cr = AVCTP_RESPONSE;
    588 		avrcp->code = CTYPE_STABLE;
    589 		/* The first operand should be 0x07 for the UNITINFO response.
    590 		 * Neither AVRCP (section 22.1, page 117) nor AVC Digital
    591 		 * Interface Command Set (section 9.2.1, page 45) specs
    592 		 * explain this value but both use it */
    593 		if (operand_count >= 1 && avrcp->opcode == OP_UNITINFO)
    594 			operands[0] = 0x07;
    595 		if (operand_count >= 2)
    596 			operands[1] = SUBUNIT_PANEL << 3;
    597 		DBG("reply to %s", avrcp->opcode == OP_UNITINFO ?
    598 				"OP_UNITINFO" : "OP_SUBUNITINFO");
    599 	} else {
    600 		avctp->cr = AVCTP_RESPONSE;
    601 		avrcp->code = CTYPE_REJECTED;
    602 	}
    603 	ret = write(sock, buf, packet_size);
    604 
    605 	return TRUE;
    606 
    607 failed:
    608 	DBG("AVCTP session %p got disconnected", control);
    609 	avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    610 	return FALSE;
    611 }
    612 
    613 static int uinput_create(char *name)
    614 {
    615 	struct uinput_dev dev;
    616 	int fd, err, i;
    617 
    618 	fd = open("/dev/uinput", O_RDWR);
    619 	if (fd < 0) {
    620 		fd = open("/dev/input/uinput", O_RDWR);
    621 		if (fd < 0) {
    622 			fd = open("/dev/misc/uinput", O_RDWR);
    623 			if (fd < 0) {
    624 				err = errno;
    625 				error("Can't open input device: %s (%d)",
    626 							strerror(err), err);
    627 				return -err;
    628 			}
    629 		}
    630 	}
    631 
    632 	memset(&dev, 0, sizeof(dev));
    633 	if (name)
    634 		strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE - 1);
    635 
    636 	dev.id.bustype = BUS_BLUETOOTH;
    637 	dev.id.vendor  = 0x0000;
    638 	dev.id.product = 0x0000;
    639 	dev.id.version = 0x0000;
    640 
    641 	if (write(fd, &dev, sizeof(dev)) < 0) {
    642 		err = errno;
    643 		error("Can't write device information: %s (%d)",
    644 						strerror(err), err);
    645 		close(fd);
    646 		errno = err;
    647 		return -err;
    648 	}
    649 
    650 	ioctl(fd, UI_SET_EVBIT, EV_KEY);
    651 	ioctl(fd, UI_SET_EVBIT, EV_REL);
    652 	ioctl(fd, UI_SET_EVBIT, EV_REP);
    653 	ioctl(fd, UI_SET_EVBIT, EV_SYN);
    654 
    655 	for (i = 0; key_map[i].name != NULL; i++)
    656 		ioctl(fd, UI_SET_KEYBIT, key_map[i].uinput);
    657 
    658 	if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
    659 		err = errno;
    660 		error("Can't create uinput device: %s (%d)",
    661 						strerror(err), err);
    662 		close(fd);
    663 		errno = err;
    664 		return -err;
    665 	}
    666 
    667 	return fd;
    668 }
    669 
    670 static void init_uinput(struct control *control)
    671 {
    672 	struct audio_device *dev = control->dev;
    673 	char address[18], name[248 + 1], *uinput_dev_name;
    674 
    675 	device_get_name(dev->btd_dev, name, sizeof(name));
    676 	if (g_str_equal(name, "Nokia CK-20W")) {
    677 		control->key_quirks[FORWARD_OP] |= QUIRK_NO_RELEASE;
    678 		control->key_quirks[BACKWARD_OP] |= QUIRK_NO_RELEASE;
    679 		control->key_quirks[PLAY_OP] |= QUIRK_NO_RELEASE;
    680 		control->key_quirks[PAUSE_OP] |= QUIRK_NO_RELEASE;
    681 	}
    682 	control->ignore_pause = FALSE;
    683 
    684 	ba2str(&dev->dst, address);
    685 
    686 	/* Use device name from config file if specified */
    687 	uinput_dev_name = input_device_name;
    688 	if (!uinput_dev_name)
    689 		uinput_dev_name = address;
    690 
    691 	control->uinput = uinput_create(uinput_dev_name);
    692 	if (control->uinput < 0)
    693 		error("AVRCP: failed to init uinput for %s", address);
    694 	else
    695 		DBG("AVRCP: uinput initialized for %s", address);
    696 }
    697 
    698 static void avctp_connect_cb(GIOChannel *chan, GError *err, gpointer data)
    699 {
    700 	struct control *control = data;
    701 	char address[18];
    702 	uint16_t imtu;
    703 	GError *gerr = NULL;
    704 
    705 	if (err) {
    706 		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    707 		error("%s", err->message);
    708 		return;
    709 	}
    710 
    711 	bt_io_get(chan, BT_IO_L2CAP, &gerr,
    712 			BT_IO_OPT_DEST, &address,
    713 			BT_IO_OPT_IMTU, &imtu,
    714 			BT_IO_OPT_INVALID);
    715 	if (gerr) {
    716 		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    717 		error("%s", gerr->message);
    718 		g_error_free(gerr);
    719 		return;
    720 	}
    721 
    722 	DBG("AVCTP: connected to %s", address);
    723 
    724 	if (!control->io)
    725 		control->io = g_io_channel_ref(chan);
    726 
    727 	init_uinput(control);
    728 
    729 	avctp_set_state(control, AVCTP_STATE_CONNECTED);
    730 	control->mtu = imtu;
    731 	control->io_id = g_io_add_watch(chan,
    732 				G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
    733 				(GIOFunc) control_cb, control);
    734 }
    735 
    736 static void auth_cb(DBusError *derr, void *user_data)
    737 {
    738 	struct control *control = user_data;
    739 	GError *err = NULL;
    740 
    741 	if (control->io_id) {
    742 		g_source_remove(control->io_id);
    743 		control->io_id = 0;
    744 	}
    745 
    746 	if (derr && dbus_error_is_set(derr)) {
    747 		error("Access denied: %s", derr->message);
    748 		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    749 		return;
    750 	}
    751 
    752 	if (!bt_io_accept(control->io, avctp_connect_cb, control,
    753 								NULL, &err)) {
    754 		error("bt_io_accept: %s", err->message);
    755 		g_error_free(err);
    756 		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    757 	}
    758 }
    759 
    760 static void avctp_confirm_cb(GIOChannel *chan, gpointer data)
    761 {
    762 	struct control *control = NULL;
    763 	struct audio_device *dev;
    764 	char address[18];
    765 	bdaddr_t src, dst;
    766 	GError *err = NULL;
    767 
    768 	bt_io_get(chan, BT_IO_L2CAP, &err,
    769 			BT_IO_OPT_SOURCE_BDADDR, &src,
    770 			BT_IO_OPT_DEST_BDADDR, &dst,
    771 			BT_IO_OPT_DEST, address,
    772 			BT_IO_OPT_INVALID);
    773 	if (err) {
    774 		error("%s", err->message);
    775 		g_error_free(err);
    776 		g_io_channel_shutdown(chan, TRUE, NULL);
    777 		return;
    778 	}
    779 
    780 	dev = manager_get_device(&src, &dst, TRUE);
    781 	if (!dev) {
    782 		error("Unable to get audio device object for %s", address);
    783 		goto drop;
    784 	}
    785 
    786 	if (!dev->control) {
    787 		btd_device_add_uuid(dev->btd_dev, AVRCP_REMOTE_UUID);
    788 		if (!dev->control)
    789 			goto drop;
    790 	}
    791 
    792 	control = dev->control;
    793 
    794 	if (control->io) {
    795 		error("Refusing unexpected connect from %s", address);
    796 		goto drop;
    797 	}
    798 
    799 	avctp_set_state(control, AVCTP_STATE_CONNECTING);
    800 	control->io = g_io_channel_ref(chan);
    801 
    802 	if (audio_device_request_authorization(dev, AVRCP_TARGET_UUID,
    803 						auth_cb, dev->control) < 0)
    804 		goto drop;
    805 
    806 	control->io_id = g_io_add_watch(chan, G_IO_ERR | G_IO_HUP | G_IO_NVAL,
    807 							control_cb, control);
    808 	return;
    809 
    810 drop:
    811 	if (!control || !control->io)
    812 		g_io_channel_shutdown(chan, TRUE, NULL);
    813 	if (control)
    814 		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    815 }
    816 
    817 static GIOChannel *avctp_server_socket(const bdaddr_t *src, gboolean master)
    818 {
    819 	GError *err = NULL;
    820 	GIOChannel *io;
    821 
    822 	io = bt_io_listen(BT_IO_L2CAP, NULL, avctp_confirm_cb, NULL,
    823 				NULL, &err,
    824 				BT_IO_OPT_SOURCE_BDADDR, src,
    825 				BT_IO_OPT_PSM, AVCTP_PSM,
    826 				BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
    827 				BT_IO_OPT_MASTER, master,
    828 				BT_IO_OPT_INVALID);
    829 	if (!io) {
    830 		error("%s", err->message);
    831 		g_error_free(err);
    832 	}
    833 
    834 	return io;
    835 }
    836 
    837 gboolean avrcp_connect(struct audio_device *dev)
    838 {
    839 	struct control *control = dev->control;
    840 	GError *err = NULL;
    841 	GIOChannel *io;
    842 
    843 	if (control->state > AVCTP_STATE_DISCONNECTED)
    844 		return TRUE;
    845 
    846 	avctp_set_state(control, AVCTP_STATE_CONNECTING);
    847 
    848 	io = bt_io_connect(BT_IO_L2CAP, avctp_connect_cb, control, NULL, &err,
    849 				BT_IO_OPT_SOURCE_BDADDR, &dev->src,
    850 				BT_IO_OPT_DEST_BDADDR, &dev->dst,
    851 				BT_IO_OPT_PSM, AVCTP_PSM,
    852 				BT_IO_OPT_INVALID);
    853 	if (err) {
    854 		avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    855 		error("%s", err->message);
    856 		g_error_free(err);
    857 		return FALSE;
    858 	}
    859 
    860 	control->io = io;
    861 
    862 	return TRUE;
    863 }
    864 
    865 void avrcp_disconnect(struct audio_device *dev)
    866 {
    867 	struct control *control = dev->control;
    868 
    869 	if (!(control && control->io))
    870 		return;
    871 
    872 	avctp_set_state(control, AVCTP_STATE_DISCONNECTED);
    873 }
    874 
    875 int avrcp_register(DBusConnection *conn, const bdaddr_t *src, GKeyFile *config)
    876 {
    877 	sdp_record_t *record;
    878 	gboolean tmp, master = TRUE;
    879 	GError *err = NULL;
    880 	struct avctp_server *server;
    881 
    882 	if (config) {
    883 		tmp = g_key_file_get_boolean(config, "General",
    884 							"Master", &err);
    885 		if (err) {
    886 			DBG("audio.conf: %s", err->message);
    887 			g_error_free(err);
    888 		} else
    889 			master = tmp;
    890 		err = NULL;
    891 		input_device_name = g_key_file_get_string(config,
    892 			"AVRCP", "InputDeviceName", &err);
    893 		if (err) {
    894 			DBG("audio.conf: %s", err->message);
    895 			input_device_name = NULL;
    896 			g_error_free(err);
    897 		}
    898 	}
    899 
    900 	server = g_new0(struct avctp_server, 1);
    901 	if (!server)
    902 		return -ENOMEM;
    903 
    904 	if (!connection)
    905 		connection = dbus_connection_ref(conn);
    906 
    907 	record = avrcp_tg_record();
    908 	if (!record) {
    909 		error("Unable to allocate new service record");
    910 		g_free(server);
    911 		return -1;
    912 	}
    913 
    914 	if (add_record_to_server(src, record) < 0) {
    915 		error("Unable to register AVRCP target service record");
    916 		g_free(server);
    917 		sdp_record_free(record);
    918 		return -1;
    919 	}
    920 	server->tg_record_id = record->handle;
    921 
    922 #ifndef ANDROID
    923 	record = avrcp_ct_record();
    924 	if (!record) {
    925 		error("Unable to allocate new service record");
    926 		g_free(server);
    927 		return -1;
    928 	}
    929 
    930 	if (add_record_to_server(src, record) < 0) {
    931 		error("Unable to register AVRCP controller service record");
    932 		sdp_record_free(record);
    933 		g_free(server);
    934 		return -1;
    935 	}
    936 	server->ct_record_id = record->handle;
    937 #endif
    938 
    939 	server->io = avctp_server_socket(src, master);
    940 	if (!server->io) {
    941 #ifndef ANDROID
    942 		remove_record_from_server(server->ct_record_id);
    943 #endif
    944 		remove_record_from_server(server->tg_record_id);
    945 		g_free(server);
    946 		return -1;
    947 	}
    948 
    949 	bacpy(&server->src, src);
    950 
    951 	servers = g_slist_append(servers, server);
    952 
    953 	return 0;
    954 }
    955 
    956 static struct avctp_server *find_server(GSList *list, const bdaddr_t *src)
    957 {
    958 	GSList *l;
    959 
    960 	for (l = list; l; l = l->next) {
    961 		struct avctp_server *server = l->data;
    962 
    963 		if (bacmp(&server->src, src) == 0)
    964 			return server;
    965 	}
    966 
    967 	return NULL;
    968 }
    969 
    970 void avrcp_unregister(const bdaddr_t *src)
    971 {
    972 	struct avctp_server *server;
    973 
    974 	server = find_server(servers, src);
    975 	if (!server)
    976 		return;
    977 
    978 	servers = g_slist_remove(servers, server);
    979 
    980 #ifndef ANDROID
    981 	remove_record_from_server(server->ct_record_id);
    982 #endif
    983 	remove_record_from_server(server->tg_record_id);
    984 
    985 	g_io_channel_shutdown(server->io, TRUE, NULL);
    986 	g_io_channel_unref(server->io);
    987 	g_free(server);
    988 
    989 	if (servers)
    990 		return;
    991 
    992 	dbus_connection_unref(connection);
    993 	connection = NULL;
    994 }
    995 
    996 static DBusMessage *control_is_connected(DBusConnection *conn,
    997 						DBusMessage *msg,
    998 						void *data)
    999 {
   1000 	struct audio_device *device = data;
   1001 	struct control *control = device->control;
   1002 	DBusMessage *reply;
   1003 	dbus_bool_t connected;
   1004 
   1005 	reply = dbus_message_new_method_return(msg);
   1006 	if (!reply)
   1007 		return NULL;
   1008 
   1009 	connected = (control->state == AVCTP_STATE_CONNECTED);
   1010 
   1011 	dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &connected,
   1012 					DBUS_TYPE_INVALID);
   1013 
   1014 	return reply;
   1015 }
   1016 
   1017 static int avctp_send_passthrough(struct control *control, uint8_t op)
   1018 {
   1019 	unsigned char buf[AVCTP_HEADER_LENGTH + AVRCP_HEADER_LENGTH + 2];
   1020 	struct avctp_header *avctp = (void *) buf;
   1021 	struct avrcp_header *avrcp = (void *) &buf[AVCTP_HEADER_LENGTH];
   1022 	uint8_t *operands = &buf[AVCTP_HEADER_LENGTH + AVRCP_HEADER_LENGTH];
   1023 	int err, sk = g_io_channel_unix_get_fd(control->io);
   1024 	static uint8_t transaction = 0;
   1025 
   1026 	memset(buf, 0, sizeof(buf));
   1027 
   1028 	avctp->transaction = transaction++;
   1029 	avctp->packet_type = AVCTP_PACKET_SINGLE;
   1030 	avctp->cr = AVCTP_COMMAND;
   1031 	avctp->pid = htons(AV_REMOTE_SVCLASS_ID);
   1032 
   1033 	avrcp->code = CTYPE_CONTROL;
   1034 	avrcp->subunit_type = SUBUNIT_PANEL;
   1035 	avrcp->opcode = OP_PASSTHROUGH;
   1036 
   1037 	operands[0] = op & 0x7f;
   1038 	operands[1] = 0;
   1039 
   1040 	err = write(sk, buf, sizeof(buf));
   1041 	if (err < 0)
   1042 		return err;
   1043 
   1044 	/* Button release */
   1045 	avctp->transaction = transaction++;
   1046 	operands[0] |= 0x80;
   1047 
   1048 	return write(sk, buf, sizeof(buf));
   1049 }
   1050 
   1051 static DBusMessage *volume_up(DBusConnection *conn, DBusMessage *msg,
   1052 								void *data)
   1053 {
   1054 	struct audio_device *device = data;
   1055 	struct control *control = device->control;
   1056 	DBusMessage *reply;
   1057 	int err;
   1058 
   1059 	reply = dbus_message_new_method_return(msg);
   1060 	if (!reply)
   1061 		return NULL;
   1062 
   1063 	if (control->state != AVCTP_STATE_CONNECTED)
   1064 		return g_dbus_create_error(msg,
   1065 					ERROR_INTERFACE ".NotConnected",
   1066 					"Device not Connected");
   1067 
   1068 	if (!control->target)
   1069 		return g_dbus_create_error(msg,
   1070 					ERROR_INTERFACE ".NotSupported",
   1071 					"AVRCP Target role not supported");
   1072 
   1073 	err = avctp_send_passthrough(control, VOL_UP_OP);
   1074 	if (err < 0)
   1075 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1076 							strerror(-err));
   1077 
   1078 	return dbus_message_new_method_return(msg);
   1079 }
   1080 
   1081 static DBusMessage *volume_down(DBusConnection *conn, DBusMessage *msg,
   1082 								void *data)
   1083 {
   1084 	struct audio_device *device = data;
   1085 	struct control *control = device->control;
   1086 	DBusMessage *reply;
   1087 	int err;
   1088 
   1089 	reply = dbus_message_new_method_return(msg);
   1090 	if (!reply)
   1091 		return NULL;
   1092 
   1093 	if (control->state != AVCTP_STATE_CONNECTED)
   1094 		return g_dbus_create_error(msg,
   1095 					ERROR_INTERFACE ".NotConnected",
   1096 					"Device not Connected");
   1097 
   1098 	if (!control->target)
   1099 		return g_dbus_create_error(msg,
   1100 					ERROR_INTERFACE ".NotSupported",
   1101 					"AVRCP Target role not supported");
   1102 
   1103 	err = avctp_send_passthrough(control, VOL_DOWN_OP);
   1104 	if (err < 0)
   1105 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1106 							strerror(-err));
   1107 
   1108 	return dbus_message_new_method_return(msg);
   1109 }
   1110 
   1111 static DBusMessage *control_get_properties(DBusConnection *conn,
   1112 					DBusMessage *msg, void *data)
   1113 {
   1114 	struct audio_device *device = data;
   1115 	DBusMessage *reply;
   1116 	DBusMessageIter iter;
   1117 	DBusMessageIter dict;
   1118 	gboolean value;
   1119 
   1120 	reply = dbus_message_new_method_return(msg);
   1121 	if (!reply)
   1122 		return NULL;
   1123 
   1124 	dbus_message_iter_init_append(reply, &iter);
   1125 
   1126 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1127 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   1128 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   1129 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   1130 
   1131 	/* Connected */
   1132 	value = (device->control->state == AVCTP_STATE_CONNECTED);
   1133 	dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &value);
   1134 
   1135 	dbus_message_iter_close_container(&iter, &dict);
   1136 
   1137 	return reply;
   1138 }
   1139 
   1140 static GDBusMethodTable control_methods[] = {
   1141 	{ "IsConnected",	"",	"b",	control_is_connected,
   1142 						G_DBUS_METHOD_FLAG_DEPRECATED },
   1143 	{ "GetProperties",	"",	"a{sv}",control_get_properties },
   1144 	{ "VolumeUp",		"",	"",	volume_up },
   1145 	{ "VolumeDown",		"",	"",	volume_down },
   1146 	{ NULL, NULL, NULL, NULL }
   1147 };
   1148 
   1149 static GDBusSignalTable control_signals[] = {
   1150 	{ "Connected",			"",	G_DBUS_SIGNAL_FLAG_DEPRECATED},
   1151 	{ "Disconnected",		"",	G_DBUS_SIGNAL_FLAG_DEPRECATED},
   1152 	{ "PropertyChanged",		"sv"	},
   1153 	{ NULL, NULL }
   1154 };
   1155 
   1156 static void path_unregister(void *data)
   1157 {
   1158 	struct audio_device *dev = data;
   1159 	struct control *control = dev->control;
   1160 
   1161 	DBG("Unregistered interface %s on path %s",
   1162 		AUDIO_CONTROL_INTERFACE, dev->path);
   1163 
   1164 	if (control->state != AVCTP_STATE_DISCONNECTED)
   1165 		avctp_disconnected(dev);
   1166 
   1167 	g_free(control);
   1168 	dev->control = NULL;
   1169 }
   1170 
   1171 void control_unregister(struct audio_device *dev)
   1172 {
   1173 	g_dbus_unregister_interface(dev->conn, dev->path,
   1174 		AUDIO_CONTROL_INTERFACE);
   1175 }
   1176 
   1177 void control_update(struct audio_device *dev, uint16_t uuid16)
   1178 {
   1179 	struct control *control = dev->control;
   1180 
   1181 	if (uuid16 == AV_REMOTE_TARGET_SVCLASS_ID)
   1182 		control->target = TRUE;
   1183 }
   1184 
   1185 struct control *control_init(struct audio_device *dev, uint16_t uuid16)
   1186 {
   1187 	struct control *control;
   1188 
   1189 	if (!g_dbus_register_interface(dev->conn, dev->path,
   1190 					AUDIO_CONTROL_INTERFACE,
   1191 					control_methods, control_signals, NULL,
   1192 					dev, path_unregister))
   1193 		return NULL;
   1194 
   1195 	DBG("Registered interface %s on path %s",
   1196 		AUDIO_CONTROL_INTERFACE, dev->path);
   1197 
   1198 	control = g_new0(struct control, 1);
   1199 	control->dev = dev;
   1200 	control->state = AVCTP_STATE_DISCONNECTED;
   1201 	control->uinput = -1;
   1202 
   1203 	if (uuid16 == AV_REMOTE_TARGET_SVCLASS_ID)
   1204 		control->target = TRUE;
   1205 
   1206 	return control;
   1207 }
   1208 
   1209 gboolean control_is_active(struct audio_device *dev)
   1210 {
   1211 	struct control *control = dev->control;
   1212 
   1213 	if (control && control->state != AVCTP_STATE_DISCONNECTED)
   1214 		return TRUE;
   1215 
   1216 	return FALSE;
   1217 }
   1218 
   1219 unsigned int avctp_add_state_cb(avctp_state_cb cb, void *user_data)
   1220 {
   1221 	struct avctp_state_callback *state_cb;
   1222 	static unsigned int id = 0;
   1223 
   1224 	state_cb = g_new(struct avctp_state_callback, 1);
   1225 	state_cb->cb = cb;
   1226 	state_cb->user_data = user_data;
   1227 	state_cb->id = ++id;
   1228 
   1229 	avctp_callbacks = g_slist_append(avctp_callbacks, state_cb);
   1230 
   1231 	return state_cb->id;
   1232 }
   1233 
   1234 gboolean avctp_remove_state_cb(unsigned int id)
   1235 {
   1236 	GSList *l;
   1237 
   1238 	for (l = avctp_callbacks; l != NULL; l = l->next) {
   1239 		struct avctp_state_callback *cb = l->data;
   1240 		if (cb && cb->id == id) {
   1241 			avctp_callbacks = g_slist_remove(avctp_callbacks, cb);
   1242 			g_free(cb);
   1243 			return TRUE;
   1244 		}
   1245 	}
   1246 
   1247 	return FALSE;
   1248 }
   1249