pulse_audio_dec.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Pulseaudio input
  3. * Copyright (c) 2011 Luca Barbato <lu_zero@gentoo.org>
  4. * Copyright 2004-2006 Lennart Poettering
  5. * Copyright (c) 2014 Michael Niedermayer <michaelni@gmx.at>
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include <pulse/rtclock.h>
  24. #include <pulse/error.h>
  25. #include "libavutil/internal.h"
  26. #include "libavutil/opt.h"
  27. #include "libavutil/time.h"
  28. #include "libavformat/avformat.h"
  29. #include "libavformat/internal.h"
  30. #include "libavformat/version.h"
  31. #include "pulse_audio_common.h"
  32. #include "timefilter.h"
  33. #define DEFAULT_CODEC_ID AV_NE(AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE)
  34. typedef struct PulseData {
  35. AVClass *class;
  36. char *server;
  37. char *name;
  38. char *stream_name;
  39. int sample_rate;
  40. int channels;
  41. int frame_size;
  42. int fragment_size;
  43. pa_threaded_mainloop *mainloop;
  44. pa_context *context;
  45. pa_stream *stream;
  46. size_t pa_frame_size;
  47. TimeFilter *timefilter;
  48. int last_period;
  49. int wallclock;
  50. } PulseData;
  51. #define CHECK_SUCCESS_GOTO(rerror, expression, label) \
  52. do { \
  53. if (!(expression)) { \
  54. rerror = AVERROR_EXTERNAL; \
  55. goto label; \
  56. } \
  57. } while (0)
  58. #define CHECK_DEAD_GOTO(p, rerror, label) \
  59. do { \
  60. if (!(p)->context || !PA_CONTEXT_IS_GOOD(pa_context_get_state((p)->context)) || \
  61. !(p)->stream || !PA_STREAM_IS_GOOD(pa_stream_get_state((p)->stream))) { \
  62. rerror = AVERROR_EXTERNAL; \
  63. goto label; \
  64. } \
  65. } while (0)
  66. static void context_state_cb(pa_context *c, void *userdata) {
  67. PulseData *p = userdata;
  68. switch (pa_context_get_state(c)) {
  69. case PA_CONTEXT_READY:
  70. case PA_CONTEXT_TERMINATED:
  71. case PA_CONTEXT_FAILED:
  72. pa_threaded_mainloop_signal(p->mainloop, 0);
  73. break;
  74. }
  75. }
  76. static void stream_state_cb(pa_stream *s, void * userdata) {
  77. PulseData *p = userdata;
  78. switch (pa_stream_get_state(s)) {
  79. case PA_STREAM_READY:
  80. case PA_STREAM_FAILED:
  81. case PA_STREAM_TERMINATED:
  82. pa_threaded_mainloop_signal(p->mainloop, 0);
  83. break;
  84. }
  85. }
  86. static void stream_request_cb(pa_stream *s, size_t length, void *userdata) {
  87. PulseData *p = userdata;
  88. pa_threaded_mainloop_signal(p->mainloop, 0);
  89. }
  90. static void stream_latency_update_cb(pa_stream *s, void *userdata) {
  91. PulseData *p = userdata;
  92. pa_threaded_mainloop_signal(p->mainloop, 0);
  93. }
  94. static av_cold int pulse_close(AVFormatContext *s)
  95. {
  96. PulseData *pd = s->priv_data;
  97. if (pd->mainloop)
  98. pa_threaded_mainloop_stop(pd->mainloop);
  99. if (pd->stream)
  100. pa_stream_unref(pd->stream);
  101. pd->stream = NULL;
  102. if (pd->context) {
  103. pa_context_disconnect(pd->context);
  104. pa_context_unref(pd->context);
  105. }
  106. pd->context = NULL;
  107. if (pd->mainloop)
  108. pa_threaded_mainloop_free(pd->mainloop);
  109. pd->mainloop = NULL;
  110. ff_timefilter_destroy(pd->timefilter);
  111. pd->timefilter = NULL;
  112. return 0;
  113. }
  114. static av_cold int pulse_read_header(AVFormatContext *s)
  115. {
  116. PulseData *pd = s->priv_data;
  117. AVStream *st;
  118. char *device = NULL;
  119. int ret;
  120. enum AVCodecID codec_id =
  121. s->audio_codec_id == AV_CODEC_ID_NONE ? DEFAULT_CODEC_ID : s->audio_codec_id;
  122. const pa_sample_spec ss = { ff_codec_id_to_pulse_format(codec_id),
  123. pd->sample_rate,
  124. pd->channels };
  125. pa_buffer_attr attr = { -1 };
  126. pa_channel_map cmap;
  127. const pa_buffer_attr *queried_attr;
  128. pa_channel_map_init_extend(&cmap, pd->channels, PA_CHANNEL_MAP_WAVEEX);
  129. st = avformat_new_stream(s, NULL);
  130. if (!st) {
  131. av_log(s, AV_LOG_ERROR, "Cannot add stream\n");
  132. return AVERROR(ENOMEM);
  133. }
  134. if (pd->fragment_size == -1) {
  135. // 50 ms fragments/latency by default seem good enough
  136. attr.fragsize = pa_frame_size(&ss) * (pd->sample_rate / 20);
  137. } else {
  138. attr.fragsize = pd->fragment_size;
  139. }
  140. if (s->url[0] != '\0' && strcmp(s->url, "default"))
  141. device = s->url;
  142. if (!(pd->mainloop = pa_threaded_mainloop_new())) {
  143. pulse_close(s);
  144. return AVERROR_EXTERNAL;
  145. }
  146. if (!(pd->context = pa_context_new(pa_threaded_mainloop_get_api(pd->mainloop), pd->name))) {
  147. pulse_close(s);
  148. return AVERROR_EXTERNAL;
  149. }
  150. pa_context_set_state_callback(pd->context, context_state_cb, pd);
  151. if (pa_context_connect(pd->context, pd->server, 0, NULL) < 0) {
  152. pulse_close(s);
  153. return AVERROR(pa_context_errno(pd->context));
  154. }
  155. pa_threaded_mainloop_lock(pd->mainloop);
  156. if (pa_threaded_mainloop_start(pd->mainloop) < 0) {
  157. ret = -1;
  158. goto unlock_and_fail;
  159. }
  160. for (;;) {
  161. pa_context_state_t state;
  162. state = pa_context_get_state(pd->context);
  163. if (state == PA_CONTEXT_READY)
  164. break;
  165. if (!PA_CONTEXT_IS_GOOD(state)) {
  166. ret = AVERROR(pa_context_errno(pd->context));
  167. goto unlock_and_fail;
  168. }
  169. /* Wait until the context is ready */
  170. pa_threaded_mainloop_wait(pd->mainloop);
  171. }
  172. if (!(pd->stream = pa_stream_new(pd->context, pd->stream_name, &ss, &cmap))) {
  173. ret = AVERROR(pa_context_errno(pd->context));
  174. goto unlock_and_fail;
  175. }
  176. pa_stream_set_state_callback(pd->stream, stream_state_cb, pd);
  177. pa_stream_set_read_callback(pd->stream, stream_request_cb, pd);
  178. pa_stream_set_write_callback(pd->stream, stream_request_cb, pd);
  179. pa_stream_set_latency_update_callback(pd->stream, stream_latency_update_cb, pd);
  180. ret = pa_stream_connect_record(pd->stream, device, &attr,
  181. PA_STREAM_INTERPOLATE_TIMING
  182. |PA_STREAM_ADJUST_LATENCY
  183. |PA_STREAM_AUTO_TIMING_UPDATE);
  184. if (ret < 0) {
  185. ret = AVERROR(pa_context_errno(pd->context));
  186. goto unlock_and_fail;
  187. }
  188. for (;;) {
  189. pa_stream_state_t state;
  190. state = pa_stream_get_state(pd->stream);
  191. if (state == PA_STREAM_READY)
  192. break;
  193. if (!PA_STREAM_IS_GOOD(state)) {
  194. ret = AVERROR(pa_context_errno(pd->context));
  195. goto unlock_and_fail;
  196. }
  197. /* Wait until the stream is ready */
  198. pa_threaded_mainloop_wait(pd->mainloop);
  199. }
  200. /* Query actual fragment size */
  201. queried_attr = pa_stream_get_buffer_attr(pd->stream);
  202. if (!queried_attr || queried_attr->fragsize > INT_MAX/100) {
  203. ret = AVERROR_EXTERNAL;
  204. goto unlock_and_fail;
  205. }
  206. pd->fragment_size = queried_attr->fragsize;
  207. pd->pa_frame_size = pa_frame_size(&ss);
  208. pa_threaded_mainloop_unlock(pd->mainloop);
  209. /* take real parameters */
  210. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  211. st->codecpar->codec_id = codec_id;
  212. st->codecpar->sample_rate = pd->sample_rate;
  213. st->codecpar->ch_layout.nb_channels = pd->channels;
  214. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  215. pd->timefilter = ff_timefilter_new(1000000.0 / pd->sample_rate,
  216. pd->fragment_size / pd->pa_frame_size, 1.5E-6);
  217. if (!pd->timefilter) {
  218. pulse_close(s);
  219. return AVERROR(ENOMEM);
  220. }
  221. return 0;
  222. unlock_and_fail:
  223. pa_threaded_mainloop_unlock(pd->mainloop);
  224. pulse_close(s);
  225. return ret;
  226. }
  227. static int pulse_read_packet(AVFormatContext *s, AVPacket *pkt)
  228. {
  229. PulseData *pd = s->priv_data;
  230. int ret;
  231. size_t read_length;
  232. const void *read_data = NULL;
  233. int64_t dts;
  234. pa_usec_t latency;
  235. int negative;
  236. ptrdiff_t pos = 0;
  237. pa_threaded_mainloop_lock(pd->mainloop);
  238. CHECK_DEAD_GOTO(pd, ret, unlock_and_fail);
  239. while (pos < pd->fragment_size) {
  240. int r;
  241. r = pa_stream_peek(pd->stream, &read_data, &read_length);
  242. CHECK_SUCCESS_GOTO(ret, r == 0, unlock_and_fail);
  243. if (read_length <= 0) {
  244. pa_threaded_mainloop_wait(pd->mainloop);
  245. CHECK_DEAD_GOTO(pd, ret, unlock_and_fail);
  246. } else if (!read_data) {
  247. /* There's a hole in the stream, skip it. We could generate
  248. * silence, but that wouldn't work for compressed streams. */
  249. r = pa_stream_drop(pd->stream);
  250. CHECK_SUCCESS_GOTO(ret, r == 0, unlock_and_fail);
  251. } else {
  252. if (!pos) {
  253. if (av_new_packet(pkt, pd->fragment_size) < 0) {
  254. ret = AVERROR(ENOMEM);
  255. goto unlock_and_fail;
  256. }
  257. dts = av_gettime();
  258. pa_operation_unref(pa_stream_update_timing_info(pd->stream, NULL, NULL));
  259. if (pa_stream_get_latency(pd->stream, &latency, &negative) >= 0) {
  260. if (negative) {
  261. dts += latency;
  262. } else
  263. dts -= latency;
  264. } else {
  265. av_log(s, AV_LOG_WARNING, "pa_stream_get_latency() failed\n");
  266. }
  267. }
  268. if (pkt->size - pos < read_length) {
  269. if (pos)
  270. break;
  271. pa_stream_drop(pd->stream);
  272. /* Oversized fragment??? */
  273. ret = AVERROR_EXTERNAL;
  274. goto unlock_and_fail;
  275. }
  276. memcpy(pkt->data + pos, read_data, read_length);
  277. pos += read_length;
  278. pa_stream_drop(pd->stream);
  279. }
  280. }
  281. pa_threaded_mainloop_unlock(pd->mainloop);
  282. av_shrink_packet(pkt, pos);
  283. if (pd->wallclock)
  284. pkt->pts = ff_timefilter_update(pd->timefilter, dts, pd->last_period);
  285. pd->last_period = pkt->size / pd->pa_frame_size;
  286. return 0;
  287. unlock_and_fail:
  288. av_packet_unref(pkt);
  289. pa_threaded_mainloop_unlock(pd->mainloop);
  290. return ret;
  291. }
  292. static int pulse_get_device_list(AVFormatContext *h, AVDeviceInfoList *device_list)
  293. {
  294. PulseData *s = h->priv_data;
  295. return ff_pulse_audio_get_devices(device_list, s->server, 0);
  296. }
  297. #define OFFSET(a) offsetof(PulseData, a)
  298. #define D AV_OPT_FLAG_DECODING_PARAM
  299. #define DEPR AV_OPT_FLAG_DEPRECATED
  300. static const AVOption options[] = {
  301. { "server", "set PulseAudio server", OFFSET(server), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, D },
  302. { "name", "set application name", OFFSET(name), AV_OPT_TYPE_STRING, {.str = LIBAVFORMAT_IDENT}, 0, 0, D },
  303. { "stream_name", "set stream description", OFFSET(stream_name), AV_OPT_TYPE_STRING, {.str = "record"}, 0, 0, D },
  304. { "sample_rate", "set sample rate in Hz", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 48000}, 1, INT_MAX, D },
  305. { "channels", "set number of audio channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 2}, 1, INT_MAX, D },
  306. { "frame_size", "set number of bytes per frame", OFFSET(frame_size), AV_OPT_TYPE_INT, {.i64 = 1024}, 1, INT_MAX, D | DEPR },
  307. { "fragment_size", "set buffering size, affects latency and cpu usage", OFFSET(fragment_size), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D },
  308. { "wallclock", "set the initial pts using the current time", OFFSET(wallclock), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, D },
  309. { NULL },
  310. };
  311. static const AVClass pulse_demuxer_class = {
  312. .class_name = "Pulse indev",
  313. .item_name = av_default_item_name,
  314. .option = options,
  315. .version = LIBAVUTIL_VERSION_INT,
  316. .category = AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT,
  317. };
  318. const AVInputFormat ff_pulse_demuxer = {
  319. .name = "pulse",
  320. .long_name = NULL_IF_CONFIG_SMALL("Pulse audio input"),
  321. .priv_data_size = sizeof(PulseData),
  322. .read_header = pulse_read_header,
  323. .read_packet = pulse_read_packet,
  324. .read_close = pulse_close,
  325. .get_device_list = pulse_get_device_list,
  326. .flags = AVFMT_NOFILE,
  327. .priv_class = &pulse_demuxer_class,
  328. };