bluez5-util.c 104 KB
Newer Older
1 2 3 4
/***
  This file is part of PulseAudio.

  Copyright 2008-2013 João Paulo Rechi Vita
pali's avatar
pali committed
5
  Copyrigth 2018-2019 Pali Rohár <pali.rohar@gmail.com>
6 7 8 9 10 11 12 13 14 15 16 17

  PulseAudio is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1 of the
  License, or (at your option) any later version.

  PulseAudio is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
18
  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
19 20 21 22 23 24
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

25 26
#include <errno.h>

27 28
#include <pulse/rtclock.h>
#include <pulse/timeval.h>
29 30 31
#include <pulse/xmalloc.h>

#include <pulsecore/core.h>
32 33 34
#include <pulsecore/core-util.h>
#include <pulsecore/dbus-shared.h>
#include <pulsecore/log.h>
35 36 37 38
#include <pulsecore/macro.h>
#include <pulsecore/refcnt.h>
#include <pulsecore/shared.h>

pali's avatar
pali committed
39
#include "a2dp-codec-util.h"
40 41
#include "a2dp-codecs.h"

42
#include "bluez5-util.h"
43
#include "hsphfpd-util.h"
44

45 46
#define WAIT_FOR_PROFILES_TIMEOUT_USEC (3 * PA_USEC_PER_SEC)

47 48
#define A2DP_MAX_GAIN 127

49
#define BLUEZ_SERVICE "org.bluez"
50 51
#define BLUEZ_ADAPTER_INTERFACE BLUEZ_SERVICE ".Adapter1"
#define BLUEZ_DEVICE_INTERFACE BLUEZ_SERVICE ".Device1"
52
#define BLUEZ_MEDIA_INTERFACE BLUEZ_SERVICE ".Media1"
53
#define BLUEZ_MEDIA_ENDPOINT_INTERFACE BLUEZ_SERVICE ".MediaEndpoint1"
54
#define BLUEZ_MEDIA_TRANSPORT_INTERFACE BLUEZ_SERVICE ".MediaTransport1"
55

56
#define BLUEZ_ERROR_NOT_SUPPORTED "org.bluez.Error.NotSupported"
57
#define BLUEZ_ERROR_NOT_AVAILABLE "org.bluez.Error.NotAvailable"
58

59 60 61
#define A2DP_OBJECT_MANAGER_PATH "/A2DPEndpoint"
#define A2DP_SOURCE_ENDPOINT A2DP_OBJECT_MANAGER_PATH "/Source"
#define A2DP_SINK_ENDPOINT A2DP_OBJECT_MANAGER_PATH "/Sink"
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

#define OBJECT_MANAGER_INTROSPECT_XML                                          \
    DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                                  \
    "<node>\n"                                                                 \
    " <interface name=\"org.freedesktop.DBus.ObjectManager\">\n"               \
    "  <method name=\"GetManagedObjects\">\n"                                  \
    "   <arg name=\"objects\" direction=\"out\" type=\"a{oa{sa{sv}}}\"/>\n"    \
    "  </method>\n"                                                            \
    "  <signal name=\"InterfacesAdded\">\n"                                    \
    "   <arg name=\"object\" type=\"o\"/>\n"                                   \
    "   <arg name=\"interfaces\" type=\"a{sa{sv}}\"/>\n"                       \
    "  </signal>\n"                                                            \
    "  <signal name=\"InterfacesRemoved\">\n"                                  \
    "   <arg name=\"object\" type=\"o\"/>\n"                                   \
    "   <arg name=\"interfaces\" type=\"as\"/>\n"                              \
    "  </signal>\n"                                                            \
    " </interface>\n"                                                          \
    " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"              \
    "  <method name=\"Introspect\">\n"                                         \
    "   <arg name=\"data\" direction=\"out\" type=\"s\"/>\n"                   \
    "  </method>\n"                                                            \
    " </interface>\n"                                                          \
    " <node name=\"A2DPSink\"/>\n"                                             \
    " <node name=\"A2DPSource\"/>\n"                                           \
    "</node>\n"
87 88 89

#define ENDPOINT_INTROSPECT_XML                                         \
    DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                           \
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    "<node>\n"                                                          \
    " <interface name=\"" BLUEZ_MEDIA_ENDPOINT_INTERFACE "\">\n"        \
    "  <method name=\"SetConfiguration\">\n"                            \
    "   <arg name=\"transport\" direction=\"in\" type=\"o\"/>\n"        \
    "   <arg name=\"properties\" direction=\"in\" type=\"ay\"/>\n"      \
    "  </method>\n"                                                     \
    "  <method name=\"SelectConfiguration\">\n"                         \
    "   <arg name=\"capabilities\" direction=\"in\" type=\"ay\"/>\n"    \
    "   <arg name=\"configuration\" direction=\"out\" type=\"ay\"/>\n"  \
    "  </method>\n"                                                     \
    "  <method name=\"ClearConfiguration\">\n"                          \
    "   <arg name=\"transport\" direction=\"in\" type=\"o\"/>\n"        \
    "  </method>\n"                                                     \
    "  <method name=\"Release\">\n"                                     \
    "  </method>\n"                                                     \
    " </interface>\n"                                                   \
    " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"       \
    "  <method name=\"Introspect\">\n"                                  \
    "   <arg name=\"data\" type=\"s\" direction=\"out\"/>\n"            \
    "  </method>\n"                                                     \
    " </interface>\n"                                                   \
    "</node>\n"
112

113 114 115 116
struct pa_bluetooth_discovery {
    PA_REFCNT_DECLARE;

    pa_core *core;
117 118 119
    pa_dbus_connection *connection;
    bool filter_added;
    bool matches_added;
120
    bool objects_listed;
121
    pa_hook hooks[PA_BLUETOOTH_HOOK_MAX];
122
    pa_hashmap *adapters;
123
    pa_hashmap *devices;
124
    pa_hashmap *transports;
125
    pa_hashmap *pending_transport_fds;
126
    pa_bluetooth_hsphfpd *hsphfpd;
127
    PA_LLIST_HEAD(pa_dbus_pending, pending);
128 129
};

130 131 132 133 134 135 136
struct pending_transport_fd {
    pa_bluetooth_discovery *discovery;
    char *path;
    size_t imtu, omtu;
    int fd;
};

137 138 139 140 141
struct a2dp_codec_capabilities {
    uint8_t size;
    uint8_t buffer[]; /* max size is 254 bytes */
};

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
static pa_dbus_pending* send_and_add_to_pending(pa_bluetooth_discovery *y, DBusMessage *m,
                                                                  DBusPendingCallNotifyFunction func, void *call_data) {
    pa_dbus_pending *p;
    DBusPendingCall *call;

    pa_assert(y);
    pa_assert(m);

    pa_assert_se(dbus_connection_send_with_reply(pa_dbus_connection_get(y->connection), m, &call, -1));

    p = pa_dbus_pending_new(pa_dbus_connection_get(y->connection), m, call, y, call_data);
    PA_LLIST_PREPEND(pa_dbus_pending, y->pending, p);
    dbus_pending_call_set_notify(call, func, p, NULL);

    return p;
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
static const char *check_variant_property(DBusMessageIter *i) {
    const char *key;

    pa_assert(i);

    if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_STRING) {
        pa_log_error("Property name not a string.");
        return NULL;
    }

    dbus_message_iter_get_basic(i, &key);

    if (!dbus_message_iter_next(i)) {
        pa_log_error("Property value missing");
        return NULL;
    }

    if (dbus_message_iter_get_arg_type(i) != DBUS_TYPE_VARIANT) {
        pa_log_error("Property value not a variant.");
        return NULL;
    }

    return key;
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
pa_bluetooth_transport *pa_bluetooth_transport_new(pa_bluetooth_device *d, const char *owner, const char *path,
                                                   pa_bluetooth_profile_t p, const uint8_t *config, size_t size) {
    pa_bluetooth_transport *t;

    t = pa_xnew0(pa_bluetooth_transport, 1);
    t->device = d;
    t->owner = pa_xstrdup(owner);
    t->path = pa_xstrdup(path);
    t->profile = p;
    t->config_size = size;

    if (size > 0) {
        t->config = pa_xnew(uint8_t, size);
        memcpy(t->config, config, size);
    }

    return t;
}

static const char *transport_state_to_string(pa_bluetooth_transport_state_t state) {
    switch(state) {
        case PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED:
            return "disconnected";
        case PA_BLUETOOTH_TRANSPORT_STATE_IDLE:
            return "idle";
        case PA_BLUETOOTH_TRANSPORT_STATE_PLAYING:
            return "playing";
    }

    return "invalid";
}

216
static bool device_supports_profile(pa_bluetooth_device *device, pa_bluetooth_profile_t profile) {
217 218 219 220 221 222
    const struct a2dp_codec_capabilities *a2dp_codec_capabilities;
    const pa_a2dp_codec *a2dp_codec;
    bool is_a2dp_sink;
    pa_hashmap *endpoints;
    void *state;

223
    switch (profile) {
224
        case PA_BLUETOOTH_PROFILE_HSP_HEAD_UNIT:
225
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_HS)
226 227 228 229 230 231 232
                || !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_HS_ALT);
        case PA_BLUETOOTH_PROFILE_HFP_HEAD_UNIT:
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HFP_HF);
        case PA_BLUETOOTH_PROFILE_HSP_AUDIO_GATEWAY:
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_AG);
        case PA_BLUETOOTH_PROFILE_HFP_AUDIO_GATEWAY:
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HFP_AG);
233
        case PA_BLUETOOTH_PROFILE_OFF:
