Remove unnecessary inclusions of [sys/]time.h
[libav.git] / libavdevice / jack_audio.c
CommitLineData
80ff8a16
OG
1/*
2 * JACK Audio Connection Kit input device
3 * Copyright (c) 2009 Samalyse
4 * Author: Olivier Guilyardi <olivier samalyse com>
5 *
2912e87a 6 * This file is part of Libav.
80ff8a16 7 *
2912e87a 8 * Libav is free software; you can redistribute it and/or
80ff8a16
OG
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.
12 *
2912e87a 13 * Libav is distributed in the hope that it will be useful,
80ff8a16
OG
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.
17 *
18 * You should have received a copy of the GNU Lesser General Public
2912e87a 19 * License along with Libav; if not, write to the Free Software
80ff8a16
OG
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "config.h"
24#include <semaphore.h>
25#include <jack/jack.h>
26
27#include "libavutil/log.h"
28#include "libavutil/fifo.h"
a7c93dae 29#include "libavutil/opt.h"
80ff8a16
OG
30#include "libavcodec/avcodec.h"
31#include "libavformat/avformat.h"
c3f9ebf7 32#include "libavformat/internal.h"
5dd35b43 33#include "timefilter.h"
80ff8a16
OG
34
35/**
36 * Size of the internal FIFO buffers as a number of audio packets
37 */
38#define FIFO_PACKETS_NUM 16
39
40typedef struct {
a7c93dae 41 AVClass *class;
80ff8a16
OG
42 jack_client_t * client;
43 int activated;
44 sem_t packet_count;
45 jack_nframes_t sample_rate;
46 jack_nframes_t buffer_size;
47 jack_port_t ** ports;
48 int nports;
49 TimeFilter * timefilter;
50 AVFifoBuffer * new_pkts;
51 AVFifoBuffer * filled_pkts;
52 int pkt_xrun;
53 int jack_xrun;
54} JackData;
55
56static int process_callback(jack_nframes_t nframes, void *arg)
57{
58 /* Warning: this function runs in realtime. One mustn't allocate memory here
59 * or do any other thing that could block. */
60
61 int i, j;
62 JackData *self = arg;
63 float * buffer;
64 jack_nframes_t latency, cycle_delay;
65 AVPacket pkt;
66 float *pkt_data;
67 double cycle_time;
68
69 if (!self->client)
70 return 0;
71
72 /* The approximate delay since the hardware interrupt as a number of frames */
73 cycle_delay = jack_frames_since_cycle_start(self->client);
74
75 /* Retrieve filtered cycle time */
76 cycle_time = ff_timefilter_update(self->timefilter,
77 av_gettime() / 1000000.0 - (double) cycle_delay / self->sample_rate,
78 self->buffer_size);
79
80 /* Check if an empty packet is available, and if there's enough space to send it back once filled */
81 if ((av_fifo_size(self->new_pkts) < sizeof(pkt)) || (av_fifo_space(self->filled_pkts) < sizeof(pkt))) {
82 self->pkt_xrun = 1;
83 return 0;
84 }
85
86 /* Retrieve empty (but allocated) packet */
87 av_fifo_generic_read(self->new_pkts, &pkt, sizeof(pkt), NULL);
88
89 pkt_data = (float *) pkt.data;
90 latency = 0;
91
92 /* Copy and interleave audio data from the JACK buffer into the packet */
93 for (i = 0; i < self->nports; i++) {
8772997d
SM
94 #if HAVE_JACK_PORT_GET_LATENCY_RANGE
95 jack_latency_range_t range;
96 jack_port_get_latency_range(self->ports[i], JackCaptureLatency, &range);
97 latency += range.max;
98 #else
80ff8a16 99 latency += jack_port_get_total_latency(self->client, self->ports[i]);
8772997d 100 #endif
80ff8a16
OG
101 buffer = jack_port_get_buffer(self->ports[i], self->buffer_size);
102 for (j = 0; j < self->buffer_size; j++)
103 pkt_data[j * self->nports + i] = buffer[j];
104 }
105
106 /* Timestamp the packet with the cycle start time minus the average latency */
107 pkt.pts = (cycle_time - (double) latency / (self->nports * self->sample_rate)) * 1000000.0;
108
109 /* Send the now filled packet back, and increase packet counter */
110 av_fifo_generic_write(self->filled_pkts, &pkt, sizeof(pkt), NULL);
111 sem_post(&self->packet_count);
112
113 return 0;
114}
115
116static void shutdown_callback(void *arg)
117{
118 JackData *self = arg;
119 self->client = NULL;
120}
121
122static int xrun_callback(void *arg)
123{
124 JackData *self = arg;
125 self->jack_xrun = 1;
126 ff_timefilter_reset(self->timefilter);
127 return 0;
128}
129
130static int supply_new_packets(JackData *self, AVFormatContext *context)
131{
132 AVPacket pkt;
133 int test, pkt_size = self->buffer_size * self->nports * sizeof(float);
134
135 /* Supply the process callback with new empty packets, by filling the new
136 * packets FIFO buffer with as many packets as possible. process_callback()
137 * can't do this by itself, because it can't allocate memory in realtime. */
138 while (av_fifo_space(self->new_pkts) >= sizeof(pkt)) {
139 if ((test = av_new_packet(&pkt, pkt_size)) < 0) {
140 av_log(context, AV_LOG_ERROR, "Could not create packet of size %d\n", pkt_size);
141 return test;
142 }
143 av_fifo_generic_write(self->new_pkts, &pkt, sizeof(pkt), NULL);
144 }
145 return 0;
146}
147
a7c93dae 148static int start_jack(AVFormatContext *context)
80ff8a16
OG
149{
150 JackData *self = context->priv_data;
151 jack_status_t status;
152 int i, test;
153 double o, period;
154
155 /* Register as a JACK client, using the context filename as client name. */
34bcada4 156 self->client = jack_client_open(context->filename, JackNullOption, &status);
80ff8a16
OG
157 if (!self->client) {
158 av_log(context, AV_LOG_ERROR, "Unable to register as a JACK client\n");
159 return AVERROR(EIO);
160 }
161
162 sem_init(&self->packet_count, 0, 0);
163
164 self->sample_rate = jack_get_sample_rate(self->client);
80ff8a16
OG
165 self->ports = av_malloc(self->nports * sizeof(*self->ports));
166 self->buffer_size = jack_get_buffer_size(self->client);
167
168 /* Register JACK ports */
169 for (i = 0; i < self->nports; i++) {
170 char str[16];
171 snprintf(str, sizeof(str), "input_%d", i + 1);
172 self->ports[i] = jack_port_register(self->client, str,
173 JACK_DEFAULT_AUDIO_TYPE,
174 JackPortIsInput, 0);
175 if (!self->ports[i]) {
176 av_log(context, AV_LOG_ERROR, "Unable to register port %s:%s\n",
177 context->filename, str);
178 jack_client_close(self->client);
179 return AVERROR(EIO);
180 }
181 }
182
183 /* Register JACK callbacks */
184 jack_set_process_callback(self->client, process_callback, self);
185 jack_on_shutdown(self->client, shutdown_callback, self);
186 jack_set_xrun_callback(self->client, xrun_callback, self);
187
188 /* Create time filter */
189 period = (double) self->buffer_size / self->sample_rate;
190 o = 2 * M_PI * 1.5 * period; /// bandwidth: 1.5Hz
191 self->timefilter = ff_timefilter_new (1.0 / self->sample_rate, sqrt(2 * o), o * o);
192
193 /* Create FIFO buffers */
194 self->filled_pkts = av_fifo_alloc(FIFO_PACKETS_NUM * sizeof(AVPacket));
195 /* New packets FIFO with one extra packet for safety against underruns */
196 self->new_pkts = av_fifo_alloc((FIFO_PACKETS_NUM + 1) * sizeof(AVPacket));
197 if ((test = supply_new_packets(self, context))) {
198 jack_client_close(self->client);
199 return test;
200 }
201
202 return 0;
203
204}
205
206static void free_pkt_fifo(AVFifoBuffer *fifo)
207{
208 AVPacket pkt;
209 while (av_fifo_size(fifo)) {
210 av_fifo_generic_read(fifo, &pkt, sizeof(pkt), NULL);
211 av_free_packet(&pkt);
212 }
213 av_fifo_free(fifo);
214}
215
216static void stop_jack(JackData *self)
217{
218 if (self->client) {
219 if (self->activated)
220 jack_deactivate(self->client);
221 jack_client_close(self->client);
222 }
223 sem_destroy(&self->packet_count);
224 free_pkt_fifo(self->new_pkts);
225 free_pkt_fifo(self->filled_pkts);
226 av_freep(&self->ports);
227 ff_timefilter_destroy(self->timefilter);
228}
229
6e9651d1 230static int audio_read_header(AVFormatContext *context)
80ff8a16
OG
231{
232 JackData *self = context->priv_data;
233 AVStream *stream;
234 int test;
235
a7c93dae 236 if ((test = start_jack(context)))
80ff8a16
OG
237 return test;
238
3b3bbdd3 239 stream = avformat_new_stream(context, NULL);
80ff8a16
OG
240 if (!stream) {
241 stop_jack(self);
242 return AVERROR(ENOMEM);
243 }
244
72415b2a 245 stream->codec->codec_type = AVMEDIA_TYPE_AUDIO;
63613fe6 246#if HAVE_BIGENDIAN
80ff8a16
OG
247 stream->codec->codec_id = CODEC_ID_PCM_F32BE;
248#else
249 stream->codec->codec_id = CODEC_ID_PCM_F32LE;
250#endif
251 stream->codec->sample_rate = self->sample_rate;
252 stream->codec->channels = self->nports;
253
c3f9ebf7 254 avpriv_set_pts_info(stream, 64, 1, 1000000); /* 64 bits pts in us */
80ff8a16
OG
255 return 0;
256}
257
258static int audio_read_packet(AVFormatContext *context, AVPacket *pkt)
259{
260 JackData *self = context->priv_data;
261 struct timespec timeout = {0, 0};
262 int test;
263
264 /* Activate the JACK client on first packet read. Activating the JACK client
265 * means that process_callback() starts to get called at regular interval.
266 * If we activate it in audio_read_header(), we're actually reading audio data
267 * from the device before instructed to, and that may result in an overrun. */
268 if (!self->activated) {
269 if (!jack_activate(self->client)) {
270 self->activated = 1;
271 av_log(context, AV_LOG_INFO,
272 "JACK client registered and activated (rate=%dHz, buffer_size=%d frames)\n",
273 self->sample_rate, self->buffer_size);
274 } else {
275 av_log(context, AV_LOG_ERROR, "Unable to activate JACK client\n");
276 return AVERROR(EIO);
277 }
278 }
279
da9cea77 280 /* Wait for a packet coming back from process_callback(), if one isn't available yet */
80ff8a16
OG
281 timeout.tv_sec = av_gettime() / 1000000 + 2;
282 if (sem_timedwait(&self->packet_count, &timeout)) {
283 if (errno == ETIMEDOUT) {
284 av_log(context, AV_LOG_ERROR,
285 "Input error: timed out when waiting for JACK process callback output\n");
286 } else {
287 av_log(context, AV_LOG_ERROR, "Error while waiting for audio packet: %s\n",
288 strerror(errno));
289 }
290 if (!self->client)
291 av_log(context, AV_LOG_ERROR, "Input error: JACK server is gone\n");
292
293 return AVERROR(EIO);
294 }
295
296 if (self->pkt_xrun) {
297 av_log(context, AV_LOG_WARNING, "Audio packet xrun\n");
298 self->pkt_xrun = 0;
299 }
300
301 if (self->jack_xrun) {
302 av_log(context, AV_LOG_WARNING, "JACK xrun\n");
303 self->jack_xrun = 0;
304 }
305
306 /* Retrieve the packet filled with audio data by process_callback() */
307 av_fifo_generic_read(self->filled_pkts, pkt, sizeof(*pkt), NULL);
308
309 if ((test = supply_new_packets(self, context)))
310 return test;
311
312 return 0;
313}
314
315static int audio_read_close(AVFormatContext *context)
316{
317 JackData *self = context->priv_data;
318 stop_jack(self);
319 return 0;
320}
321
a7c93dae
AK
322#define OFFSET(x) offsetof(JackData, x)
323static const AVOption options[] = {
145f741e 324 { "channels", "Number of audio channels.", OFFSET(nports), AV_OPT_TYPE_INT, { 2 }, 1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
a7c93dae
AK
325 { NULL },
326};
327
328static const AVClass jack_indev_class = {
329 .class_name = "JACK indev",
330 .item_name = av_default_item_name,
331 .option = options,
332 .version = LIBAVUTIL_VERSION_INT,
333};
334
c6610a21 335AVInputFormat ff_jack_demuxer = {
30b4ee79
DB
336 .name = "jack",
337 .long_name = NULL_IF_CONFIG_SMALL("JACK Audio Connection Kit"),
338 .priv_data_size = sizeof(JackData),
339 .read_header = audio_read_header,
340 .read_packet = audio_read_packet,
341 .read_close = audio_read_close,
342 .flags = AVFMT_NOFILE,
343 .priv_class = &jack_indev_class,
80ff8a16 344};