bluez5-util.c 89.6 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 <pulse/rtclock.h>
#include <pulse/timeval.h>
27
28
29
#include <pulse/xmalloc.h>

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

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

40
41
#include "bluez5-util.h"

42
43
#define WAIT_FOR_PROFILES_TIMEOUT_USEC (3 * PA_USEC_PER_SEC)

44
#define BLUEZ_SERVICE "org.bluez"
45
46
#define BLUEZ_ADAPTER_INTERFACE BLUEZ_SERVICE ".Adapter1"
#define BLUEZ_DEVICE_INTERFACE BLUEZ_SERVICE ".Device1"
47
#define BLUEZ_MEDIA_INTERFACE BLUEZ_SERVICE ".Media1"
48
#define BLUEZ_MEDIA_ENDPOINT_INTERFACE BLUEZ_SERVICE ".MediaEndpoint1"
49
#define BLUEZ_MEDIA_TRANSPORT_INTERFACE BLUEZ_SERVICE ".MediaTransport1"
50

51
52
#define BLUEZ_ERROR_NOT_SUPPORTED "org.bluez.Error.NotSupported"

53
54
55
#define A2DP_OBJECT_MANAGER_PATH "/A2DPEndpoint"
#define A2DP_SOURCE_ENDPOINT A2DP_OBJECT_MANAGER_PATH "/Source"
#define A2DP_SINK_ENDPOINT A2DP_OBJECT_MANAGER_PATH "/Sink"
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

#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"
81
82
83

#define ENDPOINT_INTROSPECT_XML                                         \
    DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                           \
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    "<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"
106

107
108
109
110
struct pa_bluetooth_discovery {
    PA_REFCNT_DECLARE;

    pa_core *core;
111
112
113
    pa_dbus_connection *connection;
    bool filter_added;
    bool matches_added;
114
    bool objects_listed;
115
    pa_hook hooks[PA_BLUETOOTH_HOOK_MAX];
116
    pa_hashmap *adapters;
117
    pa_hashmap *devices;
118
    pa_hashmap *transports;
119

120
    int headset_backend;
121
    pa_bluetooth_backend *hsphfpd_backend;
122
    pa_bluetooth_backend *legacy_hsp_backend;
123
    PA_LLIST_HEAD(pa_dbus_pending, pending);
124
125
};

126
127
128
129
130
struct a2dp_codec_capabilities {
    uint8_t size;
    uint8_t buffer[]; /* max size is 254 bytes */
};

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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;
}

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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;
}

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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";
}

205
static bool device_supports_profile(pa_bluetooth_device *device, pa_bluetooth_profile_t profile) {
206
207
208
209
210
211
    const struct a2dp_codec_capabilities *a2dp_codec_capabilities;
    const pa_a2dp_codec *a2dp_codec;
    bool is_a2dp_sink;
    pa_hashmap *endpoints;
    void *state;

212
    switch (profile) {
213
        case PA_BLUETOOTH_PROFILE_HSP_HEAD_UNIT:
214
            return !!pa_hashmap_get(device->uuids, PA_BLUETOOTH_UUID_HSP_HS)
215
216
217
218
219
220
221
                || !!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);
222
        case PA_BLUETOOTH_PROFILE_OFF:
223
224
225
            return true;
        default:
            break;
226
227
    }

228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    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;
250
251
252
253
254
255
256
257
258
259
260
}

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;
}

