summaryrefslogtreecommitdiffstats
path: root/module-4a-client.c
blob: 41885aed1c500b9d603ce9dba5c678d0027e378b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
201
202
203
204
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/***
  This file is part of PulseAudio.

  Copyright 2018 Collabora Ltd.
    Author: George Kiagiadakis <george.kiagiadakis@collabora.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/>.
***/

#include <pulsecore/pulsecore-config.h>
#include <pulsecore/core-util.h>
#include <pulsecore/llist.h>
#include <pulsecore/module.h>
#include <pulsecore/mutex.h>
#include <pulsecore/modargs.h>
#include <pulsecore/dynarray.h>
#include <pulsecore/semaphore.h>

#include <stdbool.h>

#include "m4a_afb_comm.h"

#define DEFAULT_URI "unix:/run/user/0/apis/ws/ahl-4a"

PA_MODULE_AUTHOR("George Kiagiadakis");
PA_MODULE_DESCRIPTION("Makes PulseAudio work as a client of the AGL Advanced Audio Architecture");
PA_MODULE_LOAD_ONCE(true);
PA_MODULE_VERSION(PACKAGE_VERSION);
PA_MODULE_USAGE(
          "uri=<ahl-4a unix socket uri>"
          "default_role=<role>");

static const char* const valid_modargs[] = {
    "uri",
    "default_role",
    NULL
};

typedef struct _m4a_stream {
    pa_module *self;

    union {
        pa_sink_input *sink_input;
        pa_source_output *source_output;
    };

    char *role;
    char *device_uri;

    bool entity_is_sink;
    bool entity_loaded;
    uint32_t entity_id;
    uint32_t entity_module_id;

    pa_semaphore *semaphore;

    PA_LLIST_FIELDS(struct _m4a_stream);
} m4a_stream;

typedef struct {
    /* configuration data */
    pa_modargs *ma;

    /* operational data */
    pa_mutex *lock;
    pa_dynarray *roles;  /* element-type: char* */
    PA_LLIST_HEAD(m4a_stream, streams);
    pa_hook_slot
        *sink_input_put_slot,
        *sink_input_unlink_post_slot;
    m4a_afb_comm *comm;
} m4a_data;

static bool role_exists(m4a_data *d, const char *role) {
    char *r;
    int idx;

    PA_DYNARRAY_FOREACH(r, d->roles, idx) {
        if (!strcmp(role, r))
            return true;
    }
    return false;
}

static char *decide_role(m4a_data *d, pa_proplist *p) {
    const char *role;

    role = pa_proplist_gets(p, PA_PROP_MEDIA_ROLE);
    if (role && role_exists(d, role)) {
        return pa_xstrdup(role);
    }

    /* FIXME we might want to do some mapping here between the standard
     * pulseaudio roles and whatever roles might be available in 4a */

    /* try the default role specified in the module arguments, or fall back
     * to "multimedia", which we can just hope that it exists */
    role = pa_modargs_get_value(d->ma, "default_role", "multimedia");
    if (role_exists(d, role)) {
        return pa_xstrdup(role);
    }

    return NULL;
}

static pa_sink *load_sink_module(pa_core *core, const char *module, char *params) {
    pa_module *m = NULL;
    pa_sink *target = NULL;
    uint32_t idx;

    if (!(m = pa_module_load(core, module, params))) {
        pa_log("Failed to load module %s %s", module, params);
        return NULL;
    }
    pa_xfree(params);
    PA_IDXSET_FOREACH(target, core->sinks, idx) {
        if (target->module == m)
            break;
    }
    if (target->module != m) {
        pa_log("%s didn't create any sinks", module);
        pa_module_unload(m, false);
        return NULL;
    }
    return target;
}

