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