static unsigned device_count_disconnected_profiles(pa_bluetooth_device *device) {
    pa_bluetooth_profile_t profile;
261
    unsigned bluetooth_profile_count;
262
263
    unsigned count = 0;

264
265
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (profile = 0; profile < bluetooth_profile_count; profile++) {
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        if (!device_supports_profile(device, profile))
            continue;

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

    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;
288
    unsigned bluetooth_profile_count;
289
290
291
292
293
294
295
    bool first = true;
    char *profiles_str;

    device_stop_waiting_for_profiles(device);

    buf = pa_strbuf_new();

296
297
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (profile = 0; profile < bluetooth_profile_count; profile++) {
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        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);
}

326
void pa_bluetooth_transport_set_state(pa_bluetooth_transport *t, pa_bluetooth_transport_state_t state) {
327
    bool old_any_connected;
328
329
330
    unsigned n_disconnected_profiles;
    bool new_device_appeared;
    bool device_disconnected;
331
332
333
334
335
336
337
338

    pa_assert(t);

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

    old_any_connected = pa_bluetooth_device_any_transport_connected(t->device);

339
    pa_log_debug("Transport %s state: %s -> %s",
340
341
342
343
344
345
                 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);

346
347
348
349
350
351
352
    /* 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. */
353

354
    n_disconnected_profiles = device_count_disconnected_profiles(t->device);
355

356
357
    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);
358

359
360
    if (new_device_appeared) {
        if (n_disconnected_profiles > 0)
361
362
363
            device_start_waiting_for_profiles(t->device);
        else
            pa_hook_fire(&t->device->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_CONNECTION_CHANGED], t->device);
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        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;
    }

    if (n_disconnected_profiles == 0 && t->device->wait_for_profiles_timer) {
        /* 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);
384
    }
385
386
}

387
388
389
390
391
pa_bluetooth_transport *pa_bluetooth_transport_get(pa_bluetooth_discovery *y, const char *path) {
    pa_assert(path);
    return pa_hashmap_get(y->transports, path);
}

392
393
394
395
pa_hashmap *pa_bluetooth_transport_get_all(pa_bluetooth_discovery *y) {
    return y->transports;
}

396
void pa_bluetooth_transport_put(pa_bluetooth_transport *t) {
397
398
399
400
    pa_assert(t);

    t->device->transports[t->profile] = t;
    pa_assert_se(pa_hashmap_put(t->device->discovery->transports, t->path, t) >= 0);
401
    pa_bluetooth_transport_set_state(t, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
402
403
404
405
406
}

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

407
408
    if (t->destroy)
        t->destroy(t);
409
410
411
412

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

414
415
416
417
418
419
    pa_xfree(t->owner);
    pa_xfree(t->path);
    pa_xfree(t->config);
    pa_xfree(t);
}

420
static int bluez5_transport_acquire_cb(pa_bluetooth_transport *t, size_t *imtu, size_t *omtu) {
421
422
423
424
425
426
427
428
429
    DBusMessage *m, *r;
    DBusError err;
    int ret;
    uint16_t i, o;

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

430
    pa_assert_se(m = dbus_message_new_method_call(t->owner, t->path, BLUEZ_MEDIA_TRANSPORT_INTERFACE, "Acquire"));
431
432
433
434

    dbus_error_init(&err);

    r = dbus_connection_send_with_reply_and_block(pa_dbus_connection_get(t->device->discovery->connection), m, -1, &err);
Tanu Kaskinen's avatar
Tanu Kaskinen committed
435
436
    dbus_message_unref(m);
    m = NULL;
437
    if (!r) {
438
        pa_log_error("Transport Acquire() failed for transport %s (%s)", t->path, err.message);
439
440
441
442
443
444
445

        dbus_error_free(&err);
        return -1;
    }

    if (!dbus_message_get_args(r, &err, DBUS_TYPE_UNIX_FD, &ret, DBUS_TYPE_UINT16, &i, DBUS_TYPE_UINT16, &o,
                               DBUS_TYPE_INVALID)) {
446
        pa_log_error("Failed to parse Acquire() reply: %s", err.message);
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        dbus_error_free(&err);
        ret = -1;
        goto finish;
    }

    if (imtu)
        *imtu = i;

    if (omtu)
        *omtu = o;

finish:
    dbus_message_unref(r);
    return ret;
}

static void bluez5_transport_release_cb(pa_bluetooth_transport *t) {
Tanu Kaskinen's avatar
Tanu Kaskinen committed
464
    DBusMessage *m, *r;
465
466
467
468
469
470
471
472
473
474
475
476
477
478
    DBusError err;

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

    dbus_error_init(&err);

    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"));
Tanu Kaskinen's avatar
Tanu Kaskinen committed
479
480
481
482
483
484
485
    r = dbus_connection_send_with_reply_and_block(pa_dbus_connection_get(t->device->discovery->connection), m, -1, &err);
    dbus_message_unref(m);
    m = NULL;
    if (r) {
        dbus_message_unref(r);
        r = NULL;
    }
486
487
488
489
490
491
492
493
494

    if (dbus_error_is_set(&err)) {
        pa_log_error("Failed to release transport %s: %s", t->path, err.message);
        dbus_error_free(&err);
    } else
        pa_log_info("Transport %s released", t->path);
}

bool pa_bluetooth_device_any_transport_connected(const pa_bluetooth_device *d) {
495
    unsigned i, bluetooth_profile_count;
496
497
498

    pa_assert(d);

499
    if (!d->valid)
500
501
        return false;

502
503
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++)
504
505
506
507
508
509
        if (d->transports[i] && d->transports[i]->state != PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED)
            return true;

    return false;
}

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
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;
                }

549
                pa_bluetooth_transport_set_state(t, state);
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
            }

            break;
        }
    }

    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;
}

577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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;
}

613
614
615
616
617
618
619
620
621
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);
622
    d->uuids = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, pa_xfree);
623
624
625
    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());
626
627
628
629
630
631
632
633
634
635
636
637
638

    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);

639
640
    if ((d = pa_hashmap_get(y->devices, path)) && d->valid)
        return d;
641
642
643
644
645
646
647
648
649
650
651
652
653
654

    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)))
655
        if (d->valid && pa_streq(d->address, remote) && pa_streq(d->adapter->address, local))
656
            return d;
657
658
659
660

    return NULL;
}

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
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);
}

678
static void device_free(pa_bluetooth_device *d) {
679
    unsigned i, bluetooth_profile_count;
680

681
682
    pa_assert(d);

683
684
    device_stop_waiting_for_profiles(d);

685
686
    pa_hook_fire(&d->discovery->hooks[PA_BLUETOOTH_HOOK_DEVICE_UNLINK], d);

687
688
    bluetooth_profile_count = pa_bluetooth_profile_count();
    for (i = 0; i < bluetooth_profile_count; i++) {
689
690
691
692
693
694
695
696
        pa_bluetooth_transport *t;

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

        pa_bluetooth_transport_free(t);
    }

697
698
699
    pa_hashmap_free(d->uuids);
    pa_hashmap_free(d->a2dp_sink_endpoints);
    pa_hashmap_free(d->a2dp_source_endpoints);
700

701
    pa_xfree(d->transports);
702
703
704
    pa_xfree(d->path);
    pa_xfree(d->alias);
    pa_xfree(d->address);
705
    pa_xfree(d->adapter_path);
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    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);
    }
}

720
static void device_set_valid(pa_bluetooth_device *device, bool valid) {
721
722
    bool old_any_connected;

723
724
    pa_assert(device);

725
    if (valid == device->valid)
726
727
        return;

728
    old_any_connected = pa_bluetooth_device_any_transport_connected(device);
729
    device->valid = valid;
730
731
732

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

735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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);
}

768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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;
}

783
784
785
786
787
788
789
790
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)
791
792
        if (d->adapter == a)
            device_set_adapter(d, NULL);
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809

    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);
    }
}

810
static void parse_device_property(pa_bluetooth_device *d, DBusMessageIter *i) {
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
    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")) {
835
                if (d->properties_received) {
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
                    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")) {

858
                if (d->properties_received) {
859
860
861
862
                    pa_log_warn("Device property 'Adapter' expected to be constant but changed for %s, ignoring", d->path);
                    return;
                }

863
                if (d->adapter_path) {
864
865
866
867
                    pa_log_warn("Device %s: Received a duplicate 'Adapter' property, ignoring", d->path);
                    return;
                }

868
                d->adapter_path = pa_xstrdup(value);
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
                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")) {
892
893
                /* bluetoothd never removes UUIDs from a device object so we
                 * don't need to check for disappeared UUIDs here. */
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
                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;
        }
    }
}

