1 /* Spa V4l2 dbus
2  *
3  * Copyright © 2018 Wim Taymans
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  */
24 
25 #include <errno.h>
26 #include <stddef.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <fcntl.h>
33 
34 #include <bluetooth/bluetooth.h>
35 
36 #include <dbus/dbus.h>
37 
38 #include <spa/support/log.h>
39 #include <spa/support/loop.h>
40 #include <spa/support/dbus.h>
41 #include <spa/support/plugin.h>
42 #include <spa/support/plugin-loader.h>
43 #include <spa/monitor/device.h>
44 #include <spa/monitor/utils.h>
45 #include <spa/utils/hook.h>
46 #include <spa/utils/type.h>
47 #include <spa/utils/keys.h>
48 #include <spa/utils/names.h>
49 #include <spa/utils/result.h>
50 #include <spa/utils/string.h>
51 #include <spa/utils/json.h>
52 
53 #include "codec-loader.h"
54 #include "player.h"
55 #include "defs.h"
56 
57 static struct spa_log_topic log_topic = SPA_LOG_TOPIC(0, "spa.bluez5");
58 #undef SPA_LOG_TOPIC_DEFAULT
59 #define SPA_LOG_TOPIC_DEFAULT &log_topic
60 
61 enum backend_selection {
62 	BACKEND_NONE = -2,
63 	BACKEND_ANY = -1,
64 	BACKEND_HSPHFPD = 0,
65 	BACKEND_OFONO = 1,
66 	BACKEND_NATIVE = 2,
67 	BACKEND_NUM,
68 };
69 
70 /*
71  * Rate limit for BlueZ SetConfiguration calls.
72  *
73  * Too rapid calls to BlueZ API may cause A2DP profile to disappear, as the
74  * internal BlueZ/connection state gets confused. Use some reasonable minimum
75  * interval.
76  *
77  * AVDTP v1.3 Sec. 6.13 mentions 3 seconds as a reasonable timeout in one case
78  * (ACP connection reset timeout, if no INT response). The case here is
79  * different, but we assume a similar value is fine here.
80  */
81 #define BLUEZ_ACTION_RATE_MSEC	3000
82 
83 #define CODEC_SWITCH_RETRIES	1
84 
85 
86 struct spa_bt_monitor {
87 	struct spa_handle handle;
88 	struct spa_device device;
89 
90 	struct spa_log *log;
91 	struct spa_loop *main_loop;
92 	struct spa_system *main_system;
93 	struct spa_plugin_loader *plugin_loader;
94 	struct spa_dbus *dbus;
95 	struct spa_dbus_connection *dbus_connection;
96 	DBusConnection *conn;
97 
98 	struct spa_hook_list hooks;
99 
100 	uint32_t id;
101 
102 	const struct a2dp_codec * const * a2dp_codecs;
103 
104 	/*
105 	 * Lists of BlueZ objects, kept up-to-date by following DBus events
106 	 * initiated by BlueZ. Object lifetime is also determined by that.
107 	 */
108 	struct spa_list adapter_list;
109 	struct spa_list device_list;
110 	struct spa_list remote_endpoint_list;
111 	struct spa_list transport_list;
112 
113 	unsigned int filters_added:1;
114 	unsigned int objects_listed:1;
115 
116 	struct spa_bt_backend *backend;
117 	struct spa_bt_backend *backends[BACKEND_NUM];
118 	enum backend_selection backend_selection;
119 
120 	struct spa_dict enabled_codecs;
121 
122 	unsigned int connection_info_supported:1;
123 	unsigned int dummy_avrcp_player:1;
124 
125 	struct spa_bt_quirks *quirks;
126 
127 	/* A reference audio info for A2DP codec configuration. */
128 	struct a2dp_codec_audio_info default_audio_info;
129 };
130 
131 /* Stream endpoints owned by BlueZ for each device */
132 struct spa_bt_remote_endpoint {
133 	struct spa_list link;
134 	struct spa_list device_link;
135 	struct spa_bt_monitor *monitor;
136 	char *path;
137 
138 	char *uuid;
139 	unsigned int codec;
140 	struct spa_bt_device *device;
141 	uint8_t *capabilities;
142 	int capabilities_len;
143 	bool delay_reporting;
144 };
145 
146 /*
147  * Codec switching tries various codec/remote endpoint combinations
148  * in order, until an acceptable one is found. This triggers BlueZ
149  * to initiate DBus calls that result to the creation of a transport
150  * with the desired capabilities.
151  * The codec switch struct tracks candidates still to be tried.
152  */
153 struct spa_bt_a2dp_codec_switch {
154 	struct spa_bt_device *device;
155 	struct spa_list device_link;
156 
157 	/*
158 	 * Codec switch may be waiting for either DBus reply from BlueZ
159 	 * or a timeout (but not both).
160 	 */
161 	struct spa_source timer;
162 	DBusPendingCall *pending;
163 
164 	uint32_t profile;
165 
166 	/*
167 	 * Called asynchronously, so endpoint paths instead of pointers (which may be
168 	 * invalidated in the meantime).
169 	 */
170 	const struct a2dp_codec **codecs;
171 	char **paths;
172 
173 	const struct a2dp_codec **codec_iter;	/**< outer iterator over codecs */
174 	char **path_iter;			/**< inner iterator over endpoint paths */
175 
176 	uint16_t retries;
177 	size_t num_paths;
178 };
179 
180 #define DEFAULT_RECONNECT_PROFILES SPA_BT_PROFILE_NULL
181 #define DEFAULT_HW_VOLUME_PROFILES (SPA_BT_PROFILE_HEADSET_AUDIO_GATEWAY | SPA_BT_PROFILE_HEADSET_HEAD_UNIT | \
182 					SPA_BT_PROFILE_A2DP_SOURCE | SPA_BT_PROFILE_A2DP_SINK)
183 
184 #define BT_DEVICE_DISCONNECTED	0
185 #define BT_DEVICE_CONNECTED	1
186 #define BT_DEVICE_INIT		-1
187 
188 /*
189  * SCO socket connect may fail with ECONNABORTED if it is done too soon after
190  * previous close. To avoid this in cases where nodes are toggled between
191  * stopped/started rapidly, postpone release until the transport has remained
192  * unused for a time. Since this appears common to multiple SCO backends, we do
193  * it for all SCO backends here.
194  */
195 #define SCO_TRANSPORT_RELEASE_TIMEOUT_MSEC 1000
196 #define SPA_BT_TRANSPORT_IS_SCO(transport) (transport->backend != NULL)
197 
198 #define TRANSPORT_VOLUME_TIMEOUT_MSEC 200
199 
200 static int spa_bt_transport_stop_volume_timer(struct spa_bt_transport *transport);
201 static int spa_bt_transport_start_volume_timer(struct spa_bt_transport *transport);
202 static int spa_bt_transport_stop_release_timer(struct spa_bt_transport *transport);
203 static int spa_bt_transport_start_release_timer(struct spa_bt_transport *transport);
204 
205 static int device_start_timer(struct spa_bt_device *device);
206 static int device_stop_timer(struct spa_bt_device *device);
207 
208 // Working with BlueZ Battery Provider.
209 // Developed using https://github.com/dgreid/adhd/commit/655b58f as an example of DBus calls.
210 
211 // Name of battery, formatted as /org/freedesktop/pipewire/battery/org/bluez/hciX/dev_XX_XX_XX_XX_XX_XX
battery_get_name(const char * device_path)212 static char *battery_get_name(const char *device_path)
213 {
214 	char *path = malloc(strlen(PIPEWIRE_BATTERY_PROVIDER) + strlen(device_path) + 1);
215 	sprintf(path, PIPEWIRE_BATTERY_PROVIDER "%s", device_path);
216 	return path;
217 }
218 
219 // Unregister virtual battery of device
battery_remove(struct spa_bt_device * device)220 static void battery_remove(struct spa_bt_device *device) {
221 	DBusMessageIter i, entry;
222 	DBusMessage *m;
223 	const char *interface;
224 
225 	if (device->battery_pending_call) {
226 		spa_log_debug(device->monitor->log, "Cancelling and freeing pending battery provider register call");
227 		dbus_pending_call_cancel(device->battery_pending_call);
228 		dbus_pending_call_unref(device->battery_pending_call);
229 		device->battery_pending_call = NULL;
230 	}
231 
232 	if (!device->adapter->has_battery_provider || !device->has_battery)
233 		return;
234 
235 	spa_log_debug(device->monitor->log, "Removing virtual battery: %s", device->battery_path);
236 
237 	m = dbus_message_new_signal(PIPEWIRE_BATTERY_PROVIDER,
238 				      DBUS_INTERFACE_OBJECT_MANAGER,
239 				      DBUS_SIGNAL_INTERFACES_REMOVED);
240 
241 
242 	dbus_message_iter_init_append(m, &i);
243 	dbus_message_iter_append_basic(&i, DBUS_TYPE_OBJECT_PATH,
244 				       &device->battery_path);
245 	dbus_message_iter_open_container(&i, DBUS_TYPE_ARRAY,
246 					 DBUS_TYPE_STRING_AS_STRING, &entry);
247 	interface = BLUEZ_INTERFACE_BATTERY_PROVIDER;
248 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
249 				       &interface);
250 	dbus_message_iter_close_container(&i, &entry);
251 
252 	if (!dbus_connection_send(device->monitor->conn, m, NULL)) {
253 		spa_log_error(device->monitor->log, "sending " DBUS_SIGNAL_INTERFACES_REMOVED " failed");
254 	}
255 
256 	dbus_message_unref(m);
257 
258 	device->has_battery = false;
259 }
260 
261 // Create properties for Battery Provider request
battery_write_properties(DBusMessageIter * iter,struct spa_bt_device * device)262 static void battery_write_properties(DBusMessageIter *iter, struct spa_bt_device *device)
263 {
264 	DBusMessageIter dict, entry, variant;
265 
266 	dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "{sv}", &dict);
267 
268 	dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY, NULL,
269 					 &entry);
270 	const char *prop_percentage = "Percentage";
271 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &prop_percentage);
272 	dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
273 					 DBUS_TYPE_BYTE_AS_STRING, &variant);
274 	dbus_message_iter_append_basic(&variant, DBUS_TYPE_BYTE, &device->battery);
275 	dbus_message_iter_close_container(&entry, &variant);
276 	dbus_message_iter_close_container(&dict, &entry);
277 
278 	dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY, NULL, &entry);
279 	const char *prop_device = "Device";
280 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &prop_device);
281 	dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
282 					 DBUS_TYPE_OBJECT_PATH_AS_STRING,
283 					 &variant);
284 	dbus_message_iter_append_basic(&variant, DBUS_TYPE_OBJECT_PATH, &device->path);
285 	dbus_message_iter_close_container(&entry, &variant);
286 	dbus_message_iter_close_container(&dict, &entry);
287 
288 	dbus_message_iter_close_container(iter, &dict);
289 }
290 
291 // Send current percentage to BlueZ
battery_update(struct spa_bt_device * device)292 static void battery_update(struct spa_bt_device *device)
293 {
294 	spa_log_debug(device->monitor->log, "updating battery: %s", device->battery_path);
295 
296 	DBusMessage *msg;
297 	DBusMessageIter iter;
298 
299 	msg = dbus_message_new_signal(device->battery_path,
300 				      DBUS_INTERFACE_PROPERTIES,
301 				      DBUS_SIGNAL_PROPERTIES_CHANGED);
302 
303 	dbus_message_iter_init_append(msg, &iter);
304 	const char *interface = BLUEZ_INTERFACE_BATTERY_PROVIDER;
305 	dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
306 				       &interface);
307 
308 	battery_write_properties(&iter, device);
309 
310 	if (!dbus_connection_send(device->monitor->conn, msg, NULL))
311 		spa_log_error(device->monitor->log, "Error updating battery");
312 
313 	dbus_message_unref(msg);
314 }
315 
316 // Create new virtual battery with value stored in current device object
battery_create(struct spa_bt_device * device)317 static void battery_create(struct spa_bt_device *device) {
318 	DBusMessage *msg;
319 	DBusMessageIter iter, entry, dict;
320 	msg = dbus_message_new_signal(PIPEWIRE_BATTERY_PROVIDER,
321 				      DBUS_INTERFACE_OBJECT_MANAGER,
322 				      DBUS_SIGNAL_INTERFACES_ADDED);
323 
324 	dbus_message_iter_init_append(msg, &iter);
325 	dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH,
326 				       &device->battery_path);
327 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sa{sv}}", &dict);
328 	dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY, NULL, &entry);
329 	const char *interface = BLUEZ_INTERFACE_BATTERY_PROVIDER;
330 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
331 				       &interface);
332 
333 	battery_write_properties(&entry, device);
334 
335 	dbus_message_iter_close_container(&dict, &entry);
336 	dbus_message_iter_close_container(&iter, &dict);
337 
338 	if (!dbus_connection_send(device->monitor->conn, msg, NULL)) {
339 		spa_log_error(device->monitor->log, "Failed to create virtual battery for %s", device->address);
340 		return;
341 	}
342 
343 	dbus_message_unref(msg);
344 
345 	spa_log_debug(device->monitor->log, "Created virtual battery for %s", device->address);
346 	device->has_battery = true;
347 }
348 
on_battery_provider_registered(DBusPendingCall * pending_call,void * data)349 static void on_battery_provider_registered(DBusPendingCall *pending_call,
350 				       void *data)
351 {
352 	DBusMessage *reply;
353 	struct spa_bt_device *device = data;
354 
355 	reply = dbus_pending_call_steal_reply(pending_call);
356 	dbus_pending_call_unref(pending_call);
357 
358 	device->battery_pending_call = NULL;
359 
360 	if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
361 		spa_log_error(device->monitor->log, "Failed to register battery provider. Error: %s", dbus_message_get_error_name(reply));
362 		spa_log_error(device->monitor->log, "BlueZ Battery Provider is not available, won't retry to register it. Make sure you are running BlueZ 5.56+ with experimental features to use Battery Provider.");
363 		device->adapter->battery_provider_unavailable = true;
364 		dbus_message_unref(reply);
365 		return;
366 	}
367 
368 	spa_log_debug(device->monitor->log, "Registered Battery Provider");
369 
370 	device->adapter->has_battery_provider = true;
371 
372 	if (!device->has_battery)
373 		battery_create(device);
374 
375 	dbus_message_unref(reply);
376 }
377 
378 // Register Battery Provider for adapter and then create virtual battery for device
register_battery_provider(struct spa_bt_device * device)379 static void register_battery_provider(struct spa_bt_device *device)
380 {
381 	DBusMessage *method_call;
382 	DBusMessageIter message_iter;
383 
384 	if (device->battery_pending_call) {
385 		spa_log_debug(device->monitor->log, "Already registering battery provider");
386 		return;
387 	}
388 
389 	method_call = dbus_message_new_method_call(
390 		BLUEZ_SERVICE, device->adapter_path,
391 		BLUEZ_INTERFACE_BATTERY_PROVIDER_MANAGER,
392 		"RegisterBatteryProvider");
393 
394 	if (!method_call) {
395 		spa_log_error(device->monitor->log, "Failed to register battery provider");
396 		return;
397 	}
398 
399 	dbus_message_iter_init_append(method_call, &message_iter);
400 	const char *object_path = PIPEWIRE_BATTERY_PROVIDER;
401 	dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_OBJECT_PATH,
402 				       &object_path);
403 
404 	if (!dbus_connection_send_with_reply(device->monitor->conn, method_call, &device->battery_pending_call,
405 					     DBUS_TIMEOUT_USE_DEFAULT)) {
406 		dbus_message_unref(method_call);
407 		spa_log_error(device->monitor->log, "Failed to register battery provider");
408 		return;
409 	}
410 
411 	dbus_message_unref(method_call);
412 
413 	if (!device->battery_pending_call) {
414 		spa_log_error(device->monitor->log, "Failed to register battery provider");
415 		return;
416 	}
417 
418 	if (!dbus_pending_call_set_notify(
419 		    device->battery_pending_call, on_battery_provider_registered,
420 		    device, NULL)) {
421 		spa_log_error(device->monitor->log, "Failed to register battery provider");
422 		dbus_pending_call_cancel(device->battery_pending_call);
423 		dbus_pending_call_unref(device->battery_pending_call);
424 		device->battery_pending_call = NULL;
425 	}
426 }
427 
add_dict(struct spa_pod_builder * builder,const char * key,const char * val)428 static inline void add_dict(struct spa_pod_builder *builder, const char *key, const char *val)
429 {
430 	spa_pod_builder_string(builder, key);
431 	spa_pod_builder_string(builder, val);
432 }
433 
a2dp_codec_to_endpoint(const struct a2dp_codec * codec,const char * endpoint,char ** object_path)434 static int a2dp_codec_to_endpoint(const struct a2dp_codec *codec,
435 				   const char * endpoint,
436 				   char** object_path)
437 {
438 	*object_path = spa_aprintf("%s/%s", endpoint,
439 		codec->endpoint_name ? codec->endpoint_name : codec->name);
440 	if (*object_path == NULL)
441 		return -errno;
442 	return 0;
443 }
444 
a2dp_endpoint_to_codec(struct spa_bt_monitor * monitor,const char * endpoint)445 static const struct a2dp_codec *a2dp_endpoint_to_codec(struct spa_bt_monitor *monitor, const char *endpoint)
446 {
447 	const char *ep_name;
448 	const struct a2dp_codec * const * const a2dp_codecs = monitor->a2dp_codecs;
449 	int i;
450 
451 	if (spa_strstartswith(endpoint, A2DP_SINK_ENDPOINT "/"))
452 		ep_name = endpoint + strlen(A2DP_SINK_ENDPOINT "/");
453 	else if (spa_strstartswith(endpoint, A2DP_SOURCE_ENDPOINT "/"))
454 		ep_name = endpoint + strlen(A2DP_SOURCE_ENDPOINT "/");
455 	else
456 		return NULL;
457 
458 	for (i = 0; a2dp_codecs[i]; i++) {
459 		const struct a2dp_codec *codec = a2dp_codecs[i];
460 		const char *codec_ep_name =
461 			codec->endpoint_name ? codec->endpoint_name : codec->name;
462 		if (spa_streq(ep_name, codec_ep_name))
463 			return codec;
464 	}
465 	return NULL;
466 }
467 
a2dp_endpoint_to_profile(const char * endpoint)468 static int a2dp_endpoint_to_profile(const char *endpoint)
469 {
470 
471 	if (spa_strstartswith(endpoint, A2DP_SINK_ENDPOINT "/"))
472 		return SPA_BT_PROFILE_A2DP_SOURCE;
473 	else if (spa_strstartswith(endpoint, A2DP_SOURCE_ENDPOINT "/"))
474 		return SPA_BT_PROFILE_A2DP_SINK;
475 	else
476 		return SPA_BT_PROFILE_NULL;
477 }
478 
is_a2dp_codec_enabled(struct spa_bt_monitor * monitor,const struct a2dp_codec * codec)479 static bool is_a2dp_codec_enabled(struct spa_bt_monitor *monitor, const struct a2dp_codec *codec)
480 {
481 	return spa_dict_lookup(&monitor->enabled_codecs, codec->name) != NULL;
482 }
483 
endpoint_select_configuration(DBusConnection * conn,DBusMessage * m,void * userdata)484 static DBusHandlerResult endpoint_select_configuration(DBusConnection *conn, DBusMessage *m, void *userdata)
485 {
486 	struct spa_bt_monitor *monitor = userdata;
487 	const char *path;
488 	uint8_t *cap, config[A2DP_MAX_CAPS_SIZE];
489 	uint8_t *pconf = (uint8_t *) config;
490 	DBusMessage *r;
491 	DBusError err;
492 	int i, size, res;
493 	const struct a2dp_codec *codec;
494 
495 	dbus_error_init(&err);
496 
497 	path = dbus_message_get_path(m);
498 
499 	if (!dbus_message_get_args(m, &err, DBUS_TYPE_ARRAY,
500 				DBUS_TYPE_BYTE, &cap, &size, DBUS_TYPE_INVALID)) {
501 		spa_log_error(monitor->log, "Endpoint SelectConfiguration(): %s", err.message);
502 		dbus_error_free(&err);
503 		return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
504 	}
505 	spa_log_info(monitor->log, "%p: %s select conf %d", monitor, path, size);
506 	for (i = 0; i < size; i++)
507 		spa_log_debug(monitor->log, "  %d: %02x", i, cap[i]);
508 
509 	codec = a2dp_endpoint_to_codec(monitor, path);
510 	if (codec != NULL)
511 		/* FIXME: We can't determine which device the SelectConfiguration()
512 		 * call is associated with, therefore device settings are not passed.
513 		 * This causes inconsistency with SelectConfiguration() triggered
514 		 * by codec switching.
515 		  */
516 		res = codec->select_config(codec, 0, cap, size, &monitor->default_audio_info, NULL, config);
517 	else
518 		res = -ENOTSUP;
519 
520 	if (res < 0 || res != size) {
521 		spa_log_error(monitor->log, "can't select config: %d (%s)",
522 				res, spa_strerror(res));
523 		if ((r = dbus_message_new_error(m, "org.bluez.Error.InvalidArguments",
524 				"Unable to select configuration")) == NULL)
525 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
526 		goto exit_send;
527 	}
528 	for (i = 0; i < size; i++)
529 		spa_log_debug(monitor->log, "  %d: %02x", i, pconf[i]);
530 
531 	if ((r = dbus_message_new_method_return(m)) == NULL)
532 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
533 	if (!dbus_message_append_args(r, DBUS_TYPE_ARRAY,
534 			DBUS_TYPE_BYTE, &pconf, size, DBUS_TYPE_INVALID))
535 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
536 
537       exit_send:
538 	if (!dbus_connection_send(conn, r, NULL))
539 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
540 
541 	dbus_message_unref(r);
542 
543 	return DBUS_HANDLER_RESULT_HANDLED;
544 }
545 
adapter_find(struct spa_bt_monitor * monitor,const char * path)546 static struct spa_bt_adapter *adapter_find(struct spa_bt_monitor *monitor, const char *path)
547 {
548 	struct spa_bt_adapter *d;
549 	spa_list_for_each(d, &monitor->adapter_list, link)
550 		if (spa_streq(d->path, path))
551 			return d;
552 	return NULL;
553 }
554 
check_iter_signature(DBusMessageIter * it,const char * sig)555 static bool check_iter_signature(DBusMessageIter *it, const char *sig)
556 {
557 	char *v;
558 	bool res;
559 	v = dbus_message_iter_get_signature(it);
560 	res = spa_streq(v, sig);
561 	dbus_free(v);
562 	return res;
563 }
564 
parse_modalias(const char * modalias,uint16_t * source,uint16_t * vendor,uint16_t * product,uint16_t * version)565 static int parse_modalias(const char *modalias, uint16_t *source, uint16_t *vendor,
566 		uint16_t *product, uint16_t *version)
567 {
568 	char *pos;
569 	unsigned int src, i, j, k;
570 
571 	if (strncmp(modalias, "bluetooth:", strlen("bluetooth:")) == 0)
572 		src = SOURCE_ID_BLUETOOTH;
573 	else if (strncmp(modalias, "usb:", strlen("usb:")) == 0)
574 		src = SOURCE_ID_USB;
575 	else
576 		return -EINVAL;
577 
578 	pos = strchr(modalias, ':');
579 	if (pos == NULL)
580 		return -EINVAL;
581 
582 	if (sscanf(pos + 1, "v%04Xp%04Xd%04X", &i, &j, &k) != 3)
583 		return -EINVAL;
584 
585 	/* Ignore BlueZ placeholder value */
586 	if (src == SOURCE_ID_USB && i == 0x1d6b && j == 0x0246)
587 		return -ENXIO;
588 
589 	*source = src;
590 	*vendor = i;
591 	*product = j;
592 	*version = k;
593 
594 	return 0;
595 }
596 
adapter_update_props(struct spa_bt_adapter * adapter,DBusMessageIter * props_iter,DBusMessageIter * invalidated_iter)597 static int adapter_update_props(struct spa_bt_adapter *adapter,
598 				DBusMessageIter *props_iter,
599 				DBusMessageIter *invalidated_iter)
600 {
601 	struct spa_bt_monitor *monitor = adapter->monitor;
602 
603 	while (dbus_message_iter_get_arg_type(props_iter) != DBUS_TYPE_INVALID) {
604 		DBusMessageIter it[2];
605 		const char *key;
606 		int type;
607 
608 		dbus_message_iter_recurse(props_iter, &it[0]);
609 		dbus_message_iter_get_basic(&it[0], &key);
610 		dbus_message_iter_next(&it[0]);
611 		dbus_message_iter_recurse(&it[0], &it[1]);
612 
613 		type = dbus_message_iter_get_arg_type(&it[1]);
614 
615 		if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
616 			const char *value;
617 
618 			dbus_message_iter_get_basic(&it[1], &value);
619 
620 			spa_log_debug(monitor->log, "adapter %p: %s=%s", adapter, key, value);
621 
622 			if (spa_streq(key, "Alias")) {
623 				free(adapter->alias);
624 				adapter->alias = strdup(value);
625 			}
626 			else if (spa_streq(key, "Name")) {
627 				free(adapter->name);
628 				adapter->name = strdup(value);
629 			}
630 			else if (spa_streq(key, "Address")) {
631 				free(adapter->address);
632 				adapter->address = strdup(value);
633 			}
634 			else if (spa_streq(key, "Modalias")) {
635 				int ret;
636 				ret = parse_modalias(value, &adapter->source_id, &adapter->vendor_id,
637 						&adapter->product_id, &adapter->version_id);
638 				if (ret < 0)
639 					spa_log_debug(monitor->log, "adapter %p: %s=%s ignored: %s",
640 							adapter, key, value, spa_strerror(ret));
641 			}
642 		}
643 		else if (type == DBUS_TYPE_UINT32) {
644 			uint32_t value;
645 
646 			dbus_message_iter_get_basic(&it[1], &value);
647 
648 			spa_log_debug(monitor->log, "adapter %p: %s=%d", adapter, key, value);
649 
650 			if (spa_streq(key, "Class"))
651 				adapter->bluetooth_class = value;
652 
653 		}
654 		else if (type == DBUS_TYPE_BOOLEAN) {
655 			int value;
656 
657 			dbus_message_iter_get_basic(&it[1], &value);
658 
659 			spa_log_debug(monitor->log, "adapter %p: %s=%d", adapter, key, value);
660 
661 			if (spa_streq(key, "Powered")) {
662 				adapter->powered = value;
663 			}
664 		}
665 		else if (spa_streq(key, "UUIDs")) {
666 			DBusMessageIter iter;
667 
668 			if (!check_iter_signature(&it[1], "as"))
669 				goto next;
670 
671 			dbus_message_iter_recurse(&it[1], &iter);
672 
673 			while (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INVALID) {
674 				const char *uuid;
675 				enum spa_bt_profile profile;
676 
677 				dbus_message_iter_get_basic(&iter, &uuid);
678 
679 				profile = spa_bt_profile_from_uuid(uuid);
680 
681 				if (profile && (adapter->profiles & profile) == 0) {
682 					spa_log_debug(monitor->log, "adapter %p: add UUID=%s", adapter, uuid);
683 					adapter->profiles |= profile;
684 				}
685 				dbus_message_iter_next(&iter);
686 			}
687 		}
688 		else
689 			spa_log_debug(monitor->log, "adapter %p: unhandled key %s", adapter, key);
690 
691 	      next:
692 		dbus_message_iter_next(props_iter);
693 	}
694 	return 0;
695 }
696 
adapter_register_player(struct spa_bt_adapter * adapter)697 static void adapter_register_player(struct spa_bt_adapter *adapter)
698 {
699 	if (adapter->player_registered || !adapter->monitor->dummy_avrcp_player)
700 		return;
701 
702 	if (spa_bt_player_register(adapter->dummy_player, adapter->path) == 0)
703 		adapter->player_registered = true;
704 }
705 
adapter_init_bus_type(struct spa_bt_monitor * monitor,struct spa_bt_adapter * d)706 static int adapter_init_bus_type(struct spa_bt_monitor *monitor, struct spa_bt_adapter *d)
707 {
708 	char path[1024], buf[1024];
709 	const char *str;
710 	ssize_t res = -EINVAL;
711 
712 	d->bus_type = BUS_TYPE_OTHER;
713 
714 	str = strrchr(d->path, '/');  /* hciXX */
715 	if (str == NULL)
716 		return -ENOENT;
717 
718 	snprintf(path, sizeof(path), "/sys/class/bluetooth/%s/device/subsystem", str);
719 	if ((res = readlink(path, buf, sizeof(buf)-1)) < 0)
720 		return -errno;
721 	buf[res] = '\0';
722 
723 	str = strrchr(buf, '/');
724 	if (str && spa_streq(str, "/usb"))
725 		d->bus_type = BUS_TYPE_USB;
726 	return 0;
727 }
728 
adapter_init_modalias(struct spa_bt_monitor * monitor,struct spa_bt_adapter * d)729 static int adapter_init_modalias(struct spa_bt_monitor *monitor, struct spa_bt_adapter *d)
730 {
731 	char path[1024];
732 	FILE *f = NULL;
733 	int vendor_id, product_id;
734 	const char *str;
735 	int res = -EINVAL;
736 
737 	/* Lookup vendor/product id for the device, if present */
738 	str = strrchr(d->path, '/');  /* hciXX */
739 	if (str == NULL)
740 		goto fail;
741 	snprintf(path, sizeof(path), "/sys/class/bluetooth/%s/device/modalias", str);
742 	if ((f = fopen(path, "rb")) == NULL) {
743 		res = -errno;
744 		goto fail;
745 	}
746 	if (fscanf(f, "usb:v%04Xp%04X",  &vendor_id, &product_id) != 2)
747 		goto fail;
748 	d->source_id = SOURCE_ID_USB;
749 	d->vendor_id = vendor_id;
750 	d->product_id = product_id;
751 	fclose(f);
752 
753 	spa_log_debug(monitor->log, "adapter %p: usb vendor:%04x product:%04x",
754 			d, vendor_id, product_id);
755 	return 0;
756 
757 fail:
758 	if (f)
759 		fclose(f);
760 	return res;
761 }
762 
adapter_create(struct spa_bt_monitor * monitor,const char * path)763 static struct spa_bt_adapter *adapter_create(struct spa_bt_monitor *monitor, const char *path)
764 {
765 	struct spa_bt_adapter *d;
766 
767 	d = calloc(1, sizeof(struct spa_bt_adapter));
768 	if (d == NULL)
769 		return NULL;
770 
771 	d->dummy_player = spa_bt_player_new(monitor->conn, monitor->log);
772 	if (d->dummy_player == NULL) {
773 		free(d);
774 		return NULL;
775 	}
776 
777 	d->monitor = monitor;
778 	d->path = strdup(path);
779 
780 	spa_list_prepend(&monitor->adapter_list, &d->link);
781 
782 	adapter_init_bus_type(monitor, d);
783 	adapter_init_modalias(monitor, d);
784 
785 	return d;
786 }
787 
adapter_free(struct spa_bt_adapter * adapter)788 static void adapter_free(struct spa_bt_adapter *adapter)
789 {
790 	struct spa_bt_monitor *monitor = adapter->monitor;
791 	spa_log_debug(monitor->log, "%p", adapter);
792 
793 	spa_bt_player_destroy(adapter->dummy_player);
794 
795 	spa_list_remove(&adapter->link);
796 	free(adapter->alias);
797 	free(adapter->name);
798 	free(adapter->address);
799 	free(adapter->path);
800 	free(adapter);
801 }
802 
spa_bt_device_find(struct spa_bt_monitor * monitor,const char * path)803 struct spa_bt_device *spa_bt_device_find(struct spa_bt_monitor *monitor, const char *path)
804 {
805 	struct spa_bt_device *d;
806 	spa_list_for_each(d, &monitor->device_list, link)
807 		if (spa_streq(d->path, path))
808 			return d;
809 	return NULL;
810 }
811 
spa_bt_device_find_by_address(struct spa_bt_monitor * monitor,const char * remote_address,const char * local_address)812 struct spa_bt_device *spa_bt_device_find_by_address(struct spa_bt_monitor *monitor, const char *remote_address, const char *local_address)
813 {
814 	struct spa_bt_device *d;
815 	spa_list_for_each(d, &monitor->device_list, link)
816 		if (spa_streq(d->address, remote_address) && spa_streq(d->adapter->address, local_address))
817 			return d;
818 	return NULL;
819 }
820 
device_update_last_bluez_action_time(struct spa_bt_device * device)821 static void device_update_last_bluez_action_time(struct spa_bt_device *device)
822 {
823 	struct timespec ts;
824 	spa_system_clock_gettime(device->monitor->main_system, CLOCK_MONOTONIC, &ts);
825 	device->last_bluez_action_time = SPA_TIMESPEC_TO_NSEC(&ts);
826 }
827 
device_create(struct spa_bt_monitor * monitor,const char * path)828 static struct spa_bt_device *device_create(struct spa_bt_monitor *monitor, const char *path)
829 {
830 	struct spa_bt_device *d;
831 
832 	d = calloc(1, sizeof(struct spa_bt_device));
833 	if (d == NULL)
834 		return NULL;
835 
836 	d->id = monitor->id++;
837 	d->monitor = monitor;
838 	d->path = strdup(path);
839 	d->battery_path = battery_get_name(d->path);
840 	d->reconnect_profiles = DEFAULT_RECONNECT_PROFILES;
841 	d->hw_volume_profiles = DEFAULT_HW_VOLUME_PROFILES;
842 
843 	spa_list_init(&d->remote_endpoint_list);
844 	spa_list_init(&d->transport_list);
845 	spa_list_init(&d->codec_switch_list);
846 
847 	spa_hook_list_init(&d->listener_list);
848 
849 	spa_list_prepend(&monitor->device_list, &d->link);
850 
851 	device_update_last_bluez_action_time(d);
852 
853 	return d;
854 }
855 
856 static int device_stop_timer(struct spa_bt_device *device);
857 
858 static void a2dp_codec_switch_free(struct spa_bt_a2dp_codec_switch *sw);
859 
device_clear_sub(struct spa_bt_device * device)860 static void device_clear_sub(struct spa_bt_device *device)
861 {
862 	battery_remove(device);
863 	spa_bt_device_release_transports(device);
864 }
865 
device_free(struct spa_bt_device * device)866 static void device_free(struct spa_bt_device *device)
867 {
868 	struct spa_bt_remote_endpoint *ep, *tep;
869 	struct spa_bt_a2dp_codec_switch *sw;
870 	struct spa_bt_transport *t, *tt;
871 	struct spa_bt_monitor *monitor = device->monitor;
872 
873 	spa_log_debug(monitor->log, "%p", device);
874 
875 	spa_bt_device_emit_destroy(device);
876 
877 	device_clear_sub(device);
878 	device_stop_timer(device);
879 
880 	if (device->added) {
881 		spa_device_emit_object_info(&monitor->hooks, device->id, NULL);
882 	}
883 
884 	spa_list_for_each_safe(ep, tep, &device->remote_endpoint_list, device_link) {
885 		if (ep->device == device) {
886 			spa_list_remove(&ep->device_link);
887 			ep->device = NULL;
888 		}
889 	}
890 
891 	spa_list_for_each_safe(t, tt, &device->transport_list, device_link) {
892 		if (t->device == device) {
893 			spa_list_remove(&t->device_link);
894 			t->device = NULL;
895 		}
896 	}
897 
898 	spa_list_consume(sw, &device->codec_switch_list, device_link)
899 		a2dp_codec_switch_free(sw);
900 
901 	spa_list_remove(&device->link);
902 	free(device->path);
903 	free(device->alias);
904 	free(device->address);
905 	free(device->adapter_path);
906 	free(device->battery_path);
907 	free(device->name);
908 	free(device->icon);
909 	free(device);
910 }
911 
spa_bt_format_vendor_product_id(uint16_t source_id,uint16_t vendor_id,uint16_t product_id,char * vendor_str,int vendor_str_size,char * product_str,int product_str_size)912 int spa_bt_format_vendor_product_id(uint16_t source_id, uint16_t vendor_id, uint16_t product_id,
913 		char *vendor_str, int vendor_str_size, char *product_str, int product_str_size)
914 {
915 	char *source_str;
916 
917 	switch (source_id) {
918 	case SOURCE_ID_USB:
919 		source_str = "usb";
920 		break;
921 	case SOURCE_ID_BLUETOOTH:
922 		source_str = "bluetooth";
923 		break;
924 	default:
925 		return -EINVAL;
926 	}
927 
928 	spa_scnprintf(vendor_str, vendor_str_size, "%s:%04x", source_str, (unsigned int)vendor_id);
929 	spa_scnprintf(product_str, product_str_size, "%04x", (unsigned int)product_id);
930 	return 0;
931 }
932 
emit_device_info(struct spa_bt_monitor * monitor,struct spa_bt_device * device,bool with_connection)933 static void emit_device_info(struct spa_bt_monitor *monitor,
934 		struct spa_bt_device *device, bool with_connection)
935 {
936 	struct spa_device_object_info info;
937 	char dev[32], name[128], class[16], vendor_id[64], product_id[64], product_id_tot[67];
938 	struct spa_dict_item items[23];
939 	uint32_t n_items = 0;
940 
941 	info = SPA_DEVICE_OBJECT_INFO_INIT();
942 	info.type = SPA_TYPE_INTERFACE_Device;
943 	info.factory_name = SPA_NAME_API_BLUEZ5_DEVICE;
944 	info.change_mask = SPA_DEVICE_OBJECT_CHANGE_MASK_FLAGS |
945 		SPA_DEVICE_OBJECT_CHANGE_MASK_PROPS;
946 	info.flags = 0;
947 
948 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_API, "bluez5");
949 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_BUS, "bluetooth");
950 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_MEDIA_CLASS, "Audio/Device");
951 	snprintf(name, sizeof(name), "bluez_card.%s", device->address);
952 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_NAME, name);
953 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_DESCRIPTION, device->alias);
954 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_ALIAS, device->name);
955 	if (spa_bt_format_vendor_product_id(
956 				device->source_id, device->vendor_id, device->product_id,
957 				vendor_id, sizeof(vendor_id), product_id, sizeof(product_id)) == 0) {
958 		snprintf(product_id_tot, sizeof(product_id_tot), "0x%s", product_id);
959 		items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_VENDOR_ID, vendor_id);
960 		items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_PRODUCT_ID, product_id_tot);
961 	}
962 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_FORM_FACTOR,
963 			spa_bt_form_factor_name(
964 				spa_bt_form_factor_from_class(device->bluetooth_class)));
965 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_DEVICE_STRING, device->address);
966 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_API_BLUEZ5_ICON, device->icon);
967 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_API_BLUEZ5_PATH, device->path);
968 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_API_BLUEZ5_ADDRESS, device->address);
969 	snprintf(dev, sizeof(dev), "pointer:%p", device);
970 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_API_BLUEZ5_DEVICE, dev);
971 	snprintf(class, sizeof(class), "0x%06x", device->bluetooth_class);
972 	items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_API_BLUEZ5_CLASS, class);
973 
974 	if (with_connection) {
975 		items[n_items++] = SPA_DICT_ITEM_INIT(SPA_KEY_API_BLUEZ5_CONNECTION,
976 					device->connected ? "connected": "disconnected");
977 	}
978 
979 	info.props = &SPA_DICT_INIT(items, n_items);
980 	spa_device_emit_object_info(&monitor->hooks, device->id, &info);
981 }
982 
device_connected_old(struct spa_bt_monitor * monitor,struct spa_bt_device * device,int connected)983 static int device_connected_old(struct spa_bt_monitor *monitor,
984 		struct spa_bt_device *device, int connected)
985 {
986 
987 	if (connected == BT_DEVICE_INIT)
988 		return 0;
989 
990 	device->connected = connected;
991 
992 	if (device->connected) {
993 		emit_device_info(monitor, device, false);
994 		device->added = true;
995 	} else {
996 		if (!device->added)
997 			return 0;
998 
999 		device_clear_sub(device);
1000 		spa_device_emit_object_info(&monitor->hooks, device->id, NULL);
1001 		device->added = false;
1002 	}
1003 
1004 	return 0;
1005 }
1006 
1007 enum {
1008 	BT_DEVICE_RECONNECT_INIT = 0,
1009 	BT_DEVICE_RECONNECT_PROFILE,
1010 	BT_DEVICE_RECONNECT_STOP
1011 };
1012 
device_connected(struct spa_bt_monitor * monitor,struct spa_bt_device * device,int status)1013 static int device_connected(struct spa_bt_monitor *monitor,
1014 		struct spa_bt_device *device, int status)
1015 {
1016 	bool connected, init = (status == BT_DEVICE_INIT);
1017 
1018 	connected = init ? 0 : status;
1019 
1020 	if (!init) {
1021 		device->reconnect_state =
1022 			connected ? BT_DEVICE_RECONNECT_STOP
1023 				  : BT_DEVICE_RECONNECT_PROFILE;
1024 	}
1025 
1026 	if ((device->connected_profiles != 0) ^ connected) {
1027 		spa_log_error(monitor->log,
1028 			"device %p: unexpected call, connected_profiles:%08x connected:%d",
1029 			device, device->connected_profiles, device->connected);
1030 		return -EINVAL;
1031 	}
1032 
1033 	if (!monitor->connection_info_supported)
1034 		return device_connected_old(monitor, device, status);
1035 
1036 	if (init) {
1037 		device->connected = connected;
1038 	} else {
1039 		if (!device->added || !(connected ^ device->connected))
1040 			return 0;
1041 
1042 		device->connected = connected;
1043 		spa_bt_device_emit_connected(device, device->connected);
1044 
1045 		if (!device->connected)
1046 			device_clear_sub(device);
1047 	}
1048 
1049 	emit_device_info(monitor, device, true);
1050 	device->added = true;
1051 
1052 	return 0;
1053 }
1054 
1055 /*
1056  * Add profile to device based on bluez actions
1057  * (update property UUIDs, trigger profile handlers),
1058  * in case UUIDs is empty on signal InterfaceAdded for
1059  * org.bluez.Device1. And emit device info if there is
1060  * at least 1 profile on device. This should be called
1061  * before any device setting accessing.
1062  */
spa_bt_device_add_profile(struct spa_bt_device * device,enum spa_bt_profile profile)1063 int spa_bt_device_add_profile(struct spa_bt_device *device, enum spa_bt_profile profile)
1064 {
1065 	struct spa_bt_monitor *monitor = device->monitor;
1066 
1067 	if (profile && (device->profiles & profile) == 0) {
1068 		spa_log_info(monitor->log, "device %p: add new profile %08x", device, profile);
1069 		device->profiles |= profile;
1070 	}
1071 
1072 	if (!device->added && device->profiles) {
1073 		device_connected(monitor, device, BT_DEVICE_INIT);
1074 		if (device->reconnect_state == BT_DEVICE_RECONNECT_INIT)
1075 			device_start_timer(device);
1076 	}
1077 
1078 	return 0;
1079 }
1080 
1081 
device_try_connect_profile(struct spa_bt_device * device,const char * profile_uuid)1082 static int device_try_connect_profile(struct spa_bt_device *device,
1083                                       const char *profile_uuid)
1084 {
1085 	struct spa_bt_monitor *monitor = device->monitor;
1086 	DBusMessage *m;
1087 
1088 	spa_log_info(monitor->log, "device %p %s: profile %s not connected; try ConnectProfile()",
1089 	             device, device->path, profile_uuid);
1090 
1091 	/* Call org.bluez.Device1.ConnectProfile() on device, ignoring result */
1092 
1093 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
1094 	                                 device->path,
1095 	                                 BLUEZ_DEVICE_INTERFACE,
1096 	                                 "ConnectProfile");
1097 	if (m == NULL)
1098 		return -ENOMEM;
1099 	dbus_message_append_args(m, DBUS_TYPE_STRING, &profile_uuid, DBUS_TYPE_INVALID);
1100 	if (!dbus_connection_send(monitor->conn, m, NULL)) {
1101 		dbus_message_unref(m);
1102 		return -EIO;
1103 	}
1104 	dbus_message_unref(m);
1105 
1106 	return 0;
1107 }
1108 
reconnect_device_profiles(struct spa_bt_device * device)1109 static int reconnect_device_profiles(struct spa_bt_device *device)
1110 {
1111 	struct spa_bt_monitor *monitor = device->monitor;
1112 	struct spa_bt_device *d;
1113 	uint32_t reconnect = device->profiles
1114 			& device->reconnect_profiles
1115 			& (device->connected_profiles ^ device->profiles);
1116 
1117 	/* Don't try to connect to same device via multiple adapters */
1118 	spa_list_for_each(d, &monitor->device_list, link) {
1119 		if (d != device && spa_streq(d->address, device->address)) {
1120 			if (d->paired && d->trusted && !d->blocked &&
1121 					d->reconnect_state == BT_DEVICE_RECONNECT_STOP)
1122 				reconnect &= ~d->reconnect_profiles;
1123 			if (d->connected_profiles)
1124 				reconnect = 0;
1125 		}
1126 	}
1127 
1128 	if (!(device->connected_profiles & SPA_BT_PROFILE_HEADSET_HEAD_UNIT)) {
1129 		if (reconnect & SPA_BT_PROFILE_HFP_HF) {
1130 			SPA_FLAG_CLEAR(reconnect, SPA_BT_PROFILE_HSP_HS);
1131 		} else if (reconnect & SPA_BT_PROFILE_HSP_HS) {
1132 			SPA_FLAG_CLEAR(reconnect, SPA_BT_PROFILE_HFP_HF);
1133 		}
1134 	} else
1135 		SPA_FLAG_CLEAR(reconnect, SPA_BT_PROFILE_HEADSET_HEAD_UNIT);
1136 
1137 	if (!(device->connected_profiles & SPA_BT_PROFILE_HEADSET_AUDIO_GATEWAY)) {
1138 		if (reconnect & SPA_BT_PROFILE_HFP_AG)
1139 			SPA_FLAG_CLEAR(reconnect, SPA_BT_PROFILE_HSP_AG);
1140 		else if (reconnect & SPA_BT_PROFILE_HSP_AG)
1141 			SPA_FLAG_CLEAR(reconnect, SPA_BT_PROFILE_HFP_AG);
1142 	} else
1143 		SPA_FLAG_CLEAR(reconnect, SPA_BT_PROFILE_HEADSET_AUDIO_GATEWAY);
1144 
1145 	if (reconnect & SPA_BT_PROFILE_HFP_HF)
1146 		device_try_connect_profile(device, SPA_BT_UUID_HFP_HF);
1147 	if (reconnect & SPA_BT_PROFILE_HSP_HS)
1148 		device_try_connect_profile(device, SPA_BT_UUID_HSP_HS);
1149 	if (reconnect & SPA_BT_PROFILE_HFP_AG)
1150 		device_try_connect_profile(device, SPA_BT_UUID_HFP_AG);
1151 	if (reconnect & SPA_BT_PROFILE_HSP_AG)
1152 		device_try_connect_profile(device, SPA_BT_UUID_HSP_AG);
1153 	if (reconnect & SPA_BT_PROFILE_A2DP_SINK)
1154 		device_try_connect_profile(device, SPA_BT_UUID_A2DP_SINK);
1155 	if (reconnect & SPA_BT_PROFILE_A2DP_SOURCE)
1156 		device_try_connect_profile(device, SPA_BT_UUID_A2DP_SOURCE);
1157 
1158 	return reconnect;
1159 }
1160 
1161 #define DEVICE_RECONNECT_TIMEOUT_SEC 2
1162 #define DEVICE_PROFILE_TIMEOUT_SEC 3
1163 
device_timer_event(struct spa_source * source)1164 static void device_timer_event(struct spa_source *source)
1165 {
1166 	struct spa_bt_device *device = source->data;
1167 	struct spa_bt_monitor *monitor = device->monitor;
1168 	uint64_t exp;
1169 
1170 	if (spa_system_timerfd_read(monitor->main_system, source->fd, &exp) < 0)
1171                 spa_log_warn(monitor->log, "error reading timerfd: %s", strerror(errno));
1172 
1173 	spa_log_debug(monitor->log, "device %p: timeout %08x %08x",
1174 			device, device->profiles, device->connected_profiles);
1175 	device_stop_timer(device);
1176 	if (BT_DEVICE_RECONNECT_STOP != device->reconnect_state) {
1177 		device->reconnect_state = BT_DEVICE_RECONNECT_STOP;
1178 		if (device->paired
1179 			&& device->trusted
1180 			&& !device->blocked
1181 			&& device->reconnect_profiles != 0
1182 			&& reconnect_device_profiles(device))
1183 		{
1184 			device_start_timer(device);
1185 			return;
1186 		}
1187 	}
1188 	if (device->connected_profiles)
1189 		device_connected(device->monitor, device, BT_DEVICE_CONNECTED);
1190 }
1191 
device_start_timer(struct spa_bt_device * device)1192 static int device_start_timer(struct spa_bt_device *device)
1193 {
1194 	struct spa_bt_monitor *monitor = device->monitor;
1195 	struct itimerspec ts;
1196 
1197 	spa_log_debug(monitor->log, "device %p: start timer", device);
1198 	if (device->timer.data == NULL) {
1199 		device->timer.data = device;
1200 		device->timer.func = device_timer_event;
1201 		device->timer.fd = spa_system_timerfd_create(monitor->main_system,
1202 				CLOCK_MONOTONIC, SPA_FD_CLOEXEC | SPA_FD_NONBLOCK);
1203 		device->timer.mask = SPA_IO_IN;
1204 		device->timer.rmask = 0;
1205 		spa_loop_add_source(monitor->main_loop, &device->timer);
1206 	}
1207 	ts.it_value.tv_sec = device->reconnect_state == BT_DEVICE_RECONNECT_STOP
1208 				? DEVICE_PROFILE_TIMEOUT_SEC
1209 				: DEVICE_RECONNECT_TIMEOUT_SEC;
1210 	ts.it_value.tv_nsec = 0;
1211 	ts.it_interval.tv_sec = 0;
1212 	ts.it_interval.tv_nsec = 0;
1213 	spa_system_timerfd_settime(monitor->main_system, device->timer.fd, 0, &ts, NULL);
1214 	return 0;
1215 }
1216 
device_stop_timer(struct spa_bt_device * device)1217 static int device_stop_timer(struct spa_bt_device *device)
1218 {
1219 	struct spa_bt_monitor *monitor = device->monitor;
1220 	struct itimerspec ts;
1221 
1222 	if (device->timer.data == NULL)
1223 		return 0;
1224 
1225 	spa_log_debug(monitor->log, "device %p: stop timer", device);
1226 	spa_loop_remove_source(monitor->main_loop, &device->timer);
1227         ts.it_value.tv_sec = 0;
1228         ts.it_value.tv_nsec = 0;
1229         ts.it_interval.tv_sec = 0;
1230         ts.it_interval.tv_nsec = 0;
1231         spa_system_timerfd_settime(monitor->main_system, device->timer.fd, 0, &ts, NULL);
1232 	spa_system_close(monitor->main_system, device->timer.fd);
1233 	device->timer.data = NULL;
1234 	return 0;
1235 }
1236 
spa_bt_device_check_profiles(struct spa_bt_device * device,bool force)1237 int spa_bt_device_check_profiles(struct spa_bt_device *device, bool force)
1238 {
1239 	struct spa_bt_monitor *monitor = device->monitor;
1240 	uint32_t connected_profiles = device->connected_profiles;
1241 
1242 	if (connected_profiles & SPA_BT_PROFILE_HEADSET_HEAD_UNIT)
1243 		connected_profiles |= SPA_BT_PROFILE_HEADSET_HEAD_UNIT;
1244 	if (connected_profiles & SPA_BT_PROFILE_HEADSET_AUDIO_GATEWAY)
1245 		connected_profiles |= SPA_BT_PROFILE_HEADSET_AUDIO_GATEWAY;
1246 
1247 	spa_log_debug(monitor->log, "device %p: profiles %08x %08x %d",
1248 			device, device->profiles, connected_profiles, device->added);
1249 
1250 	if (connected_profiles == 0 && spa_list_is_empty(&device->codec_switch_list)) {
1251 		device_stop_timer(device);
1252 		device_connected(monitor, device, BT_DEVICE_DISCONNECTED);
1253 	} else if (force || (device->profiles & connected_profiles) == device->profiles) {
1254 		device_stop_timer(device);
1255 		device_connected(monitor, device, BT_DEVICE_CONNECTED);
1256 	} else {
1257 		/* The initial reconnect event has not been triggered,
1258 		 * the connecting is triggered by bluez. */
1259 		if (device->reconnect_state == BT_DEVICE_RECONNECT_INIT)
1260 			device->reconnect_state = BT_DEVICE_RECONNECT_PROFILE;
1261 		device_start_timer(device);
1262 	}
1263 	return 0;
1264 }
1265 
device_set_connected(struct spa_bt_device * device,int connected)1266 static void device_set_connected(struct spa_bt_device *device, int connected)
1267 {
1268 	struct spa_bt_monitor *monitor = device->monitor;
1269 
1270 	if (device->connected && !connected)
1271 		device->connected_profiles = 0;
1272 
1273 	if (connected)
1274 		spa_bt_device_check_profiles(device, false);
1275 	else {
1276 		if (device->reconnect_state != BT_DEVICE_RECONNECT_INIT)
1277 			device_stop_timer(device);
1278 		device_connected(monitor, device, BT_DEVICE_DISCONNECTED);
1279 	}
1280 }
1281 
spa_bt_device_connect_profile(struct spa_bt_device * device,enum spa_bt_profile profile)1282 int spa_bt_device_connect_profile(struct spa_bt_device *device, enum spa_bt_profile profile)
1283 {
1284 	uint32_t prev_connected = device->connected_profiles;
1285 	device->connected_profiles |= profile;
1286 	spa_bt_device_check_profiles(device, false);
1287 	if (device->connected_profiles != prev_connected)
1288 		spa_bt_device_emit_profiles_changed(device, device->profiles, prev_connected);
1289 	return 0;
1290 }
1291 
device_update_hw_volume_profiles(struct spa_bt_device * device)1292 static void device_update_hw_volume_profiles(struct spa_bt_device *device)
1293 {
1294 	struct spa_bt_monitor *monitor = device->monitor;
1295 	uint32_t bt_features = 0;
1296 
1297 	if (!monitor->quirks)
1298 		return;
1299 
1300 	if (spa_bt_quirks_get_features(monitor->quirks, device->adapter, device, &bt_features) != 0)
1301 		return;
1302 
1303 	if (!(bt_features & SPA_BT_FEATURE_HW_VOLUME))
1304 		device->hw_volume_profiles = 0;
1305 
1306 	spa_log_debug(monitor->log, "hw-volume-profiles:%08x", (int)device->hw_volume_profiles);
1307 }
1308 
device_update_props(struct spa_bt_device * device,DBusMessageIter * props_iter,DBusMessageIter * invalidated_iter)1309 static int device_update_props(struct spa_bt_device *device,
1310 			       DBusMessageIter *props_iter,
1311 			       DBusMessageIter *invalidated_iter)
1312 {
1313 	struct spa_bt_monitor *monitor = device->monitor;
1314 
1315 	while (dbus_message_iter_get_arg_type(props_iter) != DBUS_TYPE_INVALID) {
1316 		DBusMessageIter it[2];
1317 		const char *key;
1318 		int type;
1319 
1320 		dbus_message_iter_recurse(props_iter, &it[0]);
1321 		dbus_message_iter_get_basic(&it[0], &key);
1322 		dbus_message_iter_next(&it[0]);
1323 		dbus_message_iter_recurse(&it[0], &it[1]);
1324 
1325 		type = dbus_message_iter_get_arg_type(&it[1]);
1326 
1327 		if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
1328 			const char *value;
1329 
1330 			dbus_message_iter_get_basic(&it[1], &value);
1331 
1332 			spa_log_debug(monitor->log, "device %p: %s=%s", device, key, value);
1333 
1334 			if (spa_streq(key, "Alias")) {
1335 				free(device->alias);
1336 				device->alias = strdup(value);
1337 			}
1338 			else if (spa_streq(key, "Name")) {
1339 				free(device->name);
1340 				device->name = strdup(value);
1341 			}
1342 			else if (spa_streq(key, "Address")) {
1343 				free(device->address);
1344 				device->address = strdup(value);
1345 			}
1346 			else if (spa_streq(key, "Adapter")) {
1347 				free(device->adapter_path);
1348 				device->adapter_path = strdup(value);
1349 
1350 				device->adapter = adapter_find(monitor, value);
1351 				if (device->adapter == NULL) {
1352 					spa_log_warn(monitor->log, "unknown adapter %s", value);
1353 				}
1354 			}
1355 			else if (spa_streq(key, "Icon")) {
1356 				free(device->icon);
1357 				device->icon = strdup(value);
1358 			}
1359 			else if (spa_streq(key, "Modalias")) {
1360 				int ret;
1361 				ret = parse_modalias(value, &device->source_id, &device->vendor_id,
1362 						&device->product_id, &device->version_id);
1363 				if (ret < 0)
1364 					spa_log_debug(monitor->log, "device %p: %s=%s ignored: %s",
1365 							device, key, value, spa_strerror(ret));
1366 			}
1367 		}
1368 		else if (type == DBUS_TYPE_UINT32) {
1369 			uint32_t value;
1370 
1371 			dbus_message_iter_get_basic(&it[1], &value);
1372 
1373 			spa_log_debug(monitor->log, "device %p: %s=%08x", device, key, value);
1374 
1375 			if (spa_streq(key, "Class"))
1376 				device->bluetooth_class = value;
1377 		}
1378 		else if (type == DBUS_TYPE_UINT16) {
1379 			uint16_t value;
1380 
1381 			dbus_message_iter_get_basic(&it[1], &value);
1382 
1383 			spa_log_debug(monitor->log, "device %p: %s=%d", device, key, value);
1384 
1385 			if (spa_streq(key, "Appearance"))
1386 				device->appearance = value;
1387 		}
1388 		else if (type == DBUS_TYPE_INT16) {
1389 			int16_t value;
1390 
1391 			dbus_message_iter_get_basic(&it[1], &value);
1392 
1393 			spa_log_debug(monitor->log, "device %p: %s=%d", device, key, value);
1394 
1395 			if (spa_streq(key, "RSSI"))
1396 				device->RSSI = value;
1397 		}
1398 		else if (type == DBUS_TYPE_BOOLEAN) {
1399 			int value;
1400 
1401 			dbus_message_iter_get_basic(&it[1], &value);
1402 
1403 			spa_log_debug(monitor->log, "device %p: %s=%d", device, key, value);
1404 
1405 			if (spa_streq(key, "Paired")) {
1406 				device->paired = value;
1407 			}
1408 			else if (spa_streq(key, "Trusted")) {
1409 				device->trusted = value;
1410 			}
1411 			else if (spa_streq(key, "Connected")) {
1412 				device_set_connected(device, value);
1413 			}
1414 			else if (spa_streq(key, "Blocked")) {
1415 				device->blocked = value;
1416 			}
1417 			else if (spa_streq(key, "ServicesResolved")) {
1418 				if (value)
1419 					spa_bt_device_check_profiles(device, false);
1420 			}
1421 		}
1422 		else if (spa_streq(key, "UUIDs")) {
1423 			DBusMessageIter iter;
1424 			uint32_t prev_profiles = device->profiles;
1425 
1426 			if (!check_iter_signature(&it[1], "as"))
1427 				goto next;
1428 
1429 			dbus_message_iter_recurse(&it[1], &iter);
1430 
1431 			while (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INVALID) {
1432 				const char *uuid;
1433 				enum spa_bt_profile profile;
1434 
1435 				dbus_message_iter_get_basic(&iter, &uuid);
1436 
1437 				profile = spa_bt_profile_from_uuid(uuid);
1438 				if (profile && (device->profiles & profile) == 0) {
1439 					spa_log_debug(monitor->log, "device %p: add UUID=%s", device, uuid);
1440 					device->profiles |= profile;
1441 				}
1442 				dbus_message_iter_next(&iter);
1443 			}
1444 
1445 			if (device->profiles != prev_profiles)
1446 				spa_bt_device_emit_profiles_changed(
1447 					device, prev_profiles, device->connected_profiles);
1448 		}
1449 		else
1450 			spa_log_debug(monitor->log, "device %p: unhandled key %s type %d", device, key, type);
1451 
1452 	      next:
1453 		dbus_message_iter_next(props_iter);
1454 	}
1455 	return 0;
1456 }
1457 
spa_bt_device_supports_a2dp_codec(struct spa_bt_device * device,const struct a2dp_codec * codec)1458 bool spa_bt_device_supports_a2dp_codec(struct spa_bt_device *device, const struct a2dp_codec *codec)
1459 {
1460 	struct spa_bt_monitor *monitor = device->monitor;
1461 	struct spa_bt_remote_endpoint *ep;
1462 	const struct { enum spa_bluetooth_audio_codec codec; uint32_t mask; } quirks[] = {
1463 		{ SPA_BLUETOOTH_AUDIO_CODEC_SBC_XQ, SPA_BT_FEATURE_SBC_XQ },
1464 		{ SPA_BLUETOOTH_AUDIO_CODEC_FASTSTREAM, SPA_BT_FEATURE_FASTSTREAM },
1465 		{ SPA_BLUETOOTH_AUDIO_CODEC_FASTSTREAM_DUPLEX, SPA_BT_FEATURE_FASTSTREAM },
1466 		{ SPA_BLUETOOTH_AUDIO_CODEC_APTX_LL_DUPLEX, SPA_BT_FEATURE_A2DP_DUPLEX },
1467 		{ SPA_BLUETOOTH_AUDIO_CODEC_FASTSTREAM_DUPLEX, SPA_BT_FEATURE_A2DP_DUPLEX },
1468 	};
1469 	size_t i;
1470 
1471 	if (!is_a2dp_codec_enabled(device->monitor, codec))
1472 		return false;
1473 
1474 	if (!device->adapter->application_registered) {
1475 		/* Codec switching not supported: only plain SBC allowed */
1476 		return (codec->codec_id == A2DP_CODEC_SBC && spa_streq(codec->name, "sbc"));
1477 	}
1478 
1479 	/* Check codec quirks */
1480 	for (i = 0; i < SPA_N_ELEMENTS(quirks); ++i) {
1481 		uint32_t bt_features;
1482 
1483 		if (codec->id != quirks[i].codec)
1484 			continue;
1485 		if (monitor->quirks == NULL)
1486 			break;
1487 		if (spa_bt_quirks_get_features(monitor->quirks, device->adapter, device, &bt_features) < 0)
1488 			break;
1489 		if (!(bt_features & quirks[i].mask))
1490 			return false;
1491 	}
1492 
1493 	spa_list_for_each(ep, &device->remote_endpoint_list, device_link) {
1494 		if (a2dp_codec_check_caps(codec, ep->codec, ep->capabilities, ep->capabilities_len,
1495 					  &ep->monitor->default_audio_info))
1496 			return true;
1497 	}
1498 
1499 	return false;
1500 }
1501 
spa_bt_device_get_supported_a2dp_codecs(struct spa_bt_device * device,size_t * count)1502 const struct a2dp_codec **spa_bt_device_get_supported_a2dp_codecs(struct spa_bt_device *device, size_t *count)
1503 {
1504 	struct spa_bt_monitor *monitor = device->monitor;
1505 	const struct a2dp_codec * const * const a2dp_codecs = monitor->a2dp_codecs;
1506 	const struct a2dp_codec **supported_codecs;
1507 	size_t i, j, size;
1508 
1509 	*count = 0;
1510 
1511 	size = 8;
1512 	supported_codecs = malloc(size * sizeof(const struct a2dp_codec *));
1513 	if (supported_codecs == NULL)
1514 		return NULL;
1515 
1516 	j = 0;
1517 	for (i = 0; a2dp_codecs[i] != NULL; ++i) {
1518 		if (spa_bt_device_supports_a2dp_codec(device, a2dp_codecs[i])) {
1519 			supported_codecs[j] = a2dp_codecs[i];
1520 			++j;
1521 		}
1522 
1523 		if (j >= size) {
1524 			const struct a2dp_codec **p;
1525 			size = size * 2;
1526 			p = realloc(supported_codecs, size * sizeof(const struct a2dp_codec *));
1527 			if (p == NULL) {
1528 				free(supported_codecs);
1529 				return NULL;
1530 			}
1531 			supported_codecs = p;
1532 		}
1533 	}
1534 
1535 	supported_codecs[j] = NULL;
1536 	*count = j;
1537 
1538 	return supported_codecs;
1539 }
1540 
device_remote_endpoint_find(struct spa_bt_device * device,const char * path)1541 static struct spa_bt_remote_endpoint *device_remote_endpoint_find(struct spa_bt_device *device, const char *path)
1542 {
1543 	struct spa_bt_remote_endpoint *ep;
1544 	spa_list_for_each(ep, &device->remote_endpoint_list, device_link)
1545 		if (spa_streq(ep->path, path))
1546 			return ep;
1547 	return NULL;
1548 }
1549 
remote_endpoint_find(struct spa_bt_monitor * monitor,const char * path)1550 static struct spa_bt_remote_endpoint *remote_endpoint_find(struct spa_bt_monitor *monitor, const char *path)
1551 {
1552 	struct spa_bt_remote_endpoint *ep;
1553 	spa_list_for_each(ep, &monitor->remote_endpoint_list, link)
1554 		if (spa_streq(ep->path, path))
1555 			return ep;
1556 	return NULL;
1557 }
1558 
remote_endpoint_update_props(struct spa_bt_remote_endpoint * remote_endpoint,DBusMessageIter * props_iter,DBusMessageIter * invalidated_iter)1559 static int remote_endpoint_update_props(struct spa_bt_remote_endpoint *remote_endpoint,
1560 				DBusMessageIter *props_iter,
1561 				DBusMessageIter *invalidated_iter)
1562 {
1563 	struct spa_bt_monitor *monitor = remote_endpoint->monitor;
1564 
1565 	while (dbus_message_iter_get_arg_type(props_iter) != DBUS_TYPE_INVALID) {
1566 		DBusMessageIter it[2];
1567 		const char *key;
1568 		int type;
1569 
1570 		dbus_message_iter_recurse(props_iter, &it[0]);
1571 		dbus_message_iter_get_basic(&it[0], &key);
1572 		dbus_message_iter_next(&it[0]);
1573 		dbus_message_iter_recurse(&it[0], &it[1]);
1574 
1575 		type = dbus_message_iter_get_arg_type(&it[1]);
1576 
1577 		if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
1578 			const char *value;
1579 
1580 			dbus_message_iter_get_basic(&it[1], &value);
1581 
1582 			spa_log_debug(monitor->log, "remote_endpoint %p: %s=%s", remote_endpoint, key, value);
1583 
1584 			if (spa_streq(key, "UUID")) {
1585 				free(remote_endpoint->uuid);
1586 				remote_endpoint->uuid = strdup(value);
1587 			}
1588 			else if (spa_streq(key, "Device")) {
1589 				struct spa_bt_device *device;
1590 				device = spa_bt_device_find(monitor, value);
1591 				if (device == NULL)
1592 					goto next;
1593 				spa_log_debug(monitor->log, "remote_endpoint %p: device -> %p", remote_endpoint, device);
1594 
1595 				if (remote_endpoint->device != device) {
1596 					if (remote_endpoint->device != NULL)
1597 						spa_list_remove(&remote_endpoint->device_link);
1598 					remote_endpoint->device = device;
1599 					if (device != NULL)
1600 						spa_list_append(&device->remote_endpoint_list, &remote_endpoint->device_link);
1601 				}
1602 			}
1603 		}
1604 		else if (type == DBUS_TYPE_BOOLEAN) {
1605 			int value;
1606 
1607 			dbus_message_iter_get_basic(&it[1], &value);
1608 
1609 			spa_log_debug(monitor->log, "remote_endpoint %p: %s=%d", remote_endpoint, key, value);
1610 
1611 			if (spa_streq(key, "DelayReporting")) {
1612 				remote_endpoint->delay_reporting = value;
1613 			}
1614 		}
1615 		else if (type == DBUS_TYPE_BYTE) {
1616 			uint8_t value;
1617 
1618 			dbus_message_iter_get_basic(&it[1], &value);
1619 
1620 			spa_log_debug(monitor->log, "remote_endpoint %p: %s=%02x", remote_endpoint, key, value);
1621 
1622 			if (spa_streq(key, "Codec")) {
1623 				remote_endpoint->codec = value;
1624 			}
1625 		}
1626 		else if (spa_streq(key, "Capabilities")) {
1627 			DBusMessageIter iter;
1628 			uint8_t *value;
1629 			int i, len;
1630 
1631 			if (!check_iter_signature(&it[1], "ay"))
1632 				goto next;
1633 
1634 			dbus_message_iter_recurse(&it[1], &iter);
1635 			dbus_message_iter_get_fixed_array(&iter, &value, &len);
1636 
1637 			spa_log_debug(monitor->log, "remote_endpoint %p: %s=%d", remote_endpoint, key, len);
1638 			for (i = 0; i < len; i++)
1639 				spa_log_debug(monitor->log, "  %d: %02x", i, value[i]);
1640 
1641 			free(remote_endpoint->capabilities);
1642 			remote_endpoint->capabilities_len = 0;
1643 
1644 			remote_endpoint->capabilities = malloc(len);
1645 			if (remote_endpoint->capabilities) {
1646 				memcpy(remote_endpoint->capabilities, value, len);
1647 				remote_endpoint->capabilities_len = len;
1648 			}
1649 		}
1650 		else
1651 			spa_log_debug(monitor->log, "remote_endpoint %p: unhandled key %s", remote_endpoint, key);
1652 
1653 	      next:
1654 		dbus_message_iter_next(props_iter);
1655 	}
1656 	return 0;
1657 }
1658 
remote_endpoint_create(struct spa_bt_monitor * monitor,const char * path)1659 static struct spa_bt_remote_endpoint *remote_endpoint_create(struct spa_bt_monitor *monitor, const char *path)
1660 {
1661 	struct spa_bt_remote_endpoint *ep;
1662 
1663 	ep = calloc(1, sizeof(struct spa_bt_remote_endpoint));
1664 	if (ep == NULL)
1665 		return NULL;
1666 
1667 	ep->monitor = monitor;
1668 	ep->path = strdup(path);
1669 
1670 	spa_list_prepend(&monitor->remote_endpoint_list, &ep->link);
1671 
1672 	return ep;
1673 }
1674 
remote_endpoint_free(struct spa_bt_remote_endpoint * remote_endpoint)1675 static void remote_endpoint_free(struct spa_bt_remote_endpoint *remote_endpoint)
1676 {
1677 	struct spa_bt_monitor *monitor = remote_endpoint->monitor;
1678 
1679 	spa_log_debug(monitor->log, "remote endpoint %p: free %s",
1680 	              remote_endpoint, remote_endpoint->path);
1681 
1682 	if (remote_endpoint->device)
1683 		spa_list_remove(&remote_endpoint->device_link);
1684 
1685 	spa_list_remove(&remote_endpoint->link);
1686 	free(remote_endpoint->path);
1687 	free(remote_endpoint->uuid);
1688 	free(remote_endpoint->capabilities);
1689 	free(remote_endpoint);
1690 }
1691 
spa_bt_transport_find(struct spa_bt_monitor * monitor,const char * path)1692 struct spa_bt_transport *spa_bt_transport_find(struct spa_bt_monitor *monitor, const char *path)
1693 {
1694 	struct spa_bt_transport *t;
1695 	spa_list_for_each(t, &monitor->transport_list, link)
1696 		if (spa_streq(t->path, path))
1697 			return t;
1698 	return NULL;
1699 }
1700 
spa_bt_transport_find_full(struct spa_bt_monitor * monitor,bool (* callback)(struct spa_bt_transport * t,const void * data),const void * data)1701 struct spa_bt_transport *spa_bt_transport_find_full(struct spa_bt_monitor *monitor,
1702                                                     bool (*callback) (struct spa_bt_transport *t, const void *data),
1703                                                     const void *data)
1704 {
1705 	struct spa_bt_transport *t;
1706 
1707 	spa_list_for_each(t, &monitor->transport_list, link)
1708 		if (callback(t, data) == true)
1709 			return t;
1710 	return NULL;
1711 }
1712 
1713 
spa_bt_transport_create(struct spa_bt_monitor * monitor,char * path,size_t extra)1714 struct spa_bt_transport *spa_bt_transport_create(struct spa_bt_monitor *monitor, char *path, size_t extra)
1715 {
1716 	struct spa_bt_transport *t;
1717 
1718 	t = calloc(1, sizeof(struct spa_bt_transport) + extra);
1719 	if (t == NULL)
1720 		return NULL;
1721 
1722 	t->acquire_refcount = 0;
1723 	t->monitor = monitor;
1724 	t->path = path;
1725 	t->fd = -1;
1726 	t->sco_io = NULL;
1727 	t->delay = SPA_BT_UNKNOWN_DELAY;
1728 	t->user_data = SPA_PTROFF(t, sizeof(struct spa_bt_transport), void);
1729 	spa_hook_list_init(&t->listener_list);
1730 
1731 	spa_list_append(&monitor->transport_list, &t->link);
1732 
1733 	return t;
1734 }
1735 
spa_bt_transport_volume_enabled(struct spa_bt_transport * transport)1736 bool spa_bt_transport_volume_enabled(struct spa_bt_transport *transport)
1737 {
1738 	return transport->device != NULL
1739 		&& (transport->device->hw_volume_profiles & transport->profile);
1740 }
1741 
transport_sync_volume(struct spa_bt_transport * transport)1742 static void transport_sync_volume(struct spa_bt_transport *transport)
1743 {
1744 	if (!spa_bt_transport_volume_enabled(transport))
1745 		return;
1746 
1747 	for (int i = 0; i < SPA_BT_VOLUME_ID_TERM; ++i)
1748 		spa_bt_transport_set_volume(transport, i, transport->volumes[i].volume);
1749 	spa_bt_transport_emit_volume_changed(transport);
1750 }
1751 
spa_bt_transport_set_state(struct spa_bt_transport * transport,enum spa_bt_transport_state state)1752 void spa_bt_transport_set_state(struct spa_bt_transport *transport, enum spa_bt_transport_state state)
1753 {
1754 	struct spa_bt_monitor *monitor = transport->monitor;
1755 	enum spa_bt_transport_state old = transport->state;
1756 
1757 	if (old != state) {
1758 		transport->state = state;
1759 		spa_log_debug(monitor->log, "transport %p: %s state changed %d -> %d",
1760 				transport, transport->path, old, state);
1761 		spa_bt_transport_emit_state_changed(transport, old, state);
1762 		if (state >= SPA_BT_TRANSPORT_STATE_PENDING && old < SPA_BT_TRANSPORT_STATE_PENDING)
1763 			transport_sync_volume(transport);
1764 	}
1765 }
1766 
spa_bt_transport_free(struct spa_bt_transport * transport)1767 void spa_bt_transport_free(struct spa_bt_transport *transport)
1768 {
1769 	struct spa_bt_monitor *monitor = transport->monitor;
1770 	struct spa_bt_device *device = transport->device;
1771 	uint32_t prev_connected = 0;
1772 
1773 	spa_log_debug(monitor->log, "transport %p: free %s", transport, transport->path);
1774 
1775 	spa_bt_transport_set_state(transport, SPA_BT_TRANSPORT_STATE_IDLE);
1776 
1777 	spa_bt_transport_emit_destroy(transport);
1778 
1779 	spa_bt_transport_stop_volume_timer(transport);
1780 	spa_bt_transport_stop_release_timer(transport);
1781 
1782 	if (transport->sco_io) {
1783 		spa_bt_sco_io_destroy(transport->sco_io);
1784 		transport->sco_io = NULL;
1785 	}
1786 
1787 	spa_bt_transport_destroy(transport);
1788 
1789 	if (transport->fd >= 0) {
1790 		spa_bt_player_set_state(transport->device->adapter->dummy_player, SPA_BT_PLAYER_STOPPED);
1791 
1792 		shutdown(transport->fd, SHUT_RDWR);
1793 		close(transport->fd);
1794 		transport->fd = -1;
1795 	}
1796 
1797 	spa_list_remove(&transport->link);
1798 	if (transport->device) {
1799 		prev_connected = transport->device->connected_profiles;
1800 		transport->device->connected_profiles &= ~transport->profile;
1801 		spa_list_remove(&transport->device_link);
1802 	}
1803 
1804 	if (device && device->connected_profiles != prev_connected)
1805 		spa_bt_device_emit_profiles_changed(device, device->profiles, prev_connected);
1806 
1807 	free(transport->path);
1808 	free(transport);
1809 }
1810 
spa_bt_transport_acquire(struct spa_bt_transport * transport,bool optional)1811 int spa_bt_transport_acquire(struct spa_bt_transport *transport, bool optional)
1812 {
1813 	struct spa_bt_monitor *monitor = transport->monitor;
1814 	int res;
1815 
1816 	if (transport->acquire_refcount > 0) {
1817 		spa_log_debug(monitor->log, "transport %p: incref %s", transport, transport->path);
1818 		transport->acquire_refcount += 1;
1819 		return 0;
1820 	}
1821 	spa_assert(transport->acquire_refcount == 0);
1822 
1823 	res = spa_bt_transport_impl(transport, acquire, 0, optional);
1824 
1825 	if (res >= 0)
1826 		transport->acquire_refcount = 1;
1827 
1828 	return res;
1829 }
1830 
spa_bt_transport_release(struct spa_bt_transport * transport)1831 int spa_bt_transport_release(struct spa_bt_transport *transport)
1832 {
1833 	struct spa_bt_monitor *monitor = transport->monitor;
1834 	int res;
1835 
1836 	if (transport->acquire_refcount > 1) {
1837 		spa_log_debug(monitor->log, "transport %p: decref %s", transport, transport->path);
1838 		transport->acquire_refcount -= 1;
1839 		return 0;
1840 	}
1841 	else if (transport->acquire_refcount == 0) {
1842 		spa_log_info(monitor->log, "transport %s already released", transport->path);
1843 		return 0;
1844 	}
1845 	spa_assert(transport->acquire_refcount == 1);
1846 
1847 	if (SPA_BT_TRANSPORT_IS_SCO(transport)) {
1848 		/* Postpone SCO transport releases, since we might need it again soon */
1849 		res = spa_bt_transport_start_release_timer(transport);
1850 	} else {
1851 		res = spa_bt_transport_impl(transport, release, 0);
1852 		if (res >= 0)
1853 			transport->acquire_refcount = 0;
1854 	}
1855 
1856 	return res;
1857 }
1858 
spa_bt_transport_release_now(struct spa_bt_transport * transport)1859 static int spa_bt_transport_release_now(struct spa_bt_transport *transport)
1860 {
1861 	int res;
1862 
1863 	if (transport->acquire_refcount == 0)
1864 		return 0;
1865 
1866 	spa_bt_transport_stop_release_timer(transport);
1867 	res = spa_bt_transport_impl(transport, release, 0);
1868 	if (res >= 0)
1869 		transport->acquire_refcount = 0;
1870 
1871 	return res;
1872 }
1873 
spa_bt_device_release_transports(struct spa_bt_device * device)1874 int spa_bt_device_release_transports(struct spa_bt_device *device)
1875 {
1876 	struct spa_bt_transport *t;
1877 	spa_list_for_each(t, &device->transport_list, device_link)
1878 		spa_bt_transport_release_now(t);
1879 	return 0;
1880 }
1881 
start_timeout_timer(struct spa_bt_monitor * monitor,struct spa_source * timer,spa_source_func_t timer_event,time_t timeout_msec,void * data)1882 static int start_timeout_timer(struct spa_bt_monitor *monitor,
1883 		struct spa_source *timer, spa_source_func_t timer_event,
1884 		time_t timeout_msec, void *data)
1885 {
1886 	struct itimerspec ts;
1887 	if (timer->data == NULL) {
1888 		timer->data = data;
1889 		timer->func = timer_event;
1890 		timer->fd = spa_system_timerfd_create(
1891 			monitor->main_system, CLOCK_MONOTONIC, SPA_FD_CLOEXEC | SPA_FD_NONBLOCK);
1892 		timer->mask = SPA_IO_IN;
1893 		timer->rmask = 0;
1894 		spa_loop_add_source(monitor->main_loop, timer);
1895 	}
1896 	ts.it_value.tv_sec = timeout_msec / SPA_MSEC_PER_SEC;
1897 	ts.it_value.tv_nsec = (timeout_msec % SPA_MSEC_PER_SEC) * SPA_NSEC_PER_MSEC;
1898 	ts.it_interval.tv_sec = 0;
1899 	ts.it_interval.tv_nsec = 0;
1900 	spa_system_timerfd_settime(monitor->main_system, timer->fd, 0, &ts, NULL);
1901 	return 0;
1902 }
1903 
stop_timeout_timer(struct spa_bt_monitor * monitor,struct spa_source * timer)1904 static int stop_timeout_timer(struct spa_bt_monitor *monitor, struct spa_source *timer)
1905 {
1906 	struct itimerspec ts;
1907 
1908 	if (timer->data == NULL)
1909 		return 0;
1910 
1911 	spa_loop_remove_source(monitor->main_loop, timer);
1912 	ts.it_value.tv_sec = 0;
1913 	ts.it_value.tv_nsec = 0;
1914 	ts.it_interval.tv_sec = 0;
1915 	ts.it_interval.tv_nsec = 0;
1916 	spa_system_timerfd_settime(monitor->main_system, timer->fd, 0, &ts, NULL);
1917 	spa_system_close(monitor->main_system, timer->fd);
1918 	timer->data = NULL;
1919 	return 0;
1920 }
1921 
spa_bt_transport_release_timer_event(struct spa_source * source)1922 static void spa_bt_transport_release_timer_event(struct spa_source *source)
1923 {
1924 	struct spa_bt_transport *transport = source->data;
1925 	struct spa_bt_monitor *monitor = transport->monitor;
1926 
1927 	spa_assert(transport->acquire_refcount >= 1);
1928 
1929 	spa_bt_transport_stop_release_timer(transport);
1930 
1931 	if (transport->acquire_refcount == 1) {
1932 		spa_bt_transport_impl(transport, release, 0);
1933 	} else {
1934 		spa_log_debug(monitor->log, "transport %p: delayed decref %s", transport, transport->path);
1935 	}
1936 	transport->acquire_refcount -= 1;
1937 }
1938 
spa_bt_transport_start_release_timer(struct spa_bt_transport * transport)1939 static int spa_bt_transport_start_release_timer(struct spa_bt_transport *transport)
1940 {
1941 	return start_timeout_timer(transport->monitor,
1942 		&transport->release_timer,
1943 		spa_bt_transport_release_timer_event,
1944 		SCO_TRANSPORT_RELEASE_TIMEOUT_MSEC, transport);
1945 }
1946 
spa_bt_transport_stop_release_timer(struct spa_bt_transport * transport)1947 static int spa_bt_transport_stop_release_timer(struct spa_bt_transport *transport)
1948 {
1949 	return stop_timeout_timer(transport->monitor, &transport->release_timer);
1950 }
1951 
spa_bt_transport_volume_changed(struct spa_bt_transport * transport)1952 static void spa_bt_transport_volume_changed(struct spa_bt_transport *transport)
1953 {
1954 	struct spa_bt_monitor *monitor = transport->monitor;
1955 	struct spa_bt_transport_volume * t_volume;
1956 	int volume_id;
1957 
1958 	if (transport->profile & SPA_BT_PROFILE_A2DP_SINK)
1959 		volume_id = SPA_BT_VOLUME_ID_TX;
1960 	else if (transport->profile & SPA_BT_PROFILE_A2DP_SOURCE)
1961 		volume_id = SPA_BT_VOLUME_ID_RX;
1962 	else
1963 		return;
1964 
1965 	t_volume = &transport->volumes[volume_id];
1966 
1967 	if (t_volume->hw_volume != t_volume->new_hw_volume) {
1968 		t_volume->hw_volume = t_volume->new_hw_volume;
1969 		t_volume->volume = spa_bt_volume_hw_to_linear(t_volume->hw_volume,
1970 					t_volume->hw_volume_max);
1971 		spa_log_debug(monitor->log, "transport %p: volume changed %d(%f) ",
1972 			transport, t_volume->new_hw_volume, t_volume->volume);
1973 		if (spa_bt_transport_volume_enabled(transport)) {
1974 			transport->device->a2dp_volume_active[volume_id] = true;
1975 			spa_bt_transport_emit_volume_changed(transport);
1976 		}
1977 	}
1978 }
1979 
spa_bt_transport_volume_timer_event(struct spa_source * source)1980 static void spa_bt_transport_volume_timer_event(struct spa_source *source)
1981 {
1982 	struct spa_bt_transport *transport = source->data;
1983 	struct spa_bt_monitor *monitor = transport->monitor;
1984 	uint64_t exp;
1985 
1986 	if (spa_system_timerfd_read(monitor->main_system, source->fd, &exp) < 0)
1987                 spa_log_warn(monitor->log, "error reading timerfd: %s", strerror(errno));
1988 
1989 	spa_bt_transport_volume_changed(transport);
1990 }
1991 
spa_bt_transport_start_volume_timer(struct spa_bt_transport * transport)1992 static int spa_bt_transport_start_volume_timer(struct spa_bt_transport *transport)
1993 {
1994 	return start_timeout_timer(transport->monitor,
1995 			&transport->volume_timer,
1996 			spa_bt_transport_volume_timer_event,
1997 			TRANSPORT_VOLUME_TIMEOUT_MSEC, transport);
1998 }
1999 
spa_bt_transport_stop_volume_timer(struct spa_bt_transport * transport)2000 static int spa_bt_transport_stop_volume_timer(struct spa_bt_transport *transport)
2001 {
2002 	return stop_timeout_timer(transport->monitor, &transport->volume_timer);
2003 }
2004 
2005 
spa_bt_transport_ensure_sco_io(struct spa_bt_transport * t,struct spa_loop * data_loop)2006 int spa_bt_transport_ensure_sco_io(struct spa_bt_transport *t, struct spa_loop *data_loop)
2007 {
2008 	if (t->sco_io == NULL) {
2009 		t->sco_io = spa_bt_sco_io_create(data_loop,
2010 						 t->fd,
2011 						 t->read_mtu,
2012 						 t->write_mtu);
2013 		if (t->sco_io == NULL)
2014 			return -ENOMEM;
2015 	}
2016 	return 0;
2017 }
2018 
spa_bt_transport_get_delay_nsec(struct spa_bt_transport * t)2019 int64_t spa_bt_transport_get_delay_nsec(struct spa_bt_transport *t)
2020 {
2021 	if (t->delay != SPA_BT_UNKNOWN_DELAY)
2022 		return (int64_t)t->delay * 100 * SPA_NSEC_PER_USEC;
2023 
2024 	/* Fallback values when device does not provide information */
2025 
2026 	if (t->a2dp_codec == NULL)
2027 		return 30 * SPA_NSEC_PER_MSEC;
2028 
2029 	switch (t->a2dp_codec->id) {
2030 	case SPA_BLUETOOTH_AUDIO_CODEC_SBC:
2031 	case SPA_BLUETOOTH_AUDIO_CODEC_SBC_XQ:
2032 		return 200 * SPA_NSEC_PER_MSEC;
2033 	case SPA_BLUETOOTH_AUDIO_CODEC_MPEG:
2034 	case SPA_BLUETOOTH_AUDIO_CODEC_AAC:
2035 		return 200 * SPA_NSEC_PER_MSEC;
2036 	case SPA_BLUETOOTH_AUDIO_CODEC_APTX:
2037 	case SPA_BLUETOOTH_AUDIO_CODEC_APTX_HD:
2038 		return 150 * SPA_NSEC_PER_MSEC;
2039 	case SPA_BLUETOOTH_AUDIO_CODEC_LDAC:
2040 		return 175 * SPA_NSEC_PER_MSEC;
2041 	case SPA_BLUETOOTH_AUDIO_CODEC_APTX_LL:
2042 	case SPA_BLUETOOTH_AUDIO_CODEC_APTX_LL_DUPLEX:
2043 	case SPA_BLUETOOTH_AUDIO_CODEC_FASTSTREAM:
2044 	case SPA_BLUETOOTH_AUDIO_CODEC_FASTSTREAM_DUPLEX:
2045 		return 40 * SPA_NSEC_PER_MSEC;
2046 	default:
2047 		break;
2048 	};
2049 	return 150 * SPA_NSEC_PER_MSEC;
2050 }
2051 
transport_update_props(struct spa_bt_transport * transport,DBusMessageIter * props_iter,DBusMessageIter * invalidated_iter)2052 static int transport_update_props(struct spa_bt_transport *transport,
2053 				  DBusMessageIter *props_iter,
2054 				  DBusMessageIter *invalidated_iter)
2055 {
2056 	struct spa_bt_monitor *monitor = transport->monitor;
2057 
2058 	while (dbus_message_iter_get_arg_type(props_iter) != DBUS_TYPE_INVALID) {
2059 		DBusMessageIter it[2];
2060 		const char *key;
2061 		int type;
2062 
2063 		dbus_message_iter_recurse(props_iter, &it[0]);
2064 		dbus_message_iter_get_basic(&it[0], &key);
2065 		dbus_message_iter_next(&it[0]);
2066 		dbus_message_iter_recurse(&it[0], &it[1]);
2067 
2068 		type = dbus_message_iter_get_arg_type(&it[1]);
2069 
2070 		if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
2071 			const char *value;
2072 
2073 			dbus_message_iter_get_basic(&it[1], &value);
2074 
2075 			spa_log_debug(monitor->log, "transport %p: %s=%s", transport, key, value);
2076 
2077 			if (spa_streq(key, "UUID")) {
2078 				switch (spa_bt_profile_from_uuid(value)) {
2079 				case SPA_BT_PROFILE_A2DP_SOURCE:
2080 					transport->profile = SPA_BT_PROFILE_A2DP_SINK;
2081 					break;
2082 				case SPA_BT_PROFILE_A2DP_SINK:
2083 					transport->profile = SPA_BT_PROFILE_A2DP_SOURCE;
2084 					break;
2085 				default:
2086 					spa_log_warn(monitor->log, "unknown profile %s", value);
2087 					break;
2088 				}
2089 			}
2090 			else if (spa_streq(key, "State")) {
2091 				spa_bt_transport_set_state(transport, spa_bt_transport_state_from_string(value));
2092 			}
2093 			else if (spa_streq(key, "Device")) {
2094 				transport->device = spa_bt_device_find(monitor, value);
2095 				if (transport->device == NULL)
2096 					spa_log_warn(monitor->log, "could not find device %s", value);
2097 			}
2098 		}
2099 		else if (spa_streq(key, "Codec")) {
2100 			uint8_t value;
2101 
2102 			if (type != DBUS_TYPE_BYTE)
2103 				goto next;
2104 			dbus_message_iter_get_basic(&it[1], &value);
2105 
2106 			spa_log_debug(monitor->log, "transport %p: %s=%02x", transport, key, value);
2107 
2108 			transport->codec = value;
2109 		}
2110 		else if (spa_streq(key, "Configuration")) {
2111 			DBusMessageIter iter;
2112 			uint8_t *value;
2113 			int i, len;
2114 
2115 			if (!check_iter_signature(&it[1], "ay"))
2116 				goto next;
2117 
2118 			dbus_message_iter_recurse(&it[1], &iter);
2119 			dbus_message_iter_get_fixed_array(&iter, &value, &len);
2120 
2121 			spa_log_debug(monitor->log, "transport %p: %s=%d", transport, key, len);
2122 			for (i = 0; i < len; i++)
2123 				spa_log_debug(monitor->log, "  %d: %02x", i, value[i]);
2124 
2125 			free(transport->configuration);
2126 			transport->configuration_len = 0;
2127 
2128 			transport->configuration = malloc(len);
2129 			if (transport->configuration) {
2130 				memcpy(transport->configuration, value, len);
2131 				transport->configuration_len = len;
2132 			}
2133 		}
2134 		else if (spa_streq(key, "Volume")) {
2135 			uint16_t value;
2136 			struct spa_bt_transport_volume * t_volume;
2137 
2138 			if (type != DBUS_TYPE_UINT16)
2139 				goto next;
2140 			dbus_message_iter_get_basic(&it[1], &value);
2141 
2142 			spa_log_debug(monitor->log, "transport %p: %s=%d", transport, key, value);
2143 
2144 			if (transport->profile & SPA_BT_PROFILE_A2DP_SINK)
2145 				t_volume = &transport->volumes[SPA_BT_VOLUME_ID_TX];
2146 			else if (transport->profile & SPA_BT_PROFILE_A2DP_SOURCE)
2147 				t_volume = &transport->volumes[SPA_BT_VOLUME_ID_RX];
2148 			else
2149 				goto next;
2150 
2151 			t_volume->active = true;
2152 			t_volume->new_hw_volume = value;
2153 
2154 			if (transport->profile & SPA_BT_PROFILE_A2DP_SINK)
2155 				spa_bt_transport_start_volume_timer(transport);
2156 			else
2157 				spa_bt_transport_volume_changed(transport);
2158 		}
2159 		else if (spa_streq(key, "Delay")) {
2160 			uint16_t value;
2161 
2162 			if (type != DBUS_TYPE_UINT16)
2163 				goto next;
2164 			dbus_message_iter_get_basic(&it[1], &value);
2165 
2166 			spa_log_debug(monitor->log, "transport %p: %s=%02x", transport, key, value);
2167 
2168 			transport->delay = value;
2169 			spa_bt_transport_emit_delay_changed(transport);
2170 		}
2171 	      next:
2172 		dbus_message_iter_next(props_iter);
2173 	}
2174 	return 0;
2175 }
2176 
transport_set_property_volume(struct spa_bt_transport * transport,uint16_t value)2177 static int transport_set_property_volume(struct spa_bt_transport *transport, uint16_t value)
2178 {
2179 	struct spa_bt_monitor *monitor = transport->monitor;
2180 	DBusMessage *m, *r;
2181 	DBusMessageIter it[2];
2182 	DBusError err;
2183 	const char *interface = BLUEZ_MEDIA_TRANSPORT_INTERFACE;
2184 	const char *name = "Volume";
2185 	int res = 0;
2186 
2187 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
2188 					 transport->path,
2189 	                                 DBUS_INTERFACE_PROPERTIES,
2190 					 "Set");
2191 	if (m == NULL)
2192 		return -ENOMEM;
2193 
2194 	dbus_message_iter_init_append(m, &it[0]);
2195 	dbus_message_iter_append_basic(&it[0], DBUS_TYPE_STRING, &interface);
2196 	dbus_message_iter_append_basic(&it[0], DBUS_TYPE_STRING, &name);
2197 	dbus_message_iter_open_container(&it[0], DBUS_TYPE_VARIANT,
2198 					DBUS_TYPE_UINT16_AS_STRING, &it[1]);
2199 	dbus_message_iter_append_basic(&it[1], DBUS_TYPE_UINT16, &value);
2200 	dbus_message_iter_close_container(&it[0], &it[1]);
2201 
2202 	dbus_error_init(&err);
2203 
2204 	r = dbus_connection_send_with_reply_and_block(monitor->conn, m, -1, &err);
2205 
2206 	dbus_message_unref(m);
2207 
2208 	if (r == NULL) {
2209 		spa_log_error(monitor->log, "set volume %u failed for transport %s (%s)",
2210 				value, transport->path, err.message);
2211 		dbus_error_free(&err);
2212 		return -EIO;
2213 	}
2214 
2215 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR)
2216 		res = -EIO;
2217 
2218 	dbus_message_unref(r);
2219 
2220 	spa_log_debug(monitor->log, "transport %p: set volume to %d", transport, value);
2221 
2222 	return res;
2223 }
2224 
transport_set_volume(void * data,int id,float volume)2225 static int transport_set_volume(void *data, int id, float volume)
2226 {
2227 	struct spa_bt_transport *transport = data;
2228 	struct spa_bt_transport_volume *t_volume = &transport->volumes[id];
2229 	uint16_t value;
2230 
2231 	if (!t_volume->active || !spa_bt_transport_volume_enabled(transport))
2232 		return -ENOTSUP;
2233 
2234 	value = spa_bt_volume_linear_to_hw(volume, 127);
2235 	t_volume->volume = volume;
2236 
2237 	/* AVRCP volume would not applied on remote sink device
2238 	 * if transport is not acquired (idle). */
2239 	if (transport->fd < 0 && (transport->profile & SPA_BT_PROFILE_A2DP_SINK)) {
2240 		t_volume->hw_volume = SPA_BT_VOLUME_INVALID;
2241 		return 0;
2242 	} else if (t_volume->hw_volume != value) {
2243 		t_volume->hw_volume = value;
2244 		spa_bt_transport_stop_volume_timer(transport);
2245 		transport_set_property_volume(transport, value);
2246 	}
2247 	return 0;
2248 }
2249 
transport_acquire(void * data,bool optional)2250 static int transport_acquire(void *data, bool optional)
2251 {
2252 	struct spa_bt_transport *transport = data;
2253 	struct spa_bt_monitor *monitor = transport->monitor;
2254 	DBusMessage *m, *r;
2255 	DBusError err;
2256 	int ret = 0;
2257 	const char *method = optional ? "TryAcquire" : "Acquire";
2258 
2259 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
2260 					 transport->path,
2261 					 BLUEZ_MEDIA_TRANSPORT_INTERFACE,
2262 					 method);
2263 	if (m == NULL)
2264 		return -ENOMEM;
2265 
2266 	dbus_error_init(&err);
2267 
2268 	r = dbus_connection_send_with_reply_and_block(monitor->conn, m, -1, &err);
2269 	dbus_message_unref(m);
2270 	m = NULL;
2271 
2272 	if (r == NULL) {
2273 		if (optional && spa_streq(err.name, "org.bluez.Error.NotAvailable")) {
2274 			spa_log_info(monitor->log, "Failed optional acquire of unavailable transport %s",
2275 					transport->path);
2276 		}
2277 		else {
2278 			spa_log_error(monitor->log, "Transport %s() failed for transport %s (%s)",
2279 					method, transport->path, err.message);
2280 		}
2281 		dbus_error_free(&err);
2282 		return -EIO;
2283 	}
2284 
2285 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
2286 		spa_log_error(monitor->log, "%s returned error: %s", method, dbus_message_get_error_name(r));
2287 		ret = -EIO;
2288 		goto finish;
2289 	}
2290 
2291 	if (!dbus_message_get_args(r, &err,
2292 				   DBUS_TYPE_UNIX_FD, &transport->fd,
2293 				   DBUS_TYPE_UINT16, &transport->read_mtu,
2294 				   DBUS_TYPE_UINT16, &transport->write_mtu,
2295 				   DBUS_TYPE_INVALID)) {
2296 		spa_log_error(monitor->log, "Failed to parse %s() reply: %s", method, err.message);
2297 		dbus_error_free(&err);
2298 		ret = -EIO;
2299 		goto finish;
2300 	}
2301 	spa_log_debug(monitor->log, "transport %p: %s %s, fd %d MTU %d:%d", transport, method,
2302 			transport->path, transport->fd, transport->read_mtu, transport->write_mtu);
2303 
2304 	spa_bt_player_set_state(transport->device->adapter->dummy_player, SPA_BT_PLAYER_PLAYING);
2305 
2306 	transport_sync_volume(transport);
2307 
2308 finish:
2309 	dbus_message_unref(r);
2310 	return ret;
2311 }
2312 
transport_release(void * data)2313 static int transport_release(void *data)
2314 {
2315 	struct spa_bt_transport *transport = data;
2316 	struct spa_bt_monitor *monitor = transport->monitor;
2317 	DBusMessage *m, *r;
2318 	DBusError err;
2319 	bool is_idle = (transport->state == SPA_BT_TRANSPORT_STATE_IDLE);
2320 
2321 	spa_log_debug(monitor->log, "transport %p: Release %s",
2322 			transport, transport->path);
2323 
2324 	spa_bt_player_set_state(transport->device->adapter->dummy_player, SPA_BT_PLAYER_STOPPED);
2325 
2326 	close(transport->fd);
2327 	transport->fd = -1;
2328 
2329 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
2330 					 transport->path,
2331 					 BLUEZ_MEDIA_TRANSPORT_INTERFACE,
2332 					 "Release");
2333 	if (m == NULL)
2334 		return -ENOMEM;
2335 
2336 	dbus_error_init(&err);
2337 
2338 	r = dbus_connection_send_with_reply_and_block(monitor->conn, m, -1, &err);
2339 	dbus_message_unref(m);
2340 	m = NULL;
2341 
2342 	if (r != NULL)
2343 		dbus_message_unref(r);
2344 
2345 	if (dbus_error_is_set(&err)) {
2346 		if (is_idle) {
2347 			/* XXX: The fd always needs to be closed. However, Release()
2348 			 * XXX: apparently doesn't need to be called on idle transports
2349 			 * XXX: and fails. We call it just to be sure (e.g. in case
2350 			 * XXX: there's a race with updating the property), but tone down the error.
2351 			 */
2352 			spa_log_debug(monitor->log, "Failed to release idle transport %s: %s",
2353 			              transport->path, err.message);
2354 		} else {
2355 			spa_log_error(monitor->log, "Failed to release transport %s: %s",
2356 			              transport->path, err.message);
2357 		}
2358 		dbus_error_free(&err);
2359 	}
2360 	else
2361 		spa_log_info(monitor->log, "Transport %s released", transport->path);
2362 
2363 	return 0;
2364 }
2365 
2366 static const struct spa_bt_transport_implementation transport_impl = {
2367 	SPA_VERSION_BT_TRANSPORT_IMPLEMENTATION,
2368 	.acquire = transport_acquire,
2369 	.release = transport_release,
2370 	.set_volume = transport_set_volume,
2371 };
2372 
2373 static void append_basic_array_variant_dict_entry(DBusMessageIter *dict, int key_type_int, void* key, const char* variant_type_str, const char* array_type_str, int array_type_int, void* data, int data_size);
2374 
2375 static void a2dp_codec_switch_reply(DBusPendingCall *pending, void *userdata);
2376 
2377 static int a2dp_codec_switch_cmp(const void *a, const void *b);
2378 
2379 static struct spa_bt_a2dp_codec_switch *a2dp_codec_switch_cmp_sw;  /* global for qsort */
2380 
2381 static int a2dp_codec_switch_start_timer(struct spa_bt_a2dp_codec_switch *sw, uint64_t timeout);
2382 
2383 static int a2dp_codec_switch_stop_timer(struct spa_bt_a2dp_codec_switch *sw);
2384 
a2dp_codec_switch_free(struct spa_bt_a2dp_codec_switch * sw)2385 static void a2dp_codec_switch_free(struct spa_bt_a2dp_codec_switch *sw)
2386 {
2387 	char **p;
2388 
2389 	a2dp_codec_switch_stop_timer(sw);
2390 
2391 	if (sw->pending != NULL) {
2392 		dbus_pending_call_cancel(sw->pending);
2393 		dbus_pending_call_unref(sw->pending);
2394 	}
2395 
2396 	if (sw->device != NULL)
2397 		spa_list_remove(&sw->device_link);
2398 
2399 	if (sw->paths != NULL)
2400 		for (p = sw->paths; *p != NULL; ++p)
2401 			free(*p);
2402 
2403 	free(sw->paths);
2404 	free(sw->codecs);
2405 	free(sw);
2406 }
2407 
a2dp_codec_switch_next(struct spa_bt_a2dp_codec_switch * sw)2408 static void a2dp_codec_switch_next(struct spa_bt_a2dp_codec_switch *sw)
2409 {
2410 	spa_assert(*sw->codec_iter != NULL && *sw->path_iter != NULL);
2411 
2412 	++sw->path_iter;
2413 	if (*sw->path_iter == NULL) {
2414 		++sw->codec_iter;
2415 		sw->path_iter = sw->paths;
2416 	}
2417 
2418 	sw->retries = CODEC_SWITCH_RETRIES;
2419 }
2420 
a2dp_codec_switch_process_current(struct spa_bt_a2dp_codec_switch * sw)2421 static bool a2dp_codec_switch_process_current(struct spa_bt_a2dp_codec_switch *sw)
2422 {
2423 	struct spa_bt_remote_endpoint *ep;
2424 	const struct a2dp_codec *codec;
2425 	uint8_t config[A2DP_MAX_CAPS_SIZE];
2426 	char *local_endpoint_base;
2427 	char *local_endpoint = NULL;
2428 	int res, config_size;
2429 	dbus_bool_t dbus_ret;
2430 	const char *str;
2431 	DBusMessage *m;
2432 	DBusMessageIter iter, d;
2433 	int i;
2434 
2435 	/* Try setting configuration for current codec on current endpoint in list */
2436 
2437 	codec = *sw->codec_iter;
2438 
2439 	spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: consider codec %s for remote endpoint %s",
2440 	              sw, (*sw->codec_iter)->name, *sw->path_iter);
2441 
2442 	ep = device_remote_endpoint_find(sw->device, *sw->path_iter);
2443 
2444 	if (ep == NULL || ep->capabilities == NULL || ep->uuid == NULL) {
2445 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: endpoint %s not valid, try next",
2446 		              sw, *sw->path_iter);
2447 		goto next;
2448 	}
2449 
2450 	/* Setup and check compatible configuration */
2451 	if (ep->codec != codec->codec_id) {
2452 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: different codec, try next", sw);
2453 		goto next;
2454 	}
2455 
2456 	if (!(sw->profile & spa_bt_profile_from_uuid(ep->uuid))) {
2457 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: wrong uuid (%s) for profile, try next",
2458 		              sw, ep->uuid);
2459 		goto next;
2460 	}
2461 
2462 	if (sw->profile & SPA_BT_PROFILE_A2DP_SINK) {
2463 		local_endpoint_base = A2DP_SOURCE_ENDPOINT;
2464 	} else if (sw->profile & SPA_BT_PROFILE_A2DP_SOURCE) {
2465 		local_endpoint_base = A2DP_SINK_ENDPOINT;
2466 	} else {
2467 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: bad profile (%d), try next",
2468 		              sw, sw->profile);
2469 		goto next;
2470 	}
2471 
2472 	if (a2dp_codec_to_endpoint(codec, local_endpoint_base, &local_endpoint) < 0) {
2473 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: no endpoint for codec %s, try next",
2474 		              sw, codec->name);
2475 		goto next;
2476 	}
2477 
2478 	res = codec->select_config(codec, 0, ep->capabilities, ep->capabilities_len,
2479 				   &sw->device->monitor->default_audio_info,
2480 				   sw->device->settings, config);
2481 	if (res < 0) {
2482 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: incompatible capabilities (%d), try next",
2483 		              sw, res);
2484 		goto next;
2485 	}
2486 	config_size = res;
2487 
2488 	spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: configuration %d", sw, config_size);
2489 	for (i = 0; i < config_size; i++)
2490 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p:     %d: %02x", sw, i, config[i]);
2491 
2492 	/* org.bluez.MediaEndpoint1.SetConfiguration on remote endpoint */
2493 	m = dbus_message_new_method_call(BLUEZ_SERVICE, ep->path, BLUEZ_MEDIA_ENDPOINT_INTERFACE, "SetConfiguration");
2494 	if (m == NULL) {
2495 		spa_log_debug(sw->device->monitor->log, "a2dp codec switch %p: dbus allocation failure, try next", sw);
2496 		goto next;
2497 	}
2498 
2499 	device_update_last_bluez_action_time(sw->device);
2500 
2501 	spa_log_info(sw->device->monitor->log, "a2dp codec switch %p: trying codec %s for endpoint %s, local endpoint %s",
2502 	             sw, codec->name, ep->path, local_endpoint);
2503 
2504 	dbus_message_iter_init_append(m, &iter);
2505 	dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &local_endpoint);
2506 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &d);
2507 	str = "Capabilities";
2508 	append_basic_array_variant_dict_entry(&d, DBUS_TYPE_STRING, &str, "ay", "y", DBUS_TYPE_BYTE, config, config_size);
2509 	dbus_message_iter_close_container(&iter, &d);
2510 
2511 	spa_assert(sw->pending == NULL);
2512 	dbus_ret = dbus_connection_send_with_reply(sw->device->monitor->conn, m, &sw->pending, -1);
2513 
2514 	if (!dbus_ret || sw->pending == NULL) {
2515 		spa_log_error(sw->device->monitor->log, "a2dp codec switch %p: dbus call failure, try next", sw);
2516 		dbus_message_unref(m);
2517 		goto next;
2518 	}
2519 
2520 	dbus_ret = dbus_pending_call_set_notify(sw->pending, a2dp_codec_switch_reply, sw, NULL);
2521 	dbus_message_unref(m);
2522 
2523 	if (!dbus_ret) {
2524 		spa_log_error(sw->device->monitor->log, "a2dp codec switch %p: dbus set notify failure", sw);
2525 		goto next;
2526 	}
2527 
2528 	free(local_endpoint);
2529 	return true;
2530 
2531 next:
2532 	free(local_endpoint);
2533 	return false;
2534 }
2535 
a2dp_codec_switch_process(struct spa_bt_a2dp_codec_switch * sw)2536 static void a2dp_codec_switch_process(struct spa_bt_a2dp_codec_switch *sw)
2537 {
2538 	while (*sw->codec_iter != NULL && *sw->path_iter != NULL) {
2539 		struct timespec ts;
2540 		uint64_t now, threshold;
2541 
2542 		/* Rate limit BlueZ calls */
2543 		spa_system_clock_gettime(sw->device->monitor->main_system, CLOCK_MONOTONIC, &ts);
2544 		now = SPA_TIMESPEC_TO_NSEC(&ts);
2545 		threshold = sw->device->last_bluez_action_time + BLUEZ_ACTION_RATE_MSEC * SPA_NSEC_PER_MSEC;
2546 		if (now < threshold) {
2547 			/* Wait for timeout */
2548 			a2dp_codec_switch_start_timer(sw, threshold - now);
2549 			return;
2550 		}
2551 
2552 		if (sw->path_iter == sw->paths && (*sw->codec_iter)->caps_preference_cmp) {
2553 			/* Sort endpoints according to codec preference, when at a new codec. */
2554 			a2dp_codec_switch_cmp_sw = sw;
2555 			qsort(sw->paths, sw->num_paths, sizeof(char *), a2dp_codec_switch_cmp);
2556 		}
2557 
2558 		if (a2dp_codec_switch_process_current(sw)) {
2559 			/* Wait for dbus reply */
2560 			return;
2561 		}
2562 
2563 		a2dp_codec_switch_next(sw);
2564 	};
2565 
2566 	/* Didn't find any suitable endpoint. Report failure. */
2567 	spa_log_info(sw->device->monitor->log, "a2dp codec switch %p: failed to get an endpoint", sw);
2568 	spa_bt_device_emit_codec_switched(sw->device, -ENODEV);
2569 	spa_bt_device_check_profiles(sw->device, false);
2570 	a2dp_codec_switch_free(sw);
2571 }
2572 
a2dp_codec_switch_goto_active(struct spa_bt_a2dp_codec_switch * sw)2573 static bool a2dp_codec_switch_goto_active(struct spa_bt_a2dp_codec_switch *sw)
2574 {
2575 	struct spa_bt_device *device = sw->device;
2576 	struct spa_bt_a2dp_codec_switch *active_sw;
2577 
2578 	active_sw = spa_list_first(&device->codec_switch_list, struct spa_bt_a2dp_codec_switch, device_link);
2579 
2580 	if (active_sw != sw) {
2581 		struct spa_bt_a2dp_codec_switch *t;
2582 
2583 		/* This codec switch has been canceled. Switch to the newest one. */
2584 		spa_log_debug(sw->device->monitor->log,
2585 			      "a2dp codec switch %p: canceled, go to new switch", sw);
2586 
2587 		spa_list_for_each_safe(sw, t, &device->codec_switch_list, device_link) {
2588 			if (sw != active_sw)
2589 				a2dp_codec_switch_free(sw);
2590 		}
2591 
2592 		a2dp_codec_switch_process(active_sw);
2593 		return false;
2594 	}
2595 
2596 	return true;
2597 }
2598 
a2dp_codec_switch_timer_event(struct spa_source * source)2599 static void a2dp_codec_switch_timer_event(struct spa_source *source)
2600 {
2601 	struct spa_bt_a2dp_codec_switch *sw = source->data;
2602 	struct spa_bt_device *device = sw->device;
2603 	struct spa_bt_monitor *monitor = device->monitor;
2604 	uint64_t exp;
2605 
2606 	if (spa_system_timerfd_read(monitor->main_system, source->fd, &exp) < 0)
2607                 spa_log_warn(monitor->log, "error reading timerfd: %s", strerror(errno));
2608 
2609 	spa_log_debug(monitor->log, "a2dp codec switch %p: rate limit timer event", sw);
2610 
2611 	a2dp_codec_switch_stop_timer(sw);
2612 
2613 	if (!a2dp_codec_switch_goto_active(sw))
2614 		return;
2615 
2616 	a2dp_codec_switch_process(sw);
2617 }
2618 
a2dp_codec_switch_reply(DBusPendingCall * pending,void * user_data)2619 static void a2dp_codec_switch_reply(DBusPendingCall *pending, void *user_data)
2620 {
2621 	struct spa_bt_a2dp_codec_switch *sw = user_data;
2622 	struct spa_bt_device *device = sw->device;
2623 	DBusMessage *r;
2624 
2625 	r = dbus_pending_call_steal_reply(pending);
2626 
2627 	spa_assert(sw->pending == pending);
2628 	dbus_pending_call_unref(pending);
2629 	sw->pending = NULL;
2630 
2631 	device_update_last_bluez_action_time(device);
2632 
2633 	if (!a2dp_codec_switch_goto_active(sw)) {
2634 		if (r != NULL)
2635 			dbus_message_unref(r);
2636 		return;
2637 	}
2638 
2639 	if (r == NULL) {
2640 		spa_log_error(sw->device->monitor->log,
2641 		              "a2dp codec switch %p: empty reply from dbus, trying next",
2642 		              sw);
2643 		goto next;
2644 	}
2645 
2646 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
2647 		spa_log_debug(sw->device->monitor->log,
2648 		              "a2dp codec switch %p: failed (%s), trying next",
2649 		              sw, dbus_message_get_error_name(r));
2650 		dbus_message_unref(r);
2651 		goto next;
2652 	}
2653 
2654 	dbus_message_unref(r);
2655 
2656 	/* Success */
2657 	spa_log_info(sw->device->monitor->log, "a2dp codec switch %p: success", sw);
2658 	spa_bt_device_emit_codec_switched(sw->device, 0);
2659 	spa_bt_device_check_profiles(sw->device, false);
2660 	a2dp_codec_switch_free(sw);
2661 	return;
2662 
2663 next:
2664 	if (sw->retries > 0)
2665 		--sw->retries;
2666 	else
2667 		a2dp_codec_switch_next(sw);
2668 
2669 	a2dp_codec_switch_process(sw);
2670 	return;
2671 }
2672 
a2dp_codec_switch_start_timer(struct spa_bt_a2dp_codec_switch * sw,uint64_t timeout)2673 static int a2dp_codec_switch_start_timer(struct spa_bt_a2dp_codec_switch *sw, uint64_t timeout)
2674 {
2675 	struct spa_bt_monitor *monitor = sw->device->monitor;
2676 	struct itimerspec ts;
2677 
2678 	spa_assert(sw->timer.data == NULL);
2679 
2680 	spa_log_debug(monitor->log, "a2dp codec switch %p: starting rate limit timer", sw);
2681 
2682 	if (sw->timer.data == NULL) {
2683 		sw->timer.data = sw;
2684 		sw->timer.func = a2dp_codec_switch_timer_event;
2685 		sw->timer.fd = spa_system_timerfd_create(monitor->main_system,
2686 				CLOCK_MONOTONIC, SPA_FD_CLOEXEC | SPA_FD_NONBLOCK);
2687 		sw->timer.mask = SPA_IO_IN;
2688 		sw->timer.rmask = 0;
2689 		spa_loop_add_source(monitor->main_loop, &sw->timer);
2690 	}
2691 	ts.it_value.tv_sec = timeout / SPA_NSEC_PER_SEC;
2692 	ts.it_value.tv_nsec = timeout % SPA_NSEC_PER_SEC;
2693 	ts.it_interval.tv_sec = 0;
2694 	ts.it_interval.tv_nsec = 0;
2695 	spa_system_timerfd_settime(monitor->main_system, sw->timer.fd, 0, &ts, NULL);
2696 	return 0;
2697 }
2698 
a2dp_codec_switch_stop_timer(struct spa_bt_a2dp_codec_switch * sw)2699 static int a2dp_codec_switch_stop_timer(struct spa_bt_a2dp_codec_switch *sw)
2700 {
2701 	struct spa_bt_monitor *monitor = sw->device->monitor;
2702 	struct itimerspec ts;
2703 
2704 	if (sw->timer.data == NULL)
2705 		return 0;
2706 
2707 	spa_log_debug(monitor->log, "a2dp codec switch %p: stopping rate limit timer", sw);
2708 
2709 	spa_loop_remove_source(monitor->main_loop, &sw->timer);
2710 	ts.it_value.tv_sec = 0;
2711 	ts.it_value.tv_nsec = 0;
2712 	ts.it_interval.tv_sec = 0;
2713 	ts.it_interval.tv_nsec = 0;
2714 	spa_system_timerfd_settime(monitor->main_system, sw->timer.fd, 0, &ts, NULL);
2715 	spa_system_close(monitor->main_system, sw->timer.fd);
2716 	sw->timer.data = NULL;
2717 	return 0;
2718 }
2719 
a2dp_codec_switch_cmp(const void * a,const void * b)2720 static int a2dp_codec_switch_cmp(const void *a, const void *b)
2721 {
2722 	struct spa_bt_a2dp_codec_switch *sw = a2dp_codec_switch_cmp_sw;
2723 	const struct a2dp_codec *codec = *sw->codec_iter;
2724 	const char *path1 = *(char **)a, *path2 = *(char **)b;
2725 	struct spa_bt_remote_endpoint *ep1, *ep2;
2726 
2727 	ep1 = device_remote_endpoint_find(sw->device, path1);
2728 	ep2 = device_remote_endpoint_find(sw->device, path2);
2729 
2730 	if (ep1 != NULL && (ep1->uuid == NULL || ep1->codec != codec->codec_id || ep1->capabilities == NULL))
2731 		ep1 = NULL;
2732 	if (ep2 != NULL && (ep2->uuid == NULL || ep2->codec != codec->codec_id || ep2->capabilities == NULL))
2733 		ep2 = NULL;
2734 
2735 	if (ep1 == NULL && ep2 == NULL)
2736 		return 0;
2737 	else if (ep1 == NULL)
2738 		return 1;
2739 	else if (ep2 == NULL)
2740 		return -1;
2741 
2742 	return codec->caps_preference_cmp(codec, ep1->capabilities, ep1->capabilities_len,
2743 			ep2->capabilities, ep2->capabilities_len, &sw->device->monitor->default_audio_info);
2744 }
2745 
2746 /* Ensure there's a transport for at least one of the listed codecs */
spa_bt_device_ensure_a2dp_codec(struct spa_bt_device * device,const struct a2dp_codec * const * codecs)2747 int spa_bt_device_ensure_a2dp_codec(struct spa_bt_device *device, const struct a2dp_codec * const *codecs)
2748 {
2749 	struct spa_bt_a2dp_codec_switch *sw;
2750 	struct spa_bt_remote_endpoint *ep;
2751 	struct spa_bt_transport *t;
2752 	const struct a2dp_codec *preferred_codec = NULL;
2753 	size_t i, j, num_codecs, num_eps;
2754 
2755 	if (!device->adapter->application_registered) {
2756 		/* Codec switching not supported */
2757 		return -ENOTSUP;
2758 	}
2759 
2760 	for (i = 0; codecs[i] != NULL; ++i) {
2761 		if (spa_bt_device_supports_a2dp_codec(device, codecs[i])) {
2762 			preferred_codec = codecs[i];
2763 			break;
2764 		}
2765 	}
2766 
2767 	/* Check if we already have an enabled transport for the most preferred codec.
2768 	 * However, if there already was a codec switch running, these transports may
2769 	 * disappear soon. In that case, we have to do the full thing.
2770 	 */
2771 	if (spa_list_is_empty(&device->codec_switch_list) && preferred_codec != NULL) {
2772 		spa_list_for_each(t, &device->transport_list, device_link) {
2773 			if (t->a2dp_codec != preferred_codec)
2774 				continue;
2775 
2776 			if ((device->connected_profiles & t->profile) != t->profile)
2777 				continue;
2778 
2779 			spa_bt_device_emit_codec_switched(device, 0);
2780 			return 0;
2781 		}
2782 	}
2783 
2784 	/* Setup and start iteration */
2785 
2786 	sw = calloc(1, sizeof(struct spa_bt_a2dp_codec_switch));
2787 	if (sw == NULL)
2788 		return -ENOMEM;
2789 
2790 	num_eps = 0;
2791 	spa_list_for_each(ep, &device->remote_endpoint_list, device_link)
2792 		++num_eps;
2793 
2794 	num_codecs = 0;
2795 	while (codecs[num_codecs] != NULL)
2796 		++num_codecs;
2797 
2798 	sw->codecs = calloc(num_codecs + 1, sizeof(const struct a2dp_codec *));
2799 	sw->paths = calloc(num_eps + 1, sizeof(char *));
2800 	sw->num_paths = num_eps;
2801 
2802 	if (sw->codecs == NULL || sw->paths == NULL) {
2803 		a2dp_codec_switch_free(sw);
2804 		return -ENOMEM;
2805 	}
2806 
2807 	for (i = 0, j = 0; i < num_codecs; ++i) {
2808 		if (is_a2dp_codec_enabled(device->monitor, codecs[i])) {
2809 			sw->codecs[j] = codecs[i];
2810 			++j;
2811 		}
2812 	}
2813 	sw->codecs[j] = NULL;
2814 
2815 	i = 0;
2816 	spa_list_for_each(ep, &device->remote_endpoint_list, device_link) {
2817 		sw->paths[i] = strdup(ep->path);
2818 		if (sw->paths[i] == NULL) {
2819 			a2dp_codec_switch_free(sw);
2820 			return -ENOMEM;
2821 		}
2822 		++i;
2823 	}
2824 	sw->paths[i] = NULL;
2825 
2826 	sw->codec_iter = sw->codecs;
2827 	sw->path_iter = sw->paths;
2828 	sw->retries = CODEC_SWITCH_RETRIES;
2829 
2830 	sw->profile = device->connected_profiles;
2831 
2832 	sw->device = device;
2833 
2834 	if (!spa_list_is_empty(&device->codec_switch_list)) {
2835 		/*
2836 		 * There's a codec switch already running, either waiting for timeout or
2837 		 * BlueZ reply.
2838 		 *
2839 		 * BlueZ does not appear to allow calling dbus_pending_call_cancel on an
2840 		 * active request, so we have to wait for the reply to arrive first, and
2841 		 * only then start processing this request. The timeout we would also have
2842 		 * to wait to pass in any case, so we don't cancel it either.
2843 		 */
2844 		spa_log_debug(sw->device->monitor->log,
2845 				"a2dp codec switch %p: already in progress, canceling previous",
2846 				sw);
2847 
2848 		spa_list_prepend(&device->codec_switch_list, &sw->device_link);
2849 	} else {
2850 		spa_list_prepend(&device->codec_switch_list, &sw->device_link);
2851 		a2dp_codec_switch_process(sw);
2852 	}
2853 
2854 	return 0;
2855 }
2856 
spa_bt_device_ensure_hfp_codec(struct spa_bt_device * device,unsigned int codec)2857 int spa_bt_device_ensure_hfp_codec(struct spa_bt_device *device, unsigned int codec)
2858 {
2859 	struct spa_bt_monitor *monitor = device->monitor;
2860 	return spa_bt_backend_ensure_codec(monitor->backend, device, codec);
2861 }
2862 
spa_bt_device_supports_hfp_codec(struct spa_bt_device * device,unsigned int codec)2863 int spa_bt_device_supports_hfp_codec(struct spa_bt_device *device, unsigned int codec)
2864 {
2865 	struct spa_bt_monitor *monitor = device->monitor;
2866 	return spa_bt_backend_supports_codec(monitor->backend, device, codec);
2867 }
2868 
endpoint_set_configuration(DBusConnection * conn,const char * path,DBusMessage * m,void * userdata)2869 static DBusHandlerResult endpoint_set_configuration(DBusConnection *conn,
2870 		const char *path, DBusMessage *m, void *userdata)
2871 {
2872 	struct spa_bt_monitor *monitor = userdata;
2873 	const char *transport_path, *endpoint;
2874 	DBusMessageIter it[2];
2875 	DBusMessage *r;
2876 	struct spa_bt_transport *transport;
2877 	bool is_new = false;
2878 	const struct a2dp_codec *codec;
2879 	int profile;
2880 
2881 	if (!dbus_message_has_signature(m, "oa{sv}")) {
2882 		spa_log_warn(monitor->log, "invalid SetConfiguration() signature");
2883 		return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2884 	}
2885 	endpoint = dbus_message_get_path(m);
2886 
2887 	profile = a2dp_endpoint_to_profile(endpoint);
2888 	codec = a2dp_endpoint_to_codec(monitor, endpoint);
2889 	if (codec == NULL) {
2890 		spa_log_warn(monitor->log, "unknown SetConfiguration() codec");
2891 		return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2892 	}
2893 
2894 	dbus_message_iter_init(m, &it[0]);
2895 	dbus_message_iter_get_basic(&it[0], &transport_path);
2896 	dbus_message_iter_next(&it[0]);
2897 	dbus_message_iter_recurse(&it[0], &it[1]);
2898 
2899 	transport = spa_bt_transport_find(monitor, transport_path);
2900 	is_new = transport == NULL;
2901 
2902 	if (is_new) {
2903 		char *tpath = strdup(transport_path);
2904 
2905 		transport = spa_bt_transport_create(monitor, tpath, 0);
2906 		if (transport == NULL) {
2907 			free(tpath);
2908 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
2909 		}
2910 
2911 		spa_bt_transport_set_implementation(transport, &transport_impl, transport);
2912 
2913 		if (profile & SPA_BT_PROFILE_A2DP_SOURCE) {
2914 			transport->volumes[SPA_BT_VOLUME_ID_RX].volume = DEFAULT_AG_VOLUME;
2915 			transport->volumes[SPA_BT_VOLUME_ID_TX].volume = DEFAULT_AG_VOLUME;
2916 		} else {
2917 			transport->volumes[SPA_BT_VOLUME_ID_RX].volume = DEFAULT_RX_VOLUME;
2918 			transport->volumes[SPA_BT_VOLUME_ID_TX].volume = DEFAULT_TX_VOLUME;
2919 		}
2920 	}
2921 
2922 	for (int i = 0; i < SPA_BT_VOLUME_ID_TERM; ++i) {
2923 		transport->volumes[i].hw_volume = SPA_BT_VOLUME_INVALID;
2924 		transport->volumes[i].hw_volume_max = SPA_BT_VOLUME_A2DP_MAX;
2925 	}
2926 
2927 	transport->profile = profile;
2928 	transport->a2dp_codec = codec;
2929 	transport_update_props(transport, &it[1], NULL);
2930 
2931 	if (transport->device == NULL) {
2932 		spa_log_warn(monitor->log, "no device found for transport");
2933 		return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2934 	}
2935 	spa_bt_device_add_profile(transport->device, transport->profile);
2936 
2937 	if (is_new)
2938 		spa_list_append(&transport->device->transport_list, &transport->device_link);
2939 
2940 	device_update_last_bluez_action_time(transport->device);
2941 
2942 	if (profile & SPA_BT_PROFILE_A2DP_SOURCE) {
2943 		/* PW is the rendering device so it's responsible for reporting hardware volume. */
2944 		transport->volumes[SPA_BT_VOLUME_ID_RX].active = true;
2945 	} else if (profile & SPA_BT_PROFILE_A2DP_SINK) {
2946 		transport->volumes[SPA_BT_VOLUME_ID_TX].active
2947 			|= transport->device->a2dp_volume_active[SPA_BT_VOLUME_ID_TX];
2948 	}
2949 
2950 	if (codec->validate_config) {
2951 		struct spa_audio_info info;
2952 		if (codec->validate_config(codec, 0,
2953 					transport->configuration, transport->configuration_len,
2954 					&info) < 0) {
2955 			spa_log_error(monitor->log, "invalid transport configuration");
2956 			return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2957 		}
2958 		transport->n_channels = info.info.raw.channels;
2959 		memcpy(transport->channels, info.info.raw.position,
2960 				transport->n_channels * sizeof(uint32_t));
2961 	} else {
2962 		transport->n_channels = 2;
2963 		transport->channels[0] = SPA_AUDIO_CHANNEL_FL;
2964 		transport->channels[1] = SPA_AUDIO_CHANNEL_FR;
2965 	}
2966 	spa_log_info(monitor->log, "%p: %s validate conf channels:%d",
2967 			monitor, path, transport->n_channels);
2968 
2969 	spa_bt_device_connect_profile(transport->device, transport->profile);
2970 
2971 	/* Sync initial volumes */
2972 	transport_sync_volume(transport);
2973 
2974 	if ((r = dbus_message_new_method_return(m)) == NULL)
2975 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
2976 	if (!dbus_connection_send(conn, r, NULL))
2977 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
2978 
2979 	dbus_message_unref(r);
2980 
2981 	return DBUS_HANDLER_RESULT_HANDLED;
2982 }
2983 
endpoint_clear_configuration(DBusConnection * conn,DBusMessage * m,void * userdata)2984 static DBusHandlerResult endpoint_clear_configuration(DBusConnection *conn, DBusMessage *m, void *userdata)
2985 {
2986 	struct spa_bt_monitor *monitor = userdata;
2987 	DBusError err;
2988 	DBusMessage *r;
2989 	const char *transport_path;
2990 	struct spa_bt_transport *transport;
2991 
2992 	dbus_error_init(&err);
2993 
2994 	if (!dbus_message_get_args(m, &err,
2995 				   DBUS_TYPE_OBJECT_PATH, &transport_path,
2996 				   DBUS_TYPE_INVALID)) {
2997 		spa_log_warn(monitor->log, "Bad ClearConfiguration method call: %s",
2998 			err.message);
2999 		dbus_error_free(&err);
3000 		return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3001 	}
3002 
3003 	transport = spa_bt_transport_find(monitor, transport_path);
3004 
3005 	if (transport != NULL) {
3006 		struct spa_bt_device *device = transport->device;
3007 
3008 		spa_log_debug(monitor->log, "transport %p: free %s",
3009 			transport, transport->path);
3010 
3011 		spa_bt_transport_free(transport);
3012 		if (device != NULL)
3013 			spa_bt_device_check_profiles(device, false);
3014 	}
3015 
3016 	if ((r = dbus_message_new_method_return(m)) == NULL)
3017 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
3018 	if (!dbus_connection_send(conn, r, NULL))
3019 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
3020 
3021 	dbus_message_unref(r);
3022 
3023 	return DBUS_HANDLER_RESULT_HANDLED;
3024 }
3025 
endpoint_release(DBusConnection * conn,DBusMessage * m,void * userdata)3026 static DBusHandlerResult endpoint_release(DBusConnection *conn, DBusMessage *m, void *userdata)
3027 {
3028 	DBusMessage *r;
3029 
3030 	r = dbus_message_new_error(m, BLUEZ_MEDIA_ENDPOINT_INTERFACE ".Error.NotImplemented",
3031                                             "Method not implemented");
3032 	if (r == NULL)
3033 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
3034 	if (!dbus_connection_send(conn, r, NULL))
3035 		return DBUS_HANDLER_RESULT_NEED_MEMORY;
3036 
3037 	dbus_message_unref(r);
3038 
3039 	return DBUS_HANDLER_RESULT_HANDLED;
3040 }
3041 
endpoint_handler(DBusConnection * c,DBusMessage * m,void * userdata)3042 static DBusHandlerResult endpoint_handler(DBusConnection *c, DBusMessage *m, void *userdata)
3043 {
3044 	struct spa_bt_monitor *monitor = userdata;
3045 	const char *path, *interface, *member;
3046 	DBusMessage *r;
3047 	DBusHandlerResult res;
3048 
3049 	path = dbus_message_get_path(m);
3050 	interface = dbus_message_get_interface(m);
3051 	member = dbus_message_get_member(m);
3052 
3053 	spa_log_debug(monitor->log, "dbus: path=%s, interface=%s, member=%s", path, interface, member);
3054 
3055 	if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) {
3056 		const char *xml = ENDPOINT_INTROSPECT_XML;
3057 
3058 		if ((r = dbus_message_new_method_return(m)) == NULL)
3059 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3060 		if (!dbus_message_append_args(r, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID))
3061 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3062 		if (!dbus_connection_send(monitor->conn, r, NULL))
3063 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3064 
3065 		dbus_message_unref(r);
3066 		res = DBUS_HANDLER_RESULT_HANDLED;
3067 	}
3068 	else if (dbus_message_is_method_call(m, BLUEZ_MEDIA_ENDPOINT_INTERFACE, "SetConfiguration"))
3069 		res = endpoint_set_configuration(c, path, m, userdata);
3070 	else if (dbus_message_is_method_call(m, BLUEZ_MEDIA_ENDPOINT_INTERFACE, "SelectConfiguration"))
3071 		res = endpoint_select_configuration(c, m, userdata);
3072 	else if (dbus_message_is_method_call(m, BLUEZ_MEDIA_ENDPOINT_INTERFACE, "ClearConfiguration"))
3073 		res = endpoint_clear_configuration(c, m, userdata);
3074 	else if (dbus_message_is_method_call(m, BLUEZ_MEDIA_ENDPOINT_INTERFACE, "Release"))
3075 		res = endpoint_release(c, m, userdata);
3076 	else
3077 		res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3078 
3079 	return res;
3080 }
3081 
bluez_register_endpoint_reply(DBusPendingCall * pending,void * user_data)3082 static void bluez_register_endpoint_reply(DBusPendingCall *pending, void *user_data)
3083 {
3084 	struct spa_bt_monitor *monitor = user_data;
3085 	DBusMessage *r;
3086 
3087 	r = dbus_pending_call_steal_reply(pending);
3088 	if (r == NULL)
3089 		return;
3090 
3091 	if (dbus_message_is_error(r, DBUS_ERROR_UNKNOWN_METHOD)) {
3092 		spa_log_warn(monitor->log, "BlueZ D-Bus ObjectManager not available");
3093 		goto finish;
3094 	}
3095 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
3096 		spa_log_error(monitor->log, "RegisterEndpoint() failed: %s",
3097 				dbus_message_get_error_name(r));
3098 		goto finish;
3099 	}
3100 
3101 	finish:
3102 	dbus_message_unref(r);
3103 	dbus_pending_call_unref(pending);
3104 }
3105 
append_basic_variant_dict_entry(DBusMessageIter * dict,int key_type_int,void * key,int variant_type_int,const char * variant_type_str,void * variant)3106 static void append_basic_variant_dict_entry(DBusMessageIter *dict, int key_type_int, void* key, int variant_type_int, const char* variant_type_str, void* variant) {
3107 	DBusMessageIter dict_entry_it, variant_it;
3108 	dbus_message_iter_open_container(dict, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry_it);
3109 	dbus_message_iter_append_basic(&dict_entry_it, key_type_int, key);
3110 
3111 	dbus_message_iter_open_container(&dict_entry_it, DBUS_TYPE_VARIANT, variant_type_str, &variant_it);
3112 	dbus_message_iter_append_basic(&variant_it, variant_type_int, variant);
3113 	dbus_message_iter_close_container(&dict_entry_it, &variant_it);
3114 	dbus_message_iter_close_container(dict, &dict_entry_it);
3115 }
3116 
append_basic_array_variant_dict_entry(DBusMessageIter * dict,int key_type_int,void * key,const char * variant_type_str,const char * array_type_str,int array_type_int,void * data,int data_size)3117 static void append_basic_array_variant_dict_entry(DBusMessageIter *dict, int key_type_int, void* key, const char* variant_type_str, const char* array_type_str, int array_type_int, void* data, int data_size) {
3118 	DBusMessageIter dict_entry_it, variant_it, array_it;
3119 	dbus_message_iter_open_container(dict, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry_it);
3120 	dbus_message_iter_append_basic(&dict_entry_it, key_type_int, key);
3121 
3122 	dbus_message_iter_open_container(&dict_entry_it, DBUS_TYPE_VARIANT, variant_type_str, &variant_it);
3123 	dbus_message_iter_open_container(&variant_it, DBUS_TYPE_ARRAY, array_type_str, &array_it);
3124 	dbus_message_iter_append_fixed_array (&array_it, array_type_int, &data, data_size);
3125 	dbus_message_iter_close_container(&variant_it, &array_it);
3126 	dbus_message_iter_close_container(&dict_entry_it, &variant_it);
3127 	dbus_message_iter_close_container(dict, &dict_entry_it);
3128 }
3129 
bluez_register_endpoint(struct spa_bt_monitor * monitor,const char * path,const char * endpoint,const char * uuid,const struct a2dp_codec * codec)3130 static int bluez_register_endpoint(struct spa_bt_monitor *monitor,
3131                              const char *path, const char *endpoint,
3132 			     const char *uuid, const struct a2dp_codec *codec) {
3133 	char *str, *object_path = NULL;
3134 	DBusMessage *m;
3135 	DBusMessageIter object_it, dict_it;
3136 	DBusPendingCall *call;
3137 	uint8_t caps[A2DP_MAX_CAPS_SIZE];
3138 	int ret, caps_size;
3139 	uint16_t codec_id = codec->codec_id;
3140 
3141 	ret = a2dp_codec_to_endpoint(codec, endpoint, &object_path);
3142 	if (ret < 0)
3143 		return ret;
3144 
3145 	caps_size = codec->fill_caps(codec, 0, caps);
3146 	if (caps_size < 0)
3147 		return caps_size;
3148 
3149 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
3150 	                                 path,
3151 	                                 BLUEZ_MEDIA_INTERFACE,
3152 	                                 "RegisterEndpoint");
3153 	if (m == NULL)
3154 		return -EIO;
3155 
3156 	dbus_message_iter_init_append(m, &object_it);
3157 	dbus_message_iter_append_basic(&object_it, DBUS_TYPE_OBJECT_PATH, &object_path);
3158 
3159 	dbus_message_iter_open_container(&object_it, DBUS_TYPE_ARRAY, "{sv}", &dict_it);
3160 
3161 	str = "UUID";
3162 	append_basic_variant_dict_entry(&dict_it, DBUS_TYPE_STRING, &str, DBUS_TYPE_STRING, "s", &uuid);
3163 	str = "Codec";
3164 	append_basic_variant_dict_entry(&dict_it, DBUS_TYPE_STRING, &str, DBUS_TYPE_BYTE, "y", &codec_id);
3165 	str = "Capabilities";
3166 	append_basic_array_variant_dict_entry(&dict_it, DBUS_TYPE_STRING, &str, "ay", "y", DBUS_TYPE_BYTE, caps, caps_size);
3167 
3168 	dbus_message_iter_close_container(&object_it, &dict_it);
3169 
3170 	dbus_connection_send_with_reply(monitor->conn, m, &call, -1);
3171 	dbus_pending_call_set_notify(call, bluez_register_endpoint_reply, monitor, NULL);
3172 	dbus_message_unref(m);
3173 
3174 	free(object_path);
3175 
3176 	return 0;
3177 }
3178 
register_a2dp_endpoint(struct spa_bt_monitor * monitor,const struct a2dp_codec * codec,const char * endpoint)3179 static int register_a2dp_endpoint(struct spa_bt_monitor *monitor,
3180 		const struct a2dp_codec *codec, const char *endpoint)
3181 {
3182 	int ret;
3183 	char* object_path = NULL;
3184 	const DBusObjectPathVTable vtable_endpoint = {
3185 		.message_function = endpoint_handler,
3186 	};
3187 
3188 	ret = a2dp_codec_to_endpoint(codec, endpoint, &object_path);
3189 	if (ret < 0)
3190 		return ret;
3191 
3192 	spa_log_info(monitor->log, "Registering endpoint: %s", object_path);
3193 
3194 	if (!dbus_connection_register_object_path(monitor->conn,
3195 	                                          object_path,
3196 	                                          &vtable_endpoint, monitor)) {
3197 		free(object_path);
3198 		return -EIO;
3199 	}
3200 
3201 	free(object_path);
3202 	return 0;
3203 
3204 }
3205 
adapter_register_endpoints(struct spa_bt_adapter * a)3206 static int adapter_register_endpoints(struct spa_bt_adapter *a)
3207 {
3208 	struct spa_bt_monitor *monitor = a->monitor;
3209 	const struct a2dp_codec * const * const a2dp_codecs = monitor->a2dp_codecs;
3210 	int i;
3211 	int err = 0;
3212 
3213 	if (a->endpoints_registered)
3214 	    return err;
3215 
3216 	/* The legacy bluez5 api doesn't support codec switching
3217 	 * It doesn't make sense to register codecs other than SBC
3218 	 * as bluez5 will probably use SBC anyway and we have no control over it
3219 	 * let's incentivize users to upgrade their bluez5 daemon
3220 	 * if they want proper a2dp codec support
3221 	 * */
3222 	spa_log_warn(monitor->log, "Using legacy bluez5 API for A2DP - only SBC will be supported. "
3223                                "Please upgrade bluez5.");
3224 
3225 	for (i = 0; a2dp_codecs[i]; i++) {
3226 		const struct a2dp_codec *codec = a2dp_codecs[i];
3227 
3228 		if (!is_a2dp_codec_enabled(monitor, codec))
3229 			continue;
3230 
3231 		if (!(codec->codec_id == A2DP_CODEC_SBC && spa_streq(codec->name, "sbc")))
3232 			continue;
3233 
3234 		if ((err = bluez_register_endpoint(monitor, a->path,
3235 						   A2DP_SOURCE_ENDPOINT,
3236 		                                   SPA_BT_UUID_A2DP_SOURCE,
3237 		                                   codec)))
3238 			goto out;
3239 
3240 		if ((err = bluez_register_endpoint(monitor, a->path,
3241 						   A2DP_SINK_ENDPOINT,
3242 		                                   SPA_BT_UUID_A2DP_SINK,
3243 		                                   codec)))
3244 			goto out;
3245 
3246 		a->endpoints_registered = true;
3247 		break;
3248 	}
3249 
3250 	if (!a->endpoints_registered) {
3251 		/* Should never happen as SBC support is always enabled */
3252 		spa_log_error(monitor->log, "Broken PipeWire build - unable to locate SBC codec");
3253 		err = -ENOSYS;
3254 	}
3255 
3256 	out:
3257 	if (err) {
3258 		spa_log_error(monitor->log, "Failed to register bluez5 endpoints");
3259 	}
3260 	return err;
3261 }
3262 
append_a2dp_object(DBusMessageIter * iter,const char * endpoint,const char * uuid,uint8_t codec_id,uint8_t * caps,size_t caps_size)3263 static void append_a2dp_object(DBusMessageIter *iter, const char *endpoint,
3264 		const char *uuid, uint8_t codec_id, uint8_t *caps, size_t caps_size)
3265 {
3266 	char* str;
3267 	const char *interface_name = BLUEZ_MEDIA_ENDPOINT_INTERFACE;
3268 	DBusMessageIter object, array, entry, dict;
3269 	dbus_bool_t delay_reporting;
3270 
3271 	dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL, &object);
3272 	dbus_message_iter_append_basic(&object, DBUS_TYPE_OBJECT_PATH, &endpoint);
3273 
3274 	dbus_message_iter_open_container(&object, DBUS_TYPE_ARRAY, "{sa{sv}}", &array);
3275 
3276 	dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, NULL, &entry);
3277 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &interface_name);
3278 
3279 	dbus_message_iter_open_container(&entry, DBUS_TYPE_ARRAY, "{sv}", &dict);
3280 
3281 	str = "UUID";
3282 	append_basic_variant_dict_entry(&dict, DBUS_TYPE_STRING, &str, DBUS_TYPE_STRING, "s", &uuid);
3283 	str = "Codec";
3284 	append_basic_variant_dict_entry(&dict, DBUS_TYPE_STRING, &str, DBUS_TYPE_BYTE, "y", &codec_id);
3285 	str = "Capabilities";
3286 	append_basic_array_variant_dict_entry(&dict, DBUS_TYPE_STRING, &str, "ay", "y", DBUS_TYPE_BYTE, caps, caps_size);
3287 	if (spa_bt_profile_from_uuid(uuid) & SPA_BT_PROFILE_A2DP_SOURCE) {
3288 		str = "DelayReporting";
3289 		delay_reporting = TRUE;
3290 		append_basic_variant_dict_entry(&dict, DBUS_TYPE_STRING, &str, DBUS_TYPE_BOOLEAN, "b", &delay_reporting);
3291 	}
3292 
3293 	dbus_message_iter_close_container(&entry, &dict);
3294 	dbus_message_iter_close_container(&array, &entry);
3295 	dbus_message_iter_close_container(&object, &array);
3296 	dbus_message_iter_close_container(iter, &object);
3297 }
3298 
object_manager_handler(DBusConnection * c,DBusMessage * m,void * user_data)3299 static DBusHandlerResult object_manager_handler(DBusConnection *c, DBusMessage *m, void *user_data)
3300 {
3301 	struct spa_bt_monitor *monitor = user_data;
3302 	const struct a2dp_codec * const * const a2dp_codecs = monitor->a2dp_codecs;
3303 	const char *path, *interface, *member;
3304 	char *endpoint;
3305 	DBusMessage *r;
3306 	DBusMessageIter iter, array;
3307 	DBusHandlerResult res;
3308 	int i;
3309 
3310 	path = dbus_message_get_path(m);
3311 	interface = dbus_message_get_interface(m);
3312 	member = dbus_message_get_member(m);
3313 
3314 	spa_log_debug(monitor->log, "dbus: path=%s, interface=%s, member=%s", path, interface, member);
3315 
3316 	if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) {
3317 		const char *xml = OBJECT_MANAGER_INTROSPECT_XML;
3318 
3319 		if ((r = dbus_message_new_method_return(m)) == NULL)
3320 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3321 		if (!dbus_message_append_args(r, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID))
3322 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3323 		if (!dbus_connection_send(monitor->conn, r, NULL))
3324 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3325 
3326 		dbus_message_unref(r);
3327 		res = DBUS_HANDLER_RESULT_HANDLED;
3328 	}
3329 	else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects")) {
3330 		if ((r = dbus_message_new_method_return(m)) == NULL)
3331 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3332 
3333 		dbus_message_iter_init_append(r, &iter);
3334 		dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{oa{sa{sv}}}", &array);
3335 
3336 		for (i = 0; a2dp_codecs[i]; i++) {
3337 			const struct a2dp_codec *codec = a2dp_codecs[i];
3338 			uint8_t caps[A2DP_MAX_CAPS_SIZE];
3339 			int caps_size, ret;
3340 			uint16_t codec_id = codec->codec_id;
3341 
3342 			if (!is_a2dp_codec_enabled(monitor, codec))
3343 				continue;
3344 
3345 			caps_size = codec->fill_caps(codec, 0, caps);
3346 			if (caps_size < 0)
3347 				continue;
3348 
3349 			if (codec->decode != NULL) {
3350 				ret = a2dp_codec_to_endpoint(codec, A2DP_SINK_ENDPOINT, &endpoint);
3351 				if (ret == 0) {
3352 					spa_log_info(monitor->log, "register A2DP sink codec %s: %s", a2dp_codecs[i]->name, endpoint);
3353 					append_a2dp_object(&array, endpoint, SPA_BT_UUID_A2DP_SINK,
3354 							codec_id, caps, caps_size);
3355 					free(endpoint);
3356 				}
3357 			}
3358 
3359 			if (codec->encode != NULL) {
3360 				ret = a2dp_codec_to_endpoint(codec, A2DP_SOURCE_ENDPOINT, &endpoint);
3361 				if (ret == 0) {
3362 					spa_log_info(monitor->log, "register A2DP source codec %s: %s", a2dp_codecs[i]->name, endpoint);
3363 					append_a2dp_object(&array, endpoint, SPA_BT_UUID_A2DP_SOURCE,
3364 							codec_id, caps, caps_size);
3365 					free(endpoint);
3366 				}
3367 			}
3368 		}
3369 
3370 		dbus_message_iter_close_container(&iter, &array);
3371 		if (!dbus_connection_send(monitor->conn, r, NULL))
3372 			return DBUS_HANDLER_RESULT_NEED_MEMORY;
3373 		res = DBUS_HANDLER_RESULT_HANDLED;
3374 	}
3375 	else
3376 		res = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3377 
3378 	return res;
3379 }
3380 
bluez_register_application_reply(DBusPendingCall * pending,void * user_data)3381 static void bluez_register_application_reply(DBusPendingCall *pending, void *user_data)
3382 {
3383 	struct spa_bt_adapter *adapter = user_data;
3384 	struct spa_bt_monitor *monitor = adapter->monitor;
3385 	DBusMessage *r;
3386 	bool fallback = true;
3387 
3388 	r = dbus_pending_call_steal_reply(pending);
3389 	if (r == NULL)
3390 		return;
3391 
3392 	if (dbus_message_is_error(r, BLUEZ_ERROR_NOT_SUPPORTED)) {
3393 		spa_log_warn(monitor->log, "Registering media applications for adapter %s is disabled in bluez5", adapter->path);
3394 		goto finish;
3395 	}
3396 
3397 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
3398 		spa_log_error(monitor->log, "RegisterApplication() failed: %s",
3399 		        dbus_message_get_error_name(r));
3400 		goto finish;
3401 	}
3402 
3403 	fallback = false;
3404 	adapter->application_registered = true;
3405 
3406 finish:
3407 	dbus_message_unref(r);
3408 	dbus_pending_call_unref(pending);
3409 
3410 	if (fallback)
3411 		adapter_register_endpoints(adapter);
3412 }
3413 
register_media_application(struct spa_bt_monitor * monitor)3414 static int register_media_application(struct spa_bt_monitor * monitor)
3415 {
3416 	const struct a2dp_codec * const * const a2dp_codecs = monitor->a2dp_codecs;
3417 	const DBusObjectPathVTable vtable_object_manager = {
3418 		.message_function = object_manager_handler,
3419 	};
3420 
3421 	spa_log_info(monitor->log, "Registering media application object: " A2DP_OBJECT_MANAGER_PATH);
3422 
3423 	if (!dbus_connection_register_object_path(monitor->conn,
3424 	                                          A2DP_OBJECT_MANAGER_PATH,
3425 	                                          &vtable_object_manager, monitor))
3426 		return -EIO;
3427 
3428 	for (int i = 0; a2dp_codecs[i]; i++) {
3429 		const struct a2dp_codec *codec = a2dp_codecs[i];
3430 
3431 		if (!is_a2dp_codec_enabled(monitor, codec))
3432 			continue;
3433 
3434 		register_a2dp_endpoint(monitor, codec, A2DP_SOURCE_ENDPOINT);
3435 		register_a2dp_endpoint(monitor, codec, A2DP_SINK_ENDPOINT);
3436 	}
3437 
3438 	return 0;
3439 }
3440 
unregister_media_application(struct spa_bt_monitor * monitor)3441 static void unregister_media_application(struct spa_bt_monitor * monitor)
3442 {
3443 	const struct a2dp_codec * const * const a2dp_codecs = monitor->a2dp_codecs;
3444 	int ret;
3445 	char *object_path = NULL;
3446 
3447 	for (int i = 0; a2dp_codecs[i]; i++) {
3448 		const struct a2dp_codec *codec = a2dp_codecs[i];
3449 
3450 		if (!is_a2dp_codec_enabled(monitor, codec))
3451 			continue;
3452 
3453 		ret = a2dp_codec_to_endpoint(codec, A2DP_SOURCE_ENDPOINT, &object_path);
3454 		if (ret == 0) {
3455 			dbus_connection_unregister_object_path(monitor->conn, object_path);
3456 			free(object_path);
3457 		}
3458 
3459 		ret = a2dp_codec_to_endpoint(codec, A2DP_SINK_ENDPOINT, &object_path);
3460 		if (ret == 0) {
3461 			dbus_connection_unregister_object_path(monitor->conn, object_path);
3462 			free(object_path);
3463 		}
3464 	}
3465 
3466 	dbus_connection_unregister_object_path(monitor->conn, A2DP_OBJECT_MANAGER_PATH);
3467 }
3468 
adapter_register_application(struct spa_bt_adapter * a)3469 static int adapter_register_application(struct spa_bt_adapter *a) {
3470 	const char *object_manager_path = A2DP_OBJECT_MANAGER_PATH;
3471 	struct spa_bt_monitor *monitor = a->monitor;
3472 	DBusMessage *m;
3473 	DBusMessageIter i, d;
3474 	DBusPendingCall *call;
3475 
3476 	if (a->application_registered)
3477 		return 0;
3478 
3479 	spa_log_debug(monitor->log, "Registering bluez5 media application on adapter %s", a->path);
3480 
3481 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
3482 	                                 a->path,
3483 	                                 BLUEZ_MEDIA_INTERFACE,
3484 	                                 "RegisterApplication");
3485 	if (m == NULL)
3486 		return -EIO;
3487 
3488 	dbus_message_iter_init_append(m, &i);
3489 	dbus_message_iter_append_basic(&i, DBUS_TYPE_OBJECT_PATH, &object_manager_path);
3490 	dbus_message_iter_open_container(&i, DBUS_TYPE_ARRAY, "{sv}", &d);
3491 	dbus_message_iter_close_container(&i, &d);
3492 
3493 	dbus_connection_send_with_reply(monitor->conn, m, &call, -1);
3494 	dbus_pending_call_set_notify(call, bluez_register_application_reply, a, NULL);
3495 	dbus_message_unref(m);
3496 
3497 	return 0;
3498 }
3499 
switch_backend(struct spa_bt_monitor * monitor,struct spa_bt_backend * backend)3500 static int switch_backend(struct spa_bt_monitor *monitor, struct spa_bt_backend *backend)
3501 {
3502 	int res;
3503 	size_t i;
3504 
3505 	spa_return_val_if_fail(backend != NULL, -EINVAL);
3506 
3507 	if (!backend->available)
3508 		return -ENODEV;
3509 
3510 	for (i = 0; i < SPA_N_ELEMENTS(monitor->backends); ++i) {
3511 		struct spa_bt_backend *b = monitor->backends[i];
3512 		if (backend != b && b && b->available && b->exclusive)
3513 			spa_log_warn(monitor->log,
3514 					"%s running, but not configured as HFP/HSP backend: "
3515 					"it may interfere with HFP/HSP functionality.",
3516 					b->name);
3517 	}
3518 
3519 	if (monitor->backend == backend)
3520 		return 0;
3521 
3522 	spa_log_info(monitor->log, "Switching to HFP/HSP backend %s", backend->name);
3523 
3524 	spa_bt_backend_unregister_profiles(monitor->backend);
3525 
3526 	if ((res = spa_bt_backend_register_profiles(backend)) < 0) {
3527 		monitor->backend = NULL;
3528 		return res;
3529 	}
3530 
3531 	monitor->backend = backend;
3532 	return 0;
3533 }
3534 
reselect_backend(struct spa_bt_monitor * monitor,bool silent)3535 static void reselect_backend(struct spa_bt_monitor *monitor, bool silent)
3536 {
3537 	struct spa_bt_backend *backend;
3538 	size_t i;
3539 
3540 	spa_log_debug(monitor->log, "re-selecting HFP/HSP backend");
3541 
3542 	if (monitor->backend_selection == BACKEND_NONE) {
3543 		spa_bt_backend_unregister_profiles(monitor->backend);
3544 		monitor->backend = NULL;
3545 		return;
3546 	} else if (monitor->backend_selection == BACKEND_ANY) {
3547 		for (i = 0; i < SPA_N_ELEMENTS(monitor->backends); ++i) {
3548 			backend = monitor->backends[i];
3549 			if (backend && switch_backend(monitor, backend) == 0)
3550 				return;
3551 		}
3552 	} else {
3553 		backend = monitor->backends[monitor->backend_selection];
3554 		if (backend && switch_backend(monitor, backend) == 0)
3555 			return;
3556 	}
3557 
3558 	spa_bt_backend_unregister_profiles(monitor->backend);
3559 	monitor->backend = NULL;
3560 
3561 	if (!silent)
3562 		spa_log_error(monitor->log, "Failed to start HFP/HSP backend %s",
3563 				backend ? backend->name : "none");
3564 }
3565 
interface_added(struct spa_bt_monitor * monitor,DBusConnection * conn,const char * object_path,const char * interface_name,DBusMessageIter * props_iter)3566 static void interface_added(struct spa_bt_monitor *monitor,
3567 			    DBusConnection *conn,
3568 			    const char *object_path,
3569 			    const char *interface_name,
3570 			    DBusMessageIter *props_iter)
3571 {
3572 	spa_log_debug(monitor->log, "Found object %s, interface %s", object_path, interface_name);
3573 
3574 	if (spa_streq(interface_name, BLUEZ_ADAPTER_INTERFACE)) {
3575 		struct spa_bt_adapter *a;
3576 
3577 		a = adapter_find(monitor, object_path);
3578 		if (a == NULL) {
3579 			a = adapter_create(monitor, object_path);
3580 			if (a == NULL) {
3581 				spa_log_warn(monitor->log, "can't create adapter: %m");
3582 				return;
3583 			}
3584 		}
3585 		adapter_update_props(a, props_iter, NULL);
3586 		adapter_register_application(a);
3587 		adapter_register_player(a);
3588 	}
3589 	else if (spa_streq(interface_name, BLUEZ_PROFILE_MANAGER_INTERFACE)) {
3590 		if (monitor->backends[BACKEND_NATIVE])
3591 			monitor->backends[BACKEND_NATIVE]->available = true;
3592 		reselect_backend(monitor, false);
3593 	}
3594 	else if (spa_streq(interface_name, BLUEZ_DEVICE_INTERFACE)) {
3595 		struct spa_bt_device *d;
3596 
3597 		d = spa_bt_device_find(monitor, object_path);
3598 		if (d == NULL) {
3599 			d = device_create(monitor, object_path);
3600 			if (d == NULL) {
3601 				spa_log_warn(monitor->log, "can't create Bluetooth device %s: %m",
3602 						object_path);
3603 				return;
3604 			}
3605 		}
3606 
3607 		device_update_props(d, props_iter, NULL);
3608 		d->reconnect_state = BT_DEVICE_RECONNECT_INIT;
3609 
3610 		device_update_hw_volume_profiles(d);
3611 
3612 		/* Trigger bluez device creation before bluez profile negotiation started so that
3613 		 * profile connection handlers can receive per-device settings during profile negotiation. */
3614 		spa_bt_device_add_profile(d, SPA_BT_PROFILE_NULL);
3615 	}
3616 	else if (spa_streq(interface_name, BLUEZ_MEDIA_ENDPOINT_INTERFACE)) {
3617 		struct spa_bt_remote_endpoint *ep;
3618 		struct spa_bt_device *d;
3619 
3620 		ep = remote_endpoint_find(monitor, object_path);
3621 		if (ep == NULL) {
3622 			ep = remote_endpoint_create(monitor, object_path);
3623 			if (ep == NULL) {
3624 				spa_log_warn(monitor->log, "can't create Bluetooth remote endpoint %s: %m",
3625 				             object_path);
3626 				return;
3627 			}
3628 		}
3629 		remote_endpoint_update_props(ep, props_iter, NULL);
3630 
3631 		d = ep->device;
3632 		if (d)
3633 			spa_bt_device_emit_profiles_changed(d, d->profiles, d->connected_profiles);
3634 	}
3635 }
3636 
interfaces_added(struct spa_bt_monitor * monitor,DBusMessageIter * arg_iter)3637 static void interfaces_added(struct spa_bt_monitor *monitor, DBusMessageIter *arg_iter)
3638 {
3639 	DBusMessageIter it[3];
3640 	const char *object_path;
3641 
3642 	dbus_message_iter_get_basic(arg_iter, &object_path);
3643 	dbus_message_iter_next(arg_iter);
3644 	dbus_message_iter_recurse(arg_iter, &it[0]);
3645 
3646 	while (dbus_message_iter_get_arg_type(&it[0]) != DBUS_TYPE_INVALID) {
3647 		const char *interface_name;
3648 
3649 		dbus_message_iter_recurse(&it[0], &it[1]);
3650 		dbus_message_iter_get_basic(&it[1], &interface_name);
3651 		dbus_message_iter_next(&it[1]);
3652 		dbus_message_iter_recurse(&it[1], &it[2]);
3653 
3654 		interface_added(monitor, monitor->conn,
3655 				object_path, interface_name,
3656 				&it[2]);
3657 
3658 		dbus_message_iter_next(&it[0]);
3659 	}
3660 }
3661 
interfaces_removed(struct spa_bt_monitor * monitor,DBusMessageIter * arg_iter)3662 static void interfaces_removed(struct spa_bt_monitor *monitor, DBusMessageIter *arg_iter)
3663 {
3664 	const char *object_path;
3665 	DBusMessageIter it;
3666 
3667 	dbus_message_iter_get_basic(arg_iter, &object_path);
3668 	dbus_message_iter_next(arg_iter);
3669 	dbus_message_iter_recurse(arg_iter, &it);
3670 
3671 	while (dbus_message_iter_get_arg_type(&it) != DBUS_TYPE_INVALID) {
3672 		const char *interface_name;
3673 
3674 		dbus_message_iter_get_basic(&it, &interface_name);
3675 
3676 		spa_log_debug(monitor->log, "Found object %s, interface %s", object_path, interface_name);
3677 
3678 		if (spa_streq(interface_name, BLUEZ_DEVICE_INTERFACE)) {
3679 			struct spa_bt_device *d;
3680 			d = spa_bt_device_find(monitor, object_path);
3681 			if (d != NULL)
3682 				device_free(d);
3683 		} else if (spa_streq(interface_name, BLUEZ_ADAPTER_INTERFACE)) {
3684 			struct spa_bt_adapter *a;
3685 			a = adapter_find(monitor, object_path);
3686 			if (a != NULL)
3687 				adapter_free(a);
3688 		} else if (spa_streq(interface_name, BLUEZ_MEDIA_ENDPOINT_INTERFACE)) {
3689 			struct spa_bt_remote_endpoint *ep;
3690 			ep = remote_endpoint_find(monitor, object_path);
3691 			if (ep != NULL) {
3692 				struct spa_bt_device *d = ep->device;
3693 				remote_endpoint_free(ep);
3694 				if (d)
3695 					spa_bt_device_emit_profiles_changed(d, d->profiles, d->connected_profiles);
3696 			}
3697 		}
3698 
3699 		dbus_message_iter_next(&it);
3700 	}
3701 }
3702 
get_managed_objects_reply(DBusPendingCall * pending,void * user_data)3703 static void get_managed_objects_reply(DBusPendingCall *pending, void *user_data)
3704 {
3705 	struct spa_bt_monitor *monitor = user_data;
3706 	DBusMessage *r;
3707 	DBusMessageIter it[6];
3708 
3709 	r = dbus_pending_call_steal_reply(pending);
3710 	if (r == NULL)
3711 		return;
3712 
3713 	if (dbus_message_is_error(r, DBUS_ERROR_UNKNOWN_METHOD)) {
3714 		spa_log_warn(monitor->log, "BlueZ D-Bus ObjectManager not available");
3715 		goto finish;
3716 	}
3717 
3718 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
3719 		spa_log_error(monitor->log, "GetManagedObjects() failed: %s",
3720 				dbus_message_get_error_name(r));
3721 		goto finish;
3722 	}
3723 
3724 	if (!dbus_message_iter_init(r, &it[0]) ||
3725 	    !spa_streq(dbus_message_get_signature(r), "a{oa{sa{sv}}}")) {
3726 		spa_log_error(monitor->log, "Invalid reply signature for GetManagedObjects()");
3727 		goto finish;
3728 	}
3729 
3730 	dbus_message_iter_recurse(&it[0], &it[1]);
3731 
3732 	while (dbus_message_iter_get_arg_type(&it[1]) != DBUS_TYPE_INVALID) {
3733 		dbus_message_iter_recurse(&it[1], &it[2]);
3734 
3735 		interfaces_added(monitor, &it[2]);
3736 
3737 		dbus_message_iter_next(&it[1]);
3738 	}
3739 
3740 	reselect_backend(monitor, false);
3741 
3742 	monitor->objects_listed = true;
3743 
3744       finish:
3745 	dbus_message_unref(r);
3746         dbus_pending_call_unref(pending);
3747 	return;
3748 }
3749 
get_managed_objects(struct spa_bt_monitor * monitor)3750 static void get_managed_objects(struct spa_bt_monitor *monitor)
3751 {
3752 	DBusMessage *m;
3753 	DBusPendingCall *call;
3754 
3755 	m = dbus_message_new_method_call(BLUEZ_SERVICE,
3756 					 "/",
3757 					 "org.freedesktop.DBus.ObjectManager",
3758 					 "GetManagedObjects");
3759 
3760 	dbus_connection_send_with_reply(monitor->conn, m, &call, -1);
3761 	dbus_pending_call_set_notify(call, get_managed_objects_reply, monitor, NULL);
3762         dbus_message_unref(m);
3763 }
3764 
check_name_owner_reply(DBusPendingCall * pending,void * user_data)3765 static void check_name_owner_reply(DBusPendingCall *pending, void *user_data)
3766 {
3767 	struct spa_bt_monitor *monitor = user_data;
3768 	DBusMessage *r;
3769 	DBusError error;
3770 	bool running;
3771 
3772 	r = dbus_pending_call_steal_reply(pending);
3773 	if (r == NULL)
3774 		return;
3775 
3776 	if (dbus_message_is_error(r, DBUS_ERROR_UNKNOWN_METHOD)) {
3777 		spa_log_warn(monitor->log, "BlueZ D-Bus ObjectManager not available");
3778 		goto finish;
3779 	}
3780 	if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
3781 		spa_log_error(monitor->log, "NameHasOwner() failed: %s",
3782 				dbus_message_get_error_name(r));
3783 		goto finish;
3784 	}
3785 	if (!spa_streq(dbus_message_get_signature(r), "b")) {
3786 		spa_log_error(monitor->log, "Invalid reply signature for NameHasOwner()");
3787 		goto finish;
3788 	}
3789 
3790 	dbus_error_init(&error);
3791 	dbus_message_get_args(r, &error, DBUS_TYPE_BOOLEAN, &running, DBUS_TYPE_INVALID);
3792 
3793 	if (dbus_error_is_set(&error)) {
3794                 spa_log_error(monitor->log, "Could not check bluetooth service: %s", error.message);
3795 		dbus_error_free(&error);
3796 		goto finish;
3797 	}
3798 
3799 	spa_log_info(monitor->log, "bluetooth service running: %s",
3800 			running ? "yes" : "no");
3801 	if (running)
3802 		get_managed_objects(monitor);
3803 
3804 finish:
3805 	dbus_message_unref(r);
3806 	dbus_pending_call_unref(pending);
3807 	return;
3808 }
3809 
check_name_owner(struct spa_bt_monitor * monitor)3810 static void check_name_owner(struct spa_bt_monitor *monitor)
3811 {
3812 	DBusMessage *m;
3813 	DBusPendingCall *call;
3814 	const char *service = BLUEZ_SERVICE;
3815 
3816 	m = dbus_message_new_method_call("org.freedesktop.DBus",
3817 					 "/org/freedesktop/DBus",
3818 					 "org.freedesktop.DBus",
3819 					 "NameHasOwner");
3820 	if (m == NULL)
3821 		return;
3822 
3823 	dbus_message_append_args(m, DBUS_TYPE_STRING, &service, DBUS_TYPE_INVALID);
3824 
3825 	dbus_connection_send_with_reply(monitor->conn, m, &call, -1);
3826 	dbus_pending_call_set_notify(call, check_name_owner_reply, monitor, NULL);
3827 	dbus_message_unref(m);
3828 }
3829 
filter_cb(DBusConnection * bus,DBusMessage * m,void * user_data)3830 static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *user_data)
3831 {
3832 	struct spa_bt_monitor *monitor = user_data;
3833 	DBusError err;
3834 
3835 	dbus_error_init(&err);
3836 
3837 	if (dbus_message_is_signal(m, "org.freedesktop.DBus", "NameOwnerChanged")) {
3838 		const char *name, *old_owner, *new_owner;
3839 
3840 		spa_log_debug(monitor->log, "Name owner changed %s", dbus_message_get_path(m));
3841 
3842 		if (!dbus_message_get_args(m, &err,
3843 					   DBUS_TYPE_STRING, &name,
3844 					   DBUS_TYPE_STRING, &old_owner,
3845 					   DBUS_TYPE_STRING, &new_owner,
3846 					   DBUS_TYPE_INVALID)) {
3847 			spa_log_error(monitor->log, "Failed to parse org.freedesktop.DBus.NameOwnerChanged: %s", err.message);
3848 			goto fail;
3849 		}
3850 
3851 		if (spa_streq(name, BLUEZ_SERVICE)) {
3852 			bool has_old_owner = old_owner && *old_owner;
3853 			bool has_new_owner = new_owner && *new_owner;
3854 
3855 			if (has_old_owner) {
3856 				spa_log_debug(monitor->log, "Bluetooth daemon disappeared");
3857 
3858 				if (monitor->backends[BACKEND_NATIVE])
3859 					monitor->backends[BACKEND_NATIVE]->available = false;
3860 
3861 				reselect_backend(monitor, true);
3862 			}
3863 
3864 			if (has_old_owner || has_new_owner) {
3865 				struct spa_bt_adapter *a;
3866 				struct spa_bt_device *d;
3867 				struct spa_bt_remote_endpoint *ep;
3868 				struct spa_bt_transport *t;
3869 
3870 				monitor->objects_listed = false;
3871 
3872 				spa_list_consume(t, &monitor->transport_list, link)
3873 					spa_bt_transport_free(t);
3874 				spa_list_consume(ep, &monitor->remote_endpoint_list, link)
3875 					remote_endpoint_free(ep);
3876 				spa_list_consume(d, &monitor->device_list, link)
3877 					device_free(d);
3878 				spa_list_consume(a, &monitor->adapter_list, link)
3879 					adapter_free(a);
3880 			}
3881 
3882 			if (has_new_owner) {
3883 				spa_log_debug(monitor->log, "Bluetooth daemon appeared");
3884 				get_managed_objects(monitor);
3885 			}
3886 		} else if (spa_streq(name, OFONO_SERVICE)) {
3887 			if (monitor->backends[BACKEND_OFONO])
3888 				monitor->backends[BACKEND_OFONO]->available = (new_owner && *new_owner);
3889 			reselect_backend(monitor, false);
3890 		} else if (spa_streq(name, HSPHFPD_SERVICE)) {
3891 			if (monitor->backends[BACKEND_HSPHFPD])
3892 				monitor->backends[BACKEND_HSPHFPD]->available = (new_owner && *new_owner);
3893 			reselect_backend(monitor, false);
3894 		}
3895 	} else if (dbus_message_is_signal(m, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded")) {
3896 		DBusMessageIter it;
3897 
3898 		spa_log_debug(monitor->log, "interfaces added %s", dbus_message_get_path(m));
3899 
3900 		if (!monitor->objects_listed)
3901 			goto finish;
3902 
3903 		if (!dbus_message_iter_init(m, &it) || !spa_streq(dbus_message_get_signature(m), "oa{sa{sv}}")) {
3904 			spa_log_error(monitor->log, "Invalid signature found in InterfacesAdded");
3905 			goto finish;
3906 		}
3907 
3908 		interfaces_added(monitor, &it);
3909 	} else if (dbus_message_is_signal(m, "org.freedesktop.DBus.ObjectManager", "InterfacesRemoved")) {
3910 		DBusMessageIter it;
3911 
3912 		spa_log_debug(monitor->log, "interfaces removed %s", dbus_message_get_path(m));
3913 
3914 		if (!monitor->objects_listed)
3915 			goto finish;
3916 
3917 		if (!dbus_message_iter_init(m, &it) || !spa_streq(dbus_message_get_signature(m), "oas")) {
3918 			spa_log_error(monitor->log, "Invalid signature found in InterfacesRemoved");
3919 			goto finish;
3920 		}
3921 
3922 		interfaces_removed(monitor, &it);
3923 	} else if (dbus_message_is_signal(m, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
3924 		DBusMessageIter it[2];
3925 		const char *iface, *path;
3926 
3927 		if (!monitor->objects_listed)
3928 			goto finish;
3929 
3930 		if (!dbus_message_iter_init(m, &it[0]) ||
3931 		    !spa_streq(dbus_message_get_signature(m), "sa{sv}as")) {
3932 			spa_log_error(monitor->log, "Invalid signature found in PropertiesChanged");
3933 			goto finish;
3934 		}
3935 		path = dbus_message_get_path(m);
3936 
3937 		dbus_message_iter_get_basic(&it[0], &iface);
3938 		dbus_message_iter_next(&it[0]);
3939 		dbus_message_iter_recurse(&it[0], &it[1]);
3940 
3941 		if (spa_streq(iface, BLUEZ_ADAPTER_INTERFACE)) {
3942 			struct spa_bt_adapter *a;
3943 
3944 			a = adapter_find(monitor, path);
3945 			if (a == NULL) {
3946 				spa_log_warn(monitor->log,
3947 						"Properties changed in unknown adapter %s", path);
3948 				goto finish;
3949 			}
3950 			spa_log_debug(monitor->log, "Properties changed in adapter %s", path);
3951 
3952 			adapter_update_props(a, &it[1], NULL);
3953 		}
3954 		else if (spa_streq(iface, BLUEZ_DEVICE_INTERFACE)) {
3955 			struct spa_bt_device *d;
3956 
3957 			d = spa_bt_device_find(monitor, path);
3958 			if (d == NULL) {
3959 				spa_log_debug(monitor->log,
3960 						"Properties changed in unknown device %s", path);
3961 				goto finish;
3962 			}
3963 			spa_log_debug(monitor->log, "Properties changed in device %s", path);
3964 
3965 			device_update_props(d, &it[1], NULL);
3966 			spa_bt_device_add_profile(d, SPA_BT_PROFILE_NULL);
3967 		}
3968 		else if (spa_streq(iface, BLUEZ_MEDIA_ENDPOINT_INTERFACE)) {
3969 			struct spa_bt_remote_endpoint *ep;
3970 			struct spa_bt_device *d;
3971 
3972 			ep = remote_endpoint_find(monitor, path);
3973 			if (ep == NULL) {
3974 				spa_log_debug(monitor->log,
3975 						"Properties changed in unknown remote endpoint %s", path);
3976 				goto finish;
3977 			}
3978 			spa_log_debug(monitor->log, "Properties changed in remote endpoint %s", path);
3979 
3980 			remote_endpoint_update_props(ep, &it[1], NULL);
3981 
3982 			d = ep->device;
3983 			if (d)
3984 				spa_bt_device_emit_profiles_changed(d, d->profiles, d->connected_profiles);
3985 		}
3986 		else if (spa_streq(iface, BLUEZ_MEDIA_TRANSPORT_INTERFACE)) {
3987 			struct spa_bt_transport *transport;
3988 
3989 			transport = spa_bt_transport_find(monitor, path);
3990 			if (transport == NULL) {
3991 				spa_log_warn(monitor->log,
3992 						"Properties changed in unknown transport %s", path);
3993 				goto finish;
3994 			}
3995 
3996 			spa_log_debug(monitor->log, "Properties changed in transport %s", path);
3997 
3998 			transport_update_props(transport, &it[1], NULL);
3999 		}
4000         }
4001 
4002 fail:
4003 	dbus_error_free(&err);
4004 finish:
4005 	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4006 }
4007 
add_filters(struct spa_bt_monitor * this)4008 static void add_filters(struct spa_bt_monitor *this)
4009 {
4010 	DBusError err;
4011 
4012 	if (this->filters_added)
4013 		return;
4014 
4015 	dbus_error_init(&err);
4016 
4017 	if (!dbus_connection_add_filter(this->conn, filter_cb, this, NULL)) {
4018 		spa_log_error(this->log, "failed to add filter function");
4019 		goto fail;
4020 	}
4021 
4022 	dbus_bus_add_match(this->conn,
4023 			"type='signal',sender='org.freedesktop.DBus',"
4024 			"interface='org.freedesktop.DBus',member='NameOwnerChanged',"
4025 			"arg0='" BLUEZ_SERVICE "'", &err);
4026 #ifdef HAVE_BLUEZ_5_BACKEND_OFONO
4027 	dbus_bus_add_match(this->conn,
4028 			"type='signal',sender='org.freedesktop.DBus',"
4029 			"interface='org.freedesktop.DBus',member='NameOwnerChanged',"
4030 			"arg0='" OFONO_SERVICE "'", &err);
4031 #endif
4032 #ifdef HAVE_BLUEZ_5_BACKEND_HSPHFPD
4033 	dbus_bus_add_match(this->conn,
4034 			"type='signal',sender='org.freedesktop.DBus',"
4035 			"interface='org.freedesktop.DBus',member='NameOwnerChanged',"
4036 			"arg0='" HSPHFPD_SERVICE "'", &err);
4037 #endif
4038 	dbus_bus_add_match(this->conn,
4039 			"type='signal',sender='" BLUEZ_SERVICE "',"
4040 			"interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'", &err);
4041 	dbus_bus_add_match(this->conn,
4042 			"type='signal',sender='" BLUEZ_SERVICE "',"
4043 			"interface='org.freedesktop.DBus.ObjectManager',member='InterfacesRemoved'", &err);
4044 	dbus_bus_add_match(this->conn,
4045 			"type='signal',sender='" BLUEZ_SERVICE "',"
4046 			"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',"
4047 			"arg0='" BLUEZ_ADAPTER_INTERFACE "'", &err);
4048 	dbus_bus_add_match(this->conn,
4049 			"type='signal',sender='" BLUEZ_SERVICE "',"
4050 			"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',"
4051 			"arg0='" BLUEZ_DEVICE_INTERFACE "'", &err);
4052 	dbus_bus_add_match(this->conn,
4053 			"type='signal',sender='" BLUEZ_SERVICE "',"
4054 			"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',"
4055 			"arg0='" BLUEZ_MEDIA_ENDPOINT_INTERFACE "'", &err);
4056 	dbus_bus_add_match(this->conn,
4057 			"type='signal',sender='" BLUEZ_SERVICE "',"
4058 			"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',"
4059 			"arg0='" BLUEZ_MEDIA_TRANSPORT_INTERFACE "'", &err);
4060 
4061 	this->filters_added = true;
4062 
4063 	return;
4064 
4065 fail:
4066 	dbus_error_free(&err);
4067 }
4068 
4069 static int
impl_device_add_listener(void * object,struct spa_hook * listener,const struct spa_device_events * events,void * data)4070 impl_device_add_listener(void *object, struct spa_hook *listener,
4071 		const struct spa_device_events *events, void *data)
4072 {
4073 	struct spa_bt_monitor *this = object;
4074 	struct spa_hook_list save;
4075 
4076 	spa_return_val_if_fail(this != NULL, -EINVAL);
4077 	spa_return_val_if_fail(events != NULL, -EINVAL);
4078 
4079 	spa_hook_list_isolate(&this->hooks, &save, listener, events, data);
4080 
4081 	add_filters(this);
4082 	check_name_owner(this);
4083 
4084 	spa_hook_list_join(&this->hooks, &save);
4085 
4086 	return 0;
4087 }
4088 
4089 static const struct spa_device_methods impl_device = {
4090 	SPA_VERSION_DEVICE_METHODS,
4091 	.add_listener = impl_device_add_listener,
4092 };
4093 
impl_get_interface(struct spa_handle * handle,const char * type,void ** interface)4094 static int impl_get_interface(struct spa_handle *handle, const char *type, void **interface)
4095 {
4096 	struct spa_bt_monitor *this;
4097 
4098 	spa_return_val_if_fail(handle != NULL, -EINVAL);
4099 	spa_return_val_if_fail(interface != NULL, -EINVAL);
4100 
4101 	this = (struct spa_bt_monitor *) handle;
4102 
4103 	if (spa_streq(type, SPA_TYPE_INTERFACE_Device))
4104 		*interface = &this->device;
4105 	else
4106 		return -ENOENT;
4107 
4108 	return 0;
4109 }
4110 
impl_clear(struct spa_handle * handle)4111 static int impl_clear(struct spa_handle *handle)
4112 {
4113 	struct spa_bt_monitor *monitor;
4114 	struct spa_bt_adapter *a;
4115 	struct spa_bt_device *d;
4116 	struct spa_bt_remote_endpoint *ep;
4117 	struct spa_bt_transport *t;
4118 	size_t i;
4119 
4120 	monitor = (struct spa_bt_monitor *) handle;
4121 
4122 	/*
4123 	 * We don't call BlueZ API unregister methods here, since BlueZ generally does the
4124 	 * unregistration when the DBus connection is closed below.  We'll unregister DBus
4125 	 * object managers and filter callbacks though.
4126 	 */
4127 
4128 	unregister_media_application(monitor);
4129 
4130 	if (monitor->filters_added) {
4131 		dbus_connection_remove_filter(monitor->conn, filter_cb, monitor);
4132 		monitor->filters_added = false;
4133 	}
4134 
4135 	spa_list_consume(t, &monitor->transport_list, link)
4136 		spa_bt_transport_free(t);
4137 	spa_list_consume(ep, &monitor->remote_endpoint_list, link)
4138 		remote_endpoint_free(ep);
4139 	spa_list_consume(d, &monitor->device_list, link)
4140 		device_free(d);
4141 	spa_list_consume(a, &monitor->adapter_list, link)
4142 		adapter_free(a);
4143 
4144 	for (i = 0; i < SPA_N_ELEMENTS(monitor->backends); ++i) {
4145 		spa_bt_backend_free(monitor->backends[i]);
4146 		monitor->backends[i] = NULL;
4147 	}
4148 
4149 	free((void*)monitor->enabled_codecs.items);
4150 	spa_zero(monitor->enabled_codecs);
4151 
4152 	dbus_connection_unref(monitor->conn);
4153 	spa_dbus_connection_destroy(monitor->dbus_connection);
4154 	monitor->dbus_connection = NULL;
4155 	monitor->conn = NULL;
4156 
4157 	monitor->objects_listed = false;
4158 
4159 	monitor->connection_info_supported = false;
4160 
4161 	monitor->backend = NULL;
4162 	monitor->backend_selection = BACKEND_NATIVE;
4163 
4164 	spa_bt_quirks_destroy(monitor->quirks);
4165 
4166 	free_a2dp_codecs(monitor->a2dp_codecs);
4167 
4168 	return 0;
4169 }
4170 
4171 static size_t
impl_get_size(const struct spa_handle_factory * factory,const struct spa_dict * params)4172 impl_get_size(const struct spa_handle_factory *factory,
4173 	      const struct spa_dict *params)
4174 {
4175 	return sizeof(struct spa_bt_monitor);
4176 }
4177 
spa_bt_profiles_from_json_array(const char * str)4178 int spa_bt_profiles_from_json_array(const char *str)
4179 {
4180 	struct spa_json it, it_array;
4181 	char role_name[256];
4182 	enum spa_bt_profile profiles = SPA_BT_PROFILE_NULL;
4183 
4184 	spa_json_init(&it, str, strlen(str));
4185 
4186 	if (spa_json_enter_array(&it, &it_array) <= 0)
4187 		return -EINVAL;
4188 
4189 	while (spa_json_get_string(&it_array, role_name, sizeof(role_name)) > 0) {
4190 		if (spa_streq(role_name, "hsp_hs")) {
4191 			profiles |= SPA_BT_PROFILE_HSP_HS;
4192 		} else if (spa_streq(role_name, "hsp_ag")) {
4193 			profiles |= SPA_BT_PROFILE_HSP_AG;
4194 		} else if (spa_streq(role_name, "hfp_hf")) {
4195 			profiles |= SPA_BT_PROFILE_HFP_HF;
4196 		} else if (spa_streq(role_name, "hfp_ag")) {
4197 			profiles |= SPA_BT_PROFILE_HFP_AG;
4198 		} else if (spa_streq(role_name, "a2dp_sink")) {
4199 			profiles |= SPA_BT_PROFILE_A2DP_SINK;
4200 		} else if (spa_streq(role_name, "a2dp_source")) {
4201 			profiles |= SPA_BT_PROFILE_A2DP_SOURCE;
4202 		}
4203 	}
4204 
4205 	return profiles;
4206 }
4207 
parse_codec_array(struct spa_bt_monitor * this,const struct spa_dict * info)4208 static int parse_codec_array(struct spa_bt_monitor *this, const struct spa_dict *info)
4209 {
4210 	const struct a2dp_codec * const * const a2dp_codecs = this->a2dp_codecs;
4211 	const char *str;
4212 	struct spa_dict_item *codecs;
4213 	struct spa_json it, it_array;
4214 	char codec_name[256];
4215 	size_t num_codecs;
4216 	int i;
4217 
4218 	/* Parse bluez5.codecs property to a dict of enabled codecs */
4219 
4220 	num_codecs = 0;
4221 	while (a2dp_codecs[num_codecs])
4222 		++num_codecs;
4223 
4224 	codecs = calloc(num_codecs, sizeof(struct spa_dict_item));
4225 	if (codecs == NULL)
4226 		return -ENOMEM;
4227 
4228 	if (info == NULL || (str = spa_dict_lookup(info, "bluez5.codecs")) == NULL)
4229 		goto fallback;
4230 
4231 	spa_json_init(&it, str, strlen(str));
4232 
4233 	if (spa_json_enter_array(&it, &it_array) <= 0) {
4234 		spa_log_error(this->log, "property bluez5.codecs '%s' is not an array", str);
4235 		goto fallback;
4236 	}
4237 
4238 	this->enabled_codecs = SPA_DICT_INIT(codecs, 0);
4239 
4240 	while (spa_json_get_string(&it_array, codec_name, sizeof(codec_name)) > 0) {
4241 		int i;
4242 
4243 		for (i = 0; a2dp_codecs[i]; ++i) {
4244 			const struct a2dp_codec *codec = a2dp_codecs[i];
4245 
4246 			if (!spa_streq(codec->name, codec_name))
4247 				continue;
4248 
4249 			if (spa_dict_lookup_item(&this->enabled_codecs, codec->name) != NULL)
4250 				continue;
4251 
4252 			spa_log_debug(this->log, "enabling codec %s", codec->name);
4253 
4254 			spa_assert(this->enabled_codecs.n_items < num_codecs);
4255 
4256 			codecs[this->enabled_codecs.n_items].key = codec->name;
4257 			codecs[this->enabled_codecs.n_items].value = "true";
4258 			++this->enabled_codecs.n_items;
4259 
4260 			break;
4261 		}
4262 	}
4263 
4264 	spa_dict_qsort(&this->enabled_codecs);
4265 
4266 	for (i = 0; a2dp_codecs[i]; ++i) {
4267 		const struct a2dp_codec *codec = a2dp_codecs[i];
4268 		if (!is_a2dp_codec_enabled(this, codec))
4269 			spa_log_debug(this->log, "disabling codec %s", codec->name);
4270 	}
4271 	return 0;
4272 
4273 fallback:
4274 	for (i = 0; a2dp_codecs[i]; ++i) {
4275 		const struct a2dp_codec *codec = a2dp_codecs[i];
4276 		spa_log_debug(this->log, "enabling codec %s", codec->name);
4277 		codecs[i].key = codec->name;
4278 		codecs[i].value = "true";
4279 	}
4280 	this->enabled_codecs = SPA_DICT_INIT(codecs, i);
4281 	spa_dict_qsort(&this->enabled_codecs);
4282 	return 0;
4283 }
4284 
4285 static int
impl_init(const struct spa_handle_factory * factory,struct spa_handle * handle,const struct spa_dict * info,const struct spa_support * support,uint32_t n_support)4286 impl_init(const struct spa_handle_factory *factory,
4287 	  struct spa_handle *handle,
4288 	  const struct spa_dict *info,
4289 	  const struct spa_support *support,
4290 	  uint32_t n_support)
4291 {
4292 	struct spa_bt_monitor *this;
4293 	int res;
4294 
4295 	spa_return_val_if_fail(factory != NULL, -EINVAL);
4296 	spa_return_val_if_fail(handle != NULL, -EINVAL);
4297 
4298 	handle->get_interface = impl_get_interface;
4299 	handle->clear = impl_clear;
4300 
4301 	this = (struct spa_bt_monitor *) handle;
4302 
4303 	this->log = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_Log);
4304 	this->dbus = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_DBus);
4305 	this->main_loop = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_Loop);
4306 	this->main_system = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_System);
4307 	this->plugin_loader = spa_support_find(support, n_support, SPA_TYPE_INTERFACE_PluginLoader);
4308 
4309 	spa_log_topic_init(this->log, &log_topic);
4310 
4311 	if (this->dbus == NULL) {
4312 		spa_log_error(this->log, "a dbus is needed");
4313 		return -EINVAL;
4314 	}
4315 
4316 	if (this->plugin_loader == NULL) {
4317 		spa_log_error(this->log, "a plugin loader is needed");
4318 		return -EINVAL;
4319 	}
4320 
4321 	this->a2dp_codecs = NULL;
4322 	this->quirks = NULL;
4323 	this->conn = NULL;
4324 	this->dbus_connection = NULL;
4325 
4326 	this->a2dp_codecs = load_a2dp_codecs(this->plugin_loader, this->log);
4327 	if (this->a2dp_codecs == NULL) {
4328 		spa_log_error(this->log, "failed to load required A2DP codec plugins");
4329 		res = -EIO;
4330 		goto fail;
4331 	}
4332 
4333 	this->quirks = spa_bt_quirks_create(info, this->log);
4334 	if (this->quirks == NULL) {
4335 		spa_log_error(this->log, "failed to parse quirk table");
4336 		res = -EINVAL;
4337 		goto fail;
4338 	}
4339 
4340 	this->dbus_connection = spa_dbus_get_connection(this->dbus, SPA_DBUS_TYPE_SYSTEM);
4341 	if (this->dbus_connection == NULL) {
4342 		spa_log_error(this->log, "no dbus connection");
4343 		res = -EIO;
4344 		goto fail;
4345 	}
4346 	this->conn = spa_dbus_connection_get(this->dbus_connection);
4347 	if (this->conn == NULL) {
4348 		spa_log_error(this->log, "failed to get dbus connection");
4349 		res = -EIO;
4350 		goto fail;
4351 	}
4352 
4353 	/* XXX: We should handle spa_dbus reconnecting, but we don't, so ref
4354 	 * XXX: the handle so that we can keep it if spa_dbus unrefs it.
4355 	 */
4356 	dbus_connection_ref(this->conn);
4357 
4358 	spa_hook_list_init(&this->hooks);
4359 
4360 	this->device.iface = SPA_INTERFACE_INIT(
4361 			SPA_TYPE_INTERFACE_Device,
4362 			SPA_VERSION_DEVICE,
4363 			&impl_device, this);
4364 
4365 	spa_list_init(&this->adapter_list);
4366 	spa_list_init(&this->device_list);
4367 	spa_list_init(&this->remote_endpoint_list);
4368 	spa_list_init(&this->transport_list);
4369 
4370 	if ((res = parse_codec_array(this, info)) < 0)
4371 		goto fail;
4372 
4373 	this->default_audio_info.rate = A2DP_CODEC_DEFAULT_RATE;
4374 	this->default_audio_info.channels = A2DP_CODEC_DEFAULT_CHANNELS;
4375 
4376 	this->backend_selection = BACKEND_NATIVE;
4377 
4378 	if (info) {
4379 		const char *str;
4380 		uint32_t tmp;
4381 
4382 		if ((str = spa_dict_lookup(info, "api.bluez5.connection-info")) != NULL &&
4383 		    spa_atob(str))
4384 			this->connection_info_supported = true;
4385 
4386 		if ((str = spa_dict_lookup(info, "bluez5.default.rate")) != NULL &&
4387 		    (tmp =  atoi(str)) > 0)
4388 			this->default_audio_info.rate = tmp;
4389 
4390 		if ((str = spa_dict_lookup(info, "bluez5.default.channels")) != NULL &&
4391 		    ((tmp =  atoi(str)) > 0))
4392 			this->default_audio_info.channels = tmp;
4393 
4394 		if ((str = spa_dict_lookup(info, "bluez5.hfphsp-backend")) != NULL) {
4395 			if (spa_streq(str, "none"))
4396 				this->backend_selection = BACKEND_NONE;
4397 			else if (spa_streq(str, "any"))
4398 				this->backend_selection = BACKEND_ANY;
4399 			else if (spa_streq(str, "ofono"))
4400 				this->backend_selection = BACKEND_OFONO;
4401 			else if (spa_streq(str, "hsphfpd"))
4402 				this->backend_selection = BACKEND_HSPHFPD;
4403 			else if (spa_streq(str, "native"))
4404 				this->backend_selection = BACKEND_NATIVE;
4405 		}
4406 
4407 		if ((str = spa_dict_lookup(info, "bluez5.dummy-avrcp-player")) != NULL)
4408 			this->dummy_avrcp_player = spa_atob(str);
4409 		else
4410 			this->dummy_avrcp_player = true;
4411 	}
4412 
4413 	register_media_application(this);
4414 
4415 	/* Create backends. They're started after we get a reply from Bluez. */
4416 	this->backends[BACKEND_NATIVE] = backend_native_new(this, this->conn, info, this->quirks, support, n_support);
4417 	this->backends[BACKEND_OFONO] = backend_ofono_new(this, this->conn, info, this->quirks, support, n_support);
4418 	this->backends[BACKEND_HSPHFPD] = backend_hsphfpd_new(this, this->conn, info, this->quirks, support, n_support);
4419 
4420 	return 0;
4421 
4422 fail:
4423 	if (this->a2dp_codecs)
4424 		free_a2dp_codecs(this->a2dp_codecs);
4425 	if (this->quirks)
4426 		spa_bt_quirks_destroy(this->quirks);
4427 	if (this->conn)
4428 		dbus_connection_unref(this->conn);
4429 	if (this->dbus_connection)
4430 		spa_dbus_connection_destroy(this->dbus_connection);
4431 	this->a2dp_codecs = NULL;
4432 	this->quirks = NULL;
4433 	this->conn = NULL;
4434 	this->dbus_connection = NULL;
4435 	return res;
4436 }
4437 
4438 static const struct spa_interface_info impl_interfaces[] = {
4439 	{SPA_TYPE_INTERFACE_Device,},
4440 };
4441 
4442 static int
impl_enum_interface_info(const struct spa_handle_factory * factory,const struct spa_interface_info ** info,uint32_t * index)4443 impl_enum_interface_info(const struct spa_handle_factory *factory,
4444 			 const struct spa_interface_info **info,
4445 			 uint32_t *index)
4446 {
4447 	spa_return_val_if_fail(factory != NULL, -EINVAL);
4448 	spa_return_val_if_fail(info != NULL, -EINVAL);
4449 	spa_return_val_if_fail(index != NULL, -EINVAL);
4450 
4451 	if (*index >= SPA_N_ELEMENTS(impl_interfaces))
4452 		return 0;
4453 
4454 	*info = &impl_interfaces[(*index)++];
4455 
4456 	return 1;
4457 }
4458 
4459 const struct spa_handle_factory spa_bluez5_dbus_factory = {
4460 	SPA_VERSION_HANDLE_FACTORY,
4461 	SPA_NAME_API_BLUEZ5_ENUM_DBUS,
4462 	NULL,
4463 	impl_get_size,
4464 	impl_init,
4465 	impl_enum_interface_info,
4466 };
4467 
4468 // Report battery percentage to BlueZ using experimental (BlueZ 5.56) Battery Provider API. No-op if no changes occurred.
spa_bt_device_report_battery_level(struct spa_bt_device * device,uint8_t percentage)4469 int spa_bt_device_report_battery_level(struct spa_bt_device *device, uint8_t percentage)
4470 {
4471 	if (percentage == SPA_BT_NO_BATTERY) {
4472 		battery_remove(device);
4473 		return 0;
4474 	}
4475 
4476 	// BlueZ likely is running without battery provider support, don't try to report battery
4477 	if (device->adapter->battery_provider_unavailable) return 0;
4478 
4479 	// If everything is initialized and battery level has not changed we don't need to send anything to BlueZ
4480 	if (device->adapter->has_battery_provider && device->has_battery && device->battery == percentage) return 1;
4481 
4482 	device->battery = percentage;
4483 
4484 	if (!device->adapter->has_battery_provider) {
4485 		// No provider: register it, create battery when registered
4486 		register_battery_provider(device);
4487 	} else if (!device->has_battery) {
4488 		// Have provider but no battery: create battery with correct percentage
4489 		battery_create(device);
4490 	} else {
4491 		// Just update existing battery percentage
4492 		battery_update(device);
4493 	}
4494 
4495 	return 1;
4496 }
4497