FFmpeg
Loading...
Searching...
No Matches
pulse_audio_dec.c
Go to the documentation of this file.
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
24#include <pulse/rtclock.h>
25#include <pulse/error.h>
26
27#include "libavutil/internal.h"
28#include "libavutil/opt.h"
29#include "libavutil/time.h"
30
32#include "libavformat/demux.h"
34#include "libavformat/version.h"
35#include "pulse_audio_common.h"
36#include "timefilter.h"
37
38#define DEFAULT_CODEC_ID AV_NE(AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE)
39
40typedef struct PulseData {
41 AVClass *class;
42 char *server;
43 char *name;
49
50 pa_threaded_mainloop *mainloop;
51 pa_context *context;
52 pa_stream *stream;
54
58} PulseData;
59
60
61#define CHECK_SUCCESS_GOTO(rerror, expression, label) \
62 do { \
63 if (!(expression)) { \
64 rerror = AVERROR_EXTERNAL; \
65 goto label; \
66 } \
67 } while (0)
68
69#define CHECK_DEAD_GOTO(p, rerror, label) \
70 do { \
71 if (!(p)->context || !PA_CONTEXT_IS_GOOD(pa_context_get_state((p)->context)) || \
72 !(p)->stream || !PA_STREAM_IS_GOOD(pa_stream_get_state((p)->stream))) { \
73 rerror = AVERROR_EXTERNAL; \
74 goto label; \
75 } \
76 } while (0)
77
78static void context_state_cb(pa_context *c, void *userdata) {
79 PulseData *p = userdata;
80
81 switch (pa_context_get_state(c)) {
82 case PA_CONTEXT_READY:
83 case PA_CONTEXT_TERMINATED:
84 case PA_CONTEXT_FAILED:
85 pa_threaded_mainloop_signal(p->mainloop, 0);
86 break;
87 }
88}
89
90static void stream_state_cb(pa_stream *s, void * userdata) {
91 PulseData *p = userdata;
92
93 switch (pa_stream_get_state(s)) {
94 case PA_STREAM_READY:
95 case PA_STREAM_FAILED:
96 case PA_STREAM_TERMINATED:
97 pa_threaded_mainloop_signal(p->mainloop, 0);
98 break;
99 }
100}
101
102static void stream_request_cb(pa_stream *s, size_t length, void *userdata) {
103 PulseData *p = userdata;
104
105 pa_threaded_mainloop_signal(p->mainloop, 0);
106}
107
108static void stream_latency_update_cb(pa_stream *s, void *userdata) {
109 PulseData *p = userdata;
110
111 pa_threaded_mainloop_signal(p->mainloop, 0);
112}
113
115{
116 PulseData *pd = s->priv_data;
117
118 if (pd->mainloop)
119 pa_threaded_mainloop_stop(pd->mainloop);
120
121 if (pd->stream)
122 pa_stream_unref(pd->stream);
123 pd->stream = NULL;
124
125 if (pd->context) {
126 pa_context_disconnect(pd->context);
127 pa_context_unref(pd->context);
128 }
129 pd->context = NULL;
130
131 if (pd->mainloop)
132 pa_threaded_mainloop_free(pd->mainloop);
133 pd->mainloop = NULL;
134
136 pd->timefilter = NULL;
137
138 return 0;
139}
140
142{
143 PulseData *pd = s->priv_data;
144 AVStream *st;
145 char *device = NULL;
146 int ret;
147 enum AVCodecID codec_id =
148 s->audio_codec_id == AV_CODEC_ID_NONE ? DEFAULT_CODEC_ID : s->audio_codec_id;
149 const pa_sample_spec ss = { ff_codec_id_to_pulse_format(codec_id),
150 pd->sample_rate,
151 pd->channels };
152
153 pa_buffer_attr attr = { -1 };
154 pa_channel_map cmap;
155 const pa_buffer_attr *queried_attr;
156
157 pa_channel_map_init_extend(&cmap, pd->channels, PA_CHANNEL_MAP_WAVEEX);
158
159 if (!pa_sample_spec_valid(&ss)) {
160 av_log(s, AV_LOG_ERROR, "Invalid sample spec.\n");
161 return AVERROR(EINVAL);
162 }
163
165
166 if (!st) {
167 av_log(s, AV_LOG_ERROR, "Cannot add stream\n");
168 return AVERROR(ENOMEM);
169 }
170
171 if (pd->fragment_size == -1) {
172 // 50 ms fragments/latency by default seem good enough
173 attr.fragsize = pa_frame_size(&ss) * (pd->sample_rate / 20);
174 } else {
175 attr.fragsize = pd->fragment_size;
176 }
177
178 if (s->url[0] != '\0' && strcmp(s->url, "default"))
179 device = s->url;
180
181 if (!(pd->mainloop = pa_threaded_mainloop_new())) {
182 pulse_close(s);
183 return AVERROR_EXTERNAL;
184 }
185
186 if (!(pd->context = pa_context_new(pa_threaded_mainloop_get_api(pd->mainloop), pd->name))) {
187 pulse_close(s);
188 return AVERROR_EXTERNAL;
189 }
190
191 pa_context_set_state_callback(pd->context, context_state_cb, pd);
192
193 if (pa_context_connect(pd->context, pd->server, 0, NULL) < 0) {
194 pulse_close(s);
195 return AVERROR(pa_context_errno(pd->context));
196 }
197
198 pa_threaded_mainloop_lock(pd->mainloop);
199
200 if (pa_threaded_mainloop_start(pd->mainloop) < 0) {
201 ret = -1;
202 goto unlock_and_fail;
203 }
204
205 for (;;) {
206 pa_context_state_t state;
207
208 state = pa_context_get_state(pd->context);
209
210 if (state == PA_CONTEXT_READY)
211 break;
212
213 if (!PA_CONTEXT_IS_GOOD(state)) {
214 ret = AVERROR(pa_context_errno(pd->context));
215 goto unlock_and_fail;
216 }
217
218 /* Wait until the context is ready */
219 pa_threaded_mainloop_wait(pd->mainloop);
220 }
221
222 if (!(pd->stream = pa_stream_new(pd->context, pd->stream_name, &ss, &cmap))) {
223 ret = AVERROR(pa_context_errno(pd->context));
224 goto unlock_and_fail;
225 }
226
227 pa_stream_set_state_callback(pd->stream, stream_state_cb, pd);
228 pa_stream_set_read_callback(pd->stream, stream_request_cb, pd);
229 pa_stream_set_write_callback(pd->stream, stream_request_cb, pd);
230 pa_stream_set_latency_update_callback(pd->stream, stream_latency_update_cb, pd);
231
232 ret = pa_stream_connect_record(pd->stream, device, &attr,
233 PA_STREAM_INTERPOLATE_TIMING
234 |PA_STREAM_ADJUST_LATENCY
235 |PA_STREAM_AUTO_TIMING_UPDATE);
236
237 if (ret < 0) {
238 ret = AVERROR(pa_context_errno(pd->context));
239 goto unlock_and_fail;
240 }
241
242 for (;;) {
243 pa_stream_state_t state;
244
245 state = pa_stream_get_state(pd->stream);
246
247 if (state == PA_STREAM_READY)
248 break;
249
250 if (!PA_STREAM_IS_GOOD(state)) {
251 ret = AVERROR(pa_context_errno(pd->context));
252 goto unlock_and_fail;
253 }
254
255 /* Wait until the stream is ready */
256 pa_threaded_mainloop_wait(pd->mainloop);
257 }
258
259 /* Query actual fragment size */
260 queried_attr = pa_stream_get_buffer_attr(pd->stream);
261 if (!queried_attr || queried_attr->fragsize > INT_MAX/100) {
262 ret = AVERROR_EXTERNAL;
263 goto unlock_and_fail;
264 }
265 pd->fragment_size = queried_attr->fragsize;
266 pd->pa_frame_size = pa_frame_size(&ss);
267
268 pa_threaded_mainloop_unlock(pd->mainloop);
269
270 /* take real parameters */
275 avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
276
277 pd->timefilter = ff_timefilter_new(1000000.0 / pd->sample_rate,
278 pd->fragment_size / pd->pa_frame_size, 1.5E-6);
279
280 if (!pd->timefilter) {
281 pulse_close(s);
282 return AVERROR(ENOMEM);
283 }
284
285 return 0;
286
287unlock_and_fail:
288 pa_threaded_mainloop_unlock(pd->mainloop);
289
290 pulse_close(s);
291 return ret;
292}
293
295{
296 PulseData *pd = s->priv_data;
297 int ret;
298 size_t read_length;
299 const void *read_data = NULL;
300 int64_t dts;
301 pa_usec_t latency;
302 int negative;
303 ptrdiff_t pos = 0;
304
305 pa_threaded_mainloop_lock(pd->mainloop);
306
307 CHECK_DEAD_GOTO(pd, ret, unlock_and_fail);
308
309 while (pos < pd->fragment_size) {
310 int r;
311
312 r = pa_stream_peek(pd->stream, &read_data, &read_length);
313 CHECK_SUCCESS_GOTO(ret, r == 0, unlock_and_fail);
314
315 if (read_length <= 0) {
316 pa_threaded_mainloop_wait(pd->mainloop);
317 CHECK_DEAD_GOTO(pd, ret, unlock_and_fail);
318 } else if (!read_data) {
319 /* There's a hole in the stream, skip it. We could generate
320 * silence, but that wouldn't work for compressed streams. */
321 r = pa_stream_drop(pd->stream);
322 CHECK_SUCCESS_GOTO(ret, r == 0, unlock_and_fail);
323 } else {
324 if (!pos) {
325 if (av_new_packet(pkt, pd->fragment_size) < 0) {
326 ret = AVERROR(ENOMEM);
327 goto unlock_and_fail;
328 }
329
330 dts = av_gettime();
331 pa_operation_unref(pa_stream_update_timing_info(pd->stream, NULL, NULL));
332
333 if (pa_stream_get_latency(pd->stream, &latency, &negative) >= 0) {
334 if (negative) {
335 dts += latency;
336 } else
337 dts -= latency;
338 } else {
339 av_log(s, AV_LOG_WARNING, "pa_stream_get_latency() failed\n");
340 }
341 }
342 if (pkt->size - pos < read_length) {
343 if (pos)
344 break;
345 pa_stream_drop(pd->stream);
346 /* Oversized fragment??? */
347 ret = AVERROR_EXTERNAL;
348 goto unlock_and_fail;
349 }
350 memcpy(pkt->data + pos, read_data, read_length);
351 pos += read_length;
352 pa_stream_drop(pd->stream);
353 }
354 }
355
356 pa_threaded_mainloop_unlock(pd->mainloop);
357
359
360 if (pd->wallclock)
361 pkt->pts = ff_timefilter_update(pd->timefilter, dts, pd->last_period);
362 pd->last_period = pkt->size / pd->pa_frame_size;
363
364 return 0;
365
366unlock_and_fail:
368 pa_threaded_mainloop_unlock(pd->mainloop);
369 return ret;
370}
371
373{
374 PulseData *s = h->priv_data;
375 return ff_pulse_audio_get_devices(device_list, s->server, 0);
376}
377
378#define OFFSET(a) offsetof(PulseData, a)
379#define D AV_OPT_FLAG_DECODING_PARAM
380#define DEPR AV_OPT_FLAG_DEPRECATED
381
382static const AVOption options[] = {
383 { "server", "set PulseAudio server", OFFSET(server), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, D },
384 { "name", "set application name", OFFSET(name), AV_OPT_TYPE_STRING, {.str = LIBAVFORMAT_IDENT}, 0, 0, D },
385 { "stream_name", "set stream description", OFFSET(stream_name), AV_OPT_TYPE_STRING, {.str = "record"}, 0, 0, D },
386 { "sample_rate", "set sample rate in Hz", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 48000}, 1, INT_MAX, D },
387 { "channels", "set number of audio channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 2}, 1, INT_MAX, D },
388 { "frame_size", "set number of bytes per frame", OFFSET(frame_size), AV_OPT_TYPE_INT, {.i64 = 1024}, 1, INT_MAX, D | DEPR },
389 { "fragment_size", "set buffering size, affects latency and cpu usage", OFFSET(fragment_size), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D },
390 { "wallclock", "set the initial pts using the current time", OFFSET(wallclock), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, D },
391 { NULL },
392};
393
395 .class_name = "Pulse indev",
396 .item_name = av_default_item_name,
397 .option = options,
398 .version = LIBAVUTIL_VERSION_INT,
400};
401
403 .p.name = "pulse",
404 .p.long_name = NULL_IF_CONFIG_SMALL("Pulse audio input"),
405 .p.flags = AVFMT_NOFILE,
406 .p.priv_class = &pulse_demuxer_class,
407 .priv_data_size = sizeof(PulseData),
411 .get_device_list = pulse_get_device_list,
412};
const FFInputFormat ff_pulse_demuxer
#define DEFAULT_CODEC_ID
Definition alsa.h:43
channels
Definition aptx.h:31
#define D
Definition avdct.c:35
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:834
Main libavformat public API header.
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition avformat.h:488
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
#define ss(width, name, subs,...)
Definition cbs_vp9.c:202
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static int read_data(void *opaque, uint8_t *buf, int buf_size)
Definition dashdec.c:1848
static AVPacket * pkt
static struct @346255127015250356166251341105367306144006377143 state
static int read_header(FFV1Context *f, RangeCoder *c)
Definition ffv1dec.c:578
static const uint8_t frame_size[4]
Definition g723_1.h:222
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition codec_id.h:47
@ AV_CODEC_ID_NONE
Definition codec_id.h:48
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition packet.c:113
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition packet.c:98
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define r
Definition input.c:42
Libavformat version macros.
#define LIBAVFORMAT_IDENT
Definition version.h:45
#define av_cold
Definition attributes.h:117
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:88
static av_cold int read_close(AVFormatContext *ctx)
Definition libcdio.c:143
@ AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT
Definition log.h:44
AVOptions.
pa_sample_format_t av_cold ff_codec_id_to_pulse_format(enum AVCodecID codec_id)
int ff_pulse_audio_get_devices(AVDeviceInfoList *devices, const char *server, int output)
static av_cold int pulse_read_header(AVFormatContext *s)
static void stream_state_cb(pa_stream *s, void *userdata)
static av_cold int pulse_close(AVFormatContext *s)
#define CHECK_DEAD_GOTO(p, rerror, label)
static void context_state_cb(pa_context *c, void *userdata)
static const AVClass pulse_demuxer_class
static int pulse_get_device_list(AVFormatContext *h, AVDeviceInfoList *device_list)
#define CHECK_SUCCESS_GOTO(rerror, expression, label)
#define OFFSET(a)
static void stream_request_cb(pa_stream *s, size_t length, void *userdata)
static int pulse_read_packet(AVFormatContext *s, AVPacket *pkt)
#define DEPR
static void stream_latency_update_cb(pa_stream *s, void *userdata)
const char * name
Definition qsvenc.c:142
unsigned int pos
Definition spdifenc.c:431
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
List of devices.
Definition avdevice.h:343
Format I/O context.
Definition avformat.h:1333
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
Stream structure.
Definition avformat.h:766
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:789
pa_context * context
char * stream_name
TimeFilter * timefilter
pa_threaded_mainloop * mainloop
size_t pa_frame_size
pa_stream * stream
Opaque type representing a time filter state.
Definition timefilter.c:34
#define av_log(a,...)
int64_t av_gettime(void)
Get the current time in microseconds.
Definition time.c:40
double ff_timefilter_update(TimeFilter *self, double system_time, double period)
Update the filter.
Definition timefilter.c:76
void ff_timefilter_destroy(TimeFilter *self)
Free all resources associated with the filter.
Definition timefilter.c:66
TimeFilter * ff_timefilter_new(double time_base, double period, double bandwidth)
Create a new Delay Locked Loop time filter.
Definition timefilter.c:50
enum AVCodecID codec_id
static double c[64]