918
static void parse_device_properties(pa_bluetooth_device *d, DBusMessageIter *i) {
919
920
921
922
923
924
925
926
    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);
927
        parse_device_property(d, &dict_i);
928
929
930
        dbus_message_iter_next(&element_i);
    }

931
932
    if (!d->properties_received) {
        d->properties_received = true;
933
        device_update_valid(d);
934

935
936
937
        if (!d->address || !d->adapter_path || !d->alias)
            pa_log_error("Non-optional information missing for device %s", d->path);
    }
938
939
}

940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
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);
}

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
static void parse_adapter_properties(pa_bluetooth_adapter *a, DBusMessageIter *i, bool is_property_change) {
    DBusMessageIter element_i;

    pa_assert(a);

    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 adapter %s", a->path);
            return;
        }

        dbus_message_iter_recurse(&dict_i, &variant_i);

        if (dbus_message_iter_get_arg_type(&variant_i) == DBUS_TYPE_STRING && pa_streq(key, "Address")) {
1105
            const char *value;
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118

            if (is_property_change) {
                pa_log_warn("Adapter property 'Address' expected to be constant but changed for %s, ignoring", a->path);
                return;
            }

            if (a->address) {
                pa_log_warn("Adapter %s received a duplicate 'Address' property, ignoring", a->path);
                return;
            }

            dbus_message_iter_get_basic(&variant_i, &value);
            a->address = pa_xstrdup(value);
1119
            a->valid = true;
1120
1121
1122
1123
1124
1125
        }

        dbus_message_iter_next(&element_i);
    }
}

