2 * jack output driver. This file is part of Shairport Sync.
3 * Copyright (c) 2019 -- 2022 Mike Brady <4265913+mikebrady@users.noreply.github.com>,
4 * Jörn Nettingsmeier <nettings@luchtbeweging.nl>
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29 #include <jack/jack.h>
30 #include <jack/ringbuffer.h>
38 typedef jack_default_audio_sample_t sample_t
;
40 #define jack_sample_size sizeof(sample_t)
42 // Two-channel, 32bit audio:
43 const int bytes_per_frame
= NPORTS
* jack_sample_size
;
45 pthread_mutex_t buffer_mutex
= PTHREAD_MUTEX_INITIALIZER
;
46 pthread_mutex_t client_mutex
= PTHREAD_MUTEX_INITIALIZER
;
48 // This also affects deinterlacing.
49 // So make it exactly the number of incoming audio channels!
50 jack_port_t
*port
[NPORTS
];
51 const char *port_name
[NPORTS
] = {"out_L", "out_R"};
53 jack_client_t
*client
;
54 jack_nframes_t sample_rate
;
55 jack_nframes_t jack_latency
;
57 jack_ringbuffer_t
*jackbuf
;
60 jack_latency_range_t latest_latency_range
[NPORTS
];
61 int64_t time_of_latest_transfer
;
64 typedef struct soxr_quality
{
69 soxr_quality_t soxr_quality_table
[] = {{SOXR_VHQ
, "very high"}, {SOXR_HQ
, "high"},
70 {SOXR_MQ
, "medium"}, {SOXR_LQ
, "low"},
71 {SOXR_QQ
, "quick"}, {-1, NULL
}};
73 static int parse_soxr_quality_name(const char *name
) {
74 for (soxr_quality_t
*s
= soxr_quality_table
; s
->name
!= NULL
; ++s
) {
75 if (!strcmp(s
->name
, name
)) {
83 soxr_quality_spec_t quality_spec
;
84 soxr_io_spec_t io_spec
;
87 static inline sample_t
sample_conv(short sample
) {
88 // It sounds correct, but I don't understand it.
89 // Zero int needs to be zero float. Check.
90 // Plus 32767 int is 1.0. Check.
91 // Minus 32767 int is -0.99997. And here my brain shuts down.
92 // In my head, it should be 1.0, and we should tolerate an overflow
93 // at minus 32768. But I'm sure there's a textbook explanation somewhere.
94 return ((sample
< 0) ? (-1.0 * sample
/ SHRT_MIN
) : (1.0 * sample
/ SHRT_MAX
));
97 static void deinterleave(const char *interleaved_input_buffer
, sample_t
*jack_output_buffer
[],
98 jack_nframes_t offset
, jack_nframes_t nframes
) {
100 // We're dealing with 16bit audio here:
101 sample_t
*ifp
= (sample_t
*)interleaved_input_buffer
;
102 // Zero-copy, we're working directly on the target and destination buffers,
103 // so deal with an offset for the second part of the input ringbuffer
104 for (f
= offset
; f
< (nframes
+ offset
); f
++) {
105 for (int i
= 0; i
< NPORTS
; i
++) {
106 jack_output_buffer
[i
][f
] = *ifp
++;
111 // This is the JACK process callback. We don't decide when it runs.
112 // It must be hard-realtime safe (i.e. fully deterministic, with constant CPU
113 // usage. No calls to anything that could ever block: no syscalls, no screen
114 // output, no file access, no mutexes...
115 // The JACK ringbuffer we use to get the data in here is explicitly lock-free.
116 static int process(jack_nframes_t nframes
, __attribute__((unused
)) void *arg
) {
117 sample_t
*buffer
[NPORTS
];
118 // Expect an array of two elements because of possible ringbuffer wrap-around:
119 jack_ringbuffer_data_t v
[2] = {0};
120 jack_nframes_t i
, thisbuf
;
121 int frames_written
= 0;
122 int frames_required
= 0;
124 for (i
= 0; i
< NPORTS
; i
++) {
125 buffer
[i
] = (sample_t
*)jack_port_get_buffer(port
[i
], nframes
);
128 // We just move the read pointer ahead without doing anything with the data.
129 jack_ringbuffer_read_advance(jackbuf
, jack_ringbuffer_read_space(jackbuf
));
131 // Since we don't change nframes, the whole buffer will be zeroed later.
133 jack_ringbuffer_get_read_vector(jackbuf
, v
);
134 for (i
= 0; i
< 2; i
++) {
135 thisbuf
= v
[i
].len
/ bytes_per_frame
;
136 if (thisbuf
> nframes
) {
137 frames_required
= nframes
;
139 frames_required
= thisbuf
;
141 deinterleave(v
[i
].buf
, buffer
, frames_written
, frames_required
);
142 frames_written
+= frames_required
;
143 nframes
-= frames_required
;
145 jack_ringbuffer_read_advance(jackbuf
, frames_written
* bytes_per_frame
);
147 // If there are any more frames to put into the buffer, fill them with
148 // silence. This is a critical underflow situation. Let's at least keep the JACK
149 // graph humming along while preventing the motorboat sound of a repeating buffer.
150 while (nframes
> 0) {
151 for (i
= 0; i
< NPORTS
; i
++) {
152 buffer
[i
][frames_written
] = 0.0;
157 return 0; // Tell JACK that all is well.
160 // This is the JACK graph reorder callback. Now we know some JACK connections
161 // have changed, so we recompute the latency.
162 static int graph(__attribute__((unused
)) void *arg
) {
164 debug(2, "JACK graph reorder callback called.");
165 for (int i
= 0; i
< NPORTS
; i
++) {
166 jack_port_get_latency_range(port
[i
], JackPlaybackLatency
, &latest_latency_range
[i
]);
167 debug(2, "JACK latency for port %s\tmin: %d\t max: %d", port_name
[i
],
168 latest_latency_range
[i
].min
, latest_latency_range
[i
].max
);
169 latency
+= latest_latency_range
[i
].max
;
172 jack_latency
= latency
;
173 debug(1, "Average maximum JACK latency across all ports: %d", jack_latency
);
177 // This the function JACK will call in case of an error in the library.
178 static void error(const char *desc
) { warn("JACK error: \"%s\"", desc
); }
180 // This is the function JACK will call in case of a non-critical event in the library.
181 static void info(const char *desc
) { inform("JACK information: \"%s\"", desc
); }
183 static int jack_init(__attribute__((unused
)) int argc
, __attribute__((unused
)) char **argv
) {
186 config
.audio_backend_latency_offset
= 0;
187 config
.audio_backend_buffer_desired_length
= 0.500;
188 // Below this, soxr interpolation will not occur -- it'll be basic interpolation
190 config
.audio_backend_buffer_interpolation_threshold_in_seconds
= 0.25;
192 // Do the "general" audio options. Note, these options are in the "general" stanza!
193 parse_general_audio_options();
195 config
.jack_soxr_resample_quality
= -1; // don't resample by default
198 // Now the options specific to the backend, from the "jack" stanza:
199 if (config
.cfg
!= NULL
) {
201 if (config_lookup_string(config
.cfg
, "jack.client_name", &str
)) {
202 config
.jack_client_name
= (char *)str
;
204 if (config_lookup_string(config
.cfg
, "jack.autoconnect_pattern", &str
)) {
205 config
.jack_autoconnect_pattern
= (char *)str
;
208 if (config_lookup_string(config
.cfg
, "jack.soxr_resample_quality", &str
)) {
209 debug(1, "SOXR quality %s", str
);
210 config
.jack_soxr_resample_quality
= parse_soxr_quality_name(str
);
213 if (config_lookup_int(config
.cfg
, "jack.bufsz", &bufsz
) && bufsz
<= 0)
214 die("jack: bufsz must be > 0");
216 if (config
.jack_client_name
== NULL
)
217 config
.jack_client_name
= strdup("shairport-sync");
219 // by default a buffer that can hold up to 4 seconds of 48kHz samples
221 bufsz
= 48000 * 4 * bytes_per_frame
;
223 jackbuf
= jack_ringbuffer_create((size_t)bufsz
);
225 die("Can't allocate %d bytes for the JACK ringbuffer.", bufsz
);
226 // Lock the ringbuffer into memory so that it never gets paged out, which would
227 // break realtime constraints.
228 jack_ringbuffer_mlock(jackbuf
);
229 // This mutex should not be necessary, but removing it causes segfaults on
230 // shutdown. Apparently, there are multiple threads in the main program trying
231 // to do stuff. FIXME: Try to consolidate into one thread and get rid of this lock.
232 pthread_mutex_lock(&client_mutex
);
233 jack_status_t status
;
234 client
= jack_client_open(config
.jack_client_name
, JackNoStartServer
, &status
);
236 die("Could not start JACK server. JackStatus is %x", status
);
238 sample_rate
= jack_get_sample_rate(client
);
240 if (config
.jack_soxr_resample_quality
>= SOXR_QQ
) {
241 quality_spec
= soxr_quality_spec(config
.jack_soxr_resample_quality
, 0);
242 io_spec
= soxr_io_spec(SOXR_INT16_I
, SOXR_FLOAT32_I
);
245 if (sample_rate
!= 44100) {
246 die("The JACK server is running at the wrong sample rate (%d) for Shairport Sync."
247 " Must be 44100 Hz.",
250 jack_set_process_callback(client
, &process
, NULL
);
251 jack_set_graph_order_callback(client
, &graph
, NULL
);
252 jack_set_error_function(&error
);
253 jack_set_info_function(&info
);
254 for (i
= 0; i
< NPORTS
; i
++) {
256 jack_port_register(client
, port_name
[i
], JACK_DEFAULT_AUDIO_TYPE
, JackPortIsOutput
, 0);
258 if (jack_activate(client
)) {
259 die("Could not activate %s JACK client.", config
.jack_client_name
);
261 debug(2, "JACK client %s activated successfully.", config
.jack_client_name
);
263 if (config
.jack_autoconnect_pattern
!= NULL
) {
264 inform("config.jack_autoconnect_pattern is %s. If you see the program die after this,"
265 "you made a syntax error.",
266 config
.jack_autoconnect_pattern
);
267 // Sadly, this will throw a segfault if the user provides a syntactically incorrect regex.
268 // I've reported it to the jack-devel mailing list, they're in a better place to fix it.
269 const char **port_list
= jack_get_ports(client
, config
.jack_autoconnect_pattern
,
270 JACK_DEFAULT_AUDIO_TYPE
, JackPortIsInput
);
271 if (port_list
!= NULL
) {
272 for (i
= 0; i
< NPORTS
; i
++) {
273 char *full_port_name
[NPORTS
];
274 full_port_name
[i
] = malloc(sizeof(char) * jack_port_name_size());
275 sprintf(full_port_name
[i
], "%s:%s", config
.jack_client_name
, port_name
[i
]);
276 if (port_list
[i
] != NULL
) {
278 debug(2, "Connecting %s to %s.", full_port_name
[i
], port_list
[i
]);
279 err
= jack_connect(client
, full_port_name
[i
], port_list
[i
]);
282 inform("The requested connection from %s to %s already exists.", full_port_name
[i
],
289 warn("JACK error no. %d occurred while trying to connect %s to %s.", err
,
290 full_port_name
[i
], port_list
[i
]);
294 inform("No matching port found in %s to connect %s to. You may not hear audio.",
295 config
.jack_autoconnect_pattern
, full_port_name
[i
]);
297 free(full_port_name
[i
]);
299 while (port_list
[i
++] != NULL
) {
301 "Additional matching port %s found. Check that the connections are what you intended.",
304 jack_free(port_list
);
307 pthread_mutex_unlock(&client_mutex
);
312 static void jack_deinit() {
313 pthread_mutex_lock(&client_mutex
);
314 if (jack_deactivate(client
))
315 warn("Error deactivating jack client");
316 if (jack_client_close(client
))
317 warn("Error closing jack client");
318 pthread_mutex_unlock(&client_mutex
);
319 jack_ringbuffer_free(jackbuf
);
328 static void jack_start(int i_sample_rate
, __attribute__((unused
)) int i_sample_format
) {
329 // Nothing to do, JACK client has already been set up at jack_init().
330 // Also, we have no say over the sample rate or sample format of JACK,
331 // We convert the 16bit samples to float, and die if the sample rate is != 44k1 without soxr.
333 if (config
.jack_soxr_resample_quality
>= SOXR_QQ
) {
334 // we might improve a bit with soxr_clear if the sample_rate doesn't change
338 soxr_error_t e
= NULL
;
339 soxr
= soxr_create(i_sample_rate
, sample_rate
, NPORTS
, &e
, &io_spec
, &quality_spec
, NULL
);
341 die("Unable to create soxr resampler for JACK: %s", e
);
347 static void jack_flush() {
348 debug(2, "Only the consumer can safely flush a lock-free ringbuffer. Asking the"
349 " process callback to do it...");
353 static int jack_delay(long *the_delay
) {
354 // Semantics change: we now look at the last transfer into the lock-free
355 // ringbuffer, not into the jack buffers directly (because locking those would
356 // violate real-time constraints). On average, that should lead to just a
357 // constant additional latency.
358 // Without the mutex, we could get the time of what is the last transfer of data
359 // to a jack buffer, but then a transfer could occur and we would get the buffer
360 // occupancy after another transfer had occurred, so we could "lose" a full transfer
361 // (e.g. 1024 frames @ 44,100 fps ~ 23.2 milliseconds)
362 pthread_mutex_lock(&buffer_mutex
);
363 int64_t time_now
= get_absolute_time_in_ns();
364 int64_t delta
= time_now
- time_of_latest_transfer
; // nanoseconds
365 size_t audio_occupancy_now
= jack_ringbuffer_read_space(jackbuf
) / bytes_per_frame
;
366 debug(2, "audio_occupancy_now is %d.", audio_occupancy_now
);
367 pthread_mutex_unlock(&buffer_mutex
);
369 int64_t frames_processed_since_latest_latency_check
= (delta
* sample_rate
) / 1000000000;
370 // debug(1,"delta: %" PRId64 " frames.",frames_processed_since_latest_latency_check);
371 // jack_latency is set by the graph() callback, it's the average of the maximum
372 // latencies of all our output ports. Adjust this constant baseline delay according
373 // to the buffer fill level:
374 *the_delay
= jack_latency
+ audio_occupancy_now
- frames_processed_since_latest_latency_check
;
375 // debug(1,"reporting a delay of %d frames",*the_delay);
379 static int play(void *buf
, int samples
, __attribute__((unused
)) int sample_type
,
380 __attribute__((unused
)) uint32_t timestamp
,
381 __attribute__((unused
)) uint64_t playtime
) {
382 jack_ringbuffer_data_t v
[2] = {0};
384 jack_nframes_t thisbuf
;
385 // It's ok to lock here since we're not in the realtime callback:
386 pthread_mutex_lock(&buffer_mutex
);
387 jack_ringbuffer_get_write_vector(jackbuf
, v
);
388 short *in
= (short *)buf
;
390 for (i
= 0; i
< 2; ++i
) {
391 thisbuf
= v
[i
].len
/ (jack_sample_size
* NPORTS
); // #samples per channel
392 out
= (sample_t
*)v
[i
].buf
;
395 size_t i_done
, o_done
;
397 while (samples
> 0 && thisbuf
> 0) {
398 e
= soxr_process(soxr
, (soxr_in_t
)in
, samples
, &i_done
, (soxr_out_t
)out
, thisbuf
, &o_done
);
400 die("Error during soxr process: %s", e
);
402 in
+= i_done
* NPORTS
; // advance our input buffer
405 jack_ringbuffer_write_advance(jackbuf
, o_done
* jack_sample_size
* NPORTS
);
410 for (j
= 0; j
< thisbuf
&& samples
> 0; ++j
) {
411 for (c
= 0; c
< NPORTS
; ++c
)
412 out
[j
* NPORTS
+ c
] = sample_conv(*in
++);
415 jack_ringbuffer_write_advance(jackbuf
, j
* jack_sample_size
* NPORTS
);
420 time_of_latest_transfer
= get_absolute_time_in_ns();
421 pthread_mutex_unlock(&buffer_mutex
);
423 warn("JACK ringbuffer overrun. Dropped %d samples.", samples
);
428 audio_output audio_jack
= {.name
= "jack",
431 .deinit
= &jack_deinit
,
433 .start
= &jack_start
,
436 .flush
= &jack_flush
,
437 .delay
= &jack_delay
,