gl_common: minor cleanup/refactor
[mplayer.git] / libao2 / ao_pulse.c
blobb266d66bac8599bcefdf5c6b76df72f5a32a983f
1 /*
2 * PulseAudio audio output driver.
3 * Copyright (C) 2006 Lennart Poettering
4 * Copyright (C) 2007 Reimar Doeffinger
6 * This file is part of MPlayer.
8 * MPlayer is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * MPlayer 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
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <string.h>
27 #include <pulse/pulseaudio.h>
29 #include "config.h"
30 #include "libaf/af_format.h"
31 #include "mp_msg.h"
32 #include "audio_out.h"
33 #include "input/input.h"
35 #define PULSE_CLIENT_NAME "mplayer2"
38 struct priv {
39 // PulseAudio playback stream object
40 struct pa_stream *stream;
42 // PulseAudio connection context
43 struct pa_context *context;
45 // Main event loop object
46 struct pa_threaded_mainloop *mainloop;
48 // temporary during control()
49 struct pa_sink_input_info pi;
51 bool broken_pause;
52 int retval;
55 #define GENERIC_ERR_MSG(ctx, str) \
56 mp_msg(MSGT_AO, MSGL_ERR, "AO: [pulse] "str": %s\n", \
57 pa_strerror(pa_context_errno(ctx)))
59 static void context_state_cb(pa_context *c, void *userdata)
61 struct ao *ao = userdata;
62 struct priv *priv = ao->priv;
63 switch (pa_context_get_state(c)) {
64 case PA_CONTEXT_READY:
65 case PA_CONTEXT_TERMINATED:
66 case PA_CONTEXT_FAILED:
67 pa_threaded_mainloop_signal(priv->mainloop, 0);
68 break;
72 static void stream_state_cb(pa_stream *s, void *userdata)
74 struct ao *ao = userdata;
75 struct priv *priv = ao->priv;
76 switch (pa_stream_get_state(s)) {
77 case PA_STREAM_READY:
78 case PA_STREAM_FAILED:
79 case PA_STREAM_TERMINATED:
80 pa_threaded_mainloop_signal(priv->mainloop, 0);
81 break;
85 static void stream_request_cb(pa_stream *s, size_t length, void *userdata)
87 struct ao *ao = userdata;
88 struct priv *priv = ao->priv;
89 mp_input_wakeup(ao->input_ctx);
90 pa_threaded_mainloop_signal(priv->mainloop, 0);
93 static void stream_latency_update_cb(pa_stream *s, void *userdata)
95 struct ao *ao = userdata;
96 struct priv *priv = ao->priv;
97 pa_threaded_mainloop_signal(priv->mainloop, 0);
100 static void success_cb(pa_stream *s, int success, void *userdata)
102 struct ao *ao = userdata;
103 struct priv *priv = ao->priv;
104 priv->retval = success;
105 pa_threaded_mainloop_signal(priv->mainloop, 0);
109 * \brief waits for a pulseaudio operation to finish, frees it and
110 * unlocks the mainloop
111 * \param op operation to wait for
112 * \return 1 if operation has finished normally (DONE state), 0 otherwise
114 static int waitop(struct priv *priv, pa_operation *op)
116 if (!op) {
117 pa_threaded_mainloop_unlock(priv->mainloop);
118 return 0;
120 pa_operation_state_t state = pa_operation_get_state(op);
121 while (state == PA_OPERATION_RUNNING) {
122 pa_threaded_mainloop_wait(priv->mainloop);
123 state = pa_operation_get_state(op);
125 pa_operation_unref(op);
126 pa_threaded_mainloop_unlock(priv->mainloop);
127 return state == PA_OPERATION_DONE;
130 static const struct format_map {
131 int mp_format;
132 pa_sample_format_t pa_format;
133 } format_maps[] = {
134 {AF_FORMAT_S16_LE, PA_SAMPLE_S16LE},
135 {AF_FORMAT_S16_BE, PA_SAMPLE_S16BE},
136 {AF_FORMAT_S32_LE, PA_SAMPLE_S32LE},
137 {AF_FORMAT_S32_BE, PA_SAMPLE_S32BE},
138 {AF_FORMAT_FLOAT_LE, PA_SAMPLE_FLOAT32LE},
139 {AF_FORMAT_FLOAT_BE, PA_SAMPLE_FLOAT32BE},
140 {AF_FORMAT_U8, PA_SAMPLE_U8},
141 {AF_FORMAT_MU_LAW, PA_SAMPLE_ULAW},
142 {AF_FORMAT_A_LAW, PA_SAMPLE_ALAW},
143 {AF_FORMAT_UNKNOWN, 0}
146 static void uninit(struct ao *ao, bool cut_audio)
148 struct priv *priv = ao->priv;
149 if (priv->stream && !cut_audio) {
150 pa_threaded_mainloop_lock(priv->mainloop);
151 waitop(priv, pa_stream_drain(priv->stream, success_cb, ao));
154 if (priv->mainloop)
155 pa_threaded_mainloop_stop(priv->mainloop);
157 if (priv->stream) {
158 pa_stream_disconnect(priv->stream);
159 pa_stream_unref(priv->stream);
160 priv->stream = NULL;
163 if (priv->context) {
164 pa_context_disconnect(priv->context);
165 pa_context_unref(priv->context);
166 priv->context = NULL;
169 if (priv->mainloop) {
170 pa_threaded_mainloop_free(priv->mainloop);
171 priv->mainloop = NULL;
175 static int init(struct ao *ao, char *params)
177 struct pa_sample_spec ss;
178 struct pa_channel_map map;
179 char *devarg = NULL;
180 char *host = NULL;
181 char *sink = NULL;
182 const char *version = pa_get_library_version();
184 struct priv *priv = talloc_zero(ao, struct priv);
185 ao->priv = priv;
187 if (params) {
188 devarg = strdup(params);
189 sink = strchr(devarg, ':');
190 if (sink)
191 *sink++ = 0;
192 if (devarg[0])
193 host = devarg;
196 priv->broken_pause = false;
197 /* not sure which versions are affected, assume 0.9.11* to 0.9.14*
198 * known bad: 0.9.14, 0.9.13
199 * known good: 0.9.9, 0.9.10, 0.9.15
200 * To test: pause, wait ca. 5 seconds, framestep and see if MPlayer
201 * hangs somewhen. */
202 if (strncmp(version, "0.9.1", 5) == 0 && version[5] >= '1'
203 && version[5] <= '4') {
204 mp_msg(MSGT_AO, MSGL_WARN,
205 "[pulse] working around probably broken pause functionality,\n"
206 " see http://www.pulseaudio.org/ticket/440\n");
207 priv->broken_pause = true;
210 ss.channels = ao->channels;
211 ss.rate = ao->samplerate;
213 const struct format_map *fmt_map = format_maps;
214 while (fmt_map->mp_format != ao->format) {
215 if (fmt_map->mp_format == AF_FORMAT_UNKNOWN) {
216 mp_msg(MSGT_AO, MSGL_V,
217 "AO: [pulse] Unsupported format, using default\n");
218 fmt_map = format_maps;
219 break;
221 fmt_map++;
223 ao->format = fmt_map->mp_format;
224 ss.format = fmt_map->pa_format;
226 if (!pa_sample_spec_valid(&ss)) {
227 mp_msg(MSGT_AO, MSGL_ERR, "AO: [pulse] Invalid sample spec\n");
228 goto fail;
231 pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_ALSA);
232 ao->bps = pa_bytes_per_second(&ss);
234 if (!(priv->mainloop = pa_threaded_mainloop_new())) {
235 mp_msg(MSGT_AO, MSGL_ERR, "AO: [pulse] Failed to allocate main loop\n");
236 goto fail;
239 if (!(priv->context = pa_context_new(pa_threaded_mainloop_get_api(
240 priv->mainloop), PULSE_CLIENT_NAME))) {
241 mp_msg(MSGT_AO, MSGL_ERR, "AO: [pulse] Failed to allocate context\n");
242 goto fail;
245 pa_context_set_state_callback(priv->context, context_state_cb, ao);
247 if (pa_context_connect(priv->context, host, 0, NULL) < 0)
248 goto fail;
250 pa_threaded_mainloop_lock(priv->mainloop);
252 if (pa_threaded_mainloop_start(priv->mainloop) < 0)
253 goto unlock_and_fail;
255 /* Wait until the context is ready */
256 pa_threaded_mainloop_wait(priv->mainloop);
258 if (pa_context_get_state(priv->context) != PA_CONTEXT_READY)
259 goto unlock_and_fail;
261 if (!(priv->stream = pa_stream_new(priv->context, "audio stream", &ss,
262 &map)))
263 goto unlock_and_fail;
265 pa_stream_set_state_callback(priv->stream, stream_state_cb, ao);
266 pa_stream_set_write_callback(priv->stream, stream_request_cb, ao);
267 pa_stream_set_latency_update_callback(priv->stream,
268 stream_latency_update_cb, ao);
269 pa_buffer_attr bufattr = {
270 .maxlength = -1,
271 .tlength = pa_usec_to_bytes(1000000, &ss),
272 .prebuf = -1,
273 .minreq = -1,
274 .fragsize = -1,
276 if (pa_stream_connect_playback(priv->stream, sink, &bufattr,
277 PA_STREAM_NOT_MONOTONIC, NULL, NULL) < 0)
278 goto unlock_and_fail;
280 /* Wait until the stream is ready */
281 pa_threaded_mainloop_wait(priv->mainloop);
283 if (pa_stream_get_state(priv->stream) != PA_STREAM_READY)
284 goto unlock_and_fail;
286 pa_threaded_mainloop_unlock(priv->mainloop);
288 free(devarg);
289 return 0;
291 unlock_and_fail:
293 if (priv->mainloop)
294 pa_threaded_mainloop_unlock(priv->mainloop);
296 fail:
297 if (priv->context)
298 GENERIC_ERR_MSG(priv->context, "Init failed");
299 free(devarg);
300 uninit(ao, true);
301 return -1;
304 static void cork(struct ao *ao, bool pause)
306 struct priv *priv = ao->priv;
307 pa_threaded_mainloop_lock(priv->mainloop);
308 priv->retval = 0;
309 if (!waitop(priv, pa_stream_cork(priv->stream, pause, success_cb, ao)) ||
310 !priv->retval)
311 GENERIC_ERR_MSG(priv->context, "pa_stream_cork() failed");
314 // Play the specified data to the pulseaudio server
315 static int play(struct ao *ao, void *data, int len, int flags)
317 struct priv *priv = ao->priv;
318 pa_threaded_mainloop_lock(priv->mainloop);
319 if (pa_stream_write(priv->stream, data, len, NULL, 0,
320 PA_SEEK_RELATIVE) < 0) {
321 GENERIC_ERR_MSG(priv->context, "pa_stream_write() failed");
322 len = -1;
324 if (flags & AOPLAY_FINAL_CHUNK) {
325 // Force start in case the stream was too short for prebuf
326 pa_operation *op = pa_stream_trigger(priv->stream, NULL, NULL);
327 pa_operation_unref(op);
329 pa_threaded_mainloop_unlock(priv->mainloop);
330 return len;
333 // Reset the audio stream, i.e. flush the playback buffer on the server side
334 static void reset(struct ao *ao)
336 // pa_stream_flush() works badly if not corked
337 cork(ao, true);
338 struct priv *priv = ao->priv;
339 pa_threaded_mainloop_lock(priv->mainloop);
340 priv->retval = 0;
341 if (!waitop(priv, pa_stream_flush(priv->stream, success_cb, ao)) ||
342 !priv->retval)
343 GENERIC_ERR_MSG(priv->context, "pa_stream_flush() failed");
344 cork(ao, false);
347 // Pause the audio stream by corking it on the server
348 static void pause(struct ao *ao)
350 cork(ao, true);
353 // Resume the audio stream by uncorking it on the server
354 static void resume(struct ao *ao)
356 struct priv *priv = ao->priv;
357 /* Without this, certain versions will cause an infinite hang because
358 * pa_stream_writable_size returns 0 always.
359 * Note that this workaround causes A-V desync after pause. */
360 if (priv->broken_pause)
361 reset(ao);
362 cork(ao, false);
365 // Return number of bytes that may be written to the server without blocking
366 static int get_space(struct ao *ao)
368 struct priv *priv = ao->priv;
369 pa_threaded_mainloop_lock(priv->mainloop);
370 size_t space = pa_stream_writable_size(priv->stream);
371 pa_threaded_mainloop_unlock(priv->mainloop);
372 return space;
375 // Return the current latency in seconds
376 static float get_delay(struct ao *ao)
378 /* This code basically does what pa_stream_get_latency() _should_
379 * do, but doesn't due to multiple known bugs in PulseAudio (at
380 * PulseAudio version 2.1). In particular, the timing interpolation
381 * mode (PA_STREAM_INTERPOLATE_TIMING) can return completely bogus
382 * values, and the non-interpolating code has a bug causing too
383 * large results at end of stream (so a stream never seems to finish).
384 * This code can still return wrong values in some cases due to known
385 * PulseAudio bugs that can not be worked around on the client side.
387 * We always query the server for latest timing info. This may take
388 * too long to work well with remote audio servers, but at least
389 * this should be enough to fix the normal local playback case.
391 struct priv *priv = ao->priv;
392 pa_threaded_mainloop_lock(priv->mainloop);
393 if (!waitop(priv, pa_stream_update_timing_info(priv->stream, NULL, NULL))) {
394 GENERIC_ERR_MSG(priv->context, "pa_stream_update_timing_info() failed");
395 return 0;
397 pa_threaded_mainloop_lock(priv->mainloop);
398 const pa_timing_info *ti = pa_stream_get_timing_info(priv->stream);
399 if (!ti) {
400 pa_threaded_mainloop_unlock(priv->mainloop);
401 GENERIC_ERR_MSG(priv->context, "pa_stream_get_timing_info() failed");
402 return 0;
404 const struct pa_sample_spec *ss = pa_stream_get_sample_spec(priv->stream);
405 if (!ss) {
406 pa_threaded_mainloop_unlock(priv->mainloop);
407 GENERIC_ERR_MSG(priv->context, "pa_stream_get_sample_spec() failed");
408 return 0;
410 // data left in PulseAudio's main buffers (not written to sink yet)
411 int64_t latency = pa_bytes_to_usec(ti->write_index - ti->read_index, ss);
412 // since this info may be from a while ago, playback has progressed since
413 latency -= ti->transport_usec;
414 // data already moved from buffers to sink, but not played yet
415 int64_t sink_latency = ti->sink_usec;
416 if (!ti->playing)
417 /* At the end of a stream, part of the data "left" in the sink may
418 * be padding silence after the end; that should be subtracted to
419 * get the amount of real audio from our stream. This adjustment
420 * is missing from Pulseaudio's own get_latency calculations
421 * (as of PulseAudio 2.1). */
422 sink_latency -= pa_bytes_to_usec(ti->since_underrun, ss);
423 if (sink_latency > 0)
424 latency += sink_latency;
425 if (latency < 0)
426 latency = 0;
427 pa_threaded_mainloop_unlock(priv->mainloop);
428 return latency / 1e6;
431 /* A callback function that is called when the
432 * pa_context_get_sink_input_info() operation completes. Saves the
433 * volume field of the specified structure to the global variable volume.
435 static void info_func(struct pa_context *c, const struct pa_sink_input_info *i,
436 int is_last, void *userdata)
438 struct ao *ao = userdata;
439 struct priv *priv = ao->priv;
440 if (is_last < 0) {
441 GENERIC_ERR_MSG(priv->context, "Failed to get sink input info");
442 return;
444 if (!i)
445 return;
446 priv->pi = *i;
447 pa_threaded_mainloop_signal(priv->mainloop, 0);
450 static int control(struct ao *ao, enum aocontrol cmd, void *arg)
452 struct priv *priv = ao->priv;
453 switch (cmd) {
454 case AOCONTROL_GET_MUTE:
455 case AOCONTROL_GET_VOLUME: {
456 uint32_t devidx = pa_stream_get_index(priv->stream);
457 pa_threaded_mainloop_lock(priv->mainloop);
458 if (!waitop(priv, pa_context_get_sink_input_info(priv->context, devidx,
459 info_func, ao))) {
460 GENERIC_ERR_MSG(priv->context,
461 "pa_stream_get_sink_input_info() failed");
462 return CONTROL_ERROR;
464 // Warning: some information in pi might be unaccessible, because
465 // we naively copied the struct, without updating pointers etc.
466 // Pointers might point to invalid data, accessors might fail.
467 if (cmd == AOCONTROL_GET_VOLUME) {
468 ao_control_vol_t *vol = arg;
469 if (priv->pi.volume.channels != 2)
470 vol->left = vol->right =
471 pa_cvolume_avg(&priv->pi.volume) * 100 / PA_VOLUME_NORM;
472 else {
473 vol->left = priv->pi.volume.values[0] * 100 / PA_VOLUME_NORM;
474 vol->right = priv->pi.volume.values[1] * 100 / PA_VOLUME_NORM;
476 } else if (cmd == AOCONTROL_GET_MUTE) {
477 bool *mute = arg;
478 *mute = priv->pi.mute;
480 return CONTROL_OK;
483 case AOCONTROL_SET_MUTE:
484 case AOCONTROL_SET_VOLUME: {
485 pa_operation *o;
487 pa_threaded_mainloop_lock(priv->mainloop);
488 uint32_t stream_index = pa_stream_get_index(priv->stream);
489 if (cmd == AOCONTROL_SET_VOLUME) {
490 const ao_control_vol_t *vol = arg;
491 struct pa_cvolume volume;
493 pa_cvolume_reset(&volume, ao->channels);
494 if (volume.channels != 2)
495 pa_cvolume_set(&volume, volume.channels,
496 vol->left * PA_VOLUME_NORM / 100);
497 else {
498 volume.values[0] = vol->left * PA_VOLUME_NORM / 100;
499 volume.values[1] = vol->right * PA_VOLUME_NORM / 100;
501 o = pa_context_set_sink_input_volume(priv->context, stream_index,
502 &volume, NULL, NULL);
503 if (!o) {
504 pa_threaded_mainloop_unlock(priv->mainloop);
505 GENERIC_ERR_MSG(priv->context,
506 "pa_context_set_sink_input_volume() failed");
507 return CONTROL_ERROR;
509 } else if (cmd == AOCONTROL_SET_MUTE) {
510 const bool *mute = arg;
511 o = pa_context_set_sink_input_mute(priv->context, stream_index,
512 *mute, NULL, NULL);
513 if (!o) {
514 pa_threaded_mainloop_unlock(priv->mainloop);
515 GENERIC_ERR_MSG(priv->context,
516 "pa_context_set_sink_input_mute() failed");
517 return CONTROL_ERROR;
519 } else
520 abort();
521 /* We don't wait for completion here */
522 pa_operation_unref(o);
523 pa_threaded_mainloop_unlock(priv->mainloop);
524 return CONTROL_OK;
526 default:
527 return CONTROL_UNKNOWN;
531 const struct ao_driver audio_out_pulse = {
532 .is_new = true,
533 .info = &(const struct ao_info) {
534 "PulseAudio audio output",
535 "pulse",
536 "Lennart Poettering",
539 .control = control,
540 .init = init,
541 .uninit = uninit,
542 .reset = reset,
543 .get_space = get_space,
544 .play = play,
545 .get_delay = get_delay,
546 .pause = pause,
547 .resume = resume,