234 235 236
            return true;
        default:
            break;
237 238
    }

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    a2dp_codec = pa_bluetooth_profile_to_a2dp_codec(profile);
    is_a2dp_sink = pa_bluetooth_profile_is_a2dp_sink(profile);

    if (is_a2dp_sink && !pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SINK))
        return false;
    else if (!is_a2dp_sink && !pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SOURCE))
        return false;

    if (is_a2dp_sink)
        endpoints = pa_hashmap_get(device->a2dp_sink_endpoints, &a2dp_codec->id);
    else
        endpoints = pa_hashmap_get(device->a2dp_source_endpoints, &a2dp_codec->id);

    if (!endpoints)
        return false;

    PA_HASHMAP_FOREACH(a2dp_codec_capabilities, endpoints, state) {
        if (a2dp_codec->can_accept_capabilities(a2dp_codec_capabilities->buffer, a2dp_codec_capabilities->size, is_a2dp_sink))
            return true;
    }

    return false;
261 262 263 264 265 266 267 268 269
}

static bool device_is_profile_connected(pa_bluetooth_device *device, pa_bluetooth_profile_t profile) {
    if (device->transports[profile] && device->transports[profile]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
        return true;
    else
        return false;
}

270
static unsigned device_count_disconnected_profile_uuids(pa_bluetooth_device *device) {
271
    pa_bluetooth_profile_t profile;
272
    unsigned bluetooth_profile_count;
273 274
    unsigned count = 0;

275 276
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (profile = 0; profile < bluetooth_profile_count; profile++) {
277 278 279
        if (profile == PA_BLUETOOTH_PROFILE_OFF)
            continue;

280
        if (!device_supports_profile(device, profile) || pa_bluetooth_profile_is_a2dp(profile))
281 282 283 284 285 286
            continue;

        if (!device_is_profile_connected(device, profile))
            count++;
    }

287 288 289 290 291 292
    if (pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SINK) && !pa_bluetooth_device_a2dp_sink_transport_connected(device))
        count++;

    if (pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_A2DP_SOURCE) && !pa_bluetooth_device_a2dp_source_transport_connected(device))
        count++;

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    return count;
}

