2 * Copyright (c) 2023 Omar Polo <op@omarpolo.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <alsa/asoundlib.h>
26 static snd_pcm_t *pcm;
28 static void (*onmove_cb)(void *, int);
31 audio_open(void (*cb)(void *, int))
33 const char *device = "default";
36 err = snd_pcm_open(&pcm, device, SND_PCM_STREAM_PLAYBACK,
39 log_warnx("playback open error: %s", snd_strerror(err));
48 audio_setup(unsigned int bits, unsigned int rate, unsigned int channels,
49 struct pollfd *pfds, int nfds)
55 fmt = SND_PCM_FORMAT_S8;
57 } else if (bits == 16) {
58 fmt = SND_PCM_FORMAT_S16;
60 } else if (bits == 24) {
61 fmt = SND_PCM_FORMAT_S24;
63 } else if (bits == 32) {
64 fmt = SND_PCM_FORMAT_S32;
67 log_warnx("can't handle %d bits", bits);
73 err = snd_pcm_set_params(pcm, fmt, SND_PCM_ACCESS_RW_INTERLEAVED,
74 channels, rate, 1, 500000 /* 0.5s */);
76 log_warnx("invalid params: %s", snd_strerror(err));
80 err = snd_pcm_prepare(pcm);
82 log_warnx("snd_pcm_prepare failed: %s", snd_strerror(err));
92 return snd_pcm_poll_descriptors_count(pcm);
96 audio_pollfd(struct pollfd *pfds, int nfds, int events)
98 return snd_pcm_poll_descriptors(pcm, pfds, nfds);
102 audio_revents(struct pollfd *pfds, int nfds)
105 unsigned short revents;
107 err = snd_pcm_poll_descriptors_revents(pcm, pfds, nfds, &revents);
109 log_warnx("snd revents failure: %s", snd_strerror(err));
117 audio_write(const void *buf, size_t len)
119 snd_pcm_sframes_t avail, ret;
122 * snd_pcm_writei works in terms of FRAMES, not BYTES!
126 avail = snd_pcm_avail_update(pcm);
128 if (avail == -EPIPE) {
129 log_debug("alsa xrun occurred");
130 snd_pcm_recover(pcm, -EPIPE, 1);
133 log_warnx("snd_pcm_avail_update failure: %s",
134 snd_strerror(avail));
141 ret = snd_pcm_writei(pcm, buf, len);
143 log_warnx("snd_pcm_writei failed: %s", snd_strerror(ret));
147 onmove_cb(NULL, ret);
156 err = snd_pcm_drop(pcm);
158 log_warnx("snd_pcm_drop: %s", snd_strerror(err));
170 err = snd_pcm_drain(pcm);
172 log_warnx("snd_pcm_drain: %s", snd_strerror(err));