1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
static void register_endpoint_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    char *endpoint;

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

    if (dbus_message_is_error(r, BLUEZ_ERROR_NOT_SUPPORTED)) {
        pa_log_info("Couldn't register endpoint %s because it is disabled in BlueZ", endpoint);
        goto finish;
    }

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_error(BLUEZ_MEDIA_INTERFACE ".RegisterEndpoint() failed: %s: %s", dbus_message_get_error_name(r),
                     pa_dbus_get_error_message(r));
        goto finish;
    }

finish:
    dbus_message_unref(r);

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

    pa_xfree(endpoint);
}

pali's avatar
pali committed
1158
static void register_endpoint(pa_bluetooth_discovery *y, const pa_a2dp_codec *a2dp_codec, const char *path, const char *endpoint, const char *uuid) {
1159
1160
    DBusMessage *m;
    DBusMessageIter i, d;
pali's avatar
pali committed
1161
1162
1163
    uint8_t capabilities[MAX_A2DP_CAPS_SIZE];
    size_t capabilities_size;
    uint8_t codec_id;
1164
1165
1166

    pa_log_debug("Registering %s on adapter %s", endpoint, path);

pali's avatar
pali committed
1167
1168
1169
1170
    codec_id = a2dp_codec->id.codec_id;
    capabilities_size = a2dp_codec->fill_capabilities(capabilities);
    pa_assert(capabilities_size != 0);

1171
1172
1173
    pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, path, BLUEZ_MEDIA_INTERFACE, "RegisterEndpoint"));

    dbus_message_iter_init_append(m, &i);
1174
    pa_assert_se(dbus_message_iter_append_basic(&i, DBUS_TYPE_OBJECT_PATH, &endpoint));
1175
1176
1177
    dbus_message_iter_open_container(&i, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
                                         DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &d);
    pa_dbus_append_basic_variant_dict_entry(&d, "UUID", DBUS_TYPE_STRING, &uuid);
pali's avatar
pali committed
1178
1179
    pa_dbus_append_basic_variant_dict_entry(&d, "Codec", DBUS_TYPE_BYTE, &codec_id);
    pa_dbus_append_basic_array_variant_dict_entry(&d, "Capabilities", DBUS_TYPE_BYTE, &capabilities, capabilities_size);
1180
1181
1182
1183
1184
1185

    dbus_message_iter_close_container(&i, &d);

    send_and_add_to_pending(y, m, register_endpoint_reply, pa_xstrdup(endpoint));
}

1186
1187
1188
1189
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
static void register_application_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_adapter *a;
    pa_bluetooth_discovery *y;
    char *path;
    bool fallback = true;

    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));

    if (dbus_message_is_error(r, BLUEZ_ERROR_NOT_SUPPORTED)) {
        pa_log_info("Couldn't register media application for adapter %s because it is disabled in BlueZ", path);
        goto finish;
    }

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_warn(BLUEZ_MEDIA_INTERFACE ".RegisterApplication() failed: %s: %s", dbus_message_get_error_name(r),
                     pa_dbus_get_error_message(r));
        pa_log_warn("Couldn't register media application for adapter %s because of probably old BlueZ version which does not support additional A2DP codecs", path);
        goto finish;
    }

    a = pa_hashmap_get(y->adapters, path);
    if (!a) {
        pa_log_error("Couldn't register media application for adapter %s because it does not exist anymore", path);
        goto finish;
    }

    fallback = false;
    a->media_application_registered = true;
    pa_log_debug("Media application for adapter %s was successfully registered", path);

finish:
    dbus_message_unref(r);

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

    if (fallback) {
        /* If bluez does not support RegisterApplication, fallback to old API with just one SBC codec */
        const pa_a2dp_codec *a2dp_codec_sbc = pa_bluetooth_get_a2dp_codec("sbc");
        pa_assert(a2dp_codec_sbc);
        register_endpoint(y, a2dp_codec_sbc, path, A2DP_SINK_ENDPOINT "/sbc", PA_BLUETOOTH_UUID_A2DP_SINK);
        register_endpoint(y, a2dp_codec_sbc, path, A2DP_SOURCE_ENDPOINT "/sbc", PA_BLUETOOTH_UUID_A2DP_SOURCE);
        pa_log_warn("Only SBC codec is available for A2DP profiles");
    }

    pa_xfree(path);
}

