Merge branch 't/makefile_cleanups'
[paraslash.git] / alsa_write.c
1 /*
2 * Copyright (C) 2005-2011 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file alsa_write.c paraslash's alsa output plugin */
8
9 /*
10 * Based in parts on aplay.c from the alsa-utils-1.0.8 package,
11 * Copyright (c) by Jaroslav Kysela <perex@suse.cz>, which is
12 * based on the vplay program by Michael Beck.
13 */
14
15 #include <regex.h>
16 #include <sys/types.h>
17 #include <alsa/asoundlib.h>
18 #include <sys/time.h>
19 #include <stdbool.h>
20
21 #include "para.h"
22 #include "fd.h"
23 #include "string.h"
24 #include "list.h"
25 #include "sched.h"
26 #include "ggo.h"
27 #include "buffer_tree.h"
28 #include "write.h"
29 #include "write_common.h"
30 #include "alsa_write.cmdline.h"
31 #include "error.h"
32
33 /** Data specific to the alsa writer. */
34 struct private_alsa_write_data {
35 /** The alsa handle */
36 snd_pcm_t *handle;
37 /** Determined and set by alsa_init(). */
38 int bytes_per_frame;
39 /**
40 * The sample rate given by command line option or the decoder
41 * of the writer node group.
42 */
43 unsigned sample_rate;
44 snd_pcm_format_t sample_format;
45 /**
46 * The number of channels, given by command line option or the
47 * decoder of the writer node group.
48 */
49 unsigned channels;
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 private_alsa_write_data *pad,
70 struct alsa_write_args_info *conf)
71 {
72 snd_pcm_hw_params_t *hwparams;
73 snd_pcm_sw_params_t *swparams;
74 snd_pcm_uframes_t start_threshold, stop_threshold;
75 snd_pcm_uframes_t buffer_size, period_size;
76 snd_output_t *log;
77 unsigned buffer_time;
78 int ret;
79 const char *msg;
80
81 PARA_INFO_LOG("opening %s\n", conf->device_arg);
82 msg = "unable to open pcm";
83 ret = snd_pcm_open(&pad->handle, conf->device_arg,
84 SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
85 if (ret < 0)
86 goto fail;
87 snd_pcm_hw_params_alloca(&hwparams);
88 msg = "Broken alsa configuration";
89 ret = snd_pcm_hw_params_any(pad->handle, hwparams);
90 if (ret < 0)
91 goto fail;
92 msg = "access type not available";
93 ret = snd_pcm_hw_params_set_access(pad->handle, hwparams,
94 SND_PCM_ACCESS_RW_INTERLEAVED);
95 if (ret < 0)
96 goto fail;
97 msg = "sample format not available";
98 ret = snd_pcm_hw_params_set_format(pad->handle, hwparams,
99 pad->sample_format);
100 if (ret < 0)
101 goto fail;
102 msg = "channels count not available";
103 ret = snd_pcm_hw_params_set_channels(pad->handle, hwparams,
104 pad->channels);
105 if (ret < 0)
106 goto fail;
107 msg = "could not set sample rate";
108 ret = snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
109 &pad->sample_rate, NULL);
110 if (ret < 0)
111 goto fail;
112 msg = "unable to get buffer time";
113 ret = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time,
114 NULL);
115 if (ret < 0 || buffer_time == 0)
116 goto fail;
117 msg = "could not set buffer time";
118 ret = snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
119 &buffer_time, NULL);
120 if (ret < 0)
121 goto fail;
122 msg = "unable to install hw params";
123 ret = snd_pcm_hw_params(pad->handle, hwparams);
124 if (ret < 0)
125 goto fail;
126 snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
127 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
128 msg = "period size equals buffer size";
129 if (period_size == buffer_size)
130 goto fail;
131
132 /* software parameter setup */
133 snd_pcm_sw_params_alloca(&swparams);
134 snd_pcm_sw_params_current(pad->handle, swparams);
135 snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
136 if (buffer_size < 1)
137 start_threshold = 1;
138 else
139 start_threshold = PARA_MIN(buffer_size,
140 (snd_pcm_uframes_t)pad->sample_rate);
141 msg = "could not set start threshold";
142 ret = snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
143 start_threshold);
144 if (ret < 0)
145 goto fail;
146 stop_threshold = buffer_size;
147 msg = "could not set stop threshold";
148 ret = snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
149 stop_threshold);
150 if (ret < 0)
151 goto fail;
152 msg = "unable to install sw params";
153 ret = snd_pcm_sw_params(pad->handle, swparams);
154 if (ret < 0)
155 goto fail;
156 msg = "unable to determine bytes per frame";
157 ret = snd_pcm_format_physical_width(pad->sample_format);
158 if (ret <= 0)
159 goto fail;
160 pad->bytes_per_frame = ret * pad->channels / 8;
161 msg = "failed to set alsa handle to nonblock mode";
162 ret = snd_pcm_nonblock(pad->handle, 1);
163 if (ret < 0)
164 goto fail;
165 ret = snd_output_buffer_open(&log);
166 if (ret == 0) {
167 char *buf;
168 PARA_INFO_LOG("dumping alsa configuration\n");
169 snd_pcm_dump(pad->handle, log);
170 snd_output_buffer_string(log, &buf);
171 for (;;) {
172 char *p = strchr(buf, '\n');
173 if (!p) /* omit last output line, it's empty */
174 break;
175 *p = '\0';
176 PARA_INFO_LOG("%s\n", buf);
177 buf = p + 1;
178 }
179 snd_output_close(log);
180 }
181 return 1;
182 fail:
183 if (ret < 0)
184 PARA_ERROR_LOG("%s: %s\n", msg, snd_strerror(-ret));
185 else
186 PARA_ERROR_LOG("%s\n", msg);
187 return -E_ALSA;
188 }
189
190 static void alsa_write_pre_select(struct sched *s, struct task *t)
191 {
192 struct pollfd pfd;
193 struct writer_node *wn = container_of(t, struct writer_node, task);
194 struct private_alsa_write_data *pad = wn->private_data;
195 int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
196
197 if (pad)
198 pad->poll_fd = -1;
199 if (ret == 0)
200 return;
201 if (!pad) {
202 sched_min_delay(s);
203 return;
204 }
205 if (ret < 0) {
206 sched_request_barrier_or_min_delay(&pad->drain_barrier, s);
207 return;
208 }
209 ret = snd_pcm_poll_descriptors(pad->handle, &pfd, 1);
210 if (ret < 0) {
211 PARA_ERROR_LOG("could not get alsa poll fd: %s\n",
212 snd_strerror(-ret));
213 t->error = -E_ALSA;
214 return;
215 }
216 pad->poll_fd = pfd.fd;
217 para_fd_set(pfd.fd, &s->rfds, &s->max_fileno);
218 }
219
220 static void alsa_close(struct writer_node *wn)
221 {
222 struct private_alsa_write_data *pad = wn->private_data;
223 PARA_INFO_LOG("closing writer node %p\n", wn);
224
225 if (!pad)
226 return;
227 /*
228 * It's OK to have a blocking operation here because we already made
229 * sure that the PCM output buffer is (nearly) empty.
230 */
231 snd_pcm_nonblock(pad->handle, 0);
232 snd_pcm_drain(pad->handle);
233 snd_pcm_close(pad->handle);
234 snd_config_update_free_global();
235 free(pad);
236 }
237
238 static void alsa_write_post_select(__a_unused struct sched *s,
239 struct task *t)
240 {
241 struct writer_node *wn = container_of(t, struct writer_node, task);
242 struct private_alsa_write_data *pad = wn->private_data;
243 struct btr_node *btrn = wn->btrn;
244 char *data;
245 size_t bytes;
246 snd_pcm_sframes_t frames;
247 int ret;
248
249 again:
250 t->error = 0;
251 ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
252 if (ret == 0)
253 return;
254 btr_merge(btrn, wn->min_iqs);
255 bytes = btr_next_buffer(btrn, &data);
256 if (ret < 0 || bytes < wn->min_iqs) { /* eof */
257 assert(btr_no_parent(btrn));
258 ret = -E_WRITE_COMMON_EOF;
259 if (!pad)
260 goto err;
261 /* wait until pending frames are played */
262 if (pad->drain_barrier.tv_sec == 0) {
263 PARA_DEBUG_LOG("waiting for device to drain\n");
264 tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
265 &pad->drain_barrier);
266 return;
267 }
268 if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
269 goto err;
270 return;
271 }
272 if (!pad) {
273 int32_t val;
274
275 if (bytes == 0) /* no data available */
276 return;
277 pad = para_calloc(sizeof(*pad));
278 get_btr_sample_rate(btrn, &val);
279 pad->sample_rate = val;
280 get_btr_channels(btrn, &val);
281 pad->channels = val;
282 get_btr_sample_format(btrn, &val);
283 pad->sample_format = get_alsa_pcm_format(val);
284
285 PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels,
286 pad->sample_rate);
287 ret = alsa_init(pad, wn->conf);
288 if (ret < 0) {
289 free(pad);
290 goto err;
291 }
292 wn->private_data = pad;
293 wn->min_iqs = pad->bytes_per_frame;
294 goto again;
295 }
296 if (pad->poll_fd < 0 || !FD_ISSET(pad->poll_fd, &s->rfds))
297 return;
298 frames = bytes / pad->bytes_per_frame;
299 frames = snd_pcm_writei(pad->handle, data, frames);
300 if (frames == 0 || frames == -EAGAIN) {
301 /*
302 * The alsa poll fd was ready for IO but we failed to write to
303 * the alsa handle. This means another event is pending. We
304 * don't care about that but we have to dispatch the event in
305 * order to avoid a busy loop. So we simply read from the poll
306 * fd.
307 */
308 char buf[100];
309 if (read(pad->poll_fd, buf, 100))
310 do_nothing;
311 return;
312 }
313 if (frames > 0) {
314 btr_consume(btrn, frames * pad->bytes_per_frame);
315 goto again;
316 }
317 if (frames == -EPIPE) {
318 PARA_WARNING_LOG("underrun (tried to write %zu bytes)\n", bytes);
319 snd_pcm_prepare(pad->handle);
320 return;
321 }
322 PARA_ERROR_LOG("alsa write error: %s\n", snd_strerror(-frames));
323 ret = -E_ALSA;
324 err:
325 assert(ret < 0);
326 btr_remove_node(btrn);
327 t->error = ret;
328 }
329
330 __malloc static void *alsa_parse_config_or_die(const char *options)
331 {
332 struct alsa_write_args_info *conf = para_calloc(sizeof(*conf));
333
334 /* exits on errors */
335 alsa_cmdline_parser_string(options, conf, "alsa_write");
336 return conf;
337 }
338
339 static void alsa_free_config(void *conf)
340 {
341 alsa_cmdline_parser_free(conf);
342 }
343
344 /**
345 * The init function of the alsa writer.
346 *
347 * \param w Pointer to the writer to initialize.
348 *
349 * \sa struct \ref writer.
350 */
351 void alsa_write_init(struct writer *w)
352 {
353 struct alsa_write_args_info dummy;
354
355 alsa_cmdline_parser_init(&dummy);
356 w->close = alsa_close;
357 w->pre_select = alsa_write_pre_select;
358 w->post_select = alsa_write_post_select;
359 w->parse_config_or_die = alsa_parse_config_or_die;
360 w->shutdown = NULL; /* nothing to do */
361 w->free_config = alsa_free_config;
362 w->help = (struct ggo_help) {
363 .short_help = alsa_write_args_info_help,
364 .detailed_help = alsa_write_args_info_detailed_help
365 };
366 alsa_cmdline_parser_free(&dummy);
367 }