static void device_stop_waiting_for_profiles(pa_bluetooth_device *device) {
    if (!device->wait_for_profiles_timer)
        return;

    device->discovery->core->mainloop->time_free(device->wait_for_profiles_timer);
    device->wait_for_profiles_timer = NULL;
}

static void wait_for_profiles_cb(pa_mainloop_api *api, pa_time_event* event, const struct timeval *tv, void *userdata) {
    pa_bluetooth_device *device = userdata;
    pa_strbuf *buf;
    pa_bluetooth_profile_t profile;
308
    unsigned bluetooth_profile_count;
309 310 311 312 313 314 315
    bool first = true;
    char *profiles_str;

    device_stop_waiting_for_profiles(device);

    buf = pa_strbuf_new();

316 317
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (profile = 0; profile < bluetooth_profile_count; profile++) {
318 319 320
        if (profile == PA_BLUETOOTH_PROFILE_OFF)
            continue;

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        if (device_is_profile_connected(device, profile))
            continue;

        if (!device_supports_profile(device, profile))
            continue;

        if (first)
            first = false;
        else
            pa_strbuf_puts(buf, ", ");

        pa_strbuf_puts(buf, pa_bluetooth_profile_to_string(profile));
    }

    profiles_str = pa_strbuf_to_string_free(buf);
    pa_log_debug("Timeout expired, and device %s still has disconnected profiles: %s",
                 device->path, profiles_str);
    pa_xfree(profiles_str);
    pa_hook_fire(&device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], device);
}

static void device_start_waiting_for_profiles(pa_bluetooth_device *device) {
    pa_assert(!device->wait_for_profiles_timer);
    device->wait_for_profiles_timer = pa_core_rttime_new(device->discovery->core,
                                                         pa_rtclock_now() + WAIT_FOR_PROFILES_TIMEOUT_USEC,
                                                         wait_for_profiles_cb, device);
}

349
void pa_bluetooth_transport_set_state(pa_bluetooth_transport *t, pa_bluetooth_transport_state_t state) {
350
    bool old_any_connected;
351
    unsigned n_disconnected_profile_uuids;
352 353
    bool new_device_appeared;
    bool device_disconnected;
354 355 356 357 358 359 360 361

    pa_assert(t);

    if (t->state == state)
        return;

    old_any_connected = pa_bluetooth_device_any_transport_connected(t->device);

362
    pa_log_debug("Transport %s state: %s -> %s",
363 364 365 366 367 368
                 t->path, transport_state_to_string(t->state), transport_state_to_string(state));

    t->state = state;

    pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_TRANSPORT_STATE_CHANGED], t);

369 370 371 372 373 374 375
    /* If there are profiles that are expected to get connected soon (based
     * on the UUID list), we wait for a bit before announcing the new
     * device, so that all profiles have time to get connected before the
     * card object is created. If we didn't wait, the card would always
     * have only one profile marked as available in the initial state,
     * which would prevent module-card-restore from restoring the initial
     * profile properly. */
376

377
    n_disconnected_profile_uuids = device_count_disconnected_profile_uuids(t->device);
378

379 380
    new_device_appeared = !old_any_connected && pa_bluetooth_device_any_transport_connected(t->device);
    device_disconnected = old_any_connected && !pa_bluetooth_device_any_transport_connected(t->device);
381

382
    if (new_device_appeared) {
383
        if (n_disconnected_profile_uuids > 0)
384 385 386
            device_start_waiting_for_profiles(t->device);
        else
            pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        return;
    }

    if (device_disconnected) {
        if (t->device->wait_for_profiles_timer) {
            /* If the timer is still running when the device disconnects, we
             * never sent the notification of the device getting connected, so
             * we don't need to send a notification about the disconnection
             * either. Let's just stop the timer. */
            device_stop_waiting_for_profiles(t->device);
        } else
            pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
        return;
    }

402
    if (n_disconnected_profile_uuids == 0 && t->device->wait_for_profiles_timer) {
403 404 405 406
        /* All profiles are now connected, so we can stop the wait timer and
         * send a notification of the new device. */
        device_stop_waiting_for_profiles(t->device);
        pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
407
    }
408 409
}

410 411 412 413 414
pa_bluetooth_transport *pa_bluetooth_transport_get(pa_bluetooth_discovery *y, const char *path) {
    pa_assert(path);
    return pa_hashmap_get(y->transports, path);
}

415 416 417 418
pa_hashmap *pa_bluetooth_transport_get_all(pa_bluetooth_discovery *y) {
    return y->transports;
}

419 420
static void pa_bluetooth_transport_remote_volume_changed(pa_bluetooth_transport *t, pa_volume_t volume) {
    pa_bluetooth_hook_t hook;
421 422 423

    pa_assert(t);

424 425
    if (pa_bluetooth_profile_is_a2dp_source(t->profile)) {
        t->rx_volume_gain = volume;
pali's avatar
pali committed
426
        hook = PA_BLUETOOTH_HOOK_TRANSPORT_RX_VOLUME_GAIN_CHANGED;
427 428
    } else if (pa_bluetooth_profile_is_a2dp_sink(t->profile)) {
        t->tx_volume_gain = volume;
pali's avatar
pali committed
429
        hook = PA_BLUETOOTH_HOOK_TRANSPORT_TX_VOLUME_GAIN_CHANGED;
430 431 432
    } else {
        pa_assert_not_reached();
    }
433

434
    pa_hook_fire(pa_bluetooth_discovery_hook(t->device->discovery, hook), t);
435 436
}

437
void pa_bluetooth_transport_put(pa_bluetooth_transport *t) {
438 439 440 441
    pa_assert(t);

    t->device->transports[t->profile] = t;
    pa_assert_se(pa_hashmap_put(t->device->discovery->transports, t->path, t) >= 0);
442
    pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
443 444 445 446 447
}