/* invoked in the afb communication thread */
static void got_roles_cb(enum m4a_afb_reply r,
                         json_object *response,
                         pa_module *self) {
    m4a_data *d = self->userdata;
    int length, i;
    json_object *jr;
    char *role;

    pa_mutex_lock(d->lock);

    if (r == M4A_AFB_REPLY_OK && json_object_get_type(response) == json_type_array) {
        length = json_object_array_length(response);
        for (i = 0; i < length; i++) {
            jr = json_object_array_get_idx(response, i);
            if (json_object_get_type(jr) == json_type_string) {
                role = pa_xstrdup(json_object_get_string(jr));
                pa_log_debug("Found 4a role: %s", role);
                pa_dynarray_append(d->roles, role);
            }
        }
    }

    pa_mutex_unlock(d->lock);
}

static m4a_stream *m4a_stream_new(pa_module *self, bool sink) {
    m4a_data *d = self->userdata;
    m4a_stream *stream;

    stream = pa_xnew0(m4a_stream, 1);
    stream->self = self;
    stream->entity_is_sink = sink;
    stream->semaphore = pa_semaphore_new(0);
    pa_mutex_lock(d->lock);
    PA_LLIST_PREPEND(m4a_stream, d->streams, stream);
    pa_mutex_unlock(d->lock);
    return stream;
}

static void m4a_stream_free(m4a_stream *stream) {
    m4a_data *d = stream->self->userdata;

    if (stream->role)
        pa_xfree(stream->role);
    if (stream->device_uri)
        pa_xfree(stream->device_uri);
    if (stream->entity_loaded)
        pa_module_unload_request_by_index(stream->self->core,
                                          stream->entity_module_id, false);
    pa_semaphore_free(stream->semaphore);
    pa_mutex_lock(d->lock);
    PA_LLIST_REMOVE(m4a_stream, d->streams, stream);
    pa_mutex_unlock(d->lock);
    pa_xfree(stream);
}

/* invoked in the afb communication thread */
static void device_open_cb(enum m4a_afb_reply r,
                           json_object *response,
                           m4a_stream *stream) {
    json_object *jdu;
    const char *device_uri = NULL;

    if (r == M4A_AFB_REPLY_OK && json_object_get_type(response) == json_type_object) {
        json_object_object_get_ex(response, "device_uri", &jdu);
        if (json_object_object_get_ex(response, "device_uri", &jdu) &&
            json_object_get_type(jdu) == json_type_string) {
            device_uri = json_object_get_string(jdu);
        }
    }

    pa_log_debug("4A replied: %s, device_uri: %s",
                 (r == M4A_AFB_REPLY_OK) ? "OK" : "ERROR",
                 device_uri ? device_uri : "(null)");

    stream->device_uri = pa_xstrdup(device_uri);
    pa_semaphore_post(stream->semaphore);
}

/* invoked in the afb communication thread */
static void device_close_cb(enum m4a_afb_reply r,
                            json_object *response,
                            m4a_stream *stream) {
    pa_log_debug("4A replied: %s",
                 (r == M4A_AFB_REPLY_OK) ? "OK" : "ERROR");
    m4a_stream_free(stream);
}

static pa_hook_result_t sink_input_put_cb(pa_core *core,
                                          pa_sink_input *i,
                                          pa_module *self) {
    m4a_data *d = self->userdata;
    json_object *jparams;
    char *role;

    pa_mutex_lock(d->lock);
    role = decide_role(d, i->proplist);
    pa_mutex_unlock(d->lock);

    pa_log_info("New sink_input with role: %s", role ? role : "(null)");

    if (role) {
        m4a_stream *stream = m4a_stream_new(self, true);
        stream->role = role;
        stream->sink_input = i;

        pa_log_debug("Calling 4A to open the device");

        jparams = json_object_new_object();
        json_object_object_add(jparams, "action", json_object_new_string("open"));

        m4a_afb_call_async(d->comm, role, jparams,
                           (m4a_afb_done_cb_t) device_open_cb, stream);

        pa_log_debug("waiting for 4A to reply");
        pa_semaphore_wait(stream->semaphore);

        if (stream->device_uri) {
            pa_sink *s;

            if ((s = load_sink_module(self->core, "module-alsa-sink",
                        pa_sprintf_malloc("device=%s", stream->device_uri)))) {
                stream->entity_id = s->index;
                stream->entity_module_id = s->module->index;
                stream->entity_loaded = true;

                pa_log_info("moving sink_input to alsa sink");
                pa_sink_input_move_to(i, s, false);
            } else {
                pa_log_info("failed to load alsa sink, closing 4A device");

                jparams = json_object_new_object();
                json_object_object_add(jparams, "action",
                                       json_object_new_string("close"));

                m4a_afb_call_async(d->comm, role, jparams,
                           (m4a_afb_done_cb_t) device_close_cb, stream);
                return PA_HOOK_CANCEL;
            }
        } else {
            pa_log_info("sink_input is not authorized to connect to 4A");
            //TODO maybe queue and play this stream when 4A allows it

            m4a_stream_free(stream);
            return PA_HOOK_CANCEL;
        }
    }

    return PA_HOOK_OK;
}