static void register_application(pa_bluetooth_adapter *a) {
    DBusMessage *m;
    DBusMessageIter i, d;
    const char *object_manager_path = A2DP_OBJECT_MANAGER_PATH;

    pa_log_debug("Registering media application for adapter %s", a->path);

    pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, a->path, BLUEZ_MEDIA_INTERFACE, "RegisterApplication"));

    dbus_message_iter_init_append(m, &i);
    pa_assert_se(dbus_message_iter_append_basic(&i, DBUS_TYPE_OBJECT_PATH, &object_manager_path));
    dbus_message_iter_open_container(&i, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &d);
    dbus_message_iter_close_container(&i, &d);

    send_and_add_to_pending(a->discovery, m, register_application_reply, pa_xstrdup(a->path));
}

1257
1258
1259
static void parse_interfaces_and_properties(pa_bluetooth_discovery *y, DBusMessageIter *dict_i) {
    DBusMessageIter element_i;
    const char *path;
1260
    void *state;
1261
    pa_bluetooth_device *d;
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283

    pa_assert(dbus_message_iter_get_arg_type(dict_i) == DBUS_TYPE_OBJECT_PATH);
    dbus_message_iter_get_basic(dict_i, &path);

    pa_assert_se(dbus_message_iter_next(dict_i));
    pa_assert(dbus_message_iter_get_arg_type(dict_i) == DBUS_TYPE_ARRAY);

    dbus_message_iter_recurse(dict_i, &element_i);

    while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_DICT_ENTRY) {
        DBusMessageIter iface_i;
        const char *interface;

        dbus_message_iter_recurse(&element_i, &iface_i);

        pa_assert(dbus_message_iter_get_arg_type(&iface_i) == DBUS_TYPE_STRING);
        dbus_message_iter_get_basic(&iface_i, &interface);

        pa_assert_se(dbus_message_iter_next(&iface_i));
        pa_assert(dbus_message_iter_get_arg_type(&iface_i) == DBUS_TYPE_ARRAY);

        if (pa_streq(interface, BLUEZ_ADAPTER_INTERFACE)) {
1284

1285
1286
1287
            pa_bluetooth_adapter *a;

            if ((a = pa_hashmap_get(y->adapters, path))) {
1288
                pa_log_error("Found duplicated D-Bus path for adapter %s", path);
1289
1290
1291
1292
1293
1294
                return;
            } else
                a = adapter_create(y, path);

            pa_log_debug("Adapter %s found", path);

1295
            parse_adapter_properties(a, &iface_i, false);
1296

1297
            if (!a->valid)
1298
1299
                return;

1300
            register_application(a);
1301
1302
1303
1304

        } else if (pa_streq(interface, BLUEZ_DEVICE_INTERFACE)) {

            if ((d = pa_hashmap_get(y->devices, path))) {
1305
                if (d->properties_received) {
1306
1307
1308
1309
1310
1311
1312
1313
                    pa_log_error("Found duplicated D-Bus path for device %s", path);
                    return;
                }
            } else
                d = device_create(y, path);

            pa_log_debug("Device %s found", d->path);

1314
            parse_device_properties(d, &iface_i);
1315

1316
1317
1318
        } else if (pa_streq(interface, BLUEZ_MEDIA_ENDPOINT_INTERFACE))
            parse_remote_endpoint_properties(y, path, &iface_i);
        else
1319
1320
1321
1322
1323
            pa_log_debug("Unknown interface %s found, skipping", interface);

        dbus_message_iter_next(&element_i);
    }

1324
    PA_HASHMAP_FOREACH(d, y->devices, state) {
1325
1326
1327
        if (d->properties_received && !d->tried_to_link_with_adapter) {
            if (d->adapter_path) {
                device_set_adapter(d, pa_hashmap_get(d->discovery->adapters, d->adapter_path));
1328

1329
1330
1331
1332
1333
1334
1335
                if (!d->adapter)
                    pa_log("Device %s points to a nonexistent adapter %s.", d->path, d->adapter_path);
                else if (!d->adapter->valid)
                    pa_log("Device %s points to an invalid adapter %s.", d->path, d->adapter_path);
            }

            d->tried_to_link_with_adapter = true;
1336
        }
1337
    }
1338

1339
1340
1341
    return;
}

