]> git.ipfire.org Git - thirdparty/shairport-sync.git/blame - audio_jack.c
remove some debugging code from delay().
[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>
30#include <string.h>
31#include <unistd.h>
32
33#include <jack/jack.h>
34#include <jack/transport.h>
35
36enum ift_type {
37 IFT_frame_left_sample = 0,
38 IFT_frame_right_sample,
39} ift_type;
40
41// Four seconds buffer -- should be plenty
42#define buffer_size 44100 * 4 * 2 * 2
43
44static pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
6c6dda9c 45static pthread_mutex_t client_mutex = PTHREAD_MUTEX_INITIALIZER;
8cabb16f
MB
46
47char *audio_lmb, *audio_umb, *audio_toq, *audio_eoq;
48size_t audio_occupancy; // this is in frames, not bytes. A frame is a left and
49 // right sample, each 16 bits, hence 4 bytes
6c6dda9c
MB
50pthread_t *open_client_if_necessary_thread = NULL;
51
c1d5815c 52int jack_init(int, char **);
959aa08b 53void jack_deinit(void);
8cabb16f
MB
54void jack_start(int, int);
55int play(void *, int);
56void jack_stop(void);
57int jack_is_running(void);
8cabb16f
MB
58int jack_delay(long *);
59void jack_flush(void);
60
61audio_output audio_jack = {.name = "jack",
62 .help = NULL,
c1d5815c 63 .init = &jack_init,
959aa08b 64 .deinit = &jack_deinit,
8cabb16f
MB
65 .start = &jack_start,
66 .stop = &jack_stop,
67 .is_running = &jack_is_running,
68 .flush = &jack_flush,
69 .delay = &jack_delay,
70 .play = &play,
71 .volume = NULL,
72 .parameters = NULL,
73 .mute = NULL};
74
8cabb16f
MB
75jack_port_t *left_port;
76jack_port_t *right_port;
959aa08b 77
8cabb16f 78long offset = 0;
8cabb16f
MB
79
80int client_is_open;
81jack_client_t *client;
82jack_nframes_t sample_rate;
c1d5815c 83jack_nframes_t jack_latency;
8cabb16f 84
39545cdf 85jack_latency_range_t latest_left_latency_range, latest_right_latency_range;
959aa08b 86int64_t time_of_latest_transfer;
8cabb16f
MB
87
88int play(void *buf, int samples) {
89 // debug(1,"jack_play of %d samples.",samples);
90 // copy the samples into the queue
91 size_t bytes_to_transfer = samples * 2 * 2;
92 size_t space_to_end_of_buffer = audio_umb - audio_eoq;
93 if (space_to_end_of_buffer >= bytes_to_transfer) {
94 memcpy(audio_eoq, buf, bytes_to_transfer);
95 pthread_mutex_lock(&buffer_mutex);
96 audio_occupancy += samples;
97 audio_eoq += bytes_to_transfer;
98 pthread_mutex_unlock(&buffer_mutex);
99 } else {
100 memcpy(audio_eoq, buf, space_to_end_of_buffer);
101 buf += space_to_end_of_buffer;
102 memcpy(audio_lmb, buf, bytes_to_transfer - space_to_end_of_buffer);
103 pthread_mutex_lock(&buffer_mutex);
104 audio_occupancy += samples;
105 audio_eoq = audio_lmb + bytes_to_transfer - space_to_end_of_buffer;
106 pthread_mutex_unlock(&buffer_mutex);
107 }
8cabb16f
MB
108 return 0;
109}
110
111void deinterleave_and_convert_stream(const char *interleaved_frames,
959aa08b 112 const jack_default_audio_sample_t *jack_frame_buffer,
8cabb16f
MB
113 jack_nframes_t number_of_frames, enum ift_type side) {
114 jack_nframes_t i;
115 short *ifp = (short *)interleaved_frames;
959aa08b 116 jack_default_audio_sample_t *fp = (jack_default_audio_sample_t *)jack_frame_buffer;
8cabb16f
MB
117 if (side == IFT_frame_right_sample)
118 ifp++;
119 for (i = 0; i < number_of_frames; i++) {
120 short sample = *ifp;
959aa08b 121 jack_default_audio_sample_t converted_value;
8cabb16f
MB
122 if (sample >= 0)
123 converted_value = (1.0 * sample) / SHRT_MAX;
124 else
125 converted_value = -(1.0 * sample) / SHRT_MIN;
126 *fp = converted_value;
127 ifp++;
128 ifp++;
129 fp++;
130 }
131}
132
133int jack_stream_write_cb(jack_nframes_t nframes, __attribute__((unused)) void *arg) {
134
959aa08b
MB
135 jack_default_audio_sample_t *left_buffer =
136 (jack_default_audio_sample_t *)jack_port_get_buffer(left_port, nframes);
137 jack_default_audio_sample_t *right_buffer =
138 (jack_default_audio_sample_t *)jack_port_get_buffer(right_port, nframes);
8cabb16f
MB
139
140 size_t frames_we_can_transfer = nframes;
141 // lock
142 pthread_mutex_lock(&buffer_mutex);
143 if (audio_occupancy < frames_we_can_transfer) {
144 frames_we_can_transfer = audio_occupancy;
175d91a4
MB
145 // This means we effectively have underflow from the Shairport Sync source.
146 // In fact, it may be that there is nothing at all coming from the source,
147 // but the Shairport Sync client is open and active, so it must continue to output something.
8cabb16f
MB
148 }
149
8cabb16f
MB
150 if (frames_we_can_transfer * 2 * 2 <= (size_t)(audio_umb - audio_toq)) {
151 // the bytes are all in a row in the audio buffer
152 deinterleave_and_convert_stream(audio_toq, &left_buffer[0], frames_we_can_transfer,
153 IFT_frame_left_sample);
154 deinterleave_and_convert_stream(audio_toq, &right_buffer[0], frames_we_can_transfer,
155 IFT_frame_right_sample);
156 audio_toq += frames_we_can_transfer * 2 * 2;
157 } else {
158 // the bytes are in two places in the audio buffer
159 size_t first_portion_to_write = (audio_umb - audio_toq) / (2 * 2);
160 if (first_portion_to_write != 0) {
161 deinterleave_and_convert_stream(audio_toq, &left_buffer[0], first_portion_to_write,
162 IFT_frame_left_sample);
163 deinterleave_and_convert_stream(audio_toq, &right_buffer[0], first_portion_to_write,
164 IFT_frame_right_sample);
165 }
166 deinterleave_and_convert_stream(audio_lmb, &left_buffer[first_portion_to_write],
167 frames_we_can_transfer - first_portion_to_write,
168 IFT_frame_left_sample);
169 deinterleave_and_convert_stream(audio_lmb, &right_buffer[first_portion_to_write],
170 frames_we_can_transfer - first_portion_to_write,
171 IFT_frame_right_sample);
172 audio_toq = audio_lmb + (frames_we_can_transfer - first_portion_to_write) * 2 * 2;
173 }
174 // debug(1,"transferring %u frames",frames_we_can_transfer);
175 audio_occupancy -= frames_we_can_transfer;
959aa08b
MB
176 jack_port_get_latency_range(left_port, JackPlaybackLatency, &latest_left_latency_range);
177 jack_port_get_latency_range(right_port, JackPlaybackLatency, &latest_right_latency_range);
178 time_of_latest_transfer = get_absolute_time_in_fp();
8cabb16f
MB
179 pthread_mutex_unlock(&buffer_mutex);
180 // unlock
959aa08b
MB
181
182 // now, if there are any more frames to put into the buffer, fill them with
8cabb16f
MB
183 // silence
184 jack_nframes_t i;
8cabb16f
MB
185 for (i = frames_we_can_transfer; i < nframes; i++) {
186 left_buffer[i] = 0.0;
187 right_buffer[i] = 0.0;
188 }
8cabb16f
MB
189 return 0;
190}
191
959aa08b 192void default_jack_error_callback(const char *desc) { debug(2, "jackd error: \"%s\"", desc); }
8cabb16f 193
959aa08b 194void default_jack_info_callback(const char *desc) { inform("jackd information: \"%s\"", desc); }
8cabb16f 195
c1d5815c
MB
196void default_jack_set_latency_callback(jack_latency_callback_mode_t mode,
197 __attribute__((unused)) void *arg) {
198 if (mode == JackPlaybackLatency) {
199 jack_latency_range_t left_latency_range, right_latency_range;
200 jack_port_get_latency_range(left_port, JackPlaybackLatency, &left_latency_range);
201 jack_port_get_latency_range(right_port, JackPlaybackLatency, &right_latency_range);
202
203 jack_nframes_t b_latency = (left_latency_range.min + left_latency_range.max) / 2;
204 if (b_latency == 0)
205 b_latency = (right_latency_range.min + right_latency_range.max) / 2;
206 // jack_latency = b_latency; // actually, we are not interested in the latency of the jack
207 // devices connected...
208 jack_latency = 0;
209 debug(1, "playback latency callback: %" PRIu32 ".", jack_latency);
210 }
211}
212
8cabb16f 213int jack_is_running() {
76138873 214 int reply = -1; // meaning jack is not running
8cabb16f
MB
215 // if the client is open and initialised, see if the status is "rolling"
216 if (client_is_open) {
76138873
MB
217
218 // check if the ports have a zero latency -- if they both have, then it's disconnected.
219
220 jack_latency_range_t left_latency_range, right_latency_range;
221 jack_port_get_latency_range(left_port, JackPlaybackLatency, &left_latency_range);
222 jack_port_get_latency_range(right_port, JackPlaybackLatency, &right_latency_range);
223
c1d5815c
MB
224 // if ((left_latency_range.min == 0) && (left_latency_range.max == 0) &&
225 // (right_latency_range.min == 0) && (right_latency_range.max == 0)) {
226 // reply = -2; // meaning Shairport Sync is not connected
227 // } else {
228 reply = 0; // meaning jack is open and Shairport Sync is connected to it
229 // }
8cabb16f
MB
230 }
231 return reply;
232}
233
959aa08b 234int jack_client_open_if_needed(void) {
6c6dda9c 235 pthread_mutex_lock(&client_mutex);
959aa08b
MB
236 if (client_is_open == 0) {
237 jack_status_t status;
238 client = jack_client_open(config.jack_client_name, JackNoStartServer, &status);
239 if (client) {
240 jack_set_process_callback(client, jack_stream_write_cb, 0);
241 left_port = jack_port_register(client, config.jack_left_channel_name, JACK_DEFAULT_AUDIO_TYPE,
242 JackPortIsOutput, 0);
243 right_port = jack_port_register(client, config.jack_right_channel_name,
244 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
245 sample_rate = jack_get_sample_rate(client);
246 // debug(1, "jackaudio sample rate = %" PRId32 ".", sample_rate);
247 if (sample_rate == 44100) {
c1d5815c
MB
248 if (jack_set_latency_callback(client, default_jack_set_latency_callback, NULL) == 0) {
249 if (jack_activate(client)) {
250 debug(1, "jackaudio cannot activate client");
251 } else {
252 debug(2, "jackaudio client opened.");
253 client_is_open = 1;
254 }
959aa08b 255 } else {
c1d5815c 256 debug(1, "jackaudio cannot set latency callback");
959aa08b
MB
257 }
258 } else {
259 inform(
260 "jackaudio is running at the wrong speed (%d) for Shairport Sync, which must be 44100",
261 sample_rate);
262 }
263 }
264 }
6c6dda9c 265 pthread_mutex_unlock(&client_mutex);
959aa08b
MB
266 return client_is_open;
267}
268
6c6dda9c
MB
269void jack_close(void) {
270 pthread_mutex_lock(&client_mutex);
959aa08b
MB
271 if (client_is_open) {
272 if (jack_deactivate(client))
273 debug(1, "Error deactivating jack client");
274 if (jack_client_close(client))
275 debug(1, "Error closing jack client");
6c6dda9c
MB
276 client_is_open = 0;
277 }
278 pthread_mutex_unlock(&client_mutex);
279}
280
281void jack_deinit() {
282 jack_close();
283 if (open_client_if_necessary_thread) {
284 pthread_cancel(*open_client_if_necessary_thread);
285 free((char *)open_client_if_necessary_thread);
959aa08b
MB
286 }
287}
288
6c6dda9c
MB
289void *open_client_if_necessary_thread_function(void *arg) {
290 int *interval = (int *)arg;
291 while (*interval != 0) {
292 if (client_is_open == 0) {
293 debug(1, "Try to open the jack client");
294 jack_client_open_if_needed();
295 }
296 sleep(*interval);
39545cdf 297 }
6c6dda9c
MB
298 pthread_exit(NULL);
299}
300
c1d5815c 301int jack_init(__attribute__((unused)) int argc, __attribute__((unused)) char **argv) {
8cabb16f 302 config.audio_backend_latency_offset = 0;
76138873 303 config.audio_backend_buffer_desired_length = 0.500;
5e38fcd5 304 config.audio_backend_buffer_interpolation_threshold_in_seconds = 0.25; // below this, soxr interpolation will not occur -- it'll be basic interpolation instead.
6c6dda9c 305 config.jack_auto_client_open_interval = 1; // check every second
8cabb16f
MB
306
307 // get settings from settings file first, allow them to be overridden by
308 // command line options
309
310 // do the "general" audio options. Note, these options are in the "general" stanza!
311 parse_general_audio_options();
959aa08b 312
8cabb16f
MB
313 // other options would be picked up here...
314
959aa08b
MB
315 // now the specific options
316 if (config.cfg != NULL) {
317 const char *str;
6c6dda9c 318 int value;
959aa08b
MB
319 /* Get the Client Name. */
320 if (config_lookup_string(config.cfg, "jack.client_name", &str)) {
321 config.jack_client_name = (char *)str;
322 }
323 /* Get the Left Channel Name. */
324 if (config_lookup_string(config.cfg, "jack.left_channel_name", &str)) {
325 config.jack_left_channel_name = (char *)str;
326 }
327 /* Get the Right Channel Name. */
328 if (config_lookup_string(config.cfg, "jack.right_channel_name", &str)) {
329 config.jack_right_channel_name = (char *)str;
330 }
39545cdf
MB
331
332 /* See if we should attempt to connect to the jack server automatically, and, if so, how often
333 * we should try. */
6c6dda9c
MB
334 if (config_lookup_int(config.cfg, "jack.auto_client_open_interval", &value)) {
335 if ((value < 0) || (value > 300))
76138873
MB
336 debug(1, "Invalid jack auto_client_open_interval \"%sd\". It should be between 0 and 300, "
337 "default is %d.",
338 value, config.jack_auto_client_open_interval);
6c6dda9c
MB
339 else
340 config.jack_auto_client_open_interval = value;
341 }
342
343 /* See if we should close the client at then end of a play session. */
39545cdf
MB
344 config_set_lookup_bool(config.cfg, "jack.auto_client_disconnect",
345 &config.jack_auto_client_disconnect);
959aa08b
MB
346 }
347
348 if (config.jack_client_name == NULL)
349 config.jack_client_name = strdup("Shairport Sync");
350 if (config.jack_left_channel_name == NULL)
351 config.jack_left_channel_name = strdup("left");
352 if (config.jack_right_channel_name == NULL)
353 config.jack_right_channel_name = strdup("right");
354
355 jack_set_error_function(default_jack_error_callback);
8cabb16f 356 jack_set_info_function(default_jack_info_callback);
8cabb16f
MB
357
358 // allocate space for the audio buffer
359 audio_lmb = malloc(buffer_size);
360 if (audio_lmb == NULL)
361 die("Can't allocate %d bytes for jackaudio buffer.", buffer_size);
362 audio_toq = audio_eoq = audio_lmb;
363 audio_umb = audio_lmb + buffer_size;
364 audio_occupancy = 0; // frames
959aa08b
MB
365
366 client_is_open = 0;
39545cdf 367
175d91a4 368 // now, if selected, start a thread to automatically open a client when there is a server.
6c6dda9c
MB
369 if (config.jack_auto_client_open_interval != 0) {
370 open_client_if_necessary_thread = malloc(sizeof(pthread_t));
175d91a4 371 if (open_client_if_necessary_thread == NULL) {
76138873 372 debug(1, "Couldn't allocate space for jack server scanner thread");
175d91a4
MB
373 jack_client_open_if_needed();
374 } else {
76138873
MB
375 pthread_create(open_client_if_necessary_thread, NULL,
376 open_client_if_necessary_thread_function,
377 &config.jack_auto_client_open_interval);
175d91a4 378 }
6c6dda9c
MB
379 } else {
380 jack_client_open_if_needed();
381 }
959aa08b 382
8cabb16f
MB
383 return 0;
384}
385
959aa08b
MB
386void jack_start(__attribute__((unused)) int i_sample_rate,
387 __attribute__((unused)) int i_sample_format) {
6c6dda9c 388 // debug(1, "jack start");
959aa08b
MB
389 // see if the client is running. If not, try to open and initialise it
390
391 if (jack_client_open_if_needed() == 0)
392 debug(1, "cannot open a jack client for a play session");
8cabb16f
MB
393}
394
395int jack_delay(long *the_delay) {
39545cdf 396
959aa08b 397 // without the mutex, we could get the time of what is the last transfer of data to a jack buffer,
39545cdf
MB
398 // but then a transfer could occur and we would get the buffer occupancy after another transfer
399 // had occurred
400 // so we could "lose" a full transfer (e.g. 1024 frames @ 44,100 fps ~ 23.2 milliseconds)
401 pthread_mutex_lock(&buffer_mutex);
959aa08b 402 int64_t time_now = get_absolute_time_in_fp();
39545cdf
MB
403 int64_t delta = time_now - time_of_latest_transfer; // this is the time back to the last time data
404 // was transferred into a jack buffer
405 size_t audio_occupancy_now = audio_occupancy; // this is the buffer occupancy before any
76138873
MB
406 // subsequent transfer because transfer is blocked
407 // by the mutex
959aa08b
MB
408 pthread_mutex_unlock(&buffer_mutex);
409
8cabb16f 410 int64_t frames_processed_since_latest_latency_check = (delta * 44100) >> 32;
8cabb16f 411 // debug(1,"delta: %" PRId64 " frames.",frames_processed_since_latest_latency_check);
39545cdf 412 jack_nframes_t base_latency = (latest_left_latency_range.min + latest_left_latency_range.max) / 2;
959aa08b 413 if (base_latency == 0)
39545cdf
MB
414 base_latency = (latest_right_latency_range.min + latest_right_latency_range.max) / 2;
415 *the_delay = base_latency + audio_occupancy_now - frames_processed_since_latest_latency_check;
8cabb16f
MB
416 // debug(1,"reporting a delay of %d frames",*the_delay);
417
418 return 0;
419}
420
421void jack_flush() {
959aa08b 422 // debug(1,"jack flush");
8cabb16f
MB
423 pthread_mutex_lock(&buffer_mutex);
424 audio_toq = audio_eoq = audio_lmb;
425 audio_umb = audio_lmb + buffer_size;
426 audio_occupancy = 0; // frames
427 pthread_mutex_unlock(&buffer_mutex);
8cabb16f
MB
428}
429
6c6dda9c
MB
430void jack_stop(void) {
431 // debug(1, "jack stop");
432 if (config.jack_auto_client_disconnect)
433 jack_close();
434}