]> git.ipfire.org Git - thirdparty/shairport-sync.git/blame - audio_jack.c
Declare all JACK callbacks static (they are accessed via function pointers only).
[thirdparty/shairport-sync.git] / audio_jack.c
CommitLineData
8cabb16f
MB
1/*
2 * jack output driver. This file is part of Shairport Sync.
3 * Copyright (c) 2018 Mike Brady <mikebrady@iercom.net>
4 *
5 * All rights reserved.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include "audio.h"
21#include "common.h"
22#include <errno.h>
23#include <getopt.h>
24#include <limits.h>
25#include <math.h>
26#include <pthread.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
8cabb16f
MB
30#include <unistd.h>
31
32#include <jack/jack.h>
33#include <jack/transport.h>
f07c16a6 34#include <jack/ringbuffer.h>
8cabb16f
MB
35
36enum ift_type {
37 IFT_frame_left_sample = 0,
38 IFT_frame_right_sample,
39} ift_type;
40
e99837f8
JN
41// Two-channel, 16bit audio:
42static const int bytes_per_frame = 4;
8cabb16f 43// Four seconds buffer -- should be plenty
120e95fc 44#define buffer_size (44100 * 4 * bytes_per_frame)
8cabb16f
MB
45
46static pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
6c6dda9c 47static pthread_mutex_t client_mutex = PTHREAD_MUTEX_INITIALIZER;
8cabb16f 48
6c6dda9c
MB
49pthread_t *open_client_if_necessary_thread = NULL;
50
c1d5815c 51int jack_init(int, char **);
959aa08b 52void jack_deinit(void);
8cabb16f
MB
53void jack_start(int, int);
54int play(void *, int);
55void jack_stop(void);
56int jack_is_running(void);
8cabb16f
MB
57int jack_delay(long *);
58void jack_flush(void);
59
60audio_output audio_jack = {.name = "jack",
61 .help = NULL,
c1d5815c 62 .init = &jack_init,
959aa08b 63 .deinit = &jack_deinit,
8cabb16f
MB
64 .start = &jack_start,
65 .stop = &jack_stop,
66 .is_running = &jack_is_running,
67 .flush = &jack_flush,
68 .delay = &jack_delay,
69 .play = &play,
70 .volume = NULL,
71 .parameters = NULL,
72 .mute = NULL};
73
8cabb16f
MB
74jack_port_t *left_port;
75jack_port_t *right_port;
959aa08b 76
8cabb16f 77long offset = 0;
8cabb16f
MB
78
79int client_is_open;
80jack_client_t *client;
81jack_nframes_t sample_rate;
c1d5815c 82jack_nframes_t jack_latency;
8cabb16f 83
f07c16a6 84static jack_ringbuffer_t *jackbuf;
e99837f8 85static int flush_please = 0;
f07c16a6 86
39545cdf 87jack_latency_range_t latest_left_latency_range, latest_right_latency_range;
959aa08b 88int64_t time_of_latest_transfer;
8cabb16f
MB
89
90int play(void *buf, int samples) {
91 // debug(1,"jack_play of %d samples.",samples);
92 // copy the samples into the queue
e99837f8
JN
93 size_t bytes_to_transfer, bytes_transferred;
94 bytes_to_transfer = samples * bytes_per_frame;
95 pthread_mutex_lock(&buffer_mutex); // it's ok to lock here since we're not in the realtime callback
96 bytes_transferred = jack_ringbuffer_write(jackbuf, buf, bytes_to_transfer);
7ab56696
JN
97 // semantics change: we now measure the last time audio was moved into the ringbuffer, not the jack output buffers.
98 time_of_latest_transfer = get_absolute_time_in_fp();
e99837f8
JN
99 pthread_mutex_unlock(&buffer_mutex);
100 if (bytes_transferred < bytes_to_transfer) {
101 debug(1, "JACK ringbuffer overrun. Only wrote %d of %d bytes.", bytes_transferred, bytes_to_transfer);
102 }
8cabb16f
MB
103 return 0;
104}
105
e99837f8
JN
106static inline jack_default_audio_sample_t sample_conv(short sample) {
107 return ((sample < 0) ? (-1.0 * sample / SHRT_MIN) : (1.0 * sample / SHRT_MAX));
108}
109
a3201ff2
JN
110static void deinterleave_and_convert(const char *interleaved_frames,
111 jack_default_audio_sample_t * const jack_buffer_left,
112 jack_default_audio_sample_t * const jack_buffer_right,
113 jack_nframes_t nframes) {
e99837f8
JN
114 jack_nframes_t i;
115 short *ifp = (short *)interleaved_frames; // we're dealing with 16bit audio here
116 jack_default_audio_sample_t *fpl = jack_buffer_left;
117 jack_default_audio_sample_t *fpr = jack_buffer_right;
118 for (i=0; i<nframes; i++) {
119 fpl[i] = sample_conv(*ifp++);
120 fpr[i] = sample_conv(*ifp++);
121 }
122}
123
91a8553a 124static int jack_stream_write_cb(jack_nframes_t nframes, __attribute__((unused)) void *arg) {
8cabb16f 125
959aa08b
MB
126 jack_default_audio_sample_t *left_buffer =
127 (jack_default_audio_sample_t *)jack_port_get_buffer(left_port, nframes);
128 jack_default_audio_sample_t *right_buffer =
129 (jack_default_audio_sample_t *)jack_port_get_buffer(right_port, nframes);
8cabb16f 130
e99837f8
JN
131 jack_ringbuffer_data_t v[2] = { 0 };
132 jack_nframes_t i, thisbuf;
133 int frames_written = 0;
134 int frames_required = 0;
135
83c8857c 136 if (flush_please) {
6104c580 137 // we just move the read pointer ahead without doing anything with the data.
83c8857c 138 jack_ringbuffer_read_advance(jackbuf, jack_ringbuffer_read_space(jackbuf));
3e6ef019 139 flush_please = 0;
6104c580 140 // since we don't change nframes, the whole buffer will be zeroed later.
83c8857c
JN
141 } else {
142 jack_ringbuffer_get_read_vector(jackbuf, v); // an array of two elements because of possible ringbuffer wrap-around
143 for (i=0; i<2; i++) {
144 thisbuf = v[i].len / bytes_per_frame;
145 if (thisbuf > nframes) {
146 frames_required = nframes;
147 } else {
148 frames_required = thisbuf;
149 }
150 deinterleave_and_convert(v[i].buf, &left_buffer[frames_written], &right_buffer[frames_written], frames_required);
23d4ec2b
JN
151 frames_written += frames_required;
152 nframes -= frames_required;
e99837f8 153 }
83c8857c 154 jack_ringbuffer_read_advance(jackbuf, frames_written * bytes_per_frame);
e99837f8 155 }
e99837f8
JN
156 // now, if there are any more frames to put into the buffer, fill them with
157 // silence
158 while (nframes > 0) {
159 left_buffer[frames_written] = 0.0;
160 right_buffer[frames_written] = 0.0;
161 frames_written++;
162 nframes--;
163 }
8cabb16f
MB
164 return 0;
165}
166
e99837f8
JN
167// FIXME: set_graph_order_callback(), recompute latencies here!
168
91a8553a 169static void default_jack_error_callback(const char *desc) { debug(2, "jackd error: \"%s\"", desc); }
8cabb16f 170
91a8553a 171static void default_jack_info_callback(const char *desc) { inform("jackd information: \"%s\"", desc); }
8cabb16f
MB
172
173int jack_is_running() {
76138873 174 int reply = -1; // meaning jack is not running
8cabb16f 175 if (client_is_open) {
76138873
MB
176
177 // check if the ports have a zero latency -- if they both have, then it's disconnected.
178
83472239
JN
179 // FIXME: this causes a segfault when shairport-sync is exited with CTRL-C, because
180 // the client_is_open flag is stale by then. Also, this test is not necessary.
181 // shairport-sync should not worry what's reading its ports. As long as jack is alive,
182 // deliver audio, even if nothing is connected. This behaviour probably stems from
183 // the wish to not hog an audio device if not needed, which is no longer an issue with
184 // jack. Moreover, don't "conserve" CPU this way, because in a realtime system you want
185 // deterministic CPU load more than anything else.
186 // jack_latency_range_t left_latency_range, right_latency_range;
187 // jack_port_get_latency_range(left_port, JackPlaybackLatency, &left_latency_range);
188 // jack_port_get_latency_range(right_port, JackPlaybackLatency, &right_latency_range);
76138873 189
c1d5815c
MB
190 // if ((left_latency_range.min == 0) && (left_latency_range.max == 0) &&
191 // (right_latency_range.min == 0) && (right_latency_range.max == 0)) {
192 // reply = -2; // meaning Shairport Sync is not connected
193 // } else {
83472239
JN
194
195 // FIXME: For now, we assume JACK is always running, as it should.
196 // Still need to understand why shairport-sync needs this function.
c1d5815c
MB
197 reply = 0; // meaning jack is open and Shairport Sync is connected to it
198 // }
8cabb16f
MB
199 }
200 return reply;
201}
202
9520e891 203static int jack_client_open_if_needed(void) {
6c6dda9c 204 pthread_mutex_lock(&client_mutex);
959aa08b
MB
205 if (client_is_open == 0) {
206 jack_status_t status;
207 client = jack_client_open(config.jack_client_name, JackNoStartServer, &status);
208 if (client) {
209 jack_set_process_callback(client, jack_stream_write_cb, 0);
210 left_port = jack_port_register(client, config.jack_left_channel_name, JACK_DEFAULT_AUDIO_TYPE,
211 JackPortIsOutput, 0);
212 right_port = jack_port_register(client, config.jack_right_channel_name,
213 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
214 sample_rate = jack_get_sample_rate(client);
215 // debug(1, "jackaudio sample rate = %" PRId32 ".", sample_rate);
216 if (sample_rate == 44100) {
c1d5815c
MB
217 if (jack_activate(client)) {
218 debug(1, "jackaudio cannot activate client");
219 } else {
220 debug(2, "jackaudio client opened.");
221 client_is_open = 1;
222 }
959aa08b
MB
223 } else {
224 inform(
225 "jackaudio is running at the wrong speed (%d) for Shairport Sync, which must be 44100",
226 sample_rate);
227 }
228 }
229 }
6c6dda9c 230 pthread_mutex_unlock(&client_mutex);
959aa08b
MB
231 return client_is_open;
232}
233
9520e891 234static void jack_close(void) {
6c6dda9c 235 pthread_mutex_lock(&client_mutex);
959aa08b
MB
236 if (client_is_open) {
237 if (jack_deactivate(client))
238 debug(1, "Error deactivating jack client");
239 if (jack_client_close(client))
240 debug(1, "Error closing jack client");
6c6dda9c
MB
241 client_is_open = 0;
242 }
243 pthread_mutex_unlock(&client_mutex);
244}
245
246void jack_deinit() {
247 jack_close();
248 if (open_client_if_necessary_thread) {
249 pthread_cancel(*open_client_if_necessary_thread);
250 free((char *)open_client_if_necessary_thread);
f07c16a6
JN
251
252 jack_ringbuffer_free(jackbuf);
253
959aa08b
MB
254 }
255}
256
9520e891 257static void *open_client_if_necessary_thread_function(void *arg) {
6c6dda9c
MB
258 int *interval = (int *)arg;
259 while (*interval != 0) {
260 if (client_is_open == 0) {
261 debug(1, "Try to open the jack client");
262 jack_client_open_if_needed();
263 }
264 sleep(*interval);
39545cdf 265 }
6c6dda9c
MB
266 pthread_exit(NULL);
267}
268
c1d5815c 269int jack_init(__attribute__((unused)) int argc, __attribute__((unused)) char **argv) {
8cabb16f 270 config.audio_backend_latency_offset = 0;
76138873 271 config.audio_backend_buffer_desired_length = 0.500;
80f15e1f
MB
272 config.audio_backend_buffer_interpolation_threshold_in_seconds =
273 0.25; // below this, soxr interpolation will not occur -- it'll be basic interpolation
274 // instead.
6c6dda9c 275 config.jack_auto_client_open_interval = 1; // check every second
8cabb16f
MB
276
277 // get settings from settings file first, allow them to be overridden by
278 // command line options
279
280 // do the "general" audio options. Note, these options are in the "general" stanza!
281 parse_general_audio_options();
959aa08b 282
8cabb16f
MB
283 // other options would be picked up here...
284
959aa08b
MB
285 // now the specific options
286 if (config.cfg != NULL) {
287 const char *str;
6c6dda9c 288 int value;
959aa08b
MB
289 /* Get the Client Name. */
290 if (config_lookup_string(config.cfg, "jack.client_name", &str)) {
291 config.jack_client_name = (char *)str;
292 }
293 /* Get the Left Channel Name. */
294 if (config_lookup_string(config.cfg, "jack.left_channel_name", &str)) {
295 config.jack_left_channel_name = (char *)str;
296 }
297 /* Get the Right Channel Name. */
298 if (config_lookup_string(config.cfg, "jack.right_channel_name", &str)) {
299 config.jack_right_channel_name = (char *)str;
300 }
39545cdf
MB
301
302 /* See if we should attempt to connect to the jack server automatically, and, if so, how often
303 * we should try. */
6c6dda9c
MB
304 if (config_lookup_int(config.cfg, "jack.auto_client_open_interval", &value)) {
305 if ((value < 0) || (value > 300))
2e442853
MB
306 debug(1,
307 "Invalid jack auto_client_open_interval \"%sd\". It should be between 0 and 300, "
308 "default is %d.",
76138873 309 value, config.jack_auto_client_open_interval);
6c6dda9c
MB
310 else
311 config.jack_auto_client_open_interval = value;
312 }
313
314 /* See if we should close the client at then end of a play session. */
39545cdf
MB
315 config_set_lookup_bool(config.cfg, "jack.auto_client_disconnect",
316 &config.jack_auto_client_disconnect);
959aa08b
MB
317 }
318
319 if (config.jack_client_name == NULL)
320 config.jack_client_name = strdup("Shairport Sync");
321 if (config.jack_left_channel_name == NULL)
322 config.jack_left_channel_name = strdup("left");
323 if (config.jack_right_channel_name == NULL)
324 config.jack_right_channel_name = strdup("right");
325
aefd7cdb 326 jackbuf = jack_ringbuffer_create(buffer_size);
06504516
JN
327 if (jackbuf == NULL)
328 die("Can't allocate %d bytes for the JACK ringbuffer.", buffer_size);
f07c16a6
JN
329 jack_ringbuffer_mlock(jackbuf); // lock buffer into memory so that it never gets paged out
330
959aa08b 331 jack_set_error_function(default_jack_error_callback);
8cabb16f 332 jack_set_info_function(default_jack_info_callback);
8cabb16f 333
959aa08b 334 client_is_open = 0;
39545cdf 335
175d91a4 336 // now, if selected, start a thread to automatically open a client when there is a server.
6c6dda9c
MB
337 if (config.jack_auto_client_open_interval != 0) {
338 open_client_if_necessary_thread = malloc(sizeof(pthread_t));
175d91a4 339 if (open_client_if_necessary_thread == NULL) {
76138873 340 debug(1, "Couldn't allocate space for jack server scanner thread");
175d91a4
MB
341 jack_client_open_if_needed();
342 } else {
76138873
MB
343 pthread_create(open_client_if_necessary_thread, NULL,
344 open_client_if_necessary_thread_function,
345 &config.jack_auto_client_open_interval);
175d91a4 346 }
6c6dda9c
MB
347 } else {
348 jack_client_open_if_needed();
349 }
959aa08b 350
8cabb16f
MB
351 return 0;
352}
353
959aa08b
MB
354void jack_start(__attribute__((unused)) int i_sample_rate,
355 __attribute__((unused)) int i_sample_format) {
6c6dda9c 356 // debug(1, "jack start");
959aa08b
MB
357 // see if the client is running. If not, try to open and initialise it
358
359 if (jack_client_open_if_needed() == 0)
360 debug(1, "cannot open a jack client for a play session");
8cabb16f
MB
361}
362
363int jack_delay(long *the_delay) {
39545cdf 364
7ab56696
JN
365 // semantics change: we now look at the last transfer into the lock-free ringbuffer, not
366 // into the jack buffers directly (because locking those would violate real-time constraints).
367 // on average, that should lead to just a constant additional latency. the old comment still applies:
368
959aa08b 369 // without the mutex, we could get the time of what is the last transfer of data to a jack buffer,
39545cdf
MB
370 // but then a transfer could occur and we would get the buffer occupancy after another transfer
371 // had occurred
372 // so we could "lose" a full transfer (e.g. 1024 frames @ 44,100 fps ~ 23.2 milliseconds)
e99837f8 373
39545cdf 374 pthread_mutex_lock(&buffer_mutex);
e99837f8
JN
375 int64_t time_now = get_absolute_time_in_fp();
376 // this is the time back to the last time data
377 // was transferred into a jack buffer
378 int64_t delta = time_now - time_of_latest_transfer;
379 // this is the buffer occupancy before any
380 // subsequent transfer because transfer is blocked
381 // by the mutex
a238ac54 382 size_t audio_occupancy_now = jack_ringbuffer_read_space(jackbuf) / bytes_per_frame;
d7c7365b 383 // debug(1, "audio_occupancy_now is %d.", audio_occupancy_now);
959aa08b
MB
384 pthread_mutex_unlock(&buffer_mutex);
385
8cabb16f 386 int64_t frames_processed_since_latest_latency_check = (delta * 44100) >> 32;
9c57fe43
JN
387
388 // FIXME: this should only be done if there was an actual change, i.e. on the jack graph reorder
389 // callback, to update a static variable which can be checked here. For now, use a fixed arbitrary value:
390 jack_nframes_t base_latency = 0;
391
8cabb16f 392 // debug(1,"delta: %" PRId64 " frames.",frames_processed_since_latest_latency_check);
9c57fe43
JN
393
394 // jack_nframes_t base_latency = (latest_left_latency_range.min + latest_left_latency_range.max) / 2;
395 // if (base_latency == 0)
396 // base_latency = (latest_right_latency_range.min + latest_right_latency_range.max) / 2;
39545cdf 397 *the_delay = base_latency + audio_occupancy_now - frames_processed_since_latest_latency_check;
d7c7365b 398 // debug(1,"reporting a delay of %d frames",*the_delay);
8cabb16f
MB
399 return 0;
400}
401
402void jack_flush() {
d7c7365b 403 // debug(1, "Only the consumer can safely flush a lock-free ringbuffer. Asking the process callback to do it...");
e99837f8 404 flush_please = 1;
8cabb16f
MB
405}
406
6c6dda9c
MB
407void jack_stop(void) {
408 // debug(1, "jack stop");
409 if (config.jack_auto_client_disconnect)
410 jack_close();
aa5698fc 411}