1342
1343
1344
1345
1346
1347
1348
/* This function may be called only by hsphfpd backend.
   Legacy HSP backend may be enabled only when hsphfpd daemon is not running. */
void pa_bluetooth_discovery_legacy_hsp_backend_enable(pa_bluetooth_discovery *y, bool enable) {
    if (y->legacy_hsp_backend)
        pa_bluetooth_legacy_hsp_backend_enable(y->legacy_hsp_backend, enable);
}

1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
static void get_managed_objects_reply(DBusPendingCall *pending, void *userdata) {
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    DBusMessage *r;
    DBusMessageIter arg_i, element_i;

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

    if (dbus_message_is_error(r, DBUS_ERROR_UNKNOWN_METHOD)) {
        pa_log_warn("BlueZ D-Bus ObjectManager not available");
        goto finish;
    }

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_error("GetManagedObjects() failed: %s: %s", dbus_message_get_error_name(r), pa_dbus_get_error_message(r));
        goto finish;
    }

    if (!dbus_message_iter_init(r, &arg_i) || !pa_streq(dbus_message_get_signature(r), "a{oa{sa{sv}}}")) {
        pa_log_error("Invalid reply signature for GetManagedObjects()");
        goto finish;
    }

    dbus_message_iter_recurse(&arg_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);

1380
        parse_interfaces_and_properties(y, &dict_i);
1381
1382
1383
1384
1385
1386

        dbus_message_iter_next(&element_i);
    }

    y->objects_listed = true;

1387
1388
    if (!y->legacy_hsp_backend && (y->headset_backend == HEADSET_BACKEND_AUTO || y->headset_backend == HEADSET_BACKEND_LEGACY_HSP))
        y->legacy_hsp_backend = pa_bluetooth_legacy_hsp_backend_new(y->core, y, (y->headset_backend == HEADSET_BACKEND_LEGACY_HSP));
1389

1390
1391
1392
    if (!y->hsphfpd_backend && (y->headset_backend == HEADSET_BACKEND_AUTO || y->headset_backend == HEADSET_BACKEND_HSPHFPD))
        y->hsphfpd_backend = pa_bluetooth_hsphfpd_backend_new(y->core, y);

1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
finish:
    dbus_message_unref(r);

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

static void get_managed_objects(pa_bluetooth_discovery *y) {
    DBusMessage *m;

    pa_assert(y);

    pa_assert_se(m = dbus_message_new_method_call(BLUEZ_SERVICE, "/", "org.freedesktop.DBus.ObjectManager",
                                                  "GetManagedObjects"));
    send_and_add_to_pending(y, m, get_managed_objects_reply, NULL);
}

1410
1411
1412
1413
1414
1415
1416
pa_hook* pa_bluetooth_discovery_hook(pa_bluetooth_discovery *y, pa_bluetooth_hook_t hook) {
    pa_assert(y);
    pa_assert(PA_REFCNT_VALUE(y) > 0);

    return &y->hooks[hook];
}