void pa_bluetooth_transport_free(pa_bluetooth_transport *t) {
    pa_assert(t);

448 449
    pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED);

450 451
    if (t->destroy)
        t->destroy(t);
452 453 454

    pa_hashmap_remove(t->device->discovery->transports, t->path);
    t->device->transports[t->profile] = NULL;
455

456 457 458 459 460 461
    pa_xfree(t->owner);
    pa_xfree(t->path);
    pa_xfree(t->config);
    pa_xfree(t);
}

462 463
static void bluez5_transport_acquire_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
464
    DBusError err;
465 466 467 468 469 470
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    pa_bluetooth_transport *t;
    struct pending_transport_fd *pending_transport_fd;
    char *path;
    int fd;
471 472
    uint16_t i, o;

473 474 475 476 477
    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(y = p->context_data);
    pa_assert_se(path = p->call_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));
478 479 480

    dbus_error_init(&err);

481 482 483
    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_error("Transport Acquire() failed for transport %s (%s)", path, pa_dbus_get_error_message(r));
        goto failed;
484 485
    }

486
    if (!dbus_message_get_args(r, &err, DBUS_TYPE_UNIX_FD, &fd, DBUS_TYPE_UINT16, &i, DBUS_TYPE_UINT16, &o, DBUS_TYPE_INVALID)) {
487
        pa_log_error("Failed to parse Acquire() reply: %s", err.message);
488 489 490 491 492 493 494 495 496 497 498 499 500 501
        goto failed;
    }

    pa_log_info("Transport %s acquired", path);
    goto success;

failed:
    /* If transport state is not disconnected then switch it to disconnected state and
     * then to idle state so sinks and sources are properly released and connection
     * attempt is marked as failed, this also trigger profile change to off */
    t = pa_bluetooth_transport_get(y, path);
    if (t && t->state > PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED) {
        pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED);
        pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
502 503
    }

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    fd = -1;
    i = 0;
    o = 0;
    /* fall through, we need to put failure into pending_transport_fds hashmap */

success:
    pending_transport_fd = pa_hashmap_get(y->pending_transport_fds, path);
    if (!pending_transport_fd) {
        pending_transport_fd = pa_xnew0(struct pending_transport_fd, 1);
        pending_transport_fd->discovery = y;
        pending_transport_fd->path = pa_xstrdup(path);
        pa_hashmap_put(y->pending_transport_fds, pending_transport_fd->path, pending_transport_fd);
    } else if (pending_transport_fd->fd != fd) {
        pa_log_info("Closing staled pending fd %d for transport %s", pending_transport_fd->fd, path);
        close(pending_transport_fd->fd);
    }

    pending_transport_fd->fd = fd;
    pending_transport_fd->imtu = i;
    pending_transport_fd->omtu = o;

/* finish: */
    dbus_error_free(&err);
    dbus_message_unref(r);

    PA_LLIST_REMOVE(pa_dbus_pending, y->pending, p);
    pa_dbus_pending_free(p);

    pa_xfree(path);
}

static int bluez5_transport_acquire_cb(pa_bluetooth_transport *t, size_t *imtu, size_t *omtu) {
    struct pending_transport_fd *pending_transport_fd;
    DBusMessage *m;
    int fd;

    pa_assert(t);
    pa_assert(t->device);
    pa_assert(t->device->discovery);

    pending_transport_fd = pa_hashmap_remove(t->device->discovery->pending_transport_fds, t->path);
    if (!pending_transport_fd) {
        pa_assert_se(m = dbus_message_new_method_call(t->owner, t->path, BLUEZ_MEDIA_TRANSPORT_INTERFACE, "Acquire"));
        send_and_add_to_pending(t->device->discovery, m, bluez5_transport_acquire_reply, pa_xstrdup(t->path));
        return -EAGAIN;
    }

    fd = pending_transport_fd->fd;

553
    if (imtu)
554
        *imtu = pending_transport_fd->imtu;
555 556

    if (omtu)
557
        *omtu = pending_transport_fd->omtu;
558

559 560 561 562
    pa_xfree(pending_transport_fd->path);
    pa_xfree(pending_transport_fd);

    return fd;
563 564 565
}

static void bluez5_transport_release_cb(pa_bluetooth_transport *t) {
566
    DBusMessage *m;
567 568 569 570 571 572 573 574 575 576 577

    pa_assert(t);
    pa_assert(t->device);
    pa_assert(t->device->discovery);

    if (t->state <= PA_BLUETOOTH_TRANSPORT_STATE_IDLE) {
        pa_log_info("Transport %s auto-released by BlueZ or already released", t->path);
        return;
    }

    pa_assert_se(m = dbus_message_new_method_call(t->owner, t->path, BLUEZ_MEDIA_TRANSPORT_INTERFACE, "Release"));
578 579 580
    pa_assert_se(dbus_connection_send(pa_dbus_connection_get(t->device->discovery->connection), m, NULL));
    pa_log_info("Transport %s released", t->path);
}
581

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
static void bluez5_transport_release_staled_pending_fd(struct pending_transport_fd *pending_transport_fd) {
    pa_bluetooth_transport *t;

    pa_assert(pending_transport_fd);
    pa_assert(pending_transport_fd->discovery);

    pa_log_info("Releasing staled pending transport %s", pending_transport_fd->path);

    t = pa_hashmap_get(pending_transport_fd->discovery->transports, pending_transport_fd->path);
    if (t)
        bluez5_transport_release_cb(t);

    close(pending_transport_fd->fd);

    pa_xfree(pending_transport_fd->path);
    pa_xfree(pending_transport_fd);
598 599
}

