hsphfpd.c 56.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/***
  This file is part of PulseAudio.

  Copyright 2020 Pali Rohár <pali.rohar@gmail.com>

  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
  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
***/

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

24
25
#include <errno.h>

26
27
28
29
30
31
32
33
34
35
36
#include <pulsecore/shared.h>
#include <pulsecore/core-error.h>
#include <pulsecore/core-util.h>
#include <pulsecore/dbus-shared.h>
#include <pulsecore/log.h>

#include "bluez5-util.h"

#define HSPHFPD_SERVICE "org.hsphfpd"
#define HSPHFPD_APPLICATION_MANAGER_INTERFACE HSPHFPD_SERVICE ".ApplicationManager"
#define HSPHFPD_ENDPOINT_INTERFACE HSPHFPD_SERVICE ".Endpoint"
37
#define HSPHFPD_AUDIO_TRANSPORT_INTERFACE HSPHFPD_SERVICE ".AudioTransport"
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#define HSPHFPD_AUDIO_AGENT_INTERFACE HSPHFPD_SERVICE ".AudioAgent"

#define APPLICATION_OBJECT_MANAGER_PATH "/SCOEndpoint"
#define AUDIO_AGENT_ENDPOINT_PCM_S16LE_8KHZ APPLICATION_OBJECT_MANAGER_PATH "/PCM_s16le_8kHz"
#define AUDIO_AGENT_ENDPOINT_MSBC APPLICATION_OBJECT_MANAGER_PATH "/mSBC"

#define APPLICATION_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>\n"

#define AUDIO_AGENT_ENDPOINT_INTROSPECT_XML                                    \
    DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                                  \
    "<node>\n"                                                                 \
    " <interface name=\"" HSPHFPD_AUDIO_AGENT_INTERFACE "\">\n"                \
    "  <method name=\"NewConnection\">\n"                                      \
    "   <arg name=\"audio_transport\" direction=\"in\" type=\"o\"/>\n"         \
    "   <arg name=\"sco\" direction=\"in\" type=\"h\"/>\n"                     \
    "   <arg name=\"properties\" direction=\"in\" type=\"a{sv}\"/>\n"          \
    "  </method>\n"                                                            \
    "  <property name=\"AgentCodec\" type=\"s\" access=\"read\"/>\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"                                                          \
    " <interface name=\"org.freedesktop.DBus.Properties\">\n"                  \
    "  <method name=\"Get\">\n"                                                \
    "   <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n"               \
    "   <arg name=\"name\" direction=\"in\" type=\"s\"/>\n"                    \
    "   <arg name=\"value\" direction=\"out\" type=\"v\"/>\n"                  \
    "  </method>\n"                                                            \
    "  <method name=\"GetAll\">\n"                                             \
    "   <arg name=\"interface\" direction=\"in\" type=\"s\"/>\n"               \
    "   <arg name=\"properties\" direction=\"out\" type=\"a{sv}\"/>\n"         \
    "  </method>\n"                                                            \
    " </interface>\n"                                                          \
    "</node>\n"

enum hsphfpd_volume_control {
    HSPHFPD_VOLUME_CONTROL_NONE = 1,
    HSPHFPD_VOLUME_CONTROL_LOCAL,
    HSPHFPD_VOLUME_CONTROL_REMOTE,
};

102
103
104
105
106
enum hsphfpd_profile {
    HSPHFPD_PROFILE_HEADSET = 1,
    HSPHFPD_PROFILE_HANDSFREE,
};

107
108
109
110
111
112
enum hsphfpd_role {
    HSPHFPD_ROLE_CLIENT = 1,
    HSPHFPD_ROLE_GATEWAY,
};

struct hsphfpd_transport_data {
113
114
115
    struct pa_bluetooth_backend *backend;
    int sco_fd;
    char *transport_path;
116
117
118
119
120
121
122
123
124
125
126
127
    char *agent_codec;
    char *air_codec;
    enum hsphfpd_volume_control volume_control;
    uint16_t mtu;
};

struct hsphfpd_endpoint {
    char *path;
    bool valid;
    bool connected;
    char *remote_address;
    char *local_address;
128
    enum hsphfpd_profile profile;
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
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
    enum hsphfpd_role role;
};

struct pa_bluetooth_backend {
    pa_core *core;
    pa_bluetooth_discovery *discovery;
    pa_dbus_connection *connection;
    pa_hashmap *endpoints;
    bool endpoints_listed;
    char *hsphfpd_service_id;

    PA_LLIST_HEAD(pa_dbus_pending, pending);
};

static void hsphfpd_endpoint_free(struct hsphfpd_endpoint *endpoint) {
    pa_assert(endpoint);

    pa_xfree(endpoint->path);
    pa_xfree(endpoint->remote_address);
    pa_xfree(endpoint->local_address);
    pa_xfree(endpoint);
}

static pa_dbus_pending *send_and_add_to_pending(pa_bluetooth_backend *backend, DBusMessage *m, DBusPendingCallNotifyFunction func, void *call_data) {
    pa_dbus_pending *p;
    DBusPendingCall *call;

    pa_assert(backend);
    pa_assert(m);

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

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

    return p;
}

static void set_dbus_property_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_backend *backend;
    char *error_message;

    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(backend = p->context_data);
    pa_assert_se(error_message = 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("%s: %s: %s", error_message, dbus_message_get_error_name(r), pa_dbus_get_error_message(r));

    pa_xfree(error_message);

    dbus_message_unref(r);

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

static void set_dbus_property(pa_bluetooth_backend *backend, const char *service, const char *path, const char *interface, const char *property, int type, void *value, char *error_message) {
    DBusMessage *m;
    DBusMessageIter iter;
    pa_assert_se(m = dbus_message_new_method_call(service, path, "org.freedesktop.DBus.Properties", "Set"));
    pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID));
    dbus_message_iter_init_append(m, &iter);
    pa_dbus_append_basic_variant(&iter, type, value);
    send_and_add_to_pending(backend, m, set_dbus_property_reply, error_message);
}

