pulse_audio_dec.c 13 KB

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