summaryrefslogtreecommitdiffstats
path: root/src/modules/module-jack-sink.c
blob: c6a7e33f07e2efe93dbc92be7be71ecc9944c5c7 (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
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
/* $Id$ */

/***
  This file is part of PulseAudio.

  Copyright 2006 Lennart Poettering

  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 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, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  USA.
***/

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

#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <pthread.h>

#include <jack/jack.h>

#include <pulse/xmalloc.h>

#include <pulsecore/core-error.h>
#include <pulsecore/iochannel.h>
#include <pulsecore/sink.h>
#include <pulsecore/module.h>
#include <pulsecore/core-util.h>
#include <pulsecore/modargs.h>
#include <pulsecore/log.h>
#include <pulse/mainloop-api.h>

#include "module-jack-sink-symdef.h"

PA_MODULE_AUTHOR("Lennart Poettering")
PA_MODULE_DESCRIPTION("Jack Sink")
PA_MODULE_VERSION(PACKAGE_VERSION)
PA_MODULE_USAGE(
        "sink_name=<name of sink> "
        "server_name=<jack server name> "
        "client_name=<jack client name> "
        "channels=<number of channels> "
        "connect=<connect ports?> "
        "channel_map=<channel map>")

#define DEFAULT_SINK_NAME "jack_out"

struct userdata {
    pa_core *core;
    pa_module *module;

    pa_sink *sink;

    unsigned channels;

    jack_port_t* port[PA_CHANNELS_MAX];
    jack_client_t *client;

    pthread_mutex_t mutex;
    pthread_cond_t cond;

    void * buffer[PA_CHANNELS_MAX];
    jack_nframes_t frames_requested;
    int quit_requested;

    int pipe_fd_type;
    int pipe_fds[2];
    pa_io_event *io_event;

    jack_nframes_t frames_in_buffer;
    jack_nframes_t timestamp;
};

static const char* const valid_modargs[] = {
    "sink_name",
    "server_name",
    "client_name",
    "channels",
    "connect",
    "channel_map",
    NULL
};

static void stop_sink(struct userdata *u) {
    assert (u);

    jack_client_close(u->client);
    u->client = NULL;
    u->core->mainloop->io_free(u->io_event);
    u->io_event = NULL;
    pa_sink_disconnect(u->sink);
    pa_sink_unref(u->sink);
    u->sink = NULL;
    pa_module_unload_request(u->module);
}

static void io_event_cb(pa_mainloop_api *m, pa_io_event *e, int fd, pa_io_event_flags_t flags, void *userdata) {
    struct userdata *u = userdata;
    char x;

    assert(m);
    assert(e);
    assert(flags == PA_IO_EVENT_INPUT);
    assert(u);
    assert(u->pipe_fds[0] == fd);

    pa_read(fd, &x, 1, &u->pipe_fd_type);

    if (u->quit_requested) {
        stop_sink(u);
        u->quit_requested = 0;
        return;
    }

    pthread_mutex_lock(&u->mutex);

    if (u->frames_requested > 0) {
        unsigned fs;
        jack_nframes_t frame_idx;
        pa_memchunk chunk;

        fs = pa_frame_size(&u->sink->sample_spec);

        pa_sink_render_full(u->sink, u->frames_requested * fs, &chunk);

        for (frame_idx = 0; frame_idx < u->frames_requested; frame_idx ++) {
            unsigned c;

            for (c = 0; c < u->channels; c++) {
                float *s = ((float*) ((uint8_t*) chunk.memblock->data + chunk.index)) + (frame_idx * u->channels) + c;
                float *d = ((float*) u->buffer[c]) + frame_idx;

                *d = *s;
            }
        }

        pa_memblock_unref(chunk.memblock);

        u->frames_requested = 0;

        pthread_cond_signal(&u->cond);
    }

    pthread_mutex_unlock(&u->mutex);
}

static void request_render(struct userdata *u) {
    char c = 'x';
    assert(u);

    assert(u->pipe_fds[1] >= 0);
    pa_write(u->pipe_fds[1], &c, 1, &u->pipe_fd_type);
}

static void jack_shutdown(void *arg) {
    struct userdata *u = arg;
    assert(u);

    u->quit_requested = 1;
    request_render(u);
}

static int jack_process(jack_nframes_t nframes, void *arg) {
    struct userdata *u = arg;
    assert(u);

    if (jack_transport_query(u->client, NULL) == JackTransportRolling) {
        unsigned c;

        pthread_mutex_lock(&u->mutex);

        u->frames_requested = nframes;

        for (c = 0; c < u->channels; c++) {
            u->buffer[c] = jack_port_get_buffer(u->port[c], nframes);
            assert(u->buffer[c]);
        }

        request_render(u);

        pthread_cond_wait(&u->cond, &u->mutex);

        u->frames_in_buffer = nframes;
        u->timestamp = jack_get_current_transport_frame(u->client);

        pthread_mutex_unlock(&u->mutex);
    }

    return 0;
}

static pa_usec_t sink_get_latency_cb(pa_sink *s) {
    struct userdata *u;
    jack_nframes_t n, l, d;

    assert(s);
    u = s->userdata;

    if (jack_transport_query(u->client, NULL) != JackTransportRolling)
        return 0;

    n = jack_get_current_transport_frame(u->client);

    if (n < u->timestamp)
        return 0;

    d = n - u->timestamp;
    l = jack_port_get_total_latency(u->client, u->port[0]) + u->frames_in_buffer;

    if (d >= l)
        return 0;

    return pa_bytes_to_usec((l - d) * pa_frame_size(&s->sample_spec), &s->sample_spec);
}

static void jack_error_func(const char*t) {
    pa_log_warn("JACK error >%s<", t);
}

int pa__init(pa_core *c, pa_module*m) {
    struct userdata *u = NULL;
    pa_sample_spec ss;
    pa_channel_map map;
    pa_modargs *ma = NULL;
    jack_status_t status;
    const char *server_name, *client_name;
    uint32_t channels = 0;
    int do_connect = 1;
    unsigned i;
    const char **ports = NULL, **p;
    char *t;

    assert(c);
    assert(m);

    jack_set_error_function(jack_error_func);

    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
        pa_log("failed to parse module arguments.");
        goto fail;
    }

    if (pa_modargs_get_value_boolean(ma, "connect", &do_connect) < 0) {
        pa_log("failed to parse connect= argument.");
        goto fail;
    }

    server_name = pa_modargs_get_value(ma, "server_name", NULL);
    client_name = pa_modargs_get_value(ma, "client_name", "PulseAudio");

    u = pa_xnew0(struct userdata, 1);
    m->userdata = u;
    u->core = c;
    u->module = m;
    u->pipe_fds[0] = u->pipe_fds[1] = -1;
    u->pipe_fd_type = 0;

    pthread_mutex_init(&u->mutex, NULL);
    pthread_cond_init(&u->cond, NULL);

    if (pipe(u->pipe_fds) < 0) {
        pa_log("pipe() failed: %s", pa_cstrerror(errno));
        goto fail;
    }

    pa_make_nonblock_fd(u->pipe_fds[1]);

    if (!(u->client = jack_client_open(client_name, server_name ? JackServerName : JackNullOption, &status, server_name))) {
        pa_log("jack_client_open() failed.");
        goto fail;
    }

    ports = jack_get_ports(u->client, NULL, NULL, JackPortIsPhysical|JackPortIsInput);

    channels = 0;
    for (p = ports; *p; p++)
        channels++;

    if (!channels)
        channels = c->default_sample_spec.channels;

    if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 || channels <= 0 || channels >= PA_CHANNELS_MAX) {
        pa_log("failed to parse channels= argument.");
        goto fail;
    }

    pa_channel_map_init_auto(&map, channels, PA_CHANNEL_MAP_ALSA);
    if (pa_modargs_get_channel_map(ma, &map) < 0 || map.channels != channels) {
        pa_log("failed to parse channel_map= argument.");
        goto fail;
    }

    pa_log_info("Successfully connected as '%s'", jack_get_client_name(u->client));

    ss.channels = u->channels = channels;
    ss.rate = jack_get_sample_rate(u->client);
    ss.format = PA_SAMPLE_FLOAT32NE;

    assert(pa_sample_spec_valid(&ss));

    for (i = 0; i < ss.channels; i++) {
        if (!(u->port[i] = jack_port_register(u->client, pa_channel_position_to_string(map.map[i]), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput|JackPortIsTerminal, 0))) {
            pa_log("jack_port_register() failed.");
            goto fail;
        }
    }

    if (!(u->sink = pa_sink_new(c, __FILE__, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME), 0, &ss, &map))) {
        pa_log("failed to create sink.");
        goto fail;
    }

    u->sink->userdata = u;
    pa_sink_set_owner(u->sink, m);
    pa_sink_set_description(u->sink, t = pa_sprintf_malloc("Jack sink (%s)", jack_get_client_name(u->client)));
    pa_xfree(t);
    u->sink->get_latency = sink_get_latency_cb;

    jack_set_process_callback(u->client, jack_process, u);
    jack_on_shutdown(u->client, jack_shutdown, u);

    if (jack_activate(u->client)) {
        pa_log("jack_activate() failed");
        goto fail;
    }

    if (do_connect) {
        for (i = 0, p = ports; i < ss.channels; i++, p++) {

            if (!*p) {
                pa_log("not enough physical output ports, leaving unconnected.");
                break;
            }

            pa_log_info("connecting %s to %s", jack_port_name(u->port[i]), *p);

            if (jack_connect(u->client, jack_port_name(u->port[i]), *p)) {
                pa_log("failed to connect %s to %s, leaving unconnected.", jack_port_name(u->port[i]), *p);
                break;
            }
        }

    }

    u->io_event = c->mainloop->io_new(c->mainloop, u->pipe_fds[0], PA_IO_EVENT_INPUT, io_event_cb, u);

    free(ports);
    pa_modargs_free(ma);

    return 0;

fail:
    if (ma)
        pa_modargs_free(ma);

    free(ports);

    pa__done(c, m);

    return -1;
}

void pa__done(pa_core *c, pa_module*m) {
    struct userdata *u;
    assert(c && m);

    if (!(u = m->userdata))
        return;

    if (u->client)
        jack_client_close(u->client);

    if (u->io_event)
        c->mainloop->io_free(u->io_event);

    if (u->sink) {
        pa_sink_disconnect(u->sink);
        pa_sink_unref(u->sink);
    }

    if (u->pipe_fds[0] >= 0)
        close(u->pipe_fds[0]);
    if (u->pipe_fds[1] >= 0)
        close(u->pipe_fds[1]);

    pthread_mutex_destroy(&u->mutex);
    pthread_cond_destroy(&u->cond);
    pa_xfree(u);
}