201
202
203
204
static inline void set_microphone_gain_property(const struct hsphfpd_transport_data *transport_data, uint16_t gain) {
    if (transport_data->sco_fd < 0 || transport_data->volume_control <= HSPHFPD_VOLUME_CONTROL_NONE)
        return;
    set_dbus_property(transport_data->backend, HSPHFPD_SERVICE, transport_data->transport_path, HSPHFPD_AUDIO_TRANSPORT_INTERFACE, "MicrophoneGain", DBUS_TYPE_UINT16, &gain, pa_sprintf_malloc("Changing microphone gain to %u for transport %s failed", (unsigned)gain, transport_data->transport_path));
205
206
}

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
static inline void set_speaker_gain_property(const struct hsphfpd_transport_data *transport_data, uint16_t gain) {
    if (transport_data->sco_fd < 0 || transport_data->volume_control <= HSPHFPD_VOLUME_CONTROL_NONE)
        return;
    set_dbus_property(transport_data->backend, HSPHFPD_SERVICE, transport_data->transport_path, HSPHFPD_AUDIO_TRANSPORT_INTERFACE, "SpeakerGain", DBUS_TYPE_UINT16, &gain, pa_sprintf_malloc("Changing speaker gain to %u for transport %s failed", (unsigned)gain, transport_data->transport_path));
}

static void hsphfpd_transport_acquire_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    DBusError error;
    pa_dbus_pending *p;
    pa_bluetooth_backend *backend;
    pa_bluetooth_transport *transport;
    const char *error_name;
    char *endpoint_path;
    const char *transport_path;
    const char *service_id;
    const char *agent_path;

    pa_assert(pending);
    pa_assert_se(p = userdata);
    pa_assert_se(backend = p->context_data);
    pa_assert_se(endpoint_path = p->call_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));

    dbus_error_init(&error);

    if (!pa_safe_streq(dbus_message_get_sender(r), backend->hsphfpd_service_id)) {
        pa_log_error("Reply for " HSPHFPD_ENDPOINT_INTERFACE ".ConnectAudio() from invalid sender");
        goto failed;
    }

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        error_name = dbus_message_get_error_name(r);
        if (pa_safe_streq(error_name, HSPHFPD_SERVICE ".AlreadyConnected") || pa_safe_streq(error_name, HSPHFPD_SERVICE ".InProgress")) /* TODO: we should check that pulseaudio really get audio socket */
            goto success;
        pa_log_warn(HSPHFPD_ENDPOINT_INTERFACE ".ConnectAudio() failed: %s: %s", error_name, pa_dbus_get_error_message(r));
        goto failed;
    }

    if (!pa_streq(dbus_message_get_signature(r), "oso")) {
        pa_log_error("Invalid reply signature for " HSPHFPD_ENDPOINT_INTERFACE ".ConnectAudio()");
        goto failed;
    }

    if (!dbus_message_get_args(r, &error, DBUS_TYPE_OBJECT_PATH, &transport_path, DBUS_TYPE_STRING, &service_id, DBUS_TYPE_OBJECT_PATH, &agent_path, DBUS_TYPE_INVALID) || dbus_error_is_set(&error)) {
        pa_log_error("Failed to parse " HSPHFPD_ENDPOINT_INTERFACE ".ConnectAudio() reply: %s", error.message);
        goto failed;
    }

    if (!pa_safe_streq(service_id, dbus_bus_get_unique_name(pa_dbus_connection_get(backend->connection)))) {
        pa_log_warn(HSPHFPD_ENDPOINT_INTERFACE ".ConnectAudio() failed: Other audio application took audio socket");
        goto failed;
    }

success:
    /* On success hsphfpd daemon asynchronously calls NewConnection() method which change transport state to playing */
    goto finish;

failed:
    /* If transport state is idle switch it to disconnected state and then back to idle state
     * so sinks and sources are properly released and connected attempt is marked as failed,
     * this also trigger profile change to off */
    transport = pa_bluetooth_transport_get(backend->discovery, endpoint_path);
    if (transport && transport->state == PA_BLUETOOTH_TRANSPORT_STATE_IDLE) {
        pa_bluetooth_transport_set_state(transport, PA_BLUETOOTH_TRANSPORT_STATE_DISCONNECTED);
        pa_bluetooth_transport_set_state(transport, PA_BLUETOOTH_TRANSPORT_STATE_IDLE);
    }

finish:
    pa_xfree(endpoint_path);

    dbus_error_free(&error);
    dbus_message_unref(r);

    PA_LLIST_REMOVE(pa_dbus_pending, backend->pending, p);
    pa_dbus_pending_free(p);
283
284
}

285
286
287
static int hsphfpd_transport_acquire(pa_bluetooth_transport *transport, size_t *imtu, size_t *omtu) {
    struct hsphfpd_transport_data *transport_data = transport->userdata;

288
289
290
291
292
293
294
295
296
    if (transport_data->sco_fd < 0) {
        /* TODO: support for choosing codec is not implemented yet */
        const char *air_codec = "CVSD";
        const char *agent_codec = "PCM_s16le_8kHz";
        const char *endpoint_path = transport->path;
        DBusMessage *m;
        pa_assert_se(m = dbus_message_new_method_call(HSPHFPD_SERVICE, endpoint_path, HSPHFPD_ENDPOINT_INTERFACE, "ConnectAudio"));
        pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_STRING, &air_codec, DBUS_TYPE_STRING, &agent_codec, DBUS_TYPE_INVALID));
        send_and_add_to_pending(transport_data->backend, m, hsphfpd_transport_acquire_reply, pa_xstrdup(endpoint_path));
297
        return -EAGAIN;
298
    }
299
300
301
302
303
304
305
306
307

    if (imtu) *imtu = transport_data->mtu;
    if (omtu) *omtu = transport_data->mtu;
    return transport_data->sco_fd;
}

static void hsphfpd_transport_release(pa_bluetooth_transport *transport) {
    struct hsphfpd_transport_data *transport_data = transport->userdata;

308
309
    if (transport_data->sco_fd < 0) {
        pa_log_info("Transport for endpoint %s already released", transport->path);
310
311
312
313
314
315
        return;
    }

    shutdown(transport_data->sco_fd, SHUT_RDWR);
    transport_data->sco_fd = -1;
    /* file descriptor is closed by teardown_stream() */
316
317
318
319
320
321
322
323
324
325
326

    pa_xfree(transport_data->transport_path);
    transport_data->transport_path = NULL;

    pa_xfree(transport_data->agent_codec);
    transport_data->agent_codec = NULL;

    pa_xfree(transport_data->air_codec);
    transport_data->air_codec = NULL;

    transport_data->mtu = 0;
327
328
329
330
331
}

