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