600
static void bluez5_transport_set_volume(pa_bluetooth_transport *t, uint16_t gain) {
601 602
    static const char *volume_str = "Volume";
    static const char *mediatransport_str = BLUEZ_MEDIA_TRANSPORT_INTERFACE;
603
    DBusMessage *m;
604 605 606 607
    DBusMessageIter iter;

    pa_assert(t);
    pa_assert(t->device);
608
    pa_assert(pa_bluetooth_profile_is_a2dp(t->profile));
609 610
    pa_assert(t->device->discovery);

611 612 613
    if (pa_bluetooth_profile_is_a2dp_source(t->profile) && t->rx_volume_gain == gain)
        return;
    else if (pa_bluetooth_profile_is_a2dp_sink(t->profile) && t->tx_volume_gain == gain)
614 615
        return;

616 617
    pa_log_debug("Sending A2DP volume %d/127 to peer", gain);

618 619 620 621 622 623 624
    pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, t->path, DBUS_INTERFACE_PROPERTIES, "Set"));

    dbus_message_iter_init_append(m, &iter);
    pa_assert_se(dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &mediatransport_str));
    pa_assert_se(dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &volume_str));
    pa_dbus_append_basic_variant(&iter, DBUS_TYPE_UINT16, &gain);

625 626 627 628
    /* Ignore replies, instead wait for the Volume property changed notification */
    dbus_message_set_no_reply(m, true);
    pa_assert_se(dbus_connection_send(pa_dbus_connection_get(t->device->discovery->connection), m, NULL));
    dbus_message_unref(m);
629 630
}

631 632 633 634 635 636 637 638 639 640 641 642
static void bluez5_transport_set_sink_volume(pa_bluetooth_transport *t, uint16_t gain) {
    pa_assert(t);
    pa_assert(pa_bluetooth_profile_is_a2dp_sink(t->profile));
    bluez5_transport_set_volume(t, gain);
}

static void bluez5_transport_set_source_volume(pa_bluetooth_transport *t, uint16_t gain) {
    pa_assert(t);
    pa_assert(pa_bluetooth_profile_is_a2dp_source(t->profile));
    bluez5_transport_set_volume(t, gain);
}

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
static void request_volume_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    DBusMessageIter iter, variant;
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    pa_bluetooth_transport *t;
    uint16_t gain;

    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(y = p->context_data);
    pa_assert_se(t = p->call_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_error(DBUS_INTERFACE_PROPERTIES ".Get %s Volume failed: %s: %s",
                     dbus_message_get_path(p->message),
                     dbus_message_get_error_name(r),
                     pa_dbus_get_error_message(r));
        goto finish;
    }
    dbus_message_iter_init(r, &iter);
    pa_assert(dbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_VARIANT);
    dbus_message_iter_recurse(&iter, &variant);
    pa_assert(dbus_message_iter_get_arg_type(&variant) == DBUS_TYPE_UINT16);
    dbus_message_iter_get_basic(&variant, &gain);

    if (gain > A2DP_MAX_GAIN)
        gain = A2DP_MAX_GAIN;

    pa_log_debug("Received A2DP Absolute Volume %d", gain);

    pa_bluetooth_transport_remote_volume_changed(t, gain);

finish:
    dbus_message_unref(r);

    PA_LLIST_REMOVE(pa_dbus_pending, y->pending, p);
    pa_dbus_pending_free(p);
}

static void bluez5_transport_request_volume(pa_bluetooth_transport *t) {
    static const char *volume_str = "Volume";
    static const char *mediatransport_str = BLUEZ_MEDIA_TRANSPORT_INTERFACE;
    DBusMessage *m;

    pa_assert(t);
    pa_assert(t->device);
    pa_assert(t->device->discovery);

    pa_assert(pa_bluetooth_profile_is_a2dp(t->profile));

    pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, t->path, DBUS_INTERFACE_PROPERTIES, "Get"));
    pa_assert_se(dbus_message_append_args(m,
        DBUS_TYPE_STRING, &mediatransport_str,
        DBUS_TYPE_STRING, &volume_str,
        DBUS_TYPE_INVALID));

    send_and_add_to_pending(t->device->discovery, m, request_volume_reply, t);
}