static void hsphfpd_transport_destroy(pa_bluetooth_transport *transport) {
    struct hsphfpd_transport_data *transport_data = transport->userdata;

332
    pa_xfree(transport_data->transport_path);
333
334
335
336
337
338
339
340
341
342
343
    pa_xfree(transport_data->agent_codec);
    pa_xfree(transport_data->air_codec);
    pa_xfree(transport_data);
}

static void hsphfpd_transport_set_speaker_gain(pa_bluetooth_transport *transport, uint16_t gain) {
    struct hsphfpd_transport_data *transport_data = transport->userdata;

    if (transport->speaker_gain == gain)
        return;

344
    set_speaker_gain_property(transport_data, gain);
345
346
347
348
349
350
351
352
353
    transport->speaker_gain = gain;
}

static void hsphfpd_transport_set_microphone_gain(pa_bluetooth_transport *transport, uint16_t gain) {
    struct hsphfpd_transport_data *transport_data = transport->userdata;

    if (transport->microphone_gain == gain)
        return;

354
    set_microphone_gain_property(transport_data, gain);
355
356
357
    transport->microphone_gain = gain;
}

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
static void parse_transport_properties_values(pa_bluetooth_backend *backend, const char *transport_path, DBusMessageIter *i, const char **endpoint_path, const char **air_codec, enum hsphfpd_volume_control *volume_control, uint16_t *microphone_gain, uint16_t *speaker_gain, uint16_t *mtu) {
    DBusMessageIter element_i;

    pa_assert(i);

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

        if (dbus_message_iter_get_arg_type(&dict_i) != DBUS_TYPE_STRING) {
            pa_log_error("Received invalid property for transport %s", transport_path);
            return;
        }

        dbus_message_iter_get_basic(&dict_i, &key);

        if (!dbus_message_iter_next(&dict_i)) {
            pa_log_error("Received invalid property for transport %s", transport_path);
            return;
        }

        if (dbus_message_iter_get_arg_type(&dict_i) != DBUS_TYPE_VARIANT) {
            pa_log_error("Received invalid property for transport %s", transport_path);
            return;
        }

        dbus_message_iter_recurse(&dict_i, &variant_i);

        switch (dbus_message_iter_get_arg_type(&variant_i)) {
            case DBUS_TYPE_STRING:
                if (pa_streq(key, "VolumeControl")) {
                    const char *value;
                    dbus_message_iter_get_basic(&variant_i, &value);
                    if (pa_streq(value, "none"))
                        *volume_control = HSPHFPD_VOLUME_CONTROL_NONE;
                    else if (pa_streq(value, "local"))
                        *volume_control = HSPHFPD_VOLUME_CONTROL_LOCAL;
                    else if (pa_streq(value, "remote"))
                        *volume_control = HSPHFPD_VOLUME_CONTROL_REMOTE;
                    else
                        pa_log_warn("Transport %s received invalid '%s' property value '%s', ignoring", transport_path, key, value);
                } else if (pa_streq(key, "AirCodec"))
                    dbus_message_iter_get_basic(&variant_i, air_codec);
                break;

            case DBUS_TYPE_UINT16:
                if (pa_streq(key, "MTU"))
                    dbus_message_iter_get_basic(&variant_i, mtu);
                else if (pa_streq(key, "MicrophoneGain"))
                    dbus_message_iter_get_basic(&variant_i, microphone_gain);
                else if (pa_streq(key, "SpeakerGain"))
                    dbus_message_iter_get_basic(&variant_i, speaker_gain);
                break;

            case DBUS_TYPE_OBJECT_PATH:
                if (pa_streq(key, "Endpoint"))
                    dbus_message_iter_get_basic(&variant_i, endpoint_path);
                break;
        }

        dbus_message_iter_next(&element_i);
    }
}

static void parse_transport_properties(pa_bluetooth_transport *transport, DBusMessageIter *i) {
    struct hsphfpd_transport_data *transport_data = transport->userdata;
    bool microphone_gain_changed = false;
    bool speaker_gain_changed = false;
    bool volume_control_changed = false;
    bool soft_volume_changed = false;
    const char *endpoint_path = NULL;
    const char *air_codec = NULL;
    enum hsphfpd_volume_control volume_control = 0;
    uint16_t microphone_gain = -1;
    uint16_t speaker_gain = -1;
    uint16_t mtu = 0;

439
    parse_transport_properties_values(transport_data->backend, transport_data->transport_path, i, &endpoint_path, &air_codec, &volume_control, &microphone_gain, &speaker_gain, &mtu);
440
441

    if (endpoint_path)
442
        pa_log_warn("Transport %s received a duplicate '%s' property, ignoring", transport_data->transport_path, "Endpoint");
443
444

    if (air_codec)
445
        pa_log_warn("Transport %s received a duplicate '%s' property, ignoring", transport_data->transport_path, "AirCodec");
446
447

    if (mtu)
448
        pa_log_warn("Transport %s received a duplicate '%s' property, ignoring", transport_data->transport_path, "MTU");
449
450
451

    if (volume_control) {
        if (!!transport->soft_volume != !!(volume_control != HSPHFPD_VOLUME_CONTROL_REMOTE)) {
452
            pa_log_info("Transport %s changed soft volume from %s to %s", transport_data->transport_path, pa_yes_no(transport->soft_volume), pa_yes_no(volume_control != HSPHFPD_VOLUME_CONTROL_REMOTE));
453
454
455
456
457
458
459
460
461
462
463
            transport->soft_volume = (volume_control != HSPHFPD_VOLUME_CONTROL_REMOTE);
            soft_volume_changed = true;
        }
        if (transport_data->volume_control != volume_control) {
            transport_data->volume_control = volume_control;
            volume_control_changed = true;
        }
    }

    if (microphone_gain != (uint16_t)-1) {
        if (transport->microphone_gain != microphone_gain) {
464
            pa_log_info("Transport %s changed microphone gain from %u to %u", transport_data->transport_path, (unsigned)transport->microphone_gain, (unsigned)microphone_gain);
465
466
467
468
469
470
471
            transport->microphone_gain = microphone_gain;
            microphone_gain_changed = true;
        }
    }

    if (speaker_gain != (uint16_t)-1) {
        if (transport->speaker_gain != speaker_gain) {
472
            pa_log_info("Transport %s changed speaker gain from %u to %u", transport_data->transport_path, (unsigned)transport->speaker_gain, (unsigned)speaker_gain);
473
474
475
476
477
            transport->speaker_gain = speaker_gain;
            speaker_gain_changed = true;
        }
    }

478
479
    if (microphone_gain_changed || soft_volume_changed)
        pa_hook_fire(pa_bluetooth_discovery_hook(transport_data->backend->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_MICROPHONE_GAIN_CHANGED), transport);
480

481
482
    if (speaker_gain_changed || soft_volume_changed)
        pa_hook_fire(pa_bluetooth_discovery_hook(transport_data->backend->discovery, PA_BLUETOOTH_HOOK_TRANSPORT_SPEAKER_GAIN_CHANGED), transport);
483

484
485
486
    if (volume_control_changed) {
        set_microphone_gain_property(transport_data, transport->microphone_gain);
        set_speaker_gain_property(transport_data, transport->speaker_gain);
487
488
489
    }
}