1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *userdata) {
    pa_bluetooth_discovery *y;
    DBusError err;

    pa_assert(bus);
    pa_assert(m);
    pa_assert_se(y = userdata);

    dbus_error_init(&err);

    if (dbus_message_is_signal(m, "org.freedesktop.DBus", "NameOwnerChanged")) {
        const char *name, *old_owner, *new_owner;

        if (!dbus_message_get_args(m, &err,
                                   DBUS_TYPE_STRING, &name,
                                   DBUS_TYPE_STRING, &old_owner,
                                   DBUS_TYPE_STRING, &new_owner,
                                   DBUS_TYPE_INVALID)) {
            pa_log_error("Failed to parse org.freedesktop.DBus.NameOwnerChanged: %s", err.message);
            goto fail;
        }

        if (pa_streq(name, BLUEZ_SERVICE)) {
            if (old_owner && *old_owner) {
                pa_log_debug("Bluetooth daemon disappeared");
1442
                pa_hashmap_remove_all(y->devices);
1443
                pa_hashmap_remove_all(y->adapters);
1444
                y->objects_listed = false;
1445
1446
1447
1448
                if (y->hsphfpd_backend) {
                    pa_bluetooth_hsphfpd_backend_free(y->hsphfpd_backend);
                    y->hsphfpd_backend = NULL;
                }
1449
1450
1451
                if (y->legacy_hsp_backend) {
                    pa_bluetooth_legacy_hsp_backend_free(y->legacy_hsp_backend);
                    y->legacy_hsp_backend = NULL;
1452
                }
1453
1454
1455
1456
            }

            if (new_owner && *new_owner) {
                pa_log_debug("Bluetooth daemon appeared");
1457
                get_managed_objects(y);
1458
1459
1460
1461
            }
        }

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
    } else if (dbus_message_is_signal(m, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded")) {
        DBusMessageIter arg_i;

        if (!y->objects_listed)
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; /* No reply received yet from GetManagedObjects */

        if (!dbus_message_iter_init(m, &arg_i) || !pa_streq(dbus_message_get_signature(m), "oa{sa{sv}}")) {
            pa_log_error("Invalid signature found in InterfacesAdded");
            goto fail;
        }

1473
        parse_interfaces_and_properties(y, &arg_i);
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    } else if (dbus_message_is_signal(m, "org.freedesktop.DBus.ObjectManager", "InterfacesRemoved")) {
        const char *p;
        DBusMessageIter arg_i;
        DBusMessageIter element_i;

        if (!y->objects_listed)
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; /* No reply received yet from GetManagedObjects */

        if (!dbus_message_iter_init(m, &arg_i) || !pa_streq(dbus_message_get_signature(m), "oas")) {
            pa_log_error("Invalid signature found in InterfacesRemoved");
            goto fail;
        }

        dbus_message_iter_get_basic(&arg_i, &p);

        pa_assert_se(dbus_message_iter_next(&arg_i));
        pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_ARRAY);

        dbus_message_iter_recurse(&arg_i, &element_i);

        while (dbus_message_iter_get_arg_type(&element_i) == DBUS_TYPE_STRING) {
            const char *iface;

            dbus_message_iter_get_basic(&element_i, &iface);

            if (pa_streq(iface, BLUEZ_DEVICE_INTERFACE))
                device_remove(y, p);
1503
1504
            else if (pa_streq(iface, BLUEZ_MEDIA_ENDPOINT_INTERFACE))
                remote_endpoint_remove(y, p);
1505
1506
1507
1508
1509
1510
1511
1512
            else if (pa_streq(iface, BLUEZ_ADAPTER_INTERFACE))
                adapter_remove(y, p);

            dbus_message_iter_next(&element_i);
        }

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
    } else if (dbus_message_is_signal(m, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
        DBusMessageIter arg_i;
        const char *iface;

        if (!y->objects_listed)
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; /* No reply received yet from GetManagedObjects */

        if (!dbus_message_iter_init(m, &arg_i) || !pa_streq(dbus_message_get_signature(m), "sa{sv}as")) {
            pa_log_error("Invalid signature found in PropertiesChanged");
            goto fail;
        }

        dbus_message_iter_get_basic(&arg_i, &iface);

        pa_assert_se(dbus_message_iter_next(&arg_i));
        pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_ARRAY);

        if (pa_streq(iface, BLUEZ_ADAPTER_INTERFACE)) {
            pa_bluetooth_adapter *a;

            pa_log_debug("Properties changed in adapter %s", dbus_message_get_path(m));

            if (!(a = pa_hashmap_get(y->adapters, dbus_message_get_path(m)))) {
                pa_log_warn("Properties changed in unknown adapter");
                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
            }

            parse_adapter_properties(a, &arg_i, true);
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551

        } else if (pa_streq(iface, BLUEZ_DEVICE_INTERFACE)) {
            pa_bluetooth_device *d;

            pa_log_debug("Properties changed in device %s", dbus_message_get_path(m));

            if (!(d = pa_hashmap_get(y->devices, dbus_message_get_path(m)))) {
                pa_log_warn("Properties changed in unknown device");
                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
            }

1552
            if (!d->properties_received)
1553
1554
                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

1555
            parse_device_properties(d, &arg_i);
1556
1557
1558
1559
        } else if (pa_streq(iface, BLUEZ_MEDIA_ENDPOINT_INTERFACE)) {
            pa_log_info("Properties changed in remote endpoint %s", dbus_message_get_path(m));

            parse_remote_endpoint_properties(y, dbus_message_get_path(m), &arg_i);
1560
1561
1562
1563
1564
1565
1566
1567
1568
        } else if (pa_streq(iface, BLUEZ_MEDIA_TRANSPORT_INTERFACE)) {
            pa_bluetooth_transport *t;

            pa_log_debug("Properties changed in transport %s", dbus_message_get_path(m));

            if (!(t = pa_hashmap_get(y->transports, dbus_message_get_path(m))))
                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

            parse_transport_properties(t, &arg_i);
1569
1570
1571
        }

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1572
1573
1574
1575
1576
1577
1578
1579
    }

fail:
    dbus_error_free(&err);

    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
/* A2DP bluez endpoint name ends with /sep<num_id> string */
static int a2dp_endpoint_to_id(const char *endpoint) {
    int end = strlen(endpoint)-1;
    int pos = end;

    while (pos >= 0 && endpoint[pos] >= '0' && endpoint[pos] <= '9')
        pos--;

    if (pos == end)
        return -1;

    if (pos < 3 || memcmp(endpoint+pos-3, "/sep", 4) != 0)
        return -1;

    return atoi(endpoint+pos+1);
}

struct cmp_arg {
    const pa_a2dp_codec *a2dp_codec;
    const pa_hashmap *capabilities_hashmap;
    const pa_sample_spec *default_sample_spec;
    bool for_encoding;
};

static int cmp_endpoints(const void *p1, const void *p2, void *arg) {
    const char *endpoint1 = *(const char * const *)p1;
    const char *endpoint2 = *(const char * const *)p2;
    const struct cmp_arg *cmp_arg = (struct cmp_arg *)arg;
    const struct a2dp_codec_capabilities *capabilities1;
    const struct a2dp_codec_capabilities *capabilities2;
    int cmp, id1, id2;

    pa_assert_se(capabilities1 = pa_hashmap_get(cmp_arg->capabilities_hashmap, endpoint1));
    pa_assert_se(capabilities2 = pa_hashmap_get(cmp_arg->capabilities_hashmap, endpoint2));

    cmp = cmp_arg->a2dp_codec->cmp_endpoints(capabilities1->buffer, capabilities1->size, capabilities2->buffer, capabilities2->size, cmp_arg->default_sample_spec, cmp_arg->for_encoding);
    if (cmp != 0)
        return cmp;

    /* Prefer endpoint with smaller SEP id (endpoint which should be tried first) */
    id1 = a2dp_endpoint_to_id(endpoint1);
    id2 = a2dp_endpoint_to_id(endpoint2);
    if (id1 < id2)
        return -1;
    if (id1 > id2)
        return 1;

    return 0;
}

size_t pa_bluetooth_device_find_a2dp_endpoints_for_codec(const pa_bluetooth_device *device, const pa_a2dp_codec *a2dp_codec, bool is_a2dp_sink, const char **endpoints, size_t endpoints_max_count) {
    pa_hashmap *capabilities_hashmap;
    const struct a2dp_codec_capabilities *a2dp_capabilities;
    const char *key;
    void *state;
    size_t count;

    capabilities_hashmap = pa_hashmap_get(is_a2dp_sink ? device->a2dp_sink_endpoints : device->a2dp_source_endpoints, &a2dp_codec->id);
    if (!capabilities_hashmap)
        return 0;

    count = 0;
    /* Filter endpoints which are not compatible */
    PA_HASHMAP_FOREACH_KV(key, a2dp_capabilities, capabilities_hashmap, state) {
        if (!a2dp_codec->can_accept_capabilities(a2dp_capabilities->buffer, a2dp_capabilities->size, is_a2dp_sink))
            continue;
        if (count < endpoints_max_count)
            endpoints[count] = key;
        count++;
    }

    /* Change order of capabilities according to preference */
    qsort_r(&endpoints, (count <= endpoints_max_count) ? count : endpoints_max_count, sizeof(const char *), cmp_endpoints, &(struct cmp_arg){ a2dp_codec, capabilities_hashmap, &device->discovery->core->default_sample_spec, is_a2dp_sink });

    return count;
}

struct change_a2dp_profile_data {
    char *pa_endpoint;
    pa_bluetooth_device *device;
    pa_bluetooth_profile_t profile;
    const char **codec_endpoints;
    size_t codec_endpoints_i;
    size_t codec_endpoints_count;
    void (*cb)(bool, void *);
    void *userdata;
};

static bool change_a2dp_profile_next(pa_bluetooth_device *device, pa_bluetooth_profile_t profile, const char **codec_endpoints, size_t codec_endpoints_i, size_t codec_endpoints_count, bool from_cb, void (*cb)(bool, void *), void *userdata);

static void change_a2dp_profile_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_discovery *y;
    struct change_a2dp_profile_data *data;
    bool success;

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

    success = (dbus_message_get_type(r) != DBUS_MESSAGE_TYPE_ERROR);