jack_audio.c 11 KB

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