490
static void parse_endpoint_properties(pa_bluetooth_backend *backend, struct hsphfpd_endpoint *endpoint, DBusMessageIter *i) {
491
492
493
494
495
496
497
498
499
500
501
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
    DBusMessageIter element_i;

    pa_assert(i);

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

        if (dbus_message_iter_get_arg_type(&dict_i) != DBUS_TYPE_STRING) {
            pa_log_error("Received invalid property for endpoint %s", endpoint->path);
            return;
        }

        dbus_message_iter_get_basic(&dict_i, &key);

        if (!dbus_message_iter_next(&dict_i)) {
            pa_log_error("Received invalid property for endpoint %s", endpoint->path);
            return;
        }

        if (dbus_message_iter_get_arg_type(&dict_i) != DBUS_TYPE_VARIANT) {
            pa_log_error("Received invalid property for endpoint %s", endpoint->path);
            return;
        }

        dbus_message_iter_recurse(&dict_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, "LocalAddress")) {
                    if (endpoint->local_address)
                        pa_log_warn("Endpoint %s received a duplicate '%s' property, ignoring", endpoint->path, key);
                    else
                        endpoint->local_address = pa_xstrdup(value);
                } else if (pa_streq(key, "RemoteAddress")) {
                    if (endpoint->remote_address)
                        pa_log_warn("Endpoint %s received a duplicate '%s' property, ignoring", endpoint->path, key);
                    else
                        endpoint->remote_address = pa_xstrdup(value);
                } else if (pa_streq(key, "Profile")) {
                    if (endpoint->profile)
                        pa_log_warn("Endpoint %s received a duplicate '%s' property, ignoring", endpoint->path, key);
539
540
541
542
                    else if (pa_streq(value, "headset"))
                        endpoint->profile = HSPHFPD_PROFILE_HEADSET;
                    else if (pa_streq(value, "handsfree"))
                        endpoint->profile = HSPHFPD_PROFILE_HANDSFREE;
543
                    else
544
                        pa_log_warn("Endpoint %s received invalid '%s' property value '%s', ignoring", endpoint->path, key, value);
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
                } else if (pa_streq(key, "Role")) {
                    if (endpoint->role)
                        pa_log_warn("Endpoint %s received a duplicate '%s' property, ignoring", endpoint->path, key);
                    else if (pa_streq(value, "client"))
                        endpoint->role = HSPHFPD_ROLE_CLIENT;
                    else if (pa_streq(value, "gateway"))
                        endpoint->role = HSPHFPD_ROLE_GATEWAY;
                    else
                        pa_log_warn("Endpoint %s received invalid '%s' property value '%s', ignoring", endpoint->path, key, value);
                }
                break;
            }

            case DBUS_TYPE_BOOLEAN: {
                bool value;
                dbus_message_iter_get_basic(&variant_i, &value);
561
                if (pa_streq(key, "Connected") && endpoint->connected != value) {
562
                    endpoint->connected = value;
563
564
565
566
567
568
                    if (!endpoint->connected) {
                        pa_bluetooth_transport *transport = pa_bluetooth_transport_get(backend->discovery, endpoint->path);
                        if (transport)
                            pa_bluetooth_transport_free(transport);
                    }
                }
569
570
571
572
573
574
575
576
577
                break;
            }
        }

        dbus_message_iter_next(&element_i);
    }

    if (!endpoint->valid && endpoint->local_address && endpoint->remote_address && endpoint->profile && endpoint->role)
        endpoint->valid = true;
578
579

    if (endpoint->valid && endpoint->connected && !pa_bluetooth_transport_get(backend->discovery, endpoint->path)) {
580
        struct hsphfpd_transport_data *transport_data;
581
582
583
584
585
586
587
        pa_bluetooth_transport *transport;
        pa_bluetooth_profile_t profile;
        pa_bluetooth_device *device = pa_bluetooth_discovery_get_device_by_address(backend->discovery, endpoint->remote_address, endpoint->local_address);
        if (!device) {
            pa_log_error("Device does not exist for endpoint %s (remote addresses %s, local address %s)", endpoint->path, endpoint->remote_address, endpoint->local_address);
        } else {
            pa_log_debug("Creating a new transport for endpoint %s", endpoint->path);
588

589
590
591
592
593
594
595
596
597
598
599
            if (endpoint->profile == HSPHFPD_PROFILE_HEADSET) {
                if (endpoint->role == HSPHFPD_ROLE_CLIENT)
                    profile = PA_BLUETOOTH_PROFILE_HSP_HEAD_UNIT;
                else
                    profile = PA_BLUETOOTH_PROFILE_HSP_AUDIO_GATEWAY;
            } else {
                if (endpoint->role == HSPHFPD_ROLE_CLIENT)
                    profile = PA_BLUETOOTH_PROFILE_HFP_HEAD_UNIT;
                else
                    profile = PA_BLUETOOTH_PROFILE_HFP_AUDIO_GATEWAY;
            }
600
601
602
603
604

            transport_data = pa_xnew0(struct hsphfpd_transport_data, 1);
            transport_data->backend = backend;
            transport_data->sco_fd = -1;

605
606
607
608
609
610
            transport = pa_bluetooth_transport_new(device, backend->hsphfpd_service_id, endpoint->path, profile, NULL, 0);
            transport->acquire = hsphfpd_transport_acquire;
            transport->release = hsphfpd_transport_release;
            transport->destroy = hsphfpd_transport_destroy;
            transport->set_speaker_gain = hsphfpd_transport_set_speaker_gain;
            transport->set_microphone_gain = hsphfpd_transport_set_microphone_gain;
611
612
            transport->userdata = transport_data;

613
614
615
            pa_bluetooth_transport_put(transport);
        }
    }
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
}

