2 * JACK Audio Connection Kit input device
3 * Copyright (c) 2009 Samalyse
4 * Author: Olivier Guilyardi <olivier samalyse com>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <semaphore.h>
25 #include <jack/jack.h>
27 #include "libavutil/internal.h"
28 #include "libavutil/log.h"
29 #include "libavutil/fifo.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/time.h"
32 #include "libavcodec/avcodec.h"
33 #include "libavformat/avformat.h"
34 #include "libavformat/internal.h"
35 #include "timefilter.h"
38 #if HAVE_DISPATCH_DISPATCH_H
39 #include <dispatch/dispatch.h>
40 #define sem_t dispatch_semaphore_t
41 #define sem_init(psem,x,val) *psem = dispatch_semaphore_create(val)
42 #define sem_post(psem) dispatch_semaphore_signal(*psem)
43 #define sem_wait(psem) dispatch_semaphore_wait(*psem, DISPATCH_TIME_FOREVER)
44 #define sem_timedwait(psem, val) dispatch_semaphore_wait(*psem, dispatch_walltime(val, 0))
45 #define sem_destroy(psem) dispatch_release(*psem)
49 * Size of the internal FIFO buffers as a number of audio packets
51 #define FIFO_PACKETS_NUM 16
53 typedef struct JackData {
55 jack_client_t * client;
58 jack_nframes_t sample_rate;
59 jack_nframes_t buffer_size;
62 TimeFilter * timefilter;
63 AVFifoBuffer * new_pkts;
64 AVFifoBuffer * filled_pkts;
69 static int process_callback(jack_nframes_t nframes, void *arg)
71 /* Warning: this function runs in realtime. One mustn't allocate memory here
72 * or do any other thing that could block. */
77 jack_nframes_t latency, cycle_delay;
85 /* The approximate delay since the hardware interrupt as a number of frames */
86 cycle_delay = jack_frames_since_cycle_start(self->client);
88 /* Retrieve filtered cycle time */
89 cycle_time = ff_timefilter_update(self->timefilter,
90 av_gettime() / 1000000.0 - (double) cycle_delay / self->sample_rate,
93 /* Check if an empty packet is available, and if there's enough space to send it back once filled */
94 if ((av_fifo_size(self->new_pkts) < sizeof(pkt)) || (av_fifo_space(self->filled_pkts) < sizeof(pkt))) {
99 /* Retrieve empty (but allocated) packet */
100 av_fifo_generic_read(self->new_pkts, &pkt, sizeof(pkt), NULL);
102 pkt_data = (float *) pkt.data;
105 /* Copy and interleave audio data from the JACK buffer into the packet */
106 for (i = 0; i < self->nports; i++) {
107 #if HAVE_JACK_PORT_GET_LATENCY_RANGE
108 jack_latency_range_t range;
109 jack_port_get_latency_range(self->ports[i], JackCaptureLatency, &range);
110 latency += range.max;
112 latency += jack_port_get_total_latency(self->client, self->ports[i]);
114 buffer = jack_port_get_buffer(self->ports[i], self->buffer_size);
115 for (j = 0; j < self->buffer_size; j++)
116 pkt_data[j * self->nports + i] = buffer[j];
119 /* Timestamp the packet with the cycle start time minus the average latency */
120 pkt.pts = (cycle_time - (double) latency / (self->nports * self->sample_rate)) * 1000000.0;
122 /* Send the now filled packet back, and increase packet counter */
123 av_fifo_generic_write(self->filled_pkts, &pkt, sizeof(pkt), NULL);
124 sem_post(&self->packet_count);
129 static void shutdown_callback(void *arg)
131 JackData *self = arg;
135 static int xrun_callback(void *arg)
137 JackData *self = arg;
139 ff_timefilter_reset(self->timefilter);
143 static int supply_new_packets(JackData *self, AVFormatContext *context)
146 int test, pkt_size = self->buffer_size * self->nports * sizeof(float);
148 /* Supply the process callback with new empty packets, by filling the new
149 * packets FIFO buffer with as many packets as possible. process_callback()
150 * can't do this by itself, because it can't allocate memory in realtime. */
151 while (av_fifo_space(self->new_pkts) >= sizeof(pkt)) {
152 if ((test = av_new_packet(&pkt, pkt_size)) < 0) {
153 av_log(context, AV_LOG_ERROR, "Could not create packet of size %d\n", pkt_size);
156 av_fifo_generic_write(self->new_pkts, &pkt, sizeof(pkt), NULL);
161 static int start_jack(AVFormatContext *context)
163 JackData *self = context->priv_data;
164 jack_status_t status;
167 /* Register as a JACK client, using the context filename as client name. */
168 self->client = jack_client_open(context->filename, JackNullOption, &status);
170 av_log(context, AV_LOG_ERROR, "Unable to register as a JACK client\n");
174 sem_init(&self->packet_count, 0, 0);
176 self->sample_rate = jack_get_sample_rate(self->client);
177 self->ports = av_malloc_array(self->nports, sizeof(*self->ports));
179 return AVERROR(ENOMEM);
180 self->buffer_size = jack_get_buffer_size(self->client);
182 /* Register JACK ports */
183 for (i = 0; i < self->nports; i++) {
185 snprintf(str, sizeof(str), "input_%d", i + 1);
186 self->ports[i] = jack_port_register(self->client, str,
187 JACK_DEFAULT_AUDIO_TYPE,
189 if (!self->ports[i]) {
190 av_log(context, AV_LOG_ERROR, "Unable to register port %s:%s\n",
191 context->filename, str);
192 jack_client_close(self->client);
197 /* Register JACK callbacks */
198 jack_set_process_callback(self->client, process_callback, self);
199 jack_on_shutdown(self->client, shutdown_callback, self);
200 jack_set_xrun_callback(self->client, xrun_callback, self);
202 /* Create time filter */
203 self->timefilter = ff_timefilter_new (1.0 / self->sample_rate, self->buffer_size, 1.5);
204 if (!self->timefilter) {
205 jack_client_close(self->client);
206 return AVERROR(ENOMEM);
209 /* Create FIFO buffers */
210 self->filled_pkts = av_fifo_alloc_array(FIFO_PACKETS_NUM, sizeof(AVPacket));
211 /* New packets FIFO with one extra packet for safety against underruns */
212 self->new_pkts = av_fifo_alloc_array((FIFO_PACKETS_NUM + 1), sizeof(AVPacket));
213 if (!self->new_pkts) {
214 jack_client_close(self->client);
215 return AVERROR(ENOMEM);
217 if ((test = supply_new_packets(self, context))) {
218 jack_client_close(self->client);
226 static void free_pkt_fifo(AVFifoBuffer **fifo)
229 while (av_fifo_size(*fifo)) {
230 av_fifo_generic_read(*fifo, &pkt, sizeof(pkt), NULL);
231 av_packet_unref(&pkt);
236 static void stop_jack(JackData *self)
240 jack_deactivate(self->client);
241 jack_client_close(self->client);
243 sem_destroy(&self->packet_count);
244 free_pkt_fifo(&self->new_pkts);
245 free_pkt_fifo(&self->filled_pkts);
246 av_freep(&self->ports);
247 ff_timefilter_destroy(self->timefilter);
250 static int audio_read_header(AVFormatContext *context)
252 JackData *self = context->priv_data;
256 if ((test = start_jack(context)))
259 stream = avformat_new_stream(context, NULL);
262 return AVERROR(ENOMEM);
265 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
267 stream->codecpar->codec_id = AV_CODEC_ID_PCM_F32BE;
269 stream->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
271 stream->codecpar->sample_rate = self->sample_rate;
272 stream->codecpar->channels = self->nports;
274 avpriv_set_pts_info(stream, 64, 1, 1000000); /* 64 bits pts in us */
278 static int audio_read_packet(AVFormatContext *context, AVPacket *pkt)
280 JackData *self = context->priv_data;
281 struct timespec timeout = {0, 0};
284 /* Activate the JACK client on first packet read. Activating the JACK client
285 * means that process_callback() starts to get called at regular interval.
286 * If we activate it in audio_read_header(), we're actually reading audio data
287 * from the device before instructed to, and that may result in an overrun. */
288 if (!self->activated) {
289 if (!jack_activate(self->client)) {
291 av_log(context, AV_LOG_INFO,
292 "JACK client registered and activated (rate=%dHz, buffer_size=%d frames)\n",
293 self->sample_rate, self->buffer_size);
295 av_log(context, AV_LOG_ERROR, "Unable to activate JACK client\n");
300 /* Wait for a packet coming back from process_callback(), if one isn't available yet */
301 timeout.tv_sec = av_gettime() / 1000000 + 2;
302 if (sem_timedwait(&self->packet_count, &timeout)) {
303 if (errno == ETIMEDOUT) {
304 av_log(context, AV_LOG_ERROR,
305 "Input error: timed out when waiting for JACK process callback output\n");
308 int ret = AVERROR(errno);
309 av_strerror(ret, errbuf, sizeof(errbuf));
310 av_log(context, AV_LOG_ERROR, "Error while waiting for audio packet: %s\n",
314 av_log(context, AV_LOG_ERROR, "Input error: JACK server is gone\n");
319 if (self->pkt_xrun) {
320 av_log(context, AV_LOG_WARNING, "Audio packet xrun\n");
324 if (self->jack_xrun) {
325 av_log(context, AV_LOG_WARNING, "JACK xrun\n");
329 /* Retrieve the packet filled with audio data by process_callback() */
330 av_fifo_generic_read(self->filled_pkts, pkt, sizeof(*pkt), NULL);
332 if ((test = supply_new_packets(self, context)))
338 static int audio_read_close(AVFormatContext *context)
340 JackData *self = context->priv_data;
345 #define OFFSET(x) offsetof(JackData, x)
346 static const AVOption options[] = {
347 { "channels", "Number of audio channels.", OFFSET(nports), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
351 static const AVClass jack_indev_class = {
352 .class_name = "JACK indev",
353 .item_name = av_default_item_name,
355 .version = LIBAVUTIL_VERSION_INT,
356 .category = AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT,
359 AVInputFormat ff_jack_demuxer = {
361 .long_name = NULL_IF_CONFIG_SMALL("JACK Audio Connection Kit"),
362 .priv_data_size = sizeof(JackData),
363 .read_header = audio_read_header,
364 .read_packet = audio_read_packet,
365 .read_close = audio_read_close,
366 .flags = AVFMT_NOFILE,
367 .priv_class = &jack_indev_class,