Merge branch 'refs/heads/t/ubsan'
[paraslash.git] / alsa_write.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file alsa_write.c paraslash's alsa output plugin */
4
5 /*
6 * Based in parts on aplay.c from the alsa-utils-1.0.8 package,
7 * Copyright (c) by Jaroslav Kysela <perex@suse.cz>, which is
8 * based on the vplay program by Michael Beck.
9 */
10
11 #include <regex.h>
12 #include <sys/types.h>
13 #include <alsa/asoundlib.h>
14 #include <lopsub.h>
15
16 #include "write_cmd.lsg.h"
17 #include "para.h"
18 #include "fd.h"
19 #include "string.h"
20 #include "list.h"
21 #include "sched.h"
22 #include "buffer_tree.h"
23 #include "write.h"
24 #include "error.h"
25
26 /** Data specific to the alsa writer. */
27 struct private_alsa_write_data {
28 /** The alsa handle */
29 snd_pcm_t *handle;
30 /** Determined and set by alsa_init(). */
31 int bytes_per_frame;
32 /*
33 * If the sample rate is not given at the command line and no wav
34 * header was detected, the btr exec mechanism is employed to query the
35 * ancestor buffer tree nodes for this information. In a typical setup
36 * the decoder passes the sample rate back to the alsa writer.
37 *
38 * \sa \ref btr_exec_up().
39 */
40 unsigned sample_rate;
41 /*
42 * The sample format (8/16 bit, signed/unsigned, little/big endian) is
43 * determined in the same way as the \a sample_rate.
44 */
45 snd_pcm_format_t sample_format;
46 /* The number of channels, again determined like \a sample_rate. */
47 unsigned channels;
48 /* time until buffer underrun occurs, in milliseconds */
49 unsigned buffer_time;
50 struct timeval drain_barrier;
51 /* File descriptor for select(). */
52 int poll_fd;
53 };
54
55 static snd_pcm_format_t get_alsa_pcm_format(enum sample_format sf)
56 {
57 switch (sf) {
58 case SF_S8: return SND_PCM_FORMAT_S8;
59 case SF_U8: return SND_PCM_FORMAT_U8;
60 case SF_S16_LE: return SND_PCM_FORMAT_S16_LE;
61 case SF_S16_BE: return SND_PCM_FORMAT_S16_BE;
62 case SF_U16_LE: return SND_PCM_FORMAT_U16_LE;
63 case SF_U16_BE: return SND_PCM_FORMAT_U16_BE;
64 default: return SND_PCM_FORMAT_S16_LE;
65 }
66 }
67
68 /* Install PCM software and hardware configuration. */
69 static int alsa_init(struct writer_node *wn)
70 {
71 struct private_alsa_write_data *pad = wn->private_data;
72 snd_pcm_hw_params_t *hwparams = NULL;
73 snd_pcm_sw_params_t *swparams = NULL;
74 snd_pcm_uframes_t start_threshold, stop_threshold;
75 snd_pcm_uframes_t buffer_size, period_size;
76 snd_output_t *output_log;
77 int ret;
78 const char *msg, *dev = WRITE_CMD_OPT_STRING_VAL(ALSA, DEVICE, wn->lpr);
79 unsigned period_time;
80
81 PARA_INFO_LOG("opening %s\n", dev);
82 msg = "unable to open pcm";
83 ret = snd_pcm_open(&pad->handle, dev, SND_PCM_STREAM_PLAYBACK,
84 SND_PCM_NONBLOCK);
85 if (ret < 0)
86 goto fail;
87 ret = snd_pcm_hw_params_malloc(&hwparams);
88 assert(ret >= 0);
89 msg = "Broken alsa configuration";
90 ret = snd_pcm_hw_params_any(pad->handle, hwparams);
91 if (ret < 0)
92 goto fail;
93 msg = "access type not available";
94 ret = snd_pcm_hw_params_set_access(pad->handle, hwparams,
95 SND_PCM_ACCESS_RW_INTERLEAVED);
96 if (ret < 0)
97 goto fail;
98 msg = "sample format not available";
99 ret = snd_pcm_hw_params_set_format(pad->handle, hwparams,
100 pad->sample_format);
101 if (ret < 0)
102 goto fail;
103 msg = "channels count not available";
104 ret = snd_pcm_hw_params_set_channels(pad->handle, hwparams,
105 pad->channels);
106 if (ret < 0)
107 goto fail;
108 msg = "could not set sample rate";
109 ret = snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
110 &pad->sample_rate, NULL);
111 if (ret < 0)
112 goto fail;
113 /* alsa wants microseconds */
114 pad->buffer_time = 1000U * WRITE_CMD_OPT_UINT32_VAL(ALSA, BUFFER_TIME,
115 wn->lpr);
116 msg = "could not set buffer time";
117 ret = snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
118 &pad->buffer_time, NULL);
119 if (ret < 0)
120 goto fail;
121 pad->buffer_time /= 1000; /* we prefer milliseconds */
122 period_time = pad->buffer_time * 250; /* buffer time / 4 */
123 msg = "could not set period time";
124 ret = snd_pcm_hw_params_set_period_time_near(pad->handle, hwparams,
125 &period_time, NULL);
126 if (ret < 0)
127 goto fail;
128
129 msg = "unable to install hw params";
130 ret = snd_pcm_hw_params(pad->handle, hwparams);
131 if (ret < 0)
132 goto fail;
133 snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
134 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
135 msg = "period size equals buffer size";
136 if (period_size == buffer_size)
137 goto fail;
138
139 /* software parameter setup */
140 ret = snd_pcm_sw_params_malloc(&swparams);
141 assert(ret >= 0);
142 snd_pcm_sw_params_current(pad->handle, swparams);
143 snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
144 if (buffer_size < 1)
145 start_threshold = 1;
146 else
147 start_threshold = PARA_MIN(buffer_size,
148 (snd_pcm_uframes_t)pad->sample_rate);
149 msg = "could not set start threshold";
150 ret = snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
151 start_threshold);
152 if (ret < 0)
153 goto fail;
154 stop_threshold = buffer_size;
155 msg = "could not set stop threshold";
156 ret = snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
157 stop_threshold);
158 if (ret < 0)
159 goto fail;
160 msg = "unable to install sw params";
161 ret = snd_pcm_sw_params(pad->handle, swparams);
162 if (ret < 0)
163 goto fail;
164 msg = "unable to determine bytes per frame";
165 ret = snd_pcm_format_physical_width(pad->sample_format);
166 if (ret <= 0)
167 goto fail;
168 pad->bytes_per_frame = ret * pad->channels / 8;
169 msg = "failed to set alsa handle to nonblock mode";
170 ret = snd_pcm_nonblock(pad->handle, 1);
171 if (ret < 0)
172 goto fail;
173 ret = snd_output_buffer_open(&output_log);
174 if (ret == 0) {
175 char *buf, *p;
176 size_t sz;
177 PARA_DEBUG_LOG("dumping alsa configuration\n");
178 snd_pcm_dump(pad->handle, output_log);
179 snd_pcm_hw_params_dump(hwparams, output_log);
180 sz = snd_output_buffer_string(output_log, &buf);
181 for (p = buf; p < buf + sz;) {
182 char *q = memchr(p, '\n', buf + sz - p);
183 if (!q)
184 break;
185 *q = '\0';
186 PARA_DEBUG_LOG("%s\n", p);
187 p = q + 1;
188 }
189 snd_output_close(output_log);
190 }
191 ret = 1;
192 goto out;
193 fail:
194 if (ret < 0)
195 PARA_ERROR_LOG("%s: %s\n", msg, snd_strerror(-ret));
196 else
197 PARA_ERROR_LOG("%s\n", msg);
198 ret = -E_ALSA;
199 out:
200 snd_pcm_hw_params_free(hwparams);
201 snd_pcm_sw_params_free(swparams);
202 return ret;
203 }
204
205 static void alsa_write_pre_select(struct sched *s, void *context)
206 {
207 struct pollfd pfd;
208 struct writer_node *wn = context;
209 struct private_alsa_write_data *pad = wn->private_data;
210 int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
211
212 if (pad)
213 pad->poll_fd = -1;
214 if (ret == 0)
215 return;
216 if (!pad) {
217 sched_min_delay(s);
218 return;
219 }
220 if (ret < 0) {
221 sched_request_barrier_or_min_delay(&pad->drain_barrier, s);
222 return;
223 }
224 /* wait at most 50% of the buffer time */
225 sched_request_timeout_ms(pad->buffer_time / 2, s);
226 ret = snd_pcm_poll_descriptors(pad->handle, &pfd, 1);
227 if (ret < 0) {
228 PARA_ERROR_LOG("could not get alsa poll fd: %s\n",
229 snd_strerror(-ret));
230 return;
231 }
232 pad->poll_fd = pfd.fd;
233 para_fd_set(pfd.fd, &s->rfds, &s->max_fileno);
234 }
235
236 static void alsa_close(struct writer_node *wn)
237 {
238 struct private_alsa_write_data *pad = wn->private_data;
239 PARA_INFO_LOG("closing writer node %p\n", wn);
240
241 if (!pad)
242 return;
243 if (!pad->handle)
244 goto free_pad;
245 /*
246 * It's OK to have a blocking operation here because we already made
247 * sure that the PCM output buffer is (nearly) empty.
248 */
249 snd_pcm_nonblock(pad->handle, 0);
250 snd_pcm_drain(pad->handle);
251 snd_pcm_close(pad->handle);
252 snd_config_update_free_global();
253 free_pad:
254 free(pad);
255 }
256
257 static int alsa_write_post_select(__a_unused struct sched *s, void *context)
258 {
259 struct writer_node *wn = context;
260 struct private_alsa_write_data *pad = wn->private_data;
261 struct btr_node *btrn = wn->btrn;
262 char *data;
263 size_t bytes;
264 snd_pcm_sframes_t frames;
265 int ret;
266
267 ret = task_get_notification(wn->task);
268 if (ret < 0)
269 goto err;
270 again:
271 ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
272 if (ret < 0)
273 goto err;
274 if (ret == 0)
275 return 0;
276 btr_merge(btrn, wn->min_iqs);
277 bytes = btr_next_buffer(btrn, &data);
278 if (ret < 0 || bytes < wn->min_iqs) { /* eof */
279 assert(btr_no_parent(btrn));
280 ret = -E_WRITE_COMMON_EOF;
281 if (!pad)
282 goto err;
283 /* wait until pending frames are played */
284 if (pad->drain_barrier.tv_sec == 0) {
285 PARA_DEBUG_LOG("waiting for device to drain\n");
286 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
287 &pad->drain_barrier);
288 return 0;
289 }
290 if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
291 goto err;
292 return 0;
293 }
294 if (!pad) {
295 int32_t val;
296
297 if (bytes == 0) /* no data available */
298 return 0;
299 pad = wn->private_data = para_calloc(sizeof(*pad));
300 ret = get_btr_sample_rate(btrn, &val);
301 if (ret < 0)
302 goto err;
303 pad->sample_rate = val;
304 ret = get_btr_channels(btrn, &val);
305 if (ret < 0)
306 goto err;
307 pad->channels = val;
308 ret = get_btr_sample_format(btrn, &val);
309 if (ret < 0)
310 goto err;
311 pad->sample_format = get_alsa_pcm_format(val);
312 PARA_INFO_LOG("%u channel(s), %uHz\n", pad->channels,
313 pad->sample_rate);
314 ret = alsa_init(wn);
315 if (ret < 0)
316 goto err;
317 wn->min_iqs = pad->bytes_per_frame;
318 goto again;
319 }
320 frames = bytes / pad->bytes_per_frame;
321 frames = snd_pcm_writei(pad->handle, data, frames);
322 if (frames == 0 || frames == -EAGAIN) {
323 char buf[100];
324 if (pad->poll_fd >= 0 && FD_ISSET(pad->poll_fd, &s->rfds))
325 if (read(pad->poll_fd, buf, 100))
326 do_nothing;
327 return 0;
328 }
329 if (frames > 0) {
330 btr_consume(btrn, frames * pad->bytes_per_frame);
331 goto again;
332 }
333 if (frames == -EPIPE) {
334 snd_pcm_status_t *status;
335 snd_pcm_status_malloc(&status);
336 if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN)
337 PARA_WARNING_LOG("underrun\n");
338 snd_pcm_status_free(status);
339 snd_pcm_prepare(pad->handle);
340 return 0;
341 }
342 PARA_ERROR_LOG("alsa write error: %s\n", snd_strerror(-frames));
343 ret = -E_ALSA;
344 err:
345 assert(ret < 0);
346 btr_remove_node(&wn->btrn);
347 return ret;
348 }
349
350 struct writer lsg_write_cmd_com_alsa_user_data = {
351
352 .pre_select = alsa_write_pre_select,
353 .post_select = alsa_write_post_select,
354 .close = alsa_close,
355 };