static void parse_interfaces(pa_bluetooth_backend *backend, DBusMessageIter *dict_i) {
    DBusMessageIter element_i;
    const char *path;

    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, HSPHFPD_ENDPOINT_INTERFACE)) {
            struct hsphfpd_endpoint *endpoint;

            endpoint = pa_hashmap_get(backend->endpoints, path);
            if (!endpoint) {
                endpoint = pa_xnew0(struct hsphfpd_endpoint, 1);
                endpoint->path = pa_xstrdup(path);
                pa_hashmap_put(backend->endpoints, endpoint->path, endpoint);
                pa_log_debug("Found endpoint %s", path);
            }

653
            parse_endpoint_properties(backend, endpoint, &iface_i);
654
655
656
657
658
659
660
661
662
663
664
665
666
        } else
            pa_log_debug("Unknown interface %s found, skipping", interface);

        dbus_message_iter_next(&element_i);
    }
}

static void hsphfpd_get_endpoints_reply(DBusPendingCall *pending, void *userdata) {
    pa_dbus_pending *p;
    pa_bluetooth_backend *backend;
    DBusMessage *r;
    DBusMessageIter arg_i, element_i;

667
    pa_assert(pending);
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    pa_assert_se(p = userdata);
    pa_assert_se(backend = p->context_data);
    pa_assert_se(r = dbus_pending_call_steal_reply(pending));

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

682
    if (!pa_safe_streq(dbus_message_get_sender(r), backend->hsphfpd_service_id)) {
683
684
685
686
        pa_log_error("Reply for GetManagedObjects() from invalid sender");
        goto finish;
    }

687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
    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);

        parse_interfaces(backend, &dict_i);

        dbus_message_iter_next(&element_i);
    }

    backend->endpoints_listed = true;

finish:
    dbus_message_unref(r);

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

static void hsphfpd_get_endpoints(pa_bluetooth_backend *backend) {
    DBusMessage *m;

    pa_assert(backend);

    pa_assert_se(m = dbus_message_new_method_call(HSPHFPD_SERVICE, "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"));
    send_and_add_to_pending(backend, m, hsphfpd_get_endpoints_reply, NULL);
}

static void hsphfpd_register_application_reply(DBusPendingCall *pending, void *userdata) {
    DBusMessage *r;
    pa_dbus_pending *p;
    pa_bluetooth_backend *backend;

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

    if (dbus_message_get_type(r) == DBUS_MESSAGE_TYPE_ERROR) {
        pa_log_warn(HSPHFPD_APPLICATION_MANAGER_INTERFACE ".RegisterApplication() failed: %s: %s",
                    dbus_message_get_error_name(r), pa_dbus_get_error_message(r));
        if (dbus_message_is_error(r, DBUS_ERROR_SERVICE_UNKNOWN))
            pa_bluetooth_discovery_legacy_hsp_backend_enable(backend->discovery, true);
        goto finish;
    }

    backend->hsphfpd_service_id = pa_xstrdup(dbus_message_get_sender(r));

    hsphfpd_get_endpoints(backend);

finish:
    dbus_message_unref(r);

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

static void hsphfpd_register_application(pa_bluetooth_backend *backend) {
    DBusMessage *m;
    const char *path = APPLICATION_OBJECT_MANAGER_PATH;

    pa_assert(backend);

    pa_assert_se(m = dbus_message_new_method_call(HSPHFPD_SERVICE, "/", HSPHFPD_APPLICATION_MANAGER_INTERFACE, "RegisterApplication"));
    pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID));

    send_and_add_to_pending(backend, m, hsphfpd_register_application_reply, NULL);
}

static void hsphfpd_unregister_application(pa_bluetooth_backend *backend) {
    DBusMessage *m;
    const char *path = APPLICATION_OBJECT_MANAGER_PATH;

    pa_assert(backend);
    pa_assert(backend->connection);

    pa_assert_se(m = dbus_message_new_method_call(HSPHFPD_SERVICE, "/", HSPHFPD_APPLICATION_MANAGER_INTERFACE, "UnregisterApplication"));
    pa_assert_se(dbus_message_append_args(m, DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID));
    pa_assert_se(dbus_connection_send(pa_dbus_connection_get(backend->connection), m, NULL));

    pa_xfree(backend->hsphfpd_service_id);
    backend->hsphfpd_service_id = NULL;
    backend->endpoints_listed = false;
    pa_hashmap_remove_all(backend->endpoints);
    pa_bluetooth_discovery_legacy_hsp_backend_enable(backend->discovery, true);
}

static DBusMessage *hsphfpd_new_connection(pa_bluetooth_backend *backend, DBusMessage *m) {
    const char *agent_path;
    const char *transport_path;
    const char *endpoint_path = NULL;
    const char *air_codec = NULL;
    enum hsphfpd_volume_control volume_control = 0;
    uint16_t microphone_gain = -1;
    uint16_t speaker_gain = -1;
    uint16_t mtu = 0;
    const char *sender;
    pa_bluetooth_transport *transport;
    struct hsphfpd_endpoint *endpoint;
    struct hsphfpd_transport_data *transport_data;
    int sco_fd;
    DBusMessage *r;
    DBusMessageIter arg_i;

    if (!dbus_message_iter_init(m, &arg_i) || !pa_streq(dbus_message_get_signature(m), "oha{sv}")) {
        pa_log_error("Invalid signature for method NewConnection()");
        return NULL;
    }

    agent_path = dbus_message_get_path(m);
    if (!pa_streq(agent_path, AUDIO_AGENT_ENDPOINT_PCM_S16LE_8KHZ)) {
        pa_log_error("Invalid handler for method NewConnection()");
        return NULL;
    }

    pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_OBJECT_PATH);
    dbus_message_iter_get_basic(&arg_i, &transport_path);

    pa_assert_se(dbus_message_iter_next(&arg_i));

    pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_UNIX_FD);
    dbus_message_iter_get_basic(&arg_i, &sco_fd);

811
812
813
814
815
816
817
818
819
820
    pa_log_debug("NewConnection path=%s, sco_fd=%d", transport_path, sco_fd);

    sender = dbus_message_get_sender(m);
    if (!pa_safe_streq(sender, backend->hsphfpd_service_id)) {
        close(sco_fd);
        pa_log_error("Sender '%s' is not authorized", sender);
        pa_assert_se(r = dbus_message_new_error_printf(m, "org.hsphfpd.Error.Rejected", "Sender '%s' is not authorized", sender));
        return r;
    }