704
bool pa_bluetooth_device_any_transport_connected(const pa_bluetooth_device *d) {
705
    unsigned i, bluetooth_profile_count;
706 707 708

    pa_assert(d);

709
    if (!d->valid)
710 711
        return false;

712 713
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
714 715 716 717 718 719
        if (d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
bool pa_bluetooth_device_a2dp_sink_transport_connected(const pa_bluetooth_device *d) {
    unsigned i, bluetooth_profile_count;

    pa_assert(d);

    if (!d->valid)
        return false;

    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
        if (pa_bluetooth_profile_is_a2dp_sink(i) && d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

bool pa_bluetooth_device_a2dp_source_transport_connected(const pa_bluetooth_device *d) {
    unsigned i, bluetooth_profile_count;

    pa_assert(d);

    if (!d->valid)
        return false;

    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
        if (pa_bluetooth_profile_is_a2dp_source(i) && d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
static int transport_state_from_string(const char* value, pa_bluetooth_transport_state_t *state) {
    pa_assert(value);
    pa_assert(state);

    if (pa_streq(value, "idle"))
        *state = PA_BLUETOOTH_TRANSPORT_STATE_IDLE;
    else if (pa_streq(value, "pending") || pa_streq(value, "active"))
        *state = PA_BLUETOOTH_TRANSPORT_STATE_PLAYING;
    else
        return -1;

    return 0;
}

static void parse_transport_property(pa_bluetooth_transport *t, DBusMessageIter *i) {
    const char *key;
    DBusMessageIter variant_i;

    key = check_variant_property(i);
    if (key == NULL)
        return;

    dbus_message_iter_recurse(i, &variant_i);

    switch (dbus_message_iter_get_arg_type(&variant_i)) {

        case DBUS_TYPE_STRING: {

            const char *value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "State")) {
                pa_bluetooth_transport_state_t state;

                if (transport_state_from_string(value, &state) < 0) {
                    pa_log_error("Invalid state received: %s", value);
                    return;
                }

791
                pa_bluetooth_transport_set_state(t, state);
792 793 794 795
            }

            break;
        }
796 797

        case DBUS_TYPE_UINT16: {
798 799
            uint16_t value;
            dbus_message_iter_get_basic(&variant_i, &value);
800

pali's avatar
pali committed
801 802 803
            if (pa_streq(key, "Volume"))
                pa_bluetooth_transport_remote_volume_changed(t, value);

804 805
            break;
        }
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
    }

    return;
}

static int parse_transport_properties(pa_bluetooth_transport *t, DBusMessageIter *i) {
    DBusMessageIter element_i;

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i;

        dbus_message_iter_recurse(&element_i, &dict_i);

        parse_transport_property(t, &dict_i);

        dbus_message_iter_next(&element_i);
    }

    return 0;
}

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
static unsigned pa_a2dp_codec_id_hash_func(const void *_p) {
    unsigned hash;
    const pa_a2dp_codec_id *p = _p;

    hash = p->codec_id;
    hash = 31 * hash + ((p->vendor_id >>  0) & 0xFF);
    hash = 31 * hash + ((p->vendor_id >>  8) & 0xFF);
    hash = 31 * hash + ((p->vendor_id >> 16) & 0xFF);
    hash = 31 * hash + ((p->vendor_id >> 24) & 0xFF);
    hash = 31 * hash + ((p->vendor_codec_id >> 0) & 0xFF);
    hash = 31 * hash + ((p->vendor_codec_id >> 8) & 0xFF);
    return hash;
}

static int pa_a2dp_codec_id_compare_func(const void *_a, const void *_b) {
    const pa_a2dp_codec_id *a = _a;
    const pa_a2dp_codec_id *b = _b;

    if (a->codec_id < b->codec_id)
        return -1;
    if (a->codec_id > b->codec_id)
        return 1;

    if (a->vendor_id < b->vendor_id)
        return -1;
    if (a->vendor_id > b->vendor_id)
        return 1;

    if (a->vendor_codec_id < b->vendor_codec_id)
        return -1;
    if (a->vendor_codec_id > b->vendor_codec_id)
        return 1;

    return 0;
}

865 866 867 868 869 870 871 872 873
static pa_bluetooth_device* device_create(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *d;

    pa_assert(y);
    pa_assert(path);

    d = pa_xnew0(pa_bluetooth_device, 1);
    d->discovery = y;
    d->path = pa_xstrdup(path);
874
    d->uuids = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, pa_xfree);
875 876 877
    d->a2dp_sink_endpoints = pa_hashmap_new_full(pa_a2dp_codec_id_hash_func, pa_a2dp_codec_id_compare_func, pa_xfree, (pa_free_cb_t)pa_hashmap_free);
    d->a2dp_source_endpoints = pa_hashmap_new_full(pa_a2dp_codec_id_hash_func, pa_a2dp_codec_id_compare_func, pa_xfree, (pa_free_cb_t)pa_hashmap_free);
    d->transports = pa_xnew0(pa_bluetooth_transport *, pa_bluetooth_profile_count());
878 879 880 881 882 883 884 885 886 887 888 889 890

    pa_hashmap_put(y->devices, d->path, d);

    return d;
}

pa_bluetooth_device* pa_bluetooth_discovery_get_device_by_path(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *d;

    pa_assert(y);
    pa_assert(PA_REFCNT_VALUE(y) > 0);
    pa_assert(path);

891 892
    if ((d = pa_hashmap_get(y->devices, path)) && d->valid)
        return d;
893 894 895 896 897 898 899 900 901 902 903 904 905 906

    return NULL;
}

pa_bluetooth_device* pa_bluetooth_discovery_get_device_by_address(pa_bluetooth_discovery *y, const char *remote, const char *local) {
    pa_bluetooth_device *d;
    void *state = NULL;

    pa_assert(y);
    pa_assert(PA_REFCNT_VALUE(y) > 0);
    pa_assert(remote);
    pa_assert(local);

    while ((d = pa_hashmap_iterate(y->devices, &state, NULL)))
907
        if (d->valid && pa_streq(d->address, remote) && pa_streq(d->adapter->address, local))
908
            return d;
909 910 911 912

    return NULL;
}

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
static void remote_endpoint_remove(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *device;
    pa_hashmap *endpoints;
    void *devices_state;
    void *state;

    PA_HASHMAP_FOREACH(device, y->devices, devices_state) {
        PA_HASHMAP_FOREACH(endpoints, device->a2dp_sink_endpoints, state)
            pa_hashmap_remove_and_free(endpoints, path);

        PA_HASHMAP_FOREACH(endpoints, device->a2dp_source_endpoints, state)
            pa_hashmap_remove_and_free(endpoints, path);
    }

    pa_log_debug("Remote endpoint %s was removed", path);
}

930
static void device_free(pa_bluetooth_device *d) {
931
    unsigned i, bluetooth_profile_count;
932

933 934
    pa_assert(d);

935 936
    device_stop_waiting_for_profiles(d);

937 938
    pa_hook_fire(&d->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_UNLINK], d);

939 940
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++) {
941 942 943 944 945 946 947 948
        pa_bluetooth_transport *t;

        if (!(t = d->transports[i]))
            continue;

        pa_bluetooth_transport_free(t);
    }

949 950 951
    pa_hashmap_free(d->uuids);
    pa_hashmap_free(d->a2dp_sink_endpoints);
    pa_hashmap_free(d->a2dp_source_endpoints);
952

953
    pa_xfree(d->transports);
954 955 956
    pa_xfree(d->path);
    pa_xfree(d->alias);
    pa_xfree(d->address);
957
    pa_xfree(d->adapter_path);
958 959 960 961 962 963 964 965 966 967 968 969 970 971
    pa_xfree(d);
}

