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 <stdio.h>
     30 #include <errno.h>
     31 #include <fcntl.h>
     32 #include <unistd.h>
     33 #include <stdlib.h>
     34 #include <stdarg.h>
     35 #include <signal.h>
     36 #include <string.h>
     37 #include <getopt.h>
     38 #include <sys/ioctl.h>
     39 #include <sys/socket.h>
     40 #include <assert.h>
     41 
     42 #include <bluetooth/bluetooth.h>
     43 #include <bluetooth/hci.h>
     44 #include <bluetooth/hci_lib.h>
     45 #include <bluetooth/sco.h>
     46 #include <bluetooth/rfcomm.h>
     47 #include <bluetooth/sdp.h>
     48 #include <bluetooth/sdp_lib.h>
     49 
     50 #include <glib.h>
     51 #include <dbus/dbus.h>
     52 #include <gdbus.h>
     53 
     54 #include "log.h"
     55 #include "device.h"
     56 #include "manager.h"
     57 #include "error.h"
     58 #include "telephony.h"
     59 #include "headset.h"
     60 #include "glib-helper.h"
     61 #include "btio.h"
     62 #include "dbus-common.h"
     63 #include "../src/adapter.h"
     64 #include "../src/device.h"
     65 
     66 #define DC_TIMEOUT 3
     67 
     68 #define RING_INTERVAL 3
     69 
     70 #define BUF_SIZE 1024
     71 
     72 #define HEADSET_GAIN_SPEAKER 'S'
     73 #define HEADSET_GAIN_MICROPHONE 'M'
     74 
     75 static struct {
     76 	gboolean telephony_ready;	/* Telephony plugin initialized */
     77 	uint32_t features;		/* HFP AG features */
     78 	const struct indicator *indicators;	/* Available HFP indicators */
     79 	int er_mode;			/* Event reporting mode */
     80 	int er_ind;			/* Event reporting for indicators */
     81 	int rh;				/* Response and Hold state */
     82 	char *number;			/* Incoming phone number */
     83 	int number_type;		/* Incoming number type */
     84 	guint ring_timer;		/* For incoming call indication */
     85 	const char *chld;		/* Response to AT+CHLD=? */
     86 } ag = {
     87 	.telephony_ready = FALSE,
     88 	.features = 0,
     89 	.er_mode = 3,
     90 	.er_ind = 0,
     91 	.rh = -1,
     92 	.number = NULL,
     93 	.number_type = 0,
     94 	.ring_timer = 0,
     95 };
     96 
     97 static gboolean sco_hci = TRUE;
     98 
     99 static GSList *active_devices = NULL;
    100 
    101 static char *str_state[] = {
    102 	"HEADSET_STATE_DISCONNECTED",
    103 	"HEADSET_STATE_CONNECTING",
    104 	"HEADSET_STATE_CONNECTED",
    105 	"HEADSET_STATE_PLAY_IN_PROGRESS",
    106 	"HEADSET_STATE_PLAYING",
    107 };
    108 
    109 struct headset_state_callback {
    110 	headset_state_cb cb;
    111 	void *user_data;
    112 	unsigned int id;
    113 };
    114 
    115 struct connect_cb {
    116 	unsigned int id;
    117 	headset_stream_cb_t cb;
    118 	void *cb_data;
    119 };
    120 
    121 struct pending_connect {
    122 	DBusMessage *msg;
    123 	DBusPendingCall *call;
    124 	GIOChannel *io;
    125 	int err;
    126 	headset_state_t target_state;
    127 	GSList *callbacks;
    128 	uint16_t svclass;
    129 };
    130 
    131 struct headset_slc {
    132 	char buf[BUF_SIZE];
    133 	int data_start;
    134 	int data_length;
    135 
    136 	gboolean cli_active;
    137 	gboolean cme_enabled;
    138 	gboolean cwa_enabled;
    139 	gboolean pending_ring;
    140 	gboolean inband_ring;
    141 	gboolean nrec;
    142 	gboolean nrec_req;
    143 
    144 	int sp_gain;
    145 	int mic_gain;
    146 
    147 	unsigned int hf_features;
    148 };
    149 
    150 struct headset {
    151 	uint32_t hsp_handle;
    152 	uint32_t hfp_handle;
    153 
    154 	int rfcomm_ch;
    155 
    156 	GIOChannel *rfcomm;
    157 	GIOChannel *tmp_rfcomm;
    158 	GIOChannel *sco;
    159 	guint sco_id;
    160 	guint dc_id;
    161 
    162 	gboolean auto_dc;
    163 
    164 	guint dc_timer;
    165 
    166 	gboolean hfp_active;
    167 	gboolean search_hfp;
    168 
    169 	headset_state_t state;
    170 	struct pending_connect *pending;
    171 
    172 	headset_lock_t lock;
    173 	struct headset_slc *slc;
    174 };
    175 
    176 struct event {
    177 	const char *cmd;
    178 	int (*callback) (struct audio_device *device, const char *buf);
    179 };
    180 
    181 static GSList *headset_callbacks = NULL;
    182 
    183 static inline DBusMessage *invalid_args(DBusMessage *msg)
    184 {
    185 	return g_dbus_create_error(msg, ERROR_INTERFACE ".InvalidArguments",
    186 			"Invalid arguments in method call");
    187 }
    188 
    189 static DBusHandlerResult error_not_supported(DBusConnection *conn,
    190 							DBusMessage *msg)
    191 {
    192 	return error_common_reply(conn, msg, ERROR_INTERFACE ".NotSupported",
    193 							"Not supported");
    194 }
    195 
    196 static DBusHandlerResult error_connection_attempt_failed(DBusConnection *conn,
    197 						DBusMessage *msg, int err)
    198 {
    199 	return error_common_reply(conn, msg,
    200 			ERROR_INTERFACE ".ConnectionAttemptFailed",
    201 			err < 0 ? strerror(-err) : "Connection attempt failed");
    202 }
    203 
    204 static int rfcomm_connect(struct audio_device *device, headset_stream_cb_t cb,
    205 				void *user_data, unsigned int *cb_id);
    206 static int get_records(struct audio_device *device, headset_stream_cb_t cb,
    207 			void *user_data, unsigned int *cb_id);
    208 
    209 static void print_ag_features(uint32_t features)
    210 {
    211 	GString *gstr;
    212 	char *str;
    213 
    214 	if (features == 0) {
    215 		DBG("HFP AG features: (none)");
    216 		return;
    217 	}
    218 
    219 	gstr = g_string_new("HFP AG features: ");
    220 
    221 	if (features & AG_FEATURE_THREE_WAY_CALLING)
    222 		g_string_append(gstr, "\"Three-way calling\" ");
    223 	if (features & AG_FEATURE_EC_ANDOR_NR)
    224 		g_string_append(gstr, "\"EC and/or NR function\" ");
    225 	if (features & AG_FEATURE_VOICE_RECOGNITION)
    226 		g_string_append(gstr, "\"Voice recognition function\" ");
    227 	if (features & AG_FEATURE_INBAND_RINGTONE)
    228 		g_string_append(gstr, "\"In-band ring tone capability\" ");
    229 	if (features & AG_FEATURE_ATTACH_NUMBER_TO_VOICETAG)
    230 		g_string_append(gstr, "\"Attach a number to a voice tag\" ");
    231 	if (features & AG_FEATURE_REJECT_A_CALL)
    232 		g_string_append(gstr, "\"Ability to reject a call\" ");
    233 	if (features & AG_FEATURE_ENHANCED_CALL_STATUS)
    234 		g_string_append(gstr, "\"Enhanced call status\" ");
    235 	if (features & AG_FEATURE_ENHANCED_CALL_CONTROL)
    236 		g_string_append(gstr, "\"Enhanced call control\" ");
    237 	if (features & AG_FEATURE_EXTENDED_ERROR_RESULT_CODES)
    238 		g_string_append(gstr, "\"Extended Error Result Codes\" ");
    239 
    240 	str = g_string_free(gstr, FALSE);
    241 
    242 	DBG("%s", str);
    243 
    244 	g_free(str);
    245 }
    246 
    247 static void print_hf_features(uint32_t features)
    248 {
    249 	GString *gstr;
    250 	char *str;
    251 
    252 	if (features == 0) {
    253 		DBG("HFP HF features: (none)");
    254 		return;
    255 	}
    256 
    257 	gstr = g_string_new("HFP HF features: ");
    258 
    259 	if (features & HF_FEATURE_EC_ANDOR_NR)
    260 		g_string_append(gstr, "\"EC and/or NR function\" ");
    261 	if (features & HF_FEATURE_CALL_WAITING_AND_3WAY)
    262 		g_string_append(gstr, "\"Call waiting and 3-way calling\" ");
    263 	if (features & HF_FEATURE_CLI_PRESENTATION)
    264 		g_string_append(gstr, "\"CLI presentation capability\" ");
    265 	if (features & HF_FEATURE_VOICE_RECOGNITION)
    266 		g_string_append(gstr, "\"Voice recognition activation\" ");
    267 	if (features & HF_FEATURE_REMOTE_VOLUME_CONTROL)
    268 		g_string_append(gstr, "\"Remote volume control\" ");
    269 	if (features & HF_FEATURE_ENHANCED_CALL_STATUS)
    270 		g_string_append(gstr, "\"Enhanced call status\" ");
    271 	if (features & HF_FEATURE_ENHANCED_CALL_CONTROL)
    272 		g_string_append(gstr, "\"Enhanced call control\" ");
    273 
    274 	str = g_string_free(gstr, FALSE);
    275 
    276 	DBG("%s", str);
    277 
    278 	g_free(str);
    279 }
    280 
    281 static const char *state2str(headset_state_t state)
    282 {
    283 	switch (state) {
    284 	case HEADSET_STATE_DISCONNECTED:
    285 		return "disconnected";
    286 	case HEADSET_STATE_CONNECTING:
    287 		return "connecting";
    288 	case HEADSET_STATE_CONNECTED:
    289 	case HEADSET_STATE_PLAY_IN_PROGRESS:
    290 		return "connected";
    291 	case HEADSET_STATE_PLAYING:
    292 		return "playing";
    293 	}
    294 
    295 	return NULL;
    296 }
    297 
    298 static int headset_send_valist(struct headset *hs, char *format, va_list ap)
    299 {
    300 	char rsp[BUF_SIZE];
    301 	ssize_t total_written, count;
    302 	int fd;
    303 
    304 	count = vsnprintf(rsp, sizeof(rsp), format, ap);
    305 
    306 	if (count < 0)
    307 		return -EINVAL;
    308 
    309 	if (!hs->rfcomm) {
    310 		error("headset_send: the headset is not connected");
    311 		return -EIO;
    312 	}
    313 
    314 	total_written = 0;
    315 	fd = g_io_channel_unix_get_fd(hs->rfcomm);
    316 
    317 	while (total_written < count) {
    318 		ssize_t written;
    319 
    320 		written = write(fd, rsp + total_written,
    321 				count - total_written);
    322 		if (written < 0)
    323 			return -errno;
    324 
    325 		total_written += written;
    326 	}
    327 
    328 	return 0;
    329 }
    330 
    331 static int headset_send(struct headset *hs, char *format, ...)
    332 {
    333 	va_list ap;
    334 	int ret;
    335 
    336 	va_start(ap, format);
    337 	ret = headset_send_valist(hs, format, ap);
    338 	va_end(ap);
    339 
    340 	return ret;
    341 }
    342 
    343 static int supported_features(struct audio_device *device, const char *buf)
    344 {
    345 	struct headset *hs = device->headset;
    346 	struct headset_slc *slc = hs->slc;
    347 	int err;
    348 
    349 	if (strlen(buf) < 9)
    350 		return -EINVAL;
    351 
    352 	slc->hf_features = strtoul(&buf[8], NULL, 10);
    353 
    354 	print_hf_features(slc->hf_features);
    355 
    356 	err = headset_send(hs, "\r\n+BRSF: %u\r\n", ag.features);
    357 	if (err < 0)
    358 		return err;
    359 
    360 	return headset_send(hs, "\r\nOK\r\n");
    361 }
    362 
    363 static char *indicator_ranges(const struct indicator *indicators)
    364 {
    365 	int i;
    366 	GString *gstr;
    367 
    368 	gstr = g_string_new("\r\n+CIND: ");
    369 
    370 	for (i = 0; indicators[i].desc != NULL; i++) {
    371 		if (i == 0)
    372 			g_string_append_printf(gstr, "(\"%s\",(%s))",
    373 						indicators[i].desc,
    374 						indicators[i].range);
    375 		else
    376 			g_string_append_printf(gstr, ",(\"%s\",(%s))",
    377 						indicators[i].desc,
    378 						indicators[i].range);
    379 	}
    380 
    381 	g_string_append(gstr, "\r\n");
    382 
    383 	return g_string_free(gstr, FALSE);
    384 }
    385 
    386 static char *indicator_values(const struct indicator *indicators)
    387 {
    388 	int i;
    389 	GString *gstr;
    390 
    391 	gstr = g_string_new("\r\n+CIND: ");
    392 
    393 	for (i = 0; indicators[i].desc != NULL; i++) {
    394 		if (i == 0)
    395 			g_string_append_printf(gstr, "%d", indicators[i].val);
    396 		else
    397 			g_string_append_printf(gstr, ",%d", indicators[i].val);
    398 	}
    399 
    400 	g_string_append(gstr, "\r\n");
    401 
    402 	return g_string_free(gstr, FALSE);
    403 }
    404 
    405 static int report_indicators(struct audio_device *device, const char *buf)
    406 {
    407 	struct headset *hs = device->headset;
    408 	int err;
    409 	char *str;
    410 
    411 	if (strlen(buf) < 8)
    412 		return -EINVAL;
    413 
    414 	if (ag.indicators == NULL) {
    415 		error("HFP AG indicators not initialized");
    416 		return headset_send(hs, "\r\nERROR\r\n");
    417 	}
    418 
    419 	if (buf[7] == '=')
    420 		str = indicator_ranges(ag.indicators);
    421 	else
    422 		str = indicator_values(ag.indicators);
    423 
    424 	err = headset_send(hs, str);
    425 
    426 	g_free(str);
    427 
    428 	if (err < 0)
    429 		return err;
    430 
    431 	return headset_send(hs, "\r\nOK\r\n");
    432 }
    433 
    434 static void pending_connect_complete(struct connect_cb *cb, struct audio_device *dev)
    435 {
    436 	struct headset *hs = dev->headset;
    437 
    438 	if (hs->pending->err < 0)
    439 		cb->cb(NULL, cb->cb_data);
    440 	else
    441 		cb->cb(dev, cb->cb_data);
    442 }
    443 
    444 static void pending_connect_finalize(struct audio_device *dev)
    445 {
    446 	struct headset *hs = dev->headset;
    447 	struct pending_connect *p = hs->pending;
    448 
    449 	if (p == NULL)
    450 		return;
    451 
    452 	if (p->svclass)
    453 		bt_cancel_discovery(&dev->src, &dev->dst);
    454 
    455 	g_slist_foreach(p->callbacks, (GFunc) pending_connect_complete, dev);
    456 
    457 	g_slist_foreach(p->callbacks, (GFunc) g_free, NULL);
    458 	g_slist_free(p->callbacks);
    459 
    460 	if (p->io) {
    461 		g_io_channel_shutdown(p->io, TRUE, NULL);
    462 		g_io_channel_unref(p->io);
    463 	}
    464 
    465 	if (p->msg)
    466 		dbus_message_unref(p->msg);
    467 
    468 	if (p->call) {
    469 		dbus_pending_call_cancel(p->call);
    470 		dbus_pending_call_unref(p->call);
    471 	}
    472 
    473 	g_free(p);
    474 
    475 	hs->pending = NULL;
    476 }
    477 
    478 static void pending_connect_init(struct headset *hs, headset_state_t target_state)
    479 {
    480 	if (hs->pending) {
    481 		if (hs->pending->target_state < target_state)
    482 			hs->pending->target_state = target_state;
    483 		return;
    484 	}
    485 
    486 	hs->pending = g_new0(struct pending_connect, 1);
    487 	hs->pending->target_state = target_state;
    488 }
    489 
    490 static unsigned int connect_cb_new(struct headset *hs,
    491 					headset_state_t target_state,
    492 					headset_stream_cb_t func,
    493 					void *user_data)
    494 {
    495 	struct connect_cb *cb;
    496 	unsigned int free_cb_id = 1;
    497 
    498 	pending_connect_init(hs, target_state);
    499 
    500 	if (!func)
    501 		return 0;
    502 
    503 	cb = g_new(struct connect_cb, 1);
    504 
    505 	cb->cb = func;
    506 	cb->cb_data = user_data;
    507 	cb->id = free_cb_id++;
    508 
    509 	hs->pending->callbacks = g_slist_append(hs->pending->callbacks,
    510 						cb);
    511 
    512 	return cb->id;
    513 }
    514 
    515 static void send_foreach_headset(GSList *devices,
    516 					int (*cmp) (struct headset *hs),
    517 					char *format, ...)
    518 {
    519 	GSList *l;
    520 	va_list ap;
    521 
    522 	for (l = devices; l != NULL; l = l->next) {
    523 		struct audio_device *device = l->data;
    524 		struct headset *hs = device->headset;
    525 		int ret;
    526 
    527 		assert(hs != NULL);
    528 
    529 		if (cmp && cmp(hs) != 0)
    530 			continue;
    531 
    532 		va_start(ap, format);
    533 		ret = headset_send_valist(hs, format, ap);
    534 		if (ret < 0)
    535 			error("Failed to send to headset: %s (%d)",
    536 					strerror(-ret), -ret);
    537 		va_end(ap);
    538 	}
    539 }
    540 
    541 static int cli_cmp(struct headset *hs)
    542 {
    543 	struct headset_slc *slc = hs->slc;
    544 
    545 	if (!hs->hfp_active)
    546 		return -1;
    547 
    548 	if (slc->cli_active)
    549 		return 0;
    550 	else
    551 		return -1;
    552 }
    553 
    554 static gboolean ring_timer_cb(gpointer data)
    555 {
    556 	send_foreach_headset(active_devices, NULL, "\r\nRING\r\n");
    557 
    558 	if (ag.number)
    559 		send_foreach_headset(active_devices, cli_cmp,
    560 					"\r\n+CLIP: \"%s\",%d\r\n",
    561 					ag.number, ag.number_type);
    562 
    563 	return TRUE;
    564 }
    565 
    566 static void sco_connect_cb(GIOChannel *chan, GError *err, gpointer user_data)
    567 {
    568 	int sk;
    569 	struct audio_device *dev = user_data;
    570 	struct headset *hs = dev->headset;
    571 	struct headset_slc *slc = hs->slc;
    572 	struct pending_connect *p = hs->pending;
    573 
    574 	if (err) {
    575 		error("%s", err->message);
    576 
    577 		if (p != NULL) {
    578 			p->err = -errno;
    579 			if (p->msg)
    580 				error_connection_attempt_failed(dev->conn,
    581 								p->msg,
    582 								p->err);
    583 			pending_connect_finalize(dev);
    584 		}
    585 
    586 		if (hs->rfcomm)
    587 			headset_set_state(dev, HEADSET_STATE_CONNECTED);
    588 		else
    589 			headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
    590 
    591 		return;
    592 	}
    593 
    594 	DBG("SCO socket opened for headset %s", dev->path);
    595 
    596 	sk = g_io_channel_unix_get_fd(chan);
    597 
    598 	DBG("SCO fd=%d", sk);
    599 
    600 	if (p) {
    601 		p->io = NULL;
    602 		if (p->msg) {
    603 			DBusMessage *reply;
    604 			reply = dbus_message_new_method_return(p->msg);
    605 			g_dbus_send_message(dev->conn, reply);
    606 		}
    607 
    608 		pending_connect_finalize(dev);
    609 	}
    610 
    611 	fcntl(sk, F_SETFL, 0);
    612 
    613 	headset_set_state(dev, HEADSET_STATE_PLAYING);
    614 
    615 	if (slc->pending_ring) {
    616 		ring_timer_cb(NULL);
    617 		ag.ring_timer = g_timeout_add_seconds(RING_INTERVAL,
    618 						ring_timer_cb,
    619 						NULL);
    620 		slc->pending_ring = FALSE;
    621 	}
    622 }
    623 
    624 static int sco_connect(struct audio_device *dev, headset_stream_cb_t cb,
    625 			void *user_data, unsigned int *cb_id)
    626 {
    627 	struct headset *hs = dev->headset;
    628 	GError *err = NULL;
    629 	GIOChannel *io;
    630 
    631 	if (hs->state != HEADSET_STATE_CONNECTED)
    632 		return -EINVAL;
    633 
    634 	io = bt_io_connect(BT_IO_SCO, sco_connect_cb, dev, NULL, &err,
    635 				BT_IO_OPT_SOURCE_BDADDR, &dev->src,
    636 				BT_IO_OPT_DEST_BDADDR, &dev->dst,
    637 				BT_IO_OPT_INVALID);
    638 	if (!io) {
    639 		error("%s", err->message);
    640 		g_error_free(err);
    641 		return -EIO;
    642 	}
    643 
    644 	hs->sco = io;
    645 
    646 	headset_set_state(dev, HEADSET_STATE_PLAY_IN_PROGRESS);
    647 
    648 	pending_connect_init(hs, HEADSET_STATE_PLAYING);
    649 
    650 	if (cb) {
    651 		unsigned int id = connect_cb_new(hs, HEADSET_STATE_PLAYING,
    652 							cb, user_data);
    653 		if (cb_id)
    654 			*cb_id = id;
    655 	}
    656 
    657 	return 0;
    658 }
    659 
    660 static int hfp_cmp(struct headset *hs)
    661 {
    662 	if (hs->hfp_active)
    663 		return 0;
    664 	else
    665 		return -1;
    666 }
    667 
    668 static void hfp_slc_complete(struct audio_device *dev)
    669 {
    670 	struct headset *hs = dev->headset;
    671 	struct pending_connect *p = hs->pending;
    672 
    673 	DBG("HFP Service Level Connection established");
    674 
    675 	headset_set_state(dev, HEADSET_STATE_CONNECTED);
    676 
    677 	if (p == NULL)
    678 		return;
    679 
    680 	if (p->target_state == HEADSET_STATE_CONNECTED) {
    681 		if (p->msg) {
    682 			DBusMessage *reply = dbus_message_new_method_return(p->msg);
    683 			g_dbus_send_message(dev->conn, reply);
    684 		}
    685 		pending_connect_finalize(dev);
    686 		return;
    687 	}
    688 
    689 	p->err = sco_connect(dev, NULL, NULL, NULL);
    690 	if (p->err < 0) {
    691 		if (p->msg)
    692 			error_connection_attempt_failed(dev->conn, p->msg, p->err);
    693 		pending_connect_finalize(dev);
    694 	}
    695 }
    696 
    697 static int telephony_generic_rsp(struct audio_device *device, cme_error_t err)
    698 {
    699 	struct headset *hs = device->headset;
    700 	struct headset_slc *slc = hs->slc;
    701 
    702 	if (err != CME_ERROR_NONE) {
    703 		if (slc->cme_enabled)
    704 			return headset_send(hs, "\r\n+CME ERROR: %d\r\n", err);
    705 		else
    706 			return headset_send(hs, "\r\nERROR\r\n");
    707 	}
    708 
    709 	return headset_send(hs, "\r\nOK\r\n");
    710 }
    711 
    712 int telephony_event_reporting_rsp(void *telephony_device, cme_error_t err)
    713 {
    714 	struct audio_device *device = telephony_device;
    715 	struct headset *hs = device->headset;
    716 	struct headset_slc *slc = hs->slc;
    717 	int ret;
    718 
    719 	if (err != CME_ERROR_NONE)
    720 		return telephony_generic_rsp(telephony_device, err);
    721 
    722 	ret = headset_send(hs, "\r\nOK\r\n");
    723 	if (ret < 0)
    724 		return ret;
    725 
    726 	if (hs->state != HEADSET_STATE_CONNECTING)
    727 		return 0;
    728 
    729 	if (slc->hf_features & HF_FEATURE_CALL_WAITING_AND_3WAY &&
    730 			ag.features & AG_FEATURE_THREE_WAY_CALLING)
    731 		return 0;
    732 
    733 	hfp_slc_complete(device);
    734 
    735 	return 0;
    736 }
    737 
    738 static int event_reporting(struct audio_device *dev, const char *buf)
    739 {
    740 	char **tokens; /* <mode>, <keyp>, <disp>, <ind>, <bfr> */
    741 
    742 	if (strlen(buf) < 13)
    743 		return -EINVAL;
    744 
    745 	tokens = g_strsplit(&buf[8], ",", 5);
    746 	if (g_strv_length(tokens) < 4) {
    747 		g_strfreev(tokens);
    748 		return -EINVAL;
    749 	}
    750 
    751 	ag.er_mode = atoi(tokens[0]);
    752 	ag.er_ind = atoi(tokens[3]);
    753 
    754 	g_strfreev(tokens);
    755 	tokens = NULL;
    756 
    757 	DBG("Event reporting (CMER): mode=%d, ind=%d",
    758 			ag.er_mode, ag.er_ind);
    759 
    760 	switch (ag.er_ind) {
    761 	case 0:
    762 	case 1:
    763 		telephony_event_reporting_req(dev, ag.er_ind);
    764 		break;
    765 	default:
    766 		return -EINVAL;
    767 	}
    768 
    769 	return 0;
    770 }
    771 
    772 static int call_hold(struct audio_device *dev, const char *buf)
    773 {
    774 	struct headset *hs = dev->headset;
    775 	int err;
    776 
    777 	if (strlen(buf) < 9)
    778 		return -EINVAL;
    779 
    780 	if (buf[8] != '?') {
    781 		telephony_call_hold_req(dev, &buf[8]);
    782 		return 0;
    783 	}
    784 
    785 	err = headset_send(hs, "\r\n+CHLD: (%s)\r\n", ag.chld);
    786 	if (err < 0)
    787 		return err;
    788 
    789 	err = headset_send(hs, "\r\nOK\r\n");
    790 	if (err < 0)
    791 		return err;
    792 
    793 	if (hs->state != HEADSET_STATE_CONNECTING)
    794 		return 0;
    795 
    796 	hfp_slc_complete(dev);
    797 
    798 	return 0;
    799 }
    800 
    801 int telephony_key_press_rsp(void *telephony_device, cme_error_t err)
    802 {
    803 	return telephony_generic_rsp(telephony_device, err);
    804 }
    805 
    806 static int key_press(struct audio_device *device, const char *buf)
    807 {
    808 	if (strlen(buf) < 9)
    809 		return -EINVAL;
    810 
    811 	g_dbus_emit_signal(device->conn, device->path,
    812 			AUDIO_HEADSET_INTERFACE, "AnswerRequested",
    813 			DBUS_TYPE_INVALID);
    814 
    815 	if (ag.ring_timer) {
    816 		g_source_remove(ag.ring_timer);
    817 		ag.ring_timer = 0;
    818 	}
    819 
    820 	telephony_key_press_req(device, &buf[8]);
    821 
    822 	return 0;
    823 }
    824 
    825 int telephony_answer_call_rsp(void *telephony_device, cme_error_t err)
    826 {
    827 	return telephony_generic_rsp(telephony_device, err);
    828 }
    829 
    830 static int answer_call(struct audio_device *device, const char *buf)
    831 {
    832 	if (ag.ring_timer) {
    833 		g_source_remove(ag.ring_timer);
    834 		ag.ring_timer = 0;
    835 	}
    836 
    837 	if (ag.number) {
    838 		g_free(ag.number);
    839 		ag.number = NULL;
    840 	}
    841 
    842 	telephony_answer_call_req(device);
    843 
    844 	return 0;
    845 }
    846 
    847 int telephony_terminate_call_rsp(void *telephony_device,
    848 					cme_error_t err)
    849 {
    850 	struct audio_device *device = telephony_device;
    851 	struct headset *hs = device->headset;
    852 
    853 	if (err != CME_ERROR_NONE)
    854 		return telephony_generic_rsp(telephony_device, err);
    855 
    856 	g_dbus_emit_signal(device->conn, device->path,
    857 			AUDIO_HEADSET_INTERFACE, "CallTerminated",
    858 			DBUS_TYPE_INVALID);
    859 
    860 	return headset_send(hs, "\r\nOK\r\n");
    861 }
    862 
    863 static int terminate_call(struct audio_device *device, const char *buf)
    864 {
    865 	if (ag.number) {
    866 		g_free(ag.number);
    867 		ag.number = NULL;
    868 	}
    869 
    870 	if (ag.ring_timer) {
    871 		g_source_remove(ag.ring_timer);
    872 		ag.ring_timer = 0;
    873 	}
    874 
    875 	telephony_terminate_call_req(device);
    876 
    877 	return 0;
    878 }
    879 
    880 static int cli_notification(struct audio_device *device, const char *buf)
    881 {
    882 	struct headset *hs = device->headset;
    883 	struct headset_slc *slc = hs->slc;
    884 
    885 	if (strlen(buf) < 9)
    886 		return -EINVAL;
    887 
    888 	slc->cli_active = buf[8] == '1' ? TRUE : FALSE;
    889 
    890 	return headset_send(hs, "\r\nOK\r\n");
    891 }
    892 
    893 int telephony_response_and_hold_rsp(void *telephony_device, cme_error_t err)
    894 {
    895 	return telephony_generic_rsp(telephony_device, err);
    896 }
    897 
    898 static int response_and_hold(struct audio_device *device, const char *buf)
    899 {
    900 	struct headset *hs = device->headset;
    901 
    902 	if (strlen(buf) < 8)
    903 		return -EINVAL;
    904 
    905 	if (buf[7] == '=') {
    906 		telephony_response_and_hold_req(device, atoi(&buf[8]) < 0);
    907 		return 0;
    908 	}
    909 
    910 	if (ag.rh >= 0)
    911 		headset_send(hs, "\r\n+BTRH: %d\r\n", ag.rh);
    912 
    913 	return headset_send(hs, "\r\nOK\r\n", ag.rh);
    914 }
    915 
    916 int telephony_last_dialed_number_rsp(void *telephony_device, cme_error_t err)
    917 {
    918 	return telephony_generic_rsp(telephony_device, err);
    919 }
    920 
    921 static int last_dialed_number(struct audio_device *device, const char *buf)
    922 {
    923 	telephony_last_dialed_number_req(device);
    924 
    925 	return 0;
    926 }
    927 
    928 int telephony_dial_number_rsp(void *telephony_device, cme_error_t err)
    929 {
    930 	return telephony_generic_rsp(telephony_device, err);
    931 }
    932 
    933 static int dial_number(struct audio_device *device, const char *buf)
    934 {
    935 	char number[BUF_SIZE];
    936 	size_t buf_len;
    937 
    938 	buf_len = strlen(buf);
    939 
    940 	if (buf[buf_len - 1] != ';') {
    941 		DBG("Rejecting non-voice call dial request");
    942 		return -EINVAL;
    943 	}
    944 
    945 	memset(number, 0, sizeof(number));
    946 	strncpy(number, &buf[3], buf_len - 4);
    947 
    948 	telephony_dial_number_req(device, number);
    949 
    950 	return 0;
    951 }
    952 
    953 static int headset_set_gain(struct audio_device *device, uint16_t gain, char type)
    954 {
    955 	struct headset *hs = device->headset;
    956 	struct headset_slc *slc = hs->slc;
    957 	const char *name, *property;
    958 
    959 	if (gain > 15) {
    960 		error("Invalid gain value: %u", gain);
    961 		return -EINVAL;
    962 	}
    963 
    964 	switch (type) {
    965 	case HEADSET_GAIN_SPEAKER:
    966 		if (slc->sp_gain == gain) {
    967 			DBG("Ignoring no-change in speaker gain");
    968 			return 0;
    969 		}
    970 		name = "SpeakerGainChanged";
    971 		property = "SpeakerGain";
    972 		slc->sp_gain = gain;
    973 		break;
    974 	case HEADSET_GAIN_MICROPHONE:
    975 		if (slc->mic_gain == gain) {
    976 			DBG("Ignoring no-change in microphone gain");
    977 			return 0;
    978 		}
    979 		name = "MicrophoneGainChanged";
    980 		property = "MicrophoneGain";
    981 		slc->mic_gain = gain;
    982 		break;
    983 	default:
    984 		error("Unknown gain setting");
    985 		return -EINVAL;
    986 	}
    987 
    988 	g_dbus_emit_signal(device->conn, device->path,
    989 				AUDIO_HEADSET_INTERFACE, name,
    990 				DBUS_TYPE_UINT16, &gain,
    991 				DBUS_TYPE_INVALID);
    992 
    993 	emit_property_changed(device->conn, device->path,
    994 				AUDIO_HEADSET_INTERFACE, property,
    995 				DBUS_TYPE_UINT16, &gain);
    996 
    997 	return 0;
    998 }
    999 
   1000 static int signal_gain_setting(struct audio_device *device, const char *buf)
   1001 {
   1002 	struct headset *hs = device->headset;
   1003 	dbus_uint16_t gain;
   1004 	int err;
   1005 
   1006 	if (strlen(buf) < 8) {
   1007 		error("Too short string for Gain setting");
   1008 		return -EINVAL;
   1009 	}
   1010 
   1011 	gain = (dbus_uint16_t) strtol(&buf[7], NULL, 10);
   1012 
   1013 	err = headset_set_gain(device, gain, buf[5]);
   1014 	if (err < 0)
   1015 		return err;
   1016 
   1017 	return headset_send(hs, "\r\nOK\r\n");
   1018 }
   1019 
   1020 int telephony_transmit_dtmf_rsp(void *telephony_device, cme_error_t err)
   1021 {
   1022 	return telephony_generic_rsp(telephony_device, err);
   1023 }
   1024 
   1025 static int dtmf_tone(struct audio_device *device, const char *buf)
   1026 {
   1027 	if (strlen(buf) < 8) {
   1028 		error("Too short string for DTMF tone");
   1029 		return -EINVAL;
   1030 	}
   1031 
   1032 	telephony_transmit_dtmf_req(device, buf[7]);
   1033 
   1034 	return 0;
   1035 }
   1036 
   1037 int telephony_subscriber_number_rsp(void *telephony_device, cme_error_t err)
   1038 {
   1039 	return telephony_generic_rsp(telephony_device, err);
   1040 }
   1041 
   1042 static int subscriber_number(struct audio_device *device, const char *buf)
   1043 {
   1044 	telephony_subscriber_number_req(device);
   1045 
   1046 	return 0;
   1047 }
   1048 
   1049 int telephony_list_current_calls_rsp(void *telephony_device, cme_error_t err)
   1050 {
   1051 	return telephony_generic_rsp(telephony_device, err);
   1052 }
   1053 
   1054 static int list_current_calls(struct audio_device *device, const char *buf)
   1055 {
   1056 	telephony_list_current_calls_req(device);
   1057 
   1058 	return 0;
   1059 }
   1060 
   1061 static int extended_errors(struct audio_device *device, const char *buf)
   1062 {
   1063 	struct headset *hs = device->headset;
   1064 	struct headset_slc *slc = hs->slc;
   1065 
   1066 	if (strlen(buf) < 9)
   1067 		return -EINVAL;
   1068 
   1069 	if (buf[8] == '1') {
   1070 		slc->cme_enabled = TRUE;
   1071 		DBG("CME errors enabled for headset %p", hs);
   1072 	} else {
   1073 		slc->cme_enabled = FALSE;
   1074 		DBG("CME errors disabled for headset %p", hs);
   1075 	}
   1076 
   1077 	return headset_send(hs, "\r\nOK\r\n");
   1078 }
   1079 
   1080 static int call_waiting_notify(struct audio_device *device, const char *buf)
   1081 {
   1082 	struct headset *hs = device->headset;
   1083 	struct headset_slc *slc = hs->slc;
   1084 
   1085 	if (strlen(buf) < 9)
   1086 		return -EINVAL;
   1087 
   1088 	if (buf[8] == '1') {
   1089 		slc->cwa_enabled = TRUE;
   1090 		DBG("Call waiting notification enabled for headset %p", hs);
   1091 	} else {
   1092 		slc->cwa_enabled = FALSE;
   1093 		DBG("Call waiting notification disabled for headset %p", hs);
   1094 	}
   1095 
   1096 	return headset_send(hs, "\r\nOK\r\n");
   1097 }
   1098 
   1099 int telephony_operator_selection_rsp(void *telephony_device, cme_error_t err)
   1100 {
   1101 	return telephony_generic_rsp(telephony_device, err);
   1102 }
   1103 
   1104 int telephony_call_hold_rsp(void *telephony_device, cme_error_t err)
   1105 {
   1106 	return telephony_generic_rsp(telephony_device, err);
   1107 }
   1108 
   1109 int telephony_nr_and_ec_rsp(void *telephony_device, cme_error_t err)
   1110 {
   1111 	struct audio_device *device = telephony_device;
   1112 	struct headset *hs = device->headset;
   1113 	struct headset_slc *slc = hs->slc;
   1114 
   1115 	if (err == CME_ERROR_NONE)
   1116 		slc->nrec = hs->slc->nrec_req;
   1117 
   1118 	return telephony_generic_rsp(telephony_device, err);
   1119 }
   1120 
   1121 int telephony_voice_dial_rsp(void *telephony_device, cme_error_t err)
   1122 {
   1123 	return telephony_generic_rsp(telephony_device, err);
   1124 }
   1125 
   1126 int telephony_operator_selection_ind(int mode, const char *oper)
   1127 {
   1128 	if (!active_devices)
   1129 		return -ENODEV;
   1130 
   1131 	send_foreach_headset(active_devices, hfp_cmp,
   1132 				"\r\n+COPS: %d,0,\"%s\"\r\n",
   1133 				mode, oper);
   1134 	return 0;
   1135 }
   1136 
   1137 static int operator_selection(struct audio_device *device, const char *buf)
   1138 {
   1139 	struct headset *hs = device->headset;
   1140 
   1141 	if (strlen(buf) < 8)
   1142 		return -EINVAL;
   1143 
   1144 	switch (buf[7]) {
   1145 	case '?':
   1146 		telephony_operator_selection_req(device);
   1147 		break;
   1148 	case '=':
   1149 		return headset_send(hs, "\r\nOK\r\n");
   1150 	default:
   1151 		return -EINVAL;
   1152 	}
   1153 
   1154 	return 0;
   1155 }
   1156 
   1157 static int nr_and_ec(struct audio_device *device, const char *buf)
   1158 {
   1159 	struct headset *hs = device->headset;
   1160 	struct headset_slc *slc = hs->slc;
   1161 
   1162 	if (strlen(buf) < 9)
   1163 		return -EINVAL;
   1164 
   1165 	if (buf[8] == '0')
   1166 		slc->nrec_req = FALSE;
   1167 	else
   1168 		slc->nrec_req = TRUE;
   1169 
   1170 	telephony_nr_and_ec_req(device, slc->nrec_req);
   1171 
   1172 	return 0;
   1173 }
   1174 
   1175 static int voice_dial(struct audio_device *device, const char *buf)
   1176 {
   1177 	gboolean enable;
   1178 
   1179 	if (strlen(buf) < 9)
   1180 		return -EINVAL;
   1181 
   1182 	if (buf[8] == '0')
   1183 		enable = FALSE;
   1184 	else
   1185 		enable = TRUE;
   1186 
   1187 	telephony_voice_dial_req(device, enable);
   1188 
   1189 	return 0;
   1190 }
   1191 
   1192 static struct event event_callbacks[] = {
   1193 	{ "ATA", answer_call },
   1194 	{ "ATD", dial_number },
   1195 	{ "AT+VG", signal_gain_setting },
   1196 	{ "AT+BRSF", supported_features },
   1197 	{ "AT+CIND", report_indicators },
   1198 	{ "AT+CMER", event_reporting },
   1199 	{ "AT+CHLD", call_hold },
   1200 	{ "AT+CHUP", terminate_call },
   1201 	{ "AT+CKPD", key_press },
   1202 	{ "AT+CLIP", cli_notification },
   1203 	{ "AT+BTRH", response_and_hold },
   1204 	{ "AT+BLDN", last_dialed_number },
   1205 	{ "AT+VTS", dtmf_tone },
   1206 	{ "AT+CNUM", subscriber_number },
   1207 	{ "AT+CLCC", list_current_calls },
   1208 	{ "AT+CMEE", extended_errors },
   1209 	{ "AT+CCWA", call_waiting_notify },
   1210 	{ "AT+COPS", operator_selection },
   1211 	{ "AT+NREC", nr_and_ec },
   1212 	{ "AT+BVRA", voice_dial },
   1213 	{ 0 }
   1214 };
   1215 
   1216 static int handle_event(struct audio_device *device, const char *buf)
   1217 {
   1218 	struct event *ev;
   1219 
   1220 	DBG("Received %s", buf);
   1221 
   1222 	for (ev = event_callbacks; ev->cmd; ev++) {
   1223 		if (!strncmp(buf, ev->cmd, strlen(ev->cmd)))
   1224 			return ev->callback(device, buf);
   1225 	}
   1226 
   1227 	return -EINVAL;
   1228 }
   1229 
   1230 static void close_sco(struct audio_device *device)
   1231 {
   1232 	struct headset *hs = device->headset;
   1233 
   1234 	if (hs->sco) {
   1235 		int sock = g_io_channel_unix_get_fd(hs->sco);
   1236 		shutdown(sock, SHUT_RDWR);
   1237 		g_io_channel_shutdown(hs->sco, TRUE, NULL);
   1238 		g_io_channel_unref(hs->sco);
   1239 		hs->sco = NULL;
   1240 	}
   1241 
   1242 	if (hs->sco_id) {
   1243 		g_source_remove(hs->sco_id);
   1244 		hs->sco_id = 0;
   1245 	}
   1246 }
   1247 
   1248 static gboolean rfcomm_io_cb(GIOChannel *chan, GIOCondition cond,
   1249 				struct audio_device *device)
   1250 {
   1251 	struct headset *hs;
   1252 	struct headset_slc *slc;
   1253 	unsigned char buf[BUF_SIZE];
   1254 	gsize bytes_read = 0;
   1255 	gsize free_space;
   1256 
   1257 	if (cond & G_IO_NVAL)
   1258 		return FALSE;
   1259 
   1260 	hs = device->headset;
   1261 	slc = hs->slc;
   1262 
   1263 	if (cond & (G_IO_ERR | G_IO_HUP)) {
   1264 		DBG("ERR or HUP on RFCOMM socket");
   1265 		goto failed;
   1266 	}
   1267 
   1268 	if (g_io_channel_read(chan, (gchar *) buf, sizeof(buf) - 1,
   1269 				&bytes_read) != G_IO_ERROR_NONE)
   1270 		return TRUE;
   1271 
   1272 	free_space = sizeof(slc->buf) - slc->data_start -
   1273 			slc->data_length - 1;
   1274 
   1275 	if (free_space < bytes_read) {
   1276 		/* Very likely that the HS is sending us garbage so
   1277 		 * just ignore the data and disconnect */
   1278 		error("Too much data to fit incomming buffer");
   1279 		goto failed;
   1280 	}
   1281 
   1282 	memcpy(&slc->buf[slc->data_start], buf, bytes_read);
   1283 	slc->data_length += bytes_read;
   1284 
   1285 	/* Make sure the data is null terminated so we can use string
   1286 	 * functions */
   1287 	slc->buf[slc->data_start + slc->data_length] = '\0';
   1288 
   1289 	while (slc->data_length > 0) {
   1290 		char *cr;
   1291 		int err;
   1292 		off_t cmd_len;
   1293 
   1294 		cr = strchr(&slc->buf[slc->data_start], '\r');
   1295 		if (!cr)
   1296 			break;
   1297 
   1298 		cmd_len = 1 + (off_t) cr - (off_t) &slc->buf[slc->data_start];
   1299 		*cr = '\0';
   1300 
   1301 		if (cmd_len > 1)
   1302 			err = handle_event(device, &slc->buf[slc->data_start]);
   1303 		else
   1304 			/* Silently skip empty commands */
   1305 			err = 0;
   1306 
   1307 		if (err == -EINVAL) {
   1308 			error("Badly formated or unrecognized command: %s",
   1309 					&slc->buf[slc->data_start]);
   1310 			err = headset_send(hs, "\r\nERROR\r\n");
   1311 		} else if (err < 0)
   1312 			error("Error handling command %s: %s (%d)",
   1313 						&slc->buf[slc->data_start],
   1314 						strerror(-err), -err);
   1315 
   1316 		slc->data_start += cmd_len;
   1317 		slc->data_length -= cmd_len;
   1318 
   1319 		if (!slc->data_length)
   1320 			slc->data_start = 0;
   1321 	}
   1322 
   1323 	return TRUE;
   1324 
   1325 failed:
   1326 	headset_set_state(device, HEADSET_STATE_DISCONNECTED);
   1327 
   1328 	return FALSE;
   1329 }
   1330 
   1331 static gboolean sco_cb(GIOChannel *chan, GIOCondition cond,
   1332 			struct audio_device *device)
   1333 {
   1334 	if (cond & G_IO_NVAL)
   1335 		return FALSE;
   1336 
   1337 	error("Audio connection got disconnected");
   1338 
   1339 	headset_set_state(device, HEADSET_STATE_CONNECTED);
   1340 
   1341 	return FALSE;
   1342 }
   1343 
   1344 void headset_connect_cb(GIOChannel *chan, GError *err, gpointer user_data)
   1345 {
   1346 	struct audio_device *dev = user_data;
   1347 	struct headset *hs = dev->headset;
   1348 	struct pending_connect *p = hs->pending;
   1349 	char hs_address[18];
   1350 
   1351 	if (err) {
   1352 		error("%s", err->message);
   1353 		goto failed;
   1354 	}
   1355 
   1356 	/* For HFP telephony isn't ready just disconnect */
   1357 	if (hs->hfp_active && !ag.telephony_ready) {
   1358 		error("Unable to accept HFP connection since the telephony "
   1359 				"subsystem isn't initialized");
   1360 		goto failed;
   1361 	}
   1362 
   1363 	hs->rfcomm = hs->tmp_rfcomm;
   1364 	hs->tmp_rfcomm = NULL;
   1365 
   1366 	ba2str(&dev->dst, hs_address);
   1367 
   1368 	if (p)
   1369 		p->io = NULL;
   1370 	else
   1371 		hs->auto_dc = FALSE;
   1372 
   1373 	g_io_add_watch(chan, G_IO_IN | G_IO_ERR | G_IO_HUP| G_IO_NVAL,
   1374 			(GIOFunc) rfcomm_io_cb, dev);
   1375 
   1376 	DBG("%s: Connected to %s", dev->path, hs_address);
   1377 
   1378 	hs->slc = g_new0(struct headset_slc, 1);
   1379 	hs->slc->nrec = TRUE;
   1380 
   1381 	/* In HFP mode wait for Service Level Connection */
   1382 	if (hs->hfp_active)
   1383 		return;
   1384 
   1385 	headset_set_state(dev, HEADSET_STATE_CONNECTED);
   1386 
   1387 	if (p && p->target_state == HEADSET_STATE_PLAYING) {
   1388 		p->err = sco_connect(dev, NULL, NULL, NULL);
   1389 		if (p->err < 0)
   1390 			goto failed;
   1391 		return;
   1392 	}
   1393 
   1394 	if (p && p->msg) {
   1395 		DBusMessage *reply = dbus_message_new_method_return(p->msg);
   1396 		g_dbus_send_message(dev->conn, reply);
   1397 	}
   1398 
   1399 	pending_connect_finalize(dev);
   1400 
   1401 	return;
   1402 
   1403 failed:
   1404 	if (p && p->msg)
   1405 		error_connection_attempt_failed(dev->conn, p->msg, p->err);
   1406 	pending_connect_finalize(dev);
   1407 	if (hs->rfcomm)
   1408 		headset_set_state(dev, HEADSET_STATE_CONNECTED);
   1409 	else
   1410 		headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
   1411 }
   1412 
   1413 static int headset_set_channel(struct headset *headset,
   1414 				const sdp_record_t *record, uint16_t svc)
   1415 {
   1416 	int ch;
   1417 	sdp_list_t *protos;
   1418 
   1419 	if (sdp_get_access_protos(record, &protos) < 0) {
   1420 		error("Unable to get access protos from headset record");
   1421 		return -1;
   1422 	}
   1423 
   1424 	ch = sdp_get_proto_port(protos, RFCOMM_UUID);
   1425 
   1426 	sdp_list_foreach(protos, (sdp_list_func_t) sdp_list_free, NULL);
   1427 	sdp_list_free(protos, NULL);
   1428 
   1429 	if (ch <= 0) {
   1430 		error("Unable to get RFCOMM channel from Headset record");
   1431 		return -1;
   1432 	}
   1433 
   1434 	headset->rfcomm_ch = ch;
   1435 
   1436 	if (svc == HANDSFREE_SVCLASS_ID) {
   1437 		headset->hfp_handle = record->handle;
   1438 		DBG("Discovered Handsfree service on channel %d", ch);
   1439 	} else {
   1440 		headset->hsp_handle = record->handle;
   1441 		DBG("Discovered Headset service on channel %d", ch);
   1442 	}
   1443 
   1444 	return 0;
   1445 }
   1446 
   1447 static void get_record_cb(sdp_list_t *recs, int err, gpointer user_data)
   1448 {
   1449 	struct audio_device *dev = user_data;
   1450 	struct headset *hs = dev->headset;
   1451 	struct pending_connect *p = hs->pending;
   1452 	sdp_record_t *record = NULL;
   1453 	sdp_list_t *r;
   1454 	uuid_t uuid;
   1455 
   1456 	assert(hs->pending != NULL);
   1457 
   1458 	if (err < 0) {
   1459 		error("Unable to get service record: %s (%d)",
   1460 							strerror(-err), -err);
   1461 		p->err = -err;
   1462 		error_connection_attempt_failed(dev->conn, p->msg, p->err);
   1463 		goto failed;
   1464 	}
   1465 
   1466 	if (!recs || !recs->data) {
   1467 		error("No records found");
   1468 		goto failed_not_supported;
   1469 	}
   1470 
   1471 	sdp_uuid16_create(&uuid, p->svclass);
   1472 
   1473 	for (r = recs; r != NULL; r = r->next) {
   1474 		sdp_list_t *classes;
   1475 		uuid_t class;
   1476 
   1477 		record = r->data;
   1478 
   1479 		if (sdp_get_service_classes(record, &classes) < 0) {
   1480 			error("Unable to get service classes from record");
   1481 			continue;
   1482 		}
   1483 
   1484 		memcpy(&class, classes->data, sizeof(uuid));
   1485 
   1486 		sdp_list_free(classes, free);
   1487 
   1488 
   1489 		if (sdp_uuid_cmp(&class, &uuid) == 0)
   1490 			break;
   1491 	}
   1492 
   1493 	if (r == NULL) {
   1494 		error("No record found with UUID 0x%04x", p->svclass);
   1495 		goto failed_not_supported;
   1496 	}
   1497 
   1498 	if (headset_set_channel(hs, record, p->svclass) < 0) {
   1499 		error("Unable to extract RFCOMM channel from service record");
   1500 		goto failed_not_supported;
   1501 	}
   1502 
   1503 	/* Set svclass to 0 so we can easily check that SDP is no-longer
   1504 	 * going on (to know if bt_cancel_discovery needs to be called) */
   1505 	p->svclass = 0;
   1506 
   1507 	err = rfcomm_connect(dev, NULL, NULL, NULL);
   1508 	if (err < 0) {
   1509 		error("Unable to connect: %s (%d)", strerror(-err), -err);
   1510 		p->err = -err;
   1511 		error_connection_attempt_failed(dev->conn, p->msg, p->err);
   1512 		goto failed;
   1513 	}
   1514 
   1515 	return;
   1516 
   1517 failed_not_supported:
   1518 	if (p->svclass == HANDSFREE_SVCLASS_ID &&
   1519 			get_records(dev, NULL, NULL, NULL) == 0)
   1520 		return;
   1521 	if (p->msg)
   1522 		error_not_supported(dev->conn, p->msg);
   1523 failed:
   1524 	p->svclass = 0;
   1525 	pending_connect_finalize(dev);
   1526 	headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
   1527 }
   1528 
   1529 static int get_records(struct audio_device *device, headset_stream_cb_t cb,
   1530 			void *user_data, unsigned int *cb_id)
   1531 {
   1532 	struct headset *hs = device->headset;
   1533 	uint16_t svclass;
   1534 	uuid_t uuid;
   1535 	int err;
   1536 
   1537 	if (hs->pending && hs->pending->svclass == HANDSFREE_SVCLASS_ID)
   1538 		svclass = HEADSET_SVCLASS_ID;
   1539 	else
   1540 		svclass = hs->search_hfp ? HANDSFREE_SVCLASS_ID :
   1541 							HEADSET_SVCLASS_ID;
   1542 
   1543 	sdp_uuid16_create(&uuid, svclass);
   1544 
   1545 	err = bt_search_service(&device->src, &device->dst, &uuid,
   1546 						get_record_cb, device, NULL);
   1547 	if (err < 0)
   1548 		return err;
   1549 
   1550 	if (hs->pending) {
   1551 		hs->pending->svclass = svclass;
   1552 		return 0;
   1553 	}
   1554 
   1555 	headset_set_state(device, HEADSET_STATE_CONNECTING);
   1556 
   1557 	pending_connect_init(hs, HEADSET_STATE_CONNECTED);
   1558 
   1559 	hs->pending->svclass = svclass;
   1560 
   1561 	if (cb) {
   1562 		unsigned int id;
   1563 		id = connect_cb_new(hs, HEADSET_STATE_CONNECTED,
   1564 					cb, user_data);
   1565 		if (cb_id)
   1566 			*cb_id = id;
   1567 	}
   1568 
   1569 	return 0;
   1570 }
   1571 
   1572 static int rfcomm_connect(struct audio_device *dev, headset_stream_cb_t cb,
   1573 				void *user_data, unsigned int *cb_id)
   1574 {
   1575 	struct headset *hs = dev->headset;
   1576 	char address[18];
   1577 	GError *err = NULL;
   1578 
   1579 	if (!manager_allow_headset_connection(dev))
   1580 		return -ECONNREFUSED;
   1581 
   1582 	if (hs->rfcomm_ch < 0)
   1583 		return get_records(dev, cb, user_data, cb_id);
   1584 
   1585 	ba2str(&dev->dst, address);
   1586 
   1587 	DBG("%s: Connecting to %s channel %d", dev->path, address,
   1588 		hs->rfcomm_ch);
   1589 
   1590 	hs->tmp_rfcomm = bt_io_connect(BT_IO_RFCOMM, headset_connect_cb, dev,
   1591 					NULL, &err,
   1592 					BT_IO_OPT_SOURCE_BDADDR, &dev->src,
   1593 					BT_IO_OPT_DEST_BDADDR, &dev->dst,
   1594 					BT_IO_OPT_CHANNEL, hs->rfcomm_ch,
   1595 					BT_IO_OPT_INVALID);
   1596 
   1597 	hs->rfcomm_ch = -1;
   1598 
   1599 	if (!hs->tmp_rfcomm) {
   1600 		error("%s", err->message);
   1601 		g_error_free(err);
   1602 		return -EIO;
   1603 	}
   1604 
   1605 	hs->hfp_active = hs->hfp_handle != 0 ? TRUE : FALSE;
   1606 
   1607 	headset_set_state(dev, HEADSET_STATE_CONNECTING);
   1608 
   1609 	pending_connect_init(hs, HEADSET_STATE_CONNECTED);
   1610 
   1611 	if (cb) {
   1612 		unsigned int id = connect_cb_new(hs, HEADSET_STATE_CONNECTED,
   1613 							cb, user_data);
   1614 		if (cb_id)
   1615 			*cb_id = id;
   1616 	}
   1617 
   1618 	return 0;
   1619 }
   1620 
   1621 static DBusMessage *hs_stop(DBusConnection *conn, DBusMessage *msg,
   1622 					void *data)
   1623 {
   1624 	struct audio_device *device = data;
   1625 	struct headset *hs = device->headset;
   1626 	DBusMessage *reply = NULL;
   1627 
   1628 	if (hs->state < HEADSET_STATE_PLAY_IN_PROGRESS)
   1629 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1630 						".NotConnected",
   1631 						"Device not Connected");
   1632 
   1633 	reply = dbus_message_new_method_return(msg);
   1634 	if (!reply)
   1635 		return NULL;
   1636 
   1637 	headset_set_state(device, HEADSET_STATE_CONNECTED);
   1638 
   1639 	return reply;
   1640 }
   1641 
   1642 static DBusMessage *hs_is_playing(DBusConnection *conn, DBusMessage *msg,
   1643 					void *data)
   1644 {
   1645 	struct audio_device *device = data;
   1646 	struct headset *hs = device->headset;
   1647 	DBusMessage *reply;
   1648 	dbus_bool_t playing;
   1649 
   1650 	reply = dbus_message_new_method_return(msg);
   1651 	if (!reply)
   1652 		return NULL;
   1653 
   1654 	playing = (hs->state == HEADSET_STATE_PLAYING);
   1655 
   1656 	dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &playing,
   1657 					DBUS_TYPE_INVALID);
   1658 
   1659 	return reply;
   1660 }
   1661 
   1662 static DBusMessage *hs_disconnect(DBusConnection *conn, DBusMessage *msg,
   1663 					void *data)
   1664 {
   1665 	struct audio_device *device = data;
   1666 	struct headset *hs = device->headset;
   1667 	char hs_address[18];
   1668 
   1669 	if (hs->state == HEADSET_STATE_DISCONNECTED)
   1670 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1671 						".NotConnected",
   1672 						"Device not Connected");
   1673 
   1674 	headset_shutdown(device);
   1675 	ba2str(&device->dst, hs_address);
   1676 	info("Disconnected from %s, %s", hs_address, device->path);
   1677 
   1678 	return dbus_message_new_method_return(msg);
   1679 
   1680 }
   1681 
   1682 static DBusMessage *hs_is_connected(DBusConnection *conn,
   1683 						DBusMessage *msg,
   1684 						void *data)
   1685 {
   1686 	struct audio_device *device = data;
   1687 	DBusMessage *reply;
   1688 	dbus_bool_t connected;
   1689 
   1690 	reply = dbus_message_new_method_return(msg);
   1691 	if (!reply)
   1692 		return NULL;
   1693 
   1694 	connected = (device->headset->state >= HEADSET_STATE_CONNECTED);
   1695 
   1696 	dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &connected,
   1697 					DBUS_TYPE_INVALID);
   1698 
   1699 	return reply;
   1700 }
   1701 
   1702 static DBusMessage *hs_connect(DBusConnection *conn, DBusMessage *msg,
   1703 					void *data)
   1704 {
   1705 	struct audio_device *device = data;
   1706 	struct headset *hs = device->headset;
   1707 	int err;
   1708 
   1709 	if (hs->state == HEADSET_STATE_CONNECTING)
   1710 		return g_dbus_create_error(msg, ERROR_INTERFACE ".InProgress",
   1711 						"Connect in Progress");
   1712 	else if (hs->state > HEADSET_STATE_CONNECTING)
   1713 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1714 						".AlreadyConnected",
   1715 						"Already Connected");
   1716 
   1717 	if (hs->hfp_handle && !ag.telephony_ready)
   1718 		return g_dbus_create_error(msg, ERROR_INTERFACE ".NotReady",
   1719 					"Telephony subsystem not ready");
   1720 
   1721 	device->auto_connect = FALSE;
   1722 
   1723 	err = rfcomm_connect(device, NULL, NULL, NULL);
   1724 	if (err == -ECONNREFUSED)
   1725 		return g_dbus_create_error(msg, ERROR_INTERFACE ".NotAllowed",
   1726 						"Too many connected devices");
   1727 	else if (err < 0)
   1728 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1729 						".ConnectAttemptFailed",
   1730 						"Connect Attempt Failed");
   1731 
   1732 	hs->auto_dc = FALSE;
   1733 
   1734 	hs->pending->msg = dbus_message_ref(msg);
   1735 
   1736 	return NULL;
   1737 }
   1738 
   1739 static DBusMessage *hs_ring(DBusConnection *conn, DBusMessage *msg,
   1740 					void *data)
   1741 {
   1742 	struct audio_device *device = data;
   1743 	struct headset *hs = device->headset;
   1744 	DBusMessage *reply = NULL;
   1745 	int err;
   1746 
   1747 	if (hs->state < HEADSET_STATE_CONNECTED)
   1748 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1749 						".NotConnected",
   1750 						"Device not Connected");
   1751 
   1752 	reply = dbus_message_new_method_return(msg);
   1753 	if (!reply)
   1754 		return NULL;
   1755 
   1756 	if (ag.ring_timer) {
   1757 		DBG("IndicateCall received when already indicating");
   1758 		goto done;
   1759 	}
   1760 
   1761 	err = headset_send(hs, "\r\nRING\r\n");
   1762 	if (err < 0) {
   1763 		dbus_message_unref(reply);
   1764 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1765 						"%s", strerror(-err));
   1766 	}
   1767 
   1768 	ring_timer_cb(NULL);
   1769 	ag.ring_timer = g_timeout_add_seconds(RING_INTERVAL, ring_timer_cb,
   1770 						NULL);
   1771 
   1772 done:
   1773 	return reply;
   1774 }
   1775 
   1776 static DBusMessage *hs_cancel_call(DBusConnection *conn,
   1777 					DBusMessage *msg,
   1778 					void *data)
   1779 {
   1780 	struct audio_device *device = data;
   1781 	struct headset *hs = device->headset;
   1782 	DBusMessage *reply = NULL;
   1783 
   1784 	if (hs->state < HEADSET_STATE_CONNECTED)
   1785 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1786 						".NotConnected",
   1787 						"Device not Connected");
   1788 
   1789 	reply = dbus_message_new_method_return(msg);
   1790 	if (!reply)
   1791 		return NULL;
   1792 
   1793 	if (ag.ring_timer) {
   1794 		g_source_remove(ag.ring_timer);
   1795 		ag.ring_timer = 0;
   1796 	} else
   1797 		DBG("Got CancelCall method call but no call is active");
   1798 
   1799 	return reply;
   1800 }
   1801 
   1802 static DBusMessage *hs_play(DBusConnection *conn, DBusMessage *msg,
   1803 				void *data)
   1804 {
   1805 	struct audio_device *device = data;
   1806 	struct headset *hs = device->headset;
   1807 	int err;
   1808 
   1809 	if (sco_hci) {
   1810 		error("Refusing Headset.Play() because SCO HCI routing "
   1811 				"is enabled");
   1812 		return g_dbus_create_error(msg, ERROR_INTERFACE ".NotAvailable",
   1813 						"Operation not Available");
   1814 	}
   1815 
   1816 	switch (hs->state) {
   1817 	case HEADSET_STATE_DISCONNECTED:
   1818 	case HEADSET_STATE_CONNECTING:
   1819 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1820 						".NotConnected",
   1821 						"Device not Connected");
   1822 	case HEADSET_STATE_PLAY_IN_PROGRESS:
   1823 		if (hs->pending && hs->pending->msg == NULL) {
   1824 			hs->pending->msg = dbus_message_ref(msg);
   1825 			return NULL;
   1826 		}
   1827 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1828 						".InProgress",
   1829 						"Play in Progress");
   1830 	case HEADSET_STATE_PLAYING:
   1831 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1832 						".AlreadyConnected",
   1833 						"Device Already Connected");
   1834 	case HEADSET_STATE_CONNECTED:
   1835 	default:
   1836 		break;
   1837 	}
   1838 
   1839 	err = sco_connect(device, NULL, NULL, NULL);
   1840 	if (err < 0)
   1841 		return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1842 						"%s", strerror(-err));
   1843 
   1844 	hs->pending->msg = dbus_message_ref(msg);
   1845 
   1846 	return NULL;
   1847 }
   1848 
   1849 static DBusMessage *hs_get_speaker_gain(DBusConnection *conn,
   1850 					DBusMessage *msg,
   1851 					void *data)
   1852 {
   1853 	struct audio_device *device = data;
   1854 	struct headset *hs = device->headset;
   1855 	struct headset_slc *slc = hs->slc;
   1856 	DBusMessage *reply;
   1857 	dbus_uint16_t gain;
   1858 
   1859 	if (hs->state < HEADSET_STATE_CONNECTED)
   1860 		return g_dbus_create_error(msg, ERROR_INTERFACE ".NotAvailable",
   1861 						"Operation not Available");
   1862 
   1863 	reply = dbus_message_new_method_return(msg);
   1864 	if (!reply)
   1865 		return NULL;
   1866 
   1867 	gain = (dbus_uint16_t) slc->sp_gain;
   1868 
   1869 	dbus_message_append_args(reply, DBUS_TYPE_UINT16, &gain,
   1870 					DBUS_TYPE_INVALID);
   1871 
   1872 	return reply;
   1873 }
   1874 
   1875 static DBusMessage *hs_get_mic_gain(DBusConnection *conn,
   1876 					DBusMessage *msg,
   1877 					void *data)
   1878 {
   1879 	struct audio_device *device = data;
   1880 	struct headset *hs = device->headset;
   1881 	struct headset_slc *slc = hs->slc;
   1882 	DBusMessage *reply;
   1883 	dbus_uint16_t gain;
   1884 
   1885 	if (hs->state < HEADSET_STATE_CONNECTED || slc == NULL)
   1886 		return g_dbus_create_error(msg, ERROR_INTERFACE ".NotAvailable",
   1887 						"Operation not Available");
   1888 
   1889 	reply = dbus_message_new_method_return(msg);
   1890 	if (!reply)
   1891 		return NULL;
   1892 
   1893 	gain = (dbus_uint16_t) slc->mic_gain;
   1894 
   1895 	dbus_message_append_args(reply, DBUS_TYPE_UINT16, &gain,
   1896 					DBUS_TYPE_INVALID);
   1897 
   1898 	return reply;
   1899 }
   1900 
   1901 static DBusMessage *hs_set_gain(DBusConnection *conn,
   1902 				DBusMessage *msg,
   1903 				void *data, uint16_t gain,
   1904 				char type)
   1905 {
   1906 	struct audio_device *device = data;
   1907 	struct headset *hs = device->headset;
   1908 	DBusMessage *reply;
   1909 	int err;
   1910 
   1911 	if (hs->state < HEADSET_STATE_CONNECTED)
   1912 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1913 						".NotConnected",
   1914 						"Device not Connected");
   1915 
   1916 	err = headset_set_gain(device, gain, type);
   1917 	if (err < 0)
   1918 		return g_dbus_create_error(msg, ERROR_INTERFACE
   1919 						".InvalidArgument",
   1920 						"Must be less than or equal to 15");
   1921 
   1922 	reply = dbus_message_new_method_return(msg);
   1923 	if (!reply)
   1924 		return NULL;
   1925 
   1926 	if (hs->state == HEADSET_STATE_PLAYING) {
   1927 		err = headset_send(hs, "\r\n+VG%c=%u\r\n", type, gain);
   1928 		if (err < 0) {
   1929 			dbus_message_unref(reply);
   1930 			return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
   1931 						"%s", strerror(-err));
   1932 		}
   1933 	}
   1934 
   1935 	return reply;
   1936 }
   1937 
   1938 static DBusMessage *hs_set_speaker_gain(DBusConnection *conn,
   1939 					DBusMessage *msg,
   1940 					void *data)
   1941 {
   1942 	uint16_t gain;
   1943 
   1944 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT16, &gain,
   1945 				DBUS_TYPE_INVALID))
   1946 		return NULL;
   1947 
   1948 	return hs_set_gain(conn, msg, data, gain, HEADSET_GAIN_SPEAKER);
   1949 }
   1950 
   1951 static DBusMessage *hs_set_mic_gain(DBusConnection *conn,
   1952 					DBusMessage *msg,
   1953 					void *data)
   1954 {
   1955 	uint16_t gain;
   1956 
   1957 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT16, &gain,
   1958 				DBUS_TYPE_INVALID))
   1959 		return NULL;
   1960 
   1961 	return hs_set_gain(conn, msg, data, gain, HEADSET_GAIN_MICROPHONE);
   1962 }
   1963 
   1964 static DBusMessage *hs_get_properties(DBusConnection *conn,
   1965 					DBusMessage *msg, void *data)
   1966 {
   1967 	struct audio_device *device = data;
   1968 	DBusMessage *reply;
   1969 	DBusMessageIter iter;
   1970 	DBusMessageIter dict;
   1971 	gboolean value;
   1972 	const char *state;
   1973 
   1974 	reply = dbus_message_new_method_return(msg);
   1975 	if (!reply)
   1976 		return NULL;
   1977 
   1978 	dbus_message_iter_init_append(reply, &iter);
   1979 
   1980 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1981 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   1982 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   1983 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   1984 
   1985 
   1986 	/* Playing */
   1987 	value = (device->headset->state == HEADSET_STATE_PLAYING);
   1988 	dict_append_entry(&dict, "Playing", DBUS_TYPE_BOOLEAN, &value);
   1989 
   1990 	/* State */
   1991 	state = state2str(device->headset->state);
   1992 	if (state)
   1993 		dict_append_entry(&dict, "State", DBUS_TYPE_STRING, &state);
   1994 
   1995 	/* Connected */
   1996 	value = (device->headset->state >= HEADSET_STATE_CONNECTED);
   1997 	dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &value);
   1998 
   1999 	if (!value)
   2000 		goto done;
   2001 
   2002 	/* SpeakerGain */
   2003 	dict_append_entry(&dict, "SpeakerGain",
   2004 				DBUS_TYPE_UINT16,
   2005 				&device->headset->slc->sp_gain);
   2006 
   2007 	/* MicrophoneGain */
   2008 	dict_append_entry(&dict, "MicrophoneGain",
   2009 				DBUS_TYPE_UINT16,
   2010 				&device->headset->slc->mic_gain);
   2011 
   2012 done:
   2013 	dbus_message_iter_close_container(&iter, &dict);
   2014 
   2015 	return reply;
   2016 }
   2017 
   2018 static DBusMessage *hs_set_property(DBusConnection *conn,
   2019 					DBusMessage *msg, void *data)
   2020 {
   2021 	const char *property;
   2022 	DBusMessageIter iter;
   2023 	DBusMessageIter sub;
   2024 	uint16_t gain;
   2025 
   2026 	if (!dbus_message_iter_init(msg, &iter))
   2027 		return invalid_args(msg);
   2028 
   2029 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
   2030 		return invalid_args(msg);
   2031 
   2032 	dbus_message_iter_get_basic(&iter, &property);
   2033 	dbus_message_iter_next(&iter);
   2034 
   2035 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
   2036 		return invalid_args(msg);
   2037 	dbus_message_iter_recurse(&iter, &sub);
   2038 
   2039 	if (g_str_equal("SpeakerGain", property)) {
   2040 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT16)
   2041 			return invalid_args(msg);
   2042 
   2043 		dbus_message_iter_get_basic(&sub, &gain);
   2044 		return hs_set_gain(conn, msg, data, gain,
   2045 					HEADSET_GAIN_SPEAKER);
   2046 	} else if (g_str_equal("MicrophoneGain", property)) {
   2047 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT16)
   2048 			return invalid_args(msg);
   2049 
   2050 		dbus_message_iter_get_basic(&sub, &gain);
   2051 		return hs_set_gain(conn, msg, data, gain,
   2052 					HEADSET_GAIN_MICROPHONE);
   2053 	}
   2054 
   2055 	return invalid_args(msg);
   2056 }
   2057 static GDBusMethodTable headset_methods[] = {
   2058 	{ "Connect",		"",	"",	hs_connect,
   2059 						G_DBUS_METHOD_FLAG_ASYNC },
   2060 	{ "Disconnect",		"",	"",	hs_disconnect },
   2061 	{ "IsConnected",	"",	"b",	hs_is_connected },
   2062 	{ "IndicateCall",	"",	"",	hs_ring },
   2063 	{ "CancelCall",		"",	"",	hs_cancel_call },
   2064 	{ "Play",		"",	"",	hs_play,
   2065 						G_DBUS_METHOD_FLAG_ASYNC },
   2066 	{ "Stop",		"",	"",	hs_stop },
   2067 	{ "IsPlaying",		"",	"b",	hs_is_playing,
   2068 						G_DBUS_METHOD_FLAG_DEPRECATED },
   2069 	{ "GetSpeakerGain",	"",	"q",	hs_get_speaker_gain,
   2070 						G_DBUS_METHOD_FLAG_DEPRECATED },
   2071 	{ "GetMicrophoneGain",	"",	"q",	hs_get_mic_gain,
   2072 						G_DBUS_METHOD_FLAG_DEPRECATED },
   2073 	{ "SetSpeakerGain",	"q",	"",	hs_set_speaker_gain,
   2074 						G_DBUS_METHOD_FLAG_DEPRECATED },
   2075 	{ "SetMicrophoneGain",	"q",	"",	hs_set_mic_gain,
   2076 						G_DBUS_METHOD_FLAG_DEPRECATED },
   2077 	{ "GetProperties",	"",	"a{sv}",hs_get_properties },
   2078 	{ "SetProperty",	"sv",	"",	hs_set_property },
   2079 	{ NULL, NULL, NULL, NULL }
   2080 };
   2081 
   2082 static GDBusSignalTable headset_signals[] = {
   2083 	{ "Connected",			"",	G_DBUS_SIGNAL_FLAG_DEPRECATED },
   2084 	{ "Disconnected",		"",	G_DBUS_SIGNAL_FLAG_DEPRECATED },
   2085 	{ "AnswerRequested",		""	},
   2086 	{ "Stopped",			"",	G_DBUS_SIGNAL_FLAG_DEPRECATED },
   2087 	{ "Playing",			"",	G_DBUS_SIGNAL_FLAG_DEPRECATED },
   2088 	{ "SpeakerGainChanged",		"q",	G_DBUS_SIGNAL_FLAG_DEPRECATED },
   2089 	{ "MicrophoneGainChanged",	"q",	G_DBUS_SIGNAL_FLAG_DEPRECATED },
   2090 	{ "CallTerminated",		""	},
   2091 	{ "PropertyChanged",		"sv"	},
   2092 	{ NULL, NULL }
   2093 };
   2094 
   2095 void headset_update(struct audio_device *dev, uint16_t svc,
   2096 			const char *uuidstr)
   2097 {
   2098 	struct headset *headset = dev->headset;
   2099 	const sdp_record_t *record;
   2100 
   2101 	record = btd_device_get_record(dev->btd_dev, uuidstr);
   2102 	if (!record)
   2103 		return;
   2104 
   2105 	switch (svc) {
   2106 	case HANDSFREE_SVCLASS_ID:
   2107 		if (headset->hfp_handle &&
   2108 				(headset->hfp_handle != record->handle)) {
   2109 			error("More than one HFP record found on device");
   2110 			return;
   2111 		}
   2112 
   2113 		headset->hfp_handle = record->handle;
   2114 		break;
   2115 
   2116 	case HEADSET_SVCLASS_ID:
   2117 		if (headset->hsp_handle &&
   2118 				(headset->hsp_handle != record->handle)) {
   2119 			error("More than one HSP record found on device");
   2120 			return;
   2121 		}
   2122 
   2123 		headset->hsp_handle = record->handle;
   2124 
   2125 		/* Ignore this record if we already have access to HFP */
   2126 		if (headset->hfp_handle)
   2127 			return;
   2128 
   2129 		break;
   2130 
   2131 	default:
   2132 		DBG("Invalid record passed to headset_update");
   2133 		return;
   2134 	}
   2135 }
   2136 
   2137 static int headset_close_rfcomm(struct audio_device *dev)
   2138 {
   2139 	struct headset *hs = dev->headset;
   2140 	GIOChannel *rfcomm = hs->tmp_rfcomm ? hs->tmp_rfcomm : hs->rfcomm;
   2141 
   2142 	if (rfcomm) {
   2143 		g_io_channel_shutdown(rfcomm, TRUE, NULL);
   2144 		g_io_channel_unref(rfcomm);
   2145 		hs->tmp_rfcomm = NULL;
   2146 		hs->rfcomm = NULL;
   2147 	}
   2148 
   2149 	g_free(hs->slc);
   2150 	hs->slc = NULL;
   2151 
   2152 	return 0;
   2153 }
   2154 
   2155 static void headset_free(struct audio_device *dev)
   2156 {
   2157 	struct headset *hs = dev->headset;
   2158 
   2159 	if (hs->dc_timer) {
   2160 		g_source_remove(hs->dc_timer);
   2161 		hs->dc_timer = 0;
   2162 	}
   2163 
   2164 	if (hs->dc_id)
   2165 		device_remove_disconnect_watch(dev->btd_dev, hs->dc_id);
   2166 
   2167 	close_sco(dev);
   2168 
   2169 	headset_close_rfcomm(dev);
   2170 
   2171 	g_free(hs);
   2172 	dev->headset = NULL;
   2173 }
   2174 
   2175 static void path_unregister(void *data)
   2176 {
   2177 	struct audio_device *dev = data;
   2178 	struct headset *hs = dev->headset;
   2179 
   2180 	if (hs->state > HEADSET_STATE_DISCONNECTED) {
   2181 		DBG("Headset unregistered while device was connected!");
   2182 		headset_shutdown(dev);
   2183 	}
   2184 
   2185 	DBG("Unregistered interface %s on path %s",
   2186 		AUDIO_HEADSET_INTERFACE, dev->path);
   2187 
   2188 	headset_free(dev);
   2189 }
   2190 
   2191 void headset_unregister(struct audio_device *dev)
   2192 {
   2193 	g_dbus_unregister_interface(dev->conn, dev->path,
   2194 		AUDIO_HEADSET_INTERFACE);
   2195 }
   2196 
   2197 struct headset *headset_init(struct audio_device *dev, uint16_t svc,
   2198 				const char *uuidstr)
   2199 {
   2200 	struct headset *hs;
   2201 	const sdp_record_t *record;
   2202 
   2203 	hs = g_new0(struct headset, 1);
   2204 	hs->rfcomm_ch = -1;
   2205 	hs->search_hfp = server_is_enabled(&dev->src, HANDSFREE_SVCLASS_ID);
   2206 
   2207 	record = btd_device_get_record(dev->btd_dev, uuidstr);
   2208 	if (!record)
   2209 		goto register_iface;
   2210 
   2211 	switch (svc) {
   2212 	case HANDSFREE_SVCLASS_ID:
   2213 		hs->hfp_handle = record->handle;
   2214 		break;
   2215 
   2216 	case HEADSET_SVCLASS_ID:
   2217 		hs->hsp_handle = record->handle;
   2218 		break;
   2219 
   2220 	default:
   2221 		DBG("Invalid record passed to headset_init");
   2222 		g_free(hs);
   2223 		return NULL;
   2224 	}
   2225 
   2226 register_iface:
   2227 	if (!g_dbus_register_interface(dev->conn, dev->path,
   2228 					AUDIO_HEADSET_INTERFACE,
   2229 					headset_methods, headset_signals, NULL,
   2230 					dev, path_unregister)) {
   2231 		g_free(hs);
   2232 		return NULL;
   2233 	}
   2234 
   2235 	DBG("Registered interface %s on path %s",
   2236 		AUDIO_HEADSET_INTERFACE, dev->path);
   2237 
   2238 	return hs;
   2239 }
   2240 
   2241 uint32_t headset_config_init(GKeyFile *config)
   2242 {
   2243 	GError *err = NULL;
   2244 	char *str;
   2245 
   2246 	/* Use the default values if there is no config file */
   2247 	if (config == NULL)
   2248 		return ag.features;
   2249 
   2250 	str = g_key_file_get_string(config, "General", "SCORouting",
   2251 					&err);
   2252 	if (err) {
   2253 		DBG("audio.conf: %s", err->message);
   2254 		g_clear_error(&err);
   2255 	} else {
   2256 		if (strcmp(str, "PCM") == 0)
   2257 			sco_hci = FALSE;
   2258 		else if (strcmp(str, "HCI") == 0)
   2259 			sco_hci = TRUE;
   2260 		else
   2261 			error("Invalid Headset Routing value: %s", str);
   2262 		g_free(str);
   2263 	}
   2264 
   2265 	return ag.features;
   2266 }
   2267 
   2268 static gboolean hs_dc_timeout(struct audio_device *dev)
   2269 {
   2270 	headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
   2271 	return FALSE;
   2272 }
   2273 
   2274 gboolean headset_cancel_stream(struct audio_device *dev, unsigned int id)
   2275 {
   2276 	struct headset *hs = dev->headset;
   2277 	struct pending_connect *p = hs->pending;
   2278 	GSList *l;
   2279 	struct connect_cb *cb = NULL;
   2280 
   2281 	if (!p)
   2282 		return FALSE;
   2283 
   2284 	for (l = p->callbacks; l != NULL; l = l->next) {
   2285 		struct connect_cb *tmp = l->data;
   2286 
   2287 		if (tmp->id == id) {
   2288 			cb = tmp;
   2289 			break;
   2290 		}
   2291 	}
   2292 
   2293 	if (!cb)
   2294 		return FALSE;
   2295 
   2296 	p->callbacks = g_slist_remove(p->callbacks, cb);
   2297 	g_free(cb);
   2298 
   2299 	if (p->callbacks || p->msg)
   2300 		return TRUE;
   2301 
   2302 	if (hs->auto_dc) {
   2303 		if (hs->rfcomm)
   2304 			hs->dc_timer = g_timeout_add_seconds(DC_TIMEOUT,
   2305 						(GSourceFunc) hs_dc_timeout,
   2306 						dev);
   2307 		else
   2308 			headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
   2309 	}
   2310 
   2311 	return TRUE;
   2312 }
   2313 
   2314 static gboolean dummy_connect_complete(struct audio_device *dev)
   2315 {
   2316 	pending_connect_finalize(dev);
   2317 	return FALSE;
   2318 }
   2319 
   2320 unsigned int headset_request_stream(struct audio_device *dev,
   2321 					headset_stream_cb_t cb,
   2322 					void *user_data)
   2323 {
   2324 	struct headset *hs = dev->headset;
   2325 	unsigned int id;
   2326 
   2327 	if (hs->state == HEADSET_STATE_PLAYING) {
   2328 		id = connect_cb_new(hs, HEADSET_STATE_PLAYING, cb, user_data);
   2329 		g_idle_add((GSourceFunc) dummy_connect_complete, dev);
   2330 		return id;
   2331 	}
   2332 
   2333 	if (hs->dc_timer) {
   2334 		g_source_remove(hs->dc_timer);
   2335 		hs->dc_timer = 0;
   2336 	}
   2337 
   2338 	if (hs->state == HEADSET_STATE_CONNECTING ||
   2339 			hs->state == HEADSET_STATE_PLAY_IN_PROGRESS)
   2340 		return connect_cb_new(hs, HEADSET_STATE_PLAYING, cb, user_data);
   2341 
   2342 	if (hs->rfcomm == NULL) {
   2343 		if (rfcomm_connect(dev, cb, user_data, &id) < 0)
   2344 			return 0;
   2345 		hs->auto_dc = TRUE;
   2346 	} else if (sco_connect(dev, cb, user_data, &id) < 0)
   2347 		return 0;
   2348 
   2349 	hs->pending->target_state = HEADSET_STATE_PLAYING;
   2350 
   2351 	return id;
   2352 }
   2353 
   2354 unsigned int headset_config_stream(struct audio_device *dev,
   2355 					gboolean auto_dc,
   2356 					headset_stream_cb_t cb,
   2357 					void *user_data)
   2358 {
   2359 	struct headset *hs = dev->headset;
   2360 	unsigned int id = 0;
   2361 
   2362 	if (hs->dc_timer) {
   2363 		g_source_remove(hs->dc_timer);
   2364 		hs->dc_timer = 0;
   2365 	}
   2366 
   2367 	if (hs->state == HEADSET_STATE_CONNECTING)
   2368 		return connect_cb_new(hs, HEADSET_STATE_CONNECTED, cb,
   2369 					user_data);
   2370 
   2371 	if (hs->rfcomm)
   2372 		goto done;
   2373 
   2374 	if (rfcomm_connect(dev, cb, user_data, &id) < 0)
   2375 		return 0;
   2376 
   2377 	hs->auto_dc = auto_dc;
   2378 	hs->pending->target_state = HEADSET_STATE_CONNECTED;
   2379 
   2380 	return id;
   2381 
   2382 done:
   2383 	id = connect_cb_new(hs, HEADSET_STATE_CONNECTED, cb, user_data);
   2384 	g_idle_add((GSourceFunc) dummy_connect_complete, dev);
   2385 	return id;
   2386 }
   2387 
   2388 unsigned int headset_suspend_stream(struct audio_device *dev,
   2389 					headset_stream_cb_t cb,
   2390 					void *user_data)
   2391 {
   2392 	struct headset *hs = dev->headset;
   2393 	unsigned int id;
   2394 
   2395 	if (hs->state == HEADSET_STATE_DISCONNECTED ||
   2396 				hs->state == HEADSET_STATE_CONNECTING)
   2397 		return 0;
   2398 
   2399 	if (hs->dc_timer) {
   2400 		g_source_remove(hs->dc_timer);
   2401 		hs->dc_timer = 0;
   2402 	}
   2403 
   2404 	headset_set_state(dev, HEADSET_STATE_CONNECTED);
   2405 
   2406 	id = connect_cb_new(hs, HEADSET_STATE_CONNECTED, cb, user_data);
   2407 	g_idle_add((GSourceFunc) dummy_connect_complete, dev);
   2408 
   2409 	return id;
   2410 }
   2411 
   2412 gboolean get_hfp_active(struct audio_device *dev)
   2413 {
   2414 	struct headset *hs = dev->headset;
   2415 
   2416 	return hs->hfp_active;
   2417 }
   2418 
   2419 void set_hfp_active(struct audio_device *dev, gboolean active)
   2420 {
   2421 	struct headset *hs = dev->headset;
   2422 
   2423 	hs->hfp_active = active;
   2424 }
   2425 
   2426 GIOChannel *headset_get_rfcomm(struct audio_device *dev)
   2427 {
   2428 	struct headset *hs = dev->headset;
   2429 
   2430 	return hs->tmp_rfcomm;
   2431 }
   2432 
   2433 int headset_connect_rfcomm(struct audio_device *dev, GIOChannel *io)
   2434 {
   2435 	struct headset *hs = dev->headset;
   2436 
   2437 	if (hs->tmp_rfcomm)
   2438 		return -EALREADY;
   2439 
   2440 	hs->tmp_rfcomm = g_io_channel_ref(io);
   2441 
   2442 	return 0;
   2443 }
   2444 
   2445 int headset_connect_sco(struct audio_device *dev, GIOChannel *io)
   2446 {
   2447 	struct headset *hs = dev->headset;
   2448 	struct headset_slc *slc = hs->slc;
   2449 
   2450 	if (hs->sco)
   2451 		return -EISCONN;
   2452 
   2453 	hs->sco = g_io_channel_ref(io);
   2454 
   2455 	if (slc->pending_ring) {
   2456 		ring_timer_cb(NULL);
   2457 		ag.ring_timer = g_timeout_add_seconds(RING_INTERVAL,
   2458 						ring_timer_cb,
   2459 						NULL);
   2460 		slc->pending_ring = FALSE;
   2461 	}
   2462 
   2463 	return 0;
   2464 }
   2465 
   2466 static void disconnect_cb(struct btd_device *btd_dev, gboolean removal,
   2467 				void *user_data)
   2468 {
   2469 	struct audio_device *device = user_data;
   2470 
   2471 	info("Headset: disconnect %s", device->path);
   2472 
   2473 	headset_shutdown(device);
   2474 }
   2475 
   2476 void headset_set_state(struct audio_device *dev, headset_state_t state)
   2477 {
   2478 	struct headset *hs = dev->headset;
   2479 	struct headset_slc *slc = hs->slc;
   2480 	gboolean value;
   2481 	const char *state_str;
   2482 	headset_state_t old_state = hs->state;
   2483 	GSList *l;
   2484 
   2485 	if (old_state == state)
   2486 		return;
   2487 
   2488 	state_str = state2str(state);
   2489 
   2490 	switch (state) {
   2491 	case HEADSET_STATE_DISCONNECTED:
   2492 		value = FALSE;
   2493 		close_sco(dev);
   2494 		headset_close_rfcomm(dev);
   2495 		emit_property_changed(dev->conn, dev->path,
   2496 					AUDIO_HEADSET_INTERFACE, "State",
   2497 					DBUS_TYPE_STRING, &state_str);
   2498 		g_dbus_emit_signal(dev->conn, dev->path,
   2499 					AUDIO_HEADSET_INTERFACE,
   2500 					"Disconnected",
   2501 					DBUS_TYPE_INVALID);
   2502 		if (hs->state > HEADSET_STATE_CONNECTING) {
   2503 			emit_property_changed(dev->conn, dev->path,
   2504 					AUDIO_HEADSET_INTERFACE, "Connected",
   2505 					DBUS_TYPE_BOOLEAN, &value);
   2506 			telephony_device_disconnected(dev);
   2507 		}
   2508 		active_devices = g_slist_remove(active_devices, dev);
   2509 		device_remove_disconnect_watch(dev->btd_dev, hs->dc_id);
   2510 		hs->dc_id = 0;
   2511 		break;
   2512 	case HEADSET_STATE_CONNECTING:
   2513 		emit_property_changed(dev->conn, dev->path,
   2514 					AUDIO_HEADSET_INTERFACE, "State",
   2515 					DBUS_TYPE_STRING, &state_str);
   2516 		break;
   2517 	case HEADSET_STATE_CONNECTED:
   2518 		close_sco(dev);
   2519 		if (hs->state != HEADSET_STATE_PLAY_IN_PROGRESS)
   2520 			emit_property_changed(dev->conn, dev->path,
   2521 					AUDIO_HEADSET_INTERFACE, "State",
   2522 					DBUS_TYPE_STRING, &state_str);
   2523 		if (hs->state < state) {
   2524 			if (ag.features & AG_FEATURE_INBAND_RINGTONE)
   2525 				slc->inband_ring = TRUE;
   2526 			else
   2527 				slc->inband_ring = FALSE;
   2528 			g_dbus_emit_signal(dev->conn, dev->path,
   2529 						AUDIO_HEADSET_INTERFACE,
   2530 						"Connected",
   2531 						DBUS_TYPE_INVALID);
   2532 			value = TRUE;
   2533 			emit_property_changed(dev->conn, dev->path,
   2534 						AUDIO_HEADSET_INTERFACE,
   2535 						"Connected",
   2536 						DBUS_TYPE_BOOLEAN, &value);
   2537 			active_devices = g_slist_append(active_devices, dev);
   2538 			telephony_device_connected(dev);
   2539 			hs->dc_id = device_add_disconnect_watch(dev->btd_dev,
   2540 								disconnect_cb,
   2541 								dev, NULL);
   2542 		} else if (hs->state == HEADSET_STATE_PLAYING) {
   2543 			value = FALSE;
   2544 			g_dbus_emit_signal(dev->conn, dev->path,
   2545 						AUDIO_HEADSET_INTERFACE,
   2546 						"Stopped",
   2547 						DBUS_TYPE_INVALID);
   2548 			emit_property_changed(dev->conn, dev->path,
   2549 						AUDIO_HEADSET_INTERFACE,
   2550 						"Playing",
   2551 						DBUS_TYPE_BOOLEAN, &value);
   2552 		}
   2553 		break;
   2554 	case HEADSET_STATE_PLAY_IN_PROGRESS:
   2555 		break;
   2556 	case HEADSET_STATE_PLAYING:
   2557 		value = TRUE;
   2558 		emit_property_changed(dev->conn, dev->path,
   2559 					AUDIO_HEADSET_INTERFACE, "State",
   2560 					DBUS_TYPE_STRING, &state_str);
   2561 		hs->sco_id = g_io_add_watch(hs->sco,
   2562 					G_IO_ERR | G_IO_HUP | G_IO_NVAL,
   2563 					(GIOFunc) sco_cb, dev);
   2564 
   2565 		g_dbus_emit_signal(dev->conn, dev->path,
   2566 					AUDIO_HEADSET_INTERFACE, "Playing",
   2567 					DBUS_TYPE_INVALID);
   2568 		emit_property_changed(dev->conn, dev->path,
   2569 					AUDIO_HEADSET_INTERFACE, "Playing",
   2570 					DBUS_TYPE_BOOLEAN, &value);
   2571 
   2572 		if (slc->sp_gain >= 0)
   2573 			headset_send(hs, "\r\n+VGS=%u\r\n", slc->sp_gain);
   2574 		if (slc->mic_gain >= 0)
   2575 			headset_send(hs, "\r\n+VGM=%u\r\n", slc->mic_gain);
   2576 		break;
   2577 	}
   2578 
   2579 	hs->state = state;
   2580 
   2581 	DBG("State changed %s: %s -> %s", dev->path, str_state[old_state],
   2582 		str_state[state]);
   2583 
   2584 	for (l = headset_callbacks; l != NULL; l = l->next) {
   2585 		struct headset_state_callback *cb = l->data;
   2586 		cb->cb(dev, old_state, state, cb->user_data);
   2587 	}
   2588 }
   2589 
   2590 headset_state_t headset_get_state(struct audio_device *dev)
   2591 {
   2592 	struct headset *hs = dev->headset;
   2593 
   2594 	return hs->state;
   2595 }
   2596 
   2597 int headset_get_channel(struct audio_device *dev)
   2598 {
   2599 	struct headset *hs = dev->headset;
   2600 
   2601 	return hs->rfcomm_ch;
   2602 }
   2603 
   2604 gboolean headset_is_active(struct audio_device *dev)
   2605 {
   2606 	struct headset *hs = dev->headset;
   2607 
   2608 	if (hs->state != HEADSET_STATE_DISCONNECTED)
   2609 		return TRUE;
   2610 
   2611 	return FALSE;
   2612 }
   2613 
   2614 headset_lock_t headset_get_lock(struct audio_device *dev)
   2615 {
   2616 	struct headset *hs = dev->headset;
   2617 
   2618 	return hs->lock;
   2619 }
   2620 
   2621 gboolean headset_lock(struct audio_device *dev, headset_lock_t lock)
   2622 {
   2623 	struct headset *hs = dev->headset;
   2624 
   2625 	if (hs->lock & lock)
   2626 		return FALSE;
   2627 
   2628 	hs->lock |= lock;
   2629 
   2630 	return TRUE;
   2631 }
   2632 
   2633 gboolean headset_unlock(struct audio_device *dev, headset_lock_t lock)
   2634 {
   2635 	struct headset *hs = dev->headset;
   2636 
   2637 	if (!(hs->lock & lock))
   2638 		return FALSE;
   2639 
   2640 	hs->lock &= ~lock;
   2641 
   2642 	if (hs->lock)
   2643 		return TRUE;
   2644 
   2645 	if (hs->state == HEADSET_STATE_PLAYING)
   2646 		headset_set_state(dev, HEADSET_STATE_CONNECTED);
   2647 
   2648 	if (hs->auto_dc) {
   2649 		if (hs->state == HEADSET_STATE_CONNECTED)
   2650 			hs->dc_timer = g_timeout_add_seconds(DC_TIMEOUT,
   2651 						(GSourceFunc) hs_dc_timeout,
   2652 						dev);
   2653 		else
   2654 			headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
   2655 	}
   2656 
   2657 	return TRUE;
   2658 }
   2659 
   2660 gboolean headset_suspend(struct audio_device *dev, void *data)
   2661 {
   2662 	return TRUE;
   2663 }
   2664 
   2665 gboolean headset_play(struct audio_device *dev, void *data)
   2666 {
   2667 	return TRUE;
   2668 }
   2669 
   2670 int headset_get_sco_fd(struct audio_device *dev)
   2671 {
   2672 	struct headset *hs = dev->headset;
   2673 
   2674 	if (!hs->sco)
   2675 		return -1;
   2676 
   2677 	return g_io_channel_unix_get_fd(hs->sco);
   2678 }
   2679 
   2680 gboolean headset_get_nrec(struct audio_device *dev)
   2681 {
   2682 	struct headset *hs = dev->headset;
   2683 
   2684 	if (!hs->slc)
   2685 		return TRUE;
   2686 
   2687 	return hs->slc->nrec;
   2688 }
   2689 
   2690 gboolean headset_get_sco_hci(struct audio_device *dev)
   2691 {
   2692 	return sco_hci;
   2693 }
   2694 
   2695 void headset_shutdown(struct audio_device *dev)
   2696 {
   2697 	struct pending_connect *p = dev->headset->pending;
   2698 
   2699 	if (p && p->msg)
   2700 		error_connection_attempt_failed(dev->conn, p->msg, ECANCELED);
   2701 
   2702 	pending_connect_finalize(dev);
   2703 	headset_set_state(dev, HEADSET_STATE_DISCONNECTED);
   2704 }
   2705 
   2706 int telephony_event_ind(int index)
   2707 {
   2708 	if (!active_devices)
   2709 		return -ENODEV;
   2710 
   2711 	if (!ag.er_ind) {
   2712 		DBG("telephony_report_event called but events are disabled");
   2713 		return -EINVAL;
   2714 	}
   2715 
   2716 	send_foreach_headset(active_devices, hfp_cmp,
   2717 				"\r\n+CIEV: %d,%d\r\n", index + 1,
   2718 				ag.indicators[index].val);
   2719 
   2720 	return 0;
   2721 }
   2722 
   2723 int telephony_response_and_hold_ind(int rh)
   2724 {
   2725 	if (!active_devices)
   2726 		return -ENODEV;
   2727 
   2728 	ag.rh = rh;
   2729 
   2730 	/* If we aren't in any response and hold state don't send anything */
   2731 	if (ag.rh < 0)
   2732 		return 0;
   2733 
   2734 	send_foreach_headset(active_devices, hfp_cmp, "\r\n+BTRH: %d\r\n",
   2735 				ag.rh);
   2736 
   2737 	return 0;
   2738 }
   2739 
   2740 int telephony_incoming_call_ind(const char *number, int type)
   2741 {
   2742 	struct audio_device *dev;
   2743 	struct headset *hs;
   2744 	struct headset_slc *slc;
   2745 
   2746 	if (!active_devices)
   2747 		return -ENODEV;
   2748 
   2749 	/* Get the latest connected device */
   2750 	dev = active_devices->data;
   2751 	hs = dev->headset;
   2752 	slc = hs->slc;
   2753 
   2754 	if (ag.ring_timer) {
   2755 		DBG("telephony_incoming_call_ind: already calling");
   2756 		return -EBUSY;
   2757 	}
   2758 
   2759 	/* With HSP 1.2 the RING messages should *not* be sent if inband
   2760 	 * ringtone is being used */
   2761 	if (!hs->hfp_active && slc->inband_ring)
   2762 		return 0;
   2763 
   2764 	g_free(ag.number);
   2765 	ag.number = g_strdup(number);
   2766 	ag.number_type = type;
   2767 
   2768 	if (slc->inband_ring && hs->hfp_active &&
   2769 					hs->state != HEADSET_STATE_PLAYING) {
   2770 		slc->pending_ring = TRUE;
   2771 		return 0;
   2772 	}
   2773 
   2774 	ring_timer_cb(NULL);
   2775 	ag.ring_timer = g_timeout_add_seconds(RING_INTERVAL, ring_timer_cb,
   2776 						NULL);
   2777 
   2778 	return 0;
   2779 }
   2780 
   2781 int telephony_calling_stopped_ind(void)
   2782 {
   2783 	struct audio_device *dev;
   2784 
   2785 	if (ag.ring_timer) {
   2786 		g_source_remove(ag.ring_timer);
   2787 		ag.ring_timer = 0;
   2788 	}
   2789 
   2790 	if (!active_devices)
   2791 		return 0;
   2792 
   2793 	/* In case SCO isn't fully up yet */
   2794 	dev = active_devices->data;
   2795 
   2796 	if (!dev->headset->slc->pending_ring && !ag.ring_timer)
   2797 		return -EINVAL;
   2798 
   2799 	dev->headset->slc->pending_ring = FALSE;
   2800 
   2801 	return 0;
   2802 }
   2803 
   2804 int telephony_ready_ind(uint32_t features,
   2805 			const struct indicator *indicators, int rh,
   2806 			const char *chld)
   2807 {
   2808 	ag.telephony_ready = TRUE;
   2809 	ag.features = features;
   2810 	ag.indicators = indicators;
   2811 	ag.rh = rh;
   2812 	ag.chld = g_strdup(chld);
   2813 
   2814 	DBG("Telephony plugin initialized");
   2815 
   2816 	print_ag_features(ag.features);
   2817 
   2818 	return 0;
   2819 }
   2820 
   2821 int telephony_list_current_call_ind(int idx, int dir, int status, int mode,
   2822 					int mprty, const char *number,
   2823 					int type)
   2824 {
   2825 	if (!active_devices)
   2826 		return -ENODEV;
   2827 
   2828 	if (number && strlen(number) > 0)
   2829 		send_foreach_headset(active_devices, hfp_cmp,
   2830 				"\r\n+CLCC: %d,%d,%d,%d,%d,\"%s\",%d\r\n",
   2831 				idx, dir, status, mode, mprty, number, type);
   2832 	else
   2833 		send_foreach_headset(active_devices, hfp_cmp,
   2834 					"\r\n+CLCC: %d,%d,%d,%d,%d\r\n",
   2835 					idx, dir, status, mode, mprty);
   2836 
   2837 	return 0;
   2838 }
   2839 
   2840 int telephony_subscriber_number_ind(const char *number, int type, int service)
   2841 {
   2842 	if (!active_devices)
   2843 		return -ENODEV;
   2844 
   2845 	send_foreach_headset(active_devices, hfp_cmp,
   2846 				"\r\n+CNUM: ,%s,%d,,%d\r\n",
   2847 				number, type, service);
   2848 
   2849 	return 0;
   2850 }
   2851 
   2852 static int cwa_cmp(struct headset *hs)
   2853 {
   2854 	if (!hs->hfp_active)
   2855 		return -1;
   2856 
   2857 	if (hs->slc->cwa_enabled)
   2858 		return 0;
   2859 	else
   2860 		return -1;
   2861 }
   2862 
   2863 int telephony_call_waiting_ind(const char *number, int type)
   2864 {
   2865 	if (!active_devices)
   2866 		return -ENODEV;
   2867 
   2868 	send_foreach_headset(active_devices, cwa_cmp,
   2869 				"\r\n+CCWA: \"%s\",%d\r\n",
   2870 				number, type);
   2871 
   2872 	return 0;
   2873 }
   2874 
   2875 unsigned int headset_add_state_cb(headset_state_cb cb, void *user_data)
   2876 {
   2877 	struct headset_state_callback *state_cb;
   2878 	static unsigned int id = 0;
   2879 
   2880 	state_cb = g_new(struct headset_state_callback, 1);
   2881 	state_cb->cb = cb;
   2882 	state_cb->user_data = user_data;
   2883 	state_cb->id = ++id;
   2884 
   2885 	headset_callbacks = g_slist_append(headset_callbacks, state_cb);
   2886 
   2887 	return state_cb->id;
   2888 }
   2889 
   2890 gboolean headset_remove_state_cb(unsigned int id)
   2891 {
   2892 	GSList *l;
   2893 
   2894 	for (l = headset_callbacks; l != NULL; l = l->next) {
   2895 		struct headset_state_callback *cb = l->data;
   2896 		if (cb && cb->id == id) {
   2897 			headset_callbacks = g_slist_remove(headset_callbacks, cb);
   2898 			g_free(cb);
   2899 			return TRUE;
   2900 		}
   2901 	}
   2902 
   2903 	return FALSE;
   2904 }
   2905