821
822
823
824
825
826
827
828
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
    pa_assert_se(dbus_message_iter_next(&arg_i));
    pa_assert(dbus_message_iter_get_arg_type(&arg_i) == DBUS_TYPE_ARRAY);
    parse_transport_properties_values(backend, transport_path, &arg_i, &endpoint_path, &air_codec, &volume_control, &microphone_gain, &speaker_gain, &mtu);

    if (!endpoint_path) {
        close(sco_fd);
        pa_log_error("Endpoint property was not specified");
        pa_assert_se(r = dbus_message_new_error(m, "org.hsphfpd.Error.Rejected", "Endpoint property was not specified"));
        return r;
    }

    if (!air_codec) {
        close(sco_fd);
        pa_log_error("AirCodec property was not specified");
        pa_assert_se(r = dbus_message_new_error(m, "org.hsphfpd.Error.Rejected", "AirCodec property was not specified"));
        return r;
    }

    if (!volume_control) {
        close(sco_fd);
        pa_log_error("VolumeControl property was not specified");
        pa_assert_se(r = dbus_message_new_error(m, "org.hsphfpd.Error.Rejected", "VolumeControl property was not specified"));
        return r;
    }

    if (volume_control != HSPHFPD_VOLUME_CONTROL_NONE) {
        if (microphone_gain == (uint16_t)-1) {
            close(sco_fd);
            pa_log_error("MicrophoneGain property was not specified, but VolumeControl is not none");
            pa_assert_se(r = dbus_message_new_error(m, "org.hsphfpd.Error.Rejected", "MicrophoneGain property was not specified, but VolumeControl is not none"));
            return r;
        }

        if (speaker_gain == (uint16_t)-1) {
            close(sco_fd);
            pa_log_error("SpeakerGain property was not specified, but VolumeControl is not none");
            pa_assert_se(r = dbus_message_new_error(m, "org.hsphfpd.Error.Rejected", "SpeakerGain property was not specified, but VolumeControl is not none"));
            return r;
        }
    } else {
        microphone_gain = 0;
        speaker_gain = 0;
    }

    if (!mtu) {
        close(sco_fd);
        pa_log_error("MTU property was not specified");
        pa_assert_se(r = dbus_message_new_error(m, "org.hsphfpd.Error.Rejected", "MTU property was not specified"));
        return r;
    }

    endpoint = pa_hashmap_get(backend->endpoints, endpoint_path);
    if (!endpoint) {
        close(sco_fd);
        pa_log_error("Endpoint %s does not exist", endpoint_path);
        pa_assert_se(r = dbus_message_new_error_printf(m, "org.hsphfpd.Error.Rejected", "Endpoint %s does not exist", endpoint_path));
        return r;
    }

    if (!endpoint->valid) {
        close(sco_fd);
        pa_log_error("Endpoint %s is not valid", endpoint_path);
        pa_assert_se(r = dbus_message_new_error_printf(m, "org.hsphfpd.Error.Rejected", "Endpoint %s is not valid", endpoint_path));
        return r;
    }

887
888
    transport = pa_bluetooth_transport_get(backend->discovery, endpoint_path);
    if (!transport) {
889
        close(sco_fd);
890
891
        pa_log_error("Endpoint %s is not connected", endpoint_path);
        pa_assert_se(r = dbus_message_new_error_printf(m, "org.hsphfpd.Error.Rejected", "Endpoint %s is not connected", endpoint_path));
892
893
894
        return r;
    }

895
896
    transport_data = transport->userdata;
    if (transport_data->sco_fd >= 0) {
897
898
899
900
901
        close(sco_fd);
        pa_log_error("Endpoint %s has already active transport", endpoint_path);
        pa_assert_se(r = dbus_message_new_error_printf(m, "org.hsphfpd.Error.Rejected", "Endpoint %s has already active transport", endpoint_path));
        return r;
    }
902

903
    transport_data->transport_path = pa_xstrdup(transport_path);
904
905
906
907
908
909
910
911
    transport_data->agent_codec = pa_xstrdup("PCM_s16le_8kHz");
    transport_data->air_codec = pa_xstrdup(air_codec);
    transport_data->volume_control = volume_control;
    transport_data->mtu = mtu;
    transport_data->sco_fd = sco_fd;

    pa_bluetooth_transport_set_state(transport, PA_BLUETOOTH_TRANSPORT_STATE_PLAYING);

912
    pa_log_debug("Transport %s with agent codec %s and air codec %s is active for profile %s on endpoint %s", transport_data->transport_path, transport_data->agent_codec, transport_data->air_codec, pa_bluetooth_profile_to_string(transport->profile), endpoint_path);
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939

    pa_assert_se(r = dbus_message_new_method_return(m));
    return r;
}