static pa_hook_result_t sink_input_unlink_post_cb(pa_core *core,
                                                  pa_sink_input *i,
                                                  pa_module *self) {
    m4a_data *d = self->userdata;
    m4a_stream *stream = NULL;
    json_object *jparams;

    PA_LLIST_FOREACH(stream, d->streams) {
        if (stream->sink_input == i)
            break;
    }

    if (stream && stream->sink_input == i) {
        pa_log_debug("unloading module-alsa-sink (%s)", stream->role);

        pa_module_unload_by_index(stream->self->core,
                                  stream->entity_module_id, false);
        stream->entity_loaded = false;

        jparams = json_object_new_object();
        json_object_object_add(jparams, "action", json_object_new_string("close"));

        m4a_afb_call_async(d->comm, stream->role, jparams,
                        (m4a_afb_done_cb_t) device_close_cb, stream);
    }

    return PA_HOOK_OK;
}

void pa__done(pa_module *self) {
    m4a_data *d;

    pa_assert(self);

    d = self->userdata;

    while (d->streams)
        m4a_stream_free(d->streams);

    pa_dynarray_free(d->roles);
    pa_mutex_free(d->lock);

    if (d->ma)
        pa_modargs_free(d->ma);

    if (d->sink_input_put_slot)
        pa_hook_slot_free(d->sink_input_put_slot);
    if (d->sink_input_unlink_post_slot)
        pa_hook_slot_free(d->sink_input_unlink_post_slot);

    if (d->comm)
        m4a_afb_comm_free(d->comm);
}

int pa__init(pa_module *self) {
    m4a_data *d;
    const char *uri;

    pa_assert(self);

    self->userdata = d = pa_xnew0(m4a_data, 1);
    d->roles = pa_dynarray_new(pa_xfree);
    d->lock = pa_mutex_new(false, false);

    if (!(d->ma = pa_modargs_new(self->argument, valid_modargs))) {
        pa_log("Failed to parse module arguments");
        goto fail;
    }

    uri = pa_modargs_get_value(d->ma, "uri", DEFAULT_URI);
    if (!(d->comm = m4a_afb_comm_new(uri))) {
        goto fail;
    }

    if (!m4a_afb_call_async(d->comm, "get_roles", NULL,
                            (m4a_afb_done_cb_t) got_roles_cb, self)) {
        goto fail;
    }

    d->sink_input_put_slot = pa_hook_connect(&self->core->hooks[PA_CORE_HOOK_SINK_INPUT_PUT],
            PA_HOOK_NORMAL, (pa_hook_cb_t) sink_input_put_cb, self);
    d->sink_input_unlink_post_slot = pa_hook_connect(&self->core->hooks[PA_CORE_HOOK_SINK_INPUT_UNLINK_POST],
            PA_HOOK_NORMAL, (pa_hook_cb_t) sink_input_unlink_post_cb, self);
    return 0;

fail:
    pa__done(self);
    return -1;
}