static void device_remove(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_device *d;

    if (!(d = pa_hashmap_remove(y->devices, path)))
        pa_log_warn("Unknown device removed %s", path);
    else {
        pa_log_debug("Device %s removed", path);
        device_free(d);
    }
}

972
static void device_set_valid(pa_bluetooth_device *device, bool valid) {
973 974
    bool old_any_connected;

975 976
    pa_assert(device);

977
    if (valid == device->valid)
978 979
        return;

980
    old_any_connected = pa_bluetooth_device_any_transport_connected(device);
981
    device->valid = valid;
982 983 984

    if (pa_bluetooth_device_any_transport_connected(device) != old_any_connected)
        pa_hook_fire(&device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], device);
985 986
}

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
static void device_update_valid(pa_bluetooth_device *d) {
    pa_assert(d);

    if (!d->properties_received) {
        pa_assert(!d->valid);
        return;
    }

    /* Check if mandatory properties are set. */
    if (!d->address || !d->adapter_path || !d->alias) {
        device_set_valid(d, false);
        return;
    }

    if (!d->adapter || !d->adapter->valid) {
        device_set_valid(d, false);
        return;
    }

    device_set_valid(d, true);
}

static void device_set_adapter(pa_bluetooth_device *device, pa_bluetooth_adapter *adapter) {
    pa_assert(device);

    if (adapter == device->adapter)
        return;

    device->adapter = adapter;

    device_update_valid(device);
}

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
static pa_bluetooth_adapter* adapter_create(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_adapter *a;

    pa_assert(y);
    pa_assert(path);

    a = pa_xnew0(pa_bluetooth_adapter, 1);
    a->discovery = y;
    a->path = pa_xstrdup(path);

    pa_hashmap_put(y->adapters, a->path, a);

    return a;
}

1035 1036 1037 1038 1039 1040 1041 1042
static void adapter_free(pa_bluetooth_adapter *a) {
    pa_bluetooth_device *d;
    void *state;

    pa_assert(a);
    pa_assert(a->discovery);

    PA_HASHMAP_FOREACH(d, a->discovery->devices, state)
1043 1044
        if (d->adapter == a)
            device_set_adapter(d, NULL);
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

    pa_xfree(a->path);
    pa_xfree(a->address);
    pa_xfree(a);
}

static void adapter_remove(pa_bluetooth_discovery *y, const char *path) {
    pa_bluetooth_adapter *a;

    if (!(a = pa_hashmap_remove(y->adapters, path)))
        pa_log_warn("Unknown adapter removed %s", path);
    else {
        pa_log_debug("Adapter %s removed", path);
        adapter_free(a);
    }
}

1062
static void parse_device_property(pa_bluetooth_device *d, DBusMessageIter *i) {
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    const char *key;
    DBusMessageIter variant_i;

    pa_assert(d);

    key = check_variant_property(i);
    if (key == NULL) {
        pa_log_error("Received invalid property for device %s", d->path);
        return;
    }

    dbus_message_iter_recurse(i, &variant_i);

    switch (dbus_message_iter_get_arg_type(&variant_i)) {

        case DBUS_TYPE_STRING: {
            const char *value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "Alias")) {
                pa_xfree(d->alias);
                d->alias = pa_xstrdup(value);
                pa_log_debug("%s: %s", key, value);
            } else if (pa_streq(key, "Address")) {
1087
                if (d->properties_received) {
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
                    pa_log_warn("Device property 'Address' expected to be constant but changed for %s, ignoring", d->path);
                    return;
                }

                if (d->address) {
                    pa_log_warn("Device %s: Received a duplicate 'Address' property, ignoring", d->path);
                    return;
                }

                d->address = pa_xstrdup(value);
                pa_log_debug("%s: %s", key, value);
            }

            break;
        }

        case DBUS_TYPE_OBJECT_PATH: {
            const char *value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "Adapter")) {

1110
                if (d->properties_received) {
1111 1112 1113 1114
                    pa_log_warn("Device property 'Adapter' expected to be constant but changed for %s, ignoring", d->path);
                    return;
                }

1115
                if (d->adapter_path) {
1116 1117 1118 1119
                    pa_log_warn("Device %s: Received a duplicate 'Adapter' property, ignoring", d->path);
                    return;
                }

1120
                d->adapter_path = pa_xstrdup(value);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
                pa_log_debug("%s: %s", key, value);
            }

            break;
        }

        case DBUS_TYPE_UINT32: {
            uint32_t value;
            dbus_message_iter_get_basic(&variant_i, &value);

            if (pa_streq(key, "Class")) {
                d->class_of_device = value;
                pa_log_debug("%s: %d", key, value);
            }

            break;
        }

        case DBUS_TYPE_ARRAY: {
            DBusMessageIter ai;
            dbus_message_iter_recurse(&variant_i, &ai);

            if (dbus_message_iter_get_arg_type(&ai) == DBUS_TYPE_STRING && pa_streq(key, "UUIDs")) {
1144 1145
                /* bluetoothd never removes UUIDs from a device object so we
                 * don't need to check for disappeared UUIDs here. */
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
                while (dbus_message_iter_get_arg_type(&ai) != DBUS_TYPE_INVALID) {
                    const char *value;
                    char *uuid;

                    dbus_message_iter_get_basic(&ai, &value);

                    if (pa_hashmap_get(d->uuids, value)) {
                        dbus_message_iter_next(&ai);
                        continue;
                    }

                    uuid = pa_xstrdup(value);
                    pa_hashmap_put(d->uuids, uuid, uuid);

                    pa_log_debug("%s: %s", key, value);
                    dbus_message_iter_next(&ai);
                }
            }

            break;
        }
    }
}

1170
static void parse_device_properties(pa_bluetooth_device *d, DBusMessageIter *i) {
1171 1172 1173 1174 1175 1176 1177 1178
    DBusMessageIter element_i;

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i;

        dbus_message_iter_recurse(&element_i, &dict_i);
1179
        parse_device_property(d, &dict_i);
1180 1181 1182
        dbus_message_iter_next(&element_i);
    }