static DBusHandlerResult filter_cb(DBusConnection *bus, DBusMessage *m, void *data) {
    const char *sender;
    DBusError err;
    pa_bluetooth_backend *backend = data;

    pa_assert(bus);
    pa_assert(m);
    pa_assert(backend);

    dbus_error_init(&err);

    sender = dbus_message_get_sender(m);

    if (pa_streq(sender, "org.freedesktop.DBus")) {

        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,
940
941
                                       DBUS_TYPE_INVALID)
                  || dbus_error_is_set(&err)) {
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
                pa_log_error("Failed to parse org.freedesktop.DBus.NameOwnerChanged: %s", err.message);
                goto finish;
            }

            if (pa_streq(name, HSPHFPD_SERVICE)) {
                if (old_owner && *old_owner) {
                    pa_log_debug("hsphfpd disappeared");
                    pa_xfree(backend->hsphfpd_service_id);
                    backend->hsphfpd_service_id = NULL;
                    backend->endpoints_listed = false;
                    pa_hashmap_remove_all(backend->endpoints);
                    pa_bluetooth_discovery_legacy_hsp_backend_enable(backend->discovery, true);
                }

                if (new_owner && *new_owner) {
                    pa_log_debug("hsphfpd appeared");
                    pa_bluetooth_discovery_legacy_hsp_backend_enable(backend->discovery, false);
                    hsphfpd_register_application(backend);
                }
            }
        }

    } else if (pa_safe_streq(sender, backend->hsphfpd_service_id)) {

        DBusMessageIter arg_i;

        if (dbus_message_is_signal(m, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded")) {
            if (!backend->endpoints_listed)
                goto finish;

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

            parse_interfaces(backend, &arg_i);
        } else if (dbus_message_is_signal(m, "org.freedesktop.DBus.ObjectManager", "InterfacesRemoved")) {
            const char *path;
            DBusMessageIter element_i;

            if (!backend->endpoints_listed)
                goto finish;

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

            dbus_message_iter_get_basic(&arg_i, &path);

            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, HSPHFPD_ENDPOINT_INTERFACE)) {
                    pa_bluetooth_transport *transport = pa_bluetooth_transport_get(backend->discovery, path);
                    if (transport)
1005
                        pa_bluetooth_transport_free(transport);
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
                    pa_log_debug("Remove endpoint %s", path);
                    pa_hashmap_remove(backend->endpoints, path);
                }

                dbus_message_iter_next(&element_i);
            }
        } else if (dbus_message_is_signal(m, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {
            const char *iface;
            const char *path;

            if (!backend->endpoints_listed)
                goto finish;

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

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

            path = dbus_message_get_path(m);

            if (pa_streq(iface, HSPHFPD_ENDPOINT_INTERFACE)) {
                struct hsphfpd_endpoint *endpoint = pa_hashmap_get(backend->endpoints, path);
                if (!endpoint) {
                    pa_log_warn("Properties changed on unknown endpoint %s", path);
                    goto finish;
                }
                pa_log_debug("Properties changed on endpoint %s", path);
1038
                parse_endpoint_properties(backend, endpoint, &arg_i);
1039
            } else if (pa_streq(iface, HSPHFPD_AUDIO_TRANSPORT_INTERFACE)) {
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
                pa_hashmap *transports = pa_bluetooth_transport_get_all(backend->discovery);
                pa_bluetooth_transport *transport;
                struct hsphfpd_transport_data *transport_data;
                void *state;

                /* Find pa_bluetooth_transport which belongs to hsphfpd transport path
                 * pa_hashmap_get() search transports by hsphfpd endpoint path and
                 * not by hsphfpd transport path, so do search routine manually */
                PA_HASHMAP_FOREACH(transport, transports, state) {
                    if (!transport->owner || !pa_safe_streq(transport->owner, backend->hsphfpd_service_id))
                        continue;
                    transport_data = transport->userdata;
                    if (transport_data->sco_fd <= 0 || !pa_safe_streq(transport_data->transport_path, path))
                        continue;
                    break;
                }

                if (!transport) {
1058
1059
1060
                    pa_log_warn("Properties changed on unknown transport %s", path);
                    goto finish;
                }
1061

1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
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
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
                pa_log_debug("Properties changed on transport %s", path);
                parse_transport_properties(transport, &arg_i);
            }
        }

    }

finish:
    dbus_error_free(&err);
    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

static void append_audio_agent_object(DBusMessageIter *iter, const char *endpoint, const char *agent_codec) {
    const char *interface_name = HSPHFPD_AUDIO_AGENT_INTERFACE;
    DBusMessageIter object, array, entry, dict;

    dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL, &object);
    pa_assert_se(dbus_message_iter_append_basic(&object, DBUS_TYPE_OBJECT_PATH, &endpoint));

    dbus_message_iter_open_container(&object, DBUS_TYPE_ARRAY,
                                     DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
                                     DBUS_TYPE_STRING_AS_STRING
                                     DBUS_TYPE_ARRAY_AS_STRING
                                     DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
                                     DBUS_TYPE_STRING_AS_STRING
                                     DBUS_TYPE_VARIANT_AS_STRING
                                     DBUS_DICT_ENTRY_END_CHAR_AS_STRING
                                     DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
                                     &array);

    dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, NULL, &entry);
    pa_assert_se(dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &interface_name));

    dbus_message_iter_open_container(&entry, 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,
                                     &dict);

    pa_dbus_append_basic_variant_dict_entry(&dict, "AgentCodec", DBUS_TYPE_STRING, &agent_codec);

    dbus_message_iter_close_container(&entry, &dict);
    dbus_message_iter_close_container(&array, &entry);
    dbus_message_iter_close_container(&object, &array);
    dbus_message_iter_close_container(iter, &object);
}

static DBusHandlerResult application_object_manager_handler(DBusConnection *c, DBusMessage *m, void *userdata) {
    struct pa_bluetooth_backend *backend = userdata;
    DBusMessage *r;
    const char *path, *interface, *member;

    pa_assert(backend);

    path = dbus_message_get_path(m);
    interface = dbus_message_get_interface(m);
    member = dbus_message_get_member(m);

    pa_log_debug("dbus: path=%s, interface=%s, member=%s", path, interface, member);

    if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) {
        const char *xml = APPLICATION_OBJECT_MANAGER_INTROSPECT_XML;

        pa_assert_se(r = dbus_message_new_method_return(m));
        pa_assert_se(dbus_message_append_args(r, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID));
    } else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects")) {
        DBusMessageIter iter, array;

        pa_assert_se(r = dbus_message_new_method_return(m));

        dbus_message_iter_init_append(r, &iter);
        dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
                                         DBUS_TYPE_OBJECT_PATH_AS_STRING
                                         DBUS_TYPE_ARRAY_AS_STRING
                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
                                         DBUS_TYPE_STRING_AS_STRING
                                         DBUS_TYPE_ARRAY_AS_STRING
                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
                                         DBUS_TYPE_STRING_AS_STRING
                                         DBUS_TYPE_VARIANT_AS_STRING
                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING
                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING
                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
                                         &array);

        append_audio_agent_object(&array, AUDIO_AGENT_ENDPOINT_PCM_S16LE_8KHZ, "PCM_s16le_8kHz");

        dbus_message_iter_close_container(&iter, &array);
    } else
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    pa_assert_se(dbus_connection_send(pa_dbus_connection_get(backend->connection), r, NULL));
    dbus_message_unref(r);

    return DBUS_HANDLER_RESULT_HANDLED;
}