1183 1184
    if (!d->properties_received) {
        d->properties_received = true;
1185
        device_update_valid(d);
1186

1187 1188 1189
        if (!d->address || !d->adapter_path || !d->alias)
            pa_log_error("Non-optional information missing for device %s", d->path);
    }
1190 1191
}

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
static void parse_remote_endpoint_properties(pa_bluetooth_discovery *y, const char *endpoint, DBusMessageIter *i) {
    DBusMessageIter element_i;
    pa_bluetooth_device *device;
    pa_hashmap *codec_endpoints;
    pa_hashmap *endpoints;
    pa_a2dp_codec_id *a2dp_codec_id;
    struct a2dp_codec_capabilities *a2dp_codec_capabilities;
    const char *uuid = NULL;
    const char *device_path = NULL;
    uint8_t codec_id = 0;
    bool have_codec_id = false;
    const uint8_t *capabilities = NULL;
    int capabilities_size = 0;

    pa_log_debug("Parsing remote endpoint %s", endpoint);

    dbus_message_iter_recurse(i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter dict_i, variant_i;
        const char *key;

        dbus_message_iter_recurse(&element_i, &dict_i);

        key = check_variant_property(&dict_i);
        if (key == NULL) {
            pa_log_error("Received invalid property for remote endpoint %s", endpoint);
            return;
        }

        dbus_message_iter_recurse(&dict_i, &variant_i);

        if (pa_streq(key, "UUID")) {
            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_STRING) {
                pa_log_warn("Remote endpoint %s property 'UUID' is not string, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &uuid);
        } else if (pa_streq(key, "Codec")) {
            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_BYTE) {
                pa_log_warn("Remote endpoint %s property 'Codec' is not byte, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &codec_id);
            have_codec_id = true;
        } else if (pa_streq(key, "Capabilities")) {
            DBusMessageIter array;

            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_ARRAY) {
                pa_log_warn("Remote endpoint %s property 'Capabilities' is not array, ignoring", endpoint);
                return;
            }

            dbus_message_iter_recurse(&variant_i, &array);
            if (dbus_message_iter_get_arg_type(&array) != DBUS_TYPE_BYTE) {
                pa_log_warn("Remote endpoint %s property 'Capabilities' is not array of bytes, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_fixed_array(&array, &capabilities, &capabilities_size);
        } else if (pa_streq(key, "Device")) {
            if (dbus_message_iter_get_arg_type(&variant_i) != DBUS_TYPE_OBJECT_PATH) {
                pa_log_warn("Remote endpoint %s property 'Device' is not path, ignoring", endpoint);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &device_path);
        }

        dbus_message_iter_next(&element_i);
    }

    if (!uuid) {
        pa_log_warn("Remote endpoint %s does not have property 'UUID', ignoring", endpoint);
        return;
    }

    if (!have_codec_id) {
        pa_log_warn("Remote endpoint %s does not have property 'Codec', ignoring", endpoint);
        return;
    }

    if (!capabilities || !capabilities_size) {
        pa_log_warn("Remote endpoint %s does not have property 'Capabilities', ignoring", endpoint);
        return;
    }

    if (!device_path) {
        pa_log_warn("Remote endpoint %s does not have property 'Device', ignoring", endpoint);
        return;
    }

    device = pa_hashmap_get(y->devices, device_path);
    if (!device) {
        pa_log_warn("Device for remote endpoint %s was not found", endpoint);
        return;
    }

    if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SINK)) {
        codec_endpoints = device->a2dp_sink_endpoints;
    } else if (pa_streq(uuid, PA_BLUETOOTH_UUID_A2DP_SOURCE)) {
        codec_endpoints = device->a2dp_source_endpoints;
    } else {
        pa_log_warn("Remote endpoint %s does not have valid property 'UUID', ignoring", endpoint);
        return;
    }

    if (capabilities_size < 0 || capabilities_size > MAX_A2DP_CAPS_SIZE) {
        pa_log_warn("Remote endpoint %s does not have valid property 'Capabilities', ignoring", endpoint);
        return;
    }

    a2dp_codec_id = pa_xmalloc0(sizeof(*a2dp_codec_id));
    a2dp_codec_id->codec_id = codec_id;
    if (codec_id == A2DP_CODEC_VENDOR) {
        if ((size_t)capabilities_size < sizeof(a2dp_vendor_codec_t)) {
            pa_log_warn("Remote endpoint %s does not have valid property 'Capabilities', ignoring", endpoint);
            return;
        }
        a2dp_codec_id->vendor_id = A2DP_GET_VENDOR_ID(*(a2dp_vendor_codec_t *)capabilities);
        a2dp_codec_id->vendor_codec_id = A2DP_GET_CODEC_ID(*(a2dp_vendor_codec_t *)capabilities);
    } else {
        a2dp_codec_id->vendor_id = 0;
        a2dp_codec_id->vendor_codec_id = 0;
    }

    a2dp_codec_capabilities = pa_xmalloc0(sizeof(*a2dp_codec_capabilities) + capabilities_size);
    a2dp_codec_capabilities->size = capabilities_size;
    memcpy(a2dp_codec_capabilities->buffer, capabilities, capabilities_size);

    endpoints = pa_hashmap_get(codec_endpoints, a2dp_codec_id);
    if (!endpoints) {
        endpoints = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, pa_xfree, pa_xfree);
        pa_hashmap_put(codec_endpoints, a2dp_codec_id, endpoints);
    }

    if (pa_hashmap_remove_and_free(endpoints, endpoint) >= 0)
        pa_log_debug("Replacing existing remote endpoint %s", endpoint);
    pa_hashmap_put(endpoints, pa_xstrdup(endpoint), a2dp_codec_capabilities);
}