static DBusHandlerResult audio_agent_endpoint_pcm_s16le_8khz_handler(DBusConnection *c, DBusMessage *m, void *userdata) {
    pa_bluetooth_backend *backend = userdata;
    DBusMessage *r = NULL;

    pa_assert(backend);

    pa_log_debug("dbus: path=%s, interface=%s, member=%s", dbus_message_get_path(m), dbus_message_get_interface(m), dbus_message_get_member(m));

    if (!pa_streq(dbus_message_get_path(m), AUDIO_AGENT_ENDPOINT_PCM_S16LE_8KHZ))
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) {
        const char *xml = AUDIO_AGENT_ENDPOINT_INTROSPECT_XML;

        pa_assert_se(r = dbus_message_new_method_return(m));
        pa_assert_se(dbus_message_append_args(r, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID));
    } else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Properties", "Get")) {
        const char *interface;
        const char *property;
        DBusError error;

        if (!pa_streq(dbus_message_get_signature(m), "ss")) {
            pa_log_error("Invalid signature for method Get()");
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        dbus_error_init(&error);
        if (!dbus_message_get_args(m, &error, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID) || dbus_error_is_set(&error)) {
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
        dbus_error_free(&error);

        if (!pa_streq(interface, HSPHFPD_AUDIO_AGENT_INTERFACE))
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

        if (pa_streq(property, "AgentCodec")) {
            const char *agent_codec = "PCM_s16le_8kHz";
            pa_assert_se(r = dbus_message_new_method_return(m));
            pa_assert_se(dbus_message_append_args(r, DBUS_TYPE_STRING, &agent_codec, DBUS_TYPE_INVALID));
        } else
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    } else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Properties", "GetAll")) {
        DBusError error;
        DBusMessageIter iter, dict;
        const char *interface;
        const char *agent_codec = "PCM_s16le_8kHz";

        if (!pa_streq(dbus_message_get_signature(m), "s")) {
            pa_log_error("Invalid signature for method GetAll()");
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        dbus_error_init(&error);
        if (!dbus_message_get_args(m, &error, DBUS_TYPE_STRING, &interface, DBUS_TYPE_INVALID) || dbus_error_is_set(&error)) {
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
        dbus_error_free(&error);

        if (!pa_streq(interface, HSPHFPD_AUDIO_AGENT_INTERFACE))
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

        pa_assert_se(r = dbus_message_new_method_return(m));
        dbus_message_iter_init_append(r, &iter);
        pa_assert_se(dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &dict));
        pa_dbus_append_basic_variant_dict_entry(&dict, "AgentCodec", DBUS_TYPE_STRING, &agent_codec);
        pa_assert_se(dbus_message_iter_close_container(&iter, &dict));
    } else if (dbus_message_is_method_call(m, HSPHFPD_AUDIO_AGENT_INTERFACE, "NewConnection")) {
        r = hsphfpd_new_connection(backend, m);
        if (!r)
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    } else
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    pa_assert(r);
    pa_assert_se(dbus_connection_send(pa_dbus_connection_get(backend->connection), r, NULL));
    dbus_message_unref(r);
    return DBUS_HANDLER_RESULT_HANDLED;
}

pa_bluetooth_backend *pa_bluetooth_hsphfpd_backend_new(pa_core *core, pa_bluetooth_discovery *discovery) {
    pa_bluetooth_backend *backend;
    DBusError err;
    static const DBusObjectPathVTable vtable_application_object_manager = {
        .message_function = application_object_manager_handler,
    };
    static const DBusObjectPathVTable vtable_audio_agent_endpoint_pcm_s16le_8khz = {
        .message_function = audio_agent_endpoint_pcm_s16le_8khz_handler,
    };

    pa_assert(core);
    pa_assert(discovery);

    backend = pa_xnew0(pa_bluetooth_backend, 1);
    backend->core = core;
    backend->discovery = discovery;
    backend->endpoints_listed = false;
    backend->endpoints = pa_hashmap_new_full(pa_idxset_string_hash_func, pa_idxset_string_compare_func, NULL, (pa_free_cb_t) hsphfpd_endpoint_free);

    dbus_error_init(&err);

    if (!(backend->connection = pa_dbus_bus_get(core, DBUS_BUS_SYSTEM, &err))) {
        pa_log_error("Failed to get D-Bus connection: %s", err.message);
        dbus_error_free(&err);
        pa_xfree(backend);
        return NULL;
    }

    if (!dbus_connection_add_filter(pa_dbus_connection_get(backend->connection), filter_cb, backend, NULL)) {
        pa_log_error("Failed to add filter function");
        pa_dbus_connection_unref(backend->connection);
        pa_xfree(backend);
        return NULL;
    }

    if (pa_dbus_add_matches(pa_dbus_connection_get(backend->connection), &err,
            "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='" HSPHFPD_SERVICE "'",
1278
1279
1280
1281
            "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",
            "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesRemoved'",
            "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='" HSPHFPD_ENDPOINT_INTERFACE "'",
            "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='" HSPHFPD_AUDIO_TRANSPORT_INTERFACE "'",
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
            NULL) < 0) {
        pa_log_error("Failed to add hsphfpd D-Bus matches: %s", err.message);
        dbus_connection_remove_filter(pa_dbus_connection_get(backend->connection), filter_cb, backend);
        pa_dbus_connection_unref(backend->connection);
        pa_xfree(backend);
        return NULL;
    }

    pa_assert_se(dbus_connection_register_object_path(pa_dbus_connection_get(backend->connection), APPLICATION_OBJECT_MANAGER_PATH, &vtable_application_object_manager, backend));
    pa_assert_se(dbus_connection_register_object_path(pa_dbus_connection_get(backend->connection), AUDIO_AGENT_ENDPOINT_PCM_S16LE_8KHZ, &vtable_audio_agent_endpoint_pcm_s16le_8khz, backend));

    hsphfpd_register_application(backend);

    return backend;
}

void pa_bluetooth_hsphfpd_backend_free(pa_bluetooth_backend *backend) {
    pa_assert(backend);

    pa_dbus_free_pending_list(&backend->pending);

    hsphfpd_unregister_application(backend);

    dbus_connection_unregister_object_path(pa_dbus_connection_get(backend->connection), APPLICATION_OBJECT_MANAGER_PATH);
    dbus_connection_unregister_object_path(pa_dbus_connection_get(backend->connection), AUDIO_AGENT_ENDPOINT_PCM_S16LE_8KHZ);

    pa_dbus_remove_matches(pa_dbus_connection_get(backend->connection),
            "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='" HSPHFPD_SERVICE "'",
1310
1311
1312
1313
            "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",
            "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesRemoved'",
            "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='" HSPHFPD_ENDPOINT_INTERFACE "'",
            "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='" HSPHFPD_AUDIO_TRANSPORT_INTERFACE "'",
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
            NULL);

    dbus_connection_remove_filter(pa_dbus_connection_get(backend->connection), filter_cb, backend);

    pa_dbus_connection_unref(backend->connection);

    pa_hashmap_free(backend->endpoints);

    pa_xfree(backend);
}