2dab8fe1543f9205d8d12d7fa9db85be60768df6
[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 err;
79
80         PARA_INFO_LOG("opening %s\n", conf->device_arg);
81         err = snd_pcm_open(&pad->handle, conf->device_arg,
82                 SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
83         if (err < 0)
84                 return -E_PCM_OPEN;
85
86         snd_pcm_hw_params_alloca(&hwparams);
87         snd_pcm_sw_params_alloca(&swparams);
88         if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
89                 return -E_BROKEN_CONF;
90         if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
91                         SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
92                 return -E_ACCESS_TYPE;
93         if (snd_pcm_hw_params_set_format(pad->handle, hwparams,
94                         pad->sample_format) < 0)
95                 return -E_SAMPLE_FORMAT;
96         if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
97                         pad->channels) < 0)
98                 return -E_CHANNEL_COUNT;
99         if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
100                         &pad->sample_rate, NULL) < 0)
101                 return -E_SET_RATE;
102         err = snd_pcm_hw_params_get_buffer_time_max(hwparams,
103                 &buffer_time, NULL);
104         if (err < 0 || buffer_time == 0)
105                 return -E_GET_BUFFER_TIME;
106         if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
107                         &buffer_time, NULL) < 0)
108                 return -E_SET_BUFFER_TIME;
109         if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
110                 return -E_HW_PARAMS;
111         snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
112         snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
113         if (period_size == buffer_size)
114                 return -E_BAD_PERIOD;
115         /* software parameter setup */
116         snd_pcm_sw_params_current(pad->handle, swparams);
117         snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
118         if (buffer_size < 1)
119                 start_threshold = 1;
120         else
121                 start_threshold = PARA_MIN(buffer_size,
122                         (snd_pcm_uframes_t)pad->sample_rate);
123         if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
124                         start_threshold) < 0)
125                 return -E_START_THRESHOLD;
126         stop_threshold = buffer_size;
127         if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
128                         stop_threshold) < 0)
129                 return -E_STOP_THRESHOLD;
130         if (snd_pcm_sw_params(pad->handle, swparams) < 0)
131                 PARA_WARNING_LOG("unable to install sw params\n");
132         pad->bytes_per_frame = snd_pcm_format_physical_width(pad->sample_format)
133                 * pad->channels / 8;
134         if (pad->bytes_per_frame <= 0)
135                 return -E_PHYSICAL_WIDTH;
136         if (snd_pcm_nonblock(pad->handle, 1))
137                 PARA_ERROR_LOG("failed to set nonblock mode\n");
138         err = snd_output_buffer_open(&log);
139         if (err == 0) {
140                 char *buf;
141                 PARA_INFO_LOG("dumping alsa configuration\n");
142                 snd_pcm_dump(pad->handle, log);
143                 snd_output_buffer_string(log, &buf);
144                 for (;;) {
145                         char *p = strchr(buf, '\n');
146                         if (!p) /* omit last output line, it's empty */
147                                 break;
148                         *p = '\0';
149                         PARA_INFO_LOG("%s\n", buf);
150                         buf = p + 1;
151                 }
152                 snd_output_close(log);
153         }
154         return 1;
155 }
156
157 static void alsa_write_pre_select(struct sched *s, struct task *t)
158 {
159         struct pollfd pfd;
160         struct writer_node *wn = container_of(t, struct writer_node, task);
161         struct private_alsa_write_data *pad = wn->private_data;
162         int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
163
164         if (pad)
165                 pad->poll_fd = -1;
166         if (ret == 0)
167                 return;
168         if (!pad) {
169                 sched_min_delay(s);
170                 return;
171         }
172         if (ret < 0) {
173                 sched_request_barrier_or_min_delay(&pad->drain_barrier, s);
174                 return;
175         }
176         ret = snd_pcm_poll_descriptors(pad->handle, &pfd, 1);
177         if (ret < 0) {
178                 PARA_ERROR_LOG("%s\n", snd_strerror(-ret));
179                 t->error = -E_ALSA_POLL_FDS;
180                 return;
181         }
182         pad->poll_fd = pfd.fd;
183         para_fd_set(pfd.fd, &s->rfds, &s->max_fileno);
184 }
185
186 static void alsa_close(struct writer_node *wn)
187 {
188         struct private_alsa_write_data *pad = wn->private_data;
189         PARA_INFO_LOG("closing writer node %p\n", wn);
190
191         if (!pad)
192                 return;
193         /*
194          * It's OK to have a blocking operation here because we already made
195          * sure that the PCM output buffer is (nearly) empty.
196          */
197         snd_pcm_nonblock(pad->handle, 0);
198         snd_pcm_drain(pad->handle);
199         snd_pcm_close(pad->handle);
200         snd_config_update_free_global();
201         free(pad);
202 }
203
204 static void alsa_write_post_select(__a_unused struct sched *s,
205                 struct task *t)
206 {
207         struct writer_node *wn = container_of(t, struct writer_node, task);
208         struct private_alsa_write_data *pad = wn->private_data;
209         struct btr_node *btrn = wn->btrn;
210         char *data;
211         size_t bytes;
212         snd_pcm_sframes_t frames;
213         int ret;
214
215 again:
216         t->error = 0;
217         ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
218         if (ret == 0)
219                 return;
220         btr_merge(btrn, wn->min_iqs);
221         bytes = btr_next_buffer(btrn, &data);
222         if (ret < 0 || bytes < wn->min_iqs) { /* eof */
223                 assert(btr_no_parent(btrn));
224                 ret = -E_WRITE_COMMON_EOF;
225                 if (!pad)
226                         goto err;
227                 /* wait until pending frames are played */
228                 if (pad->drain_barrier.tv_sec == 0) {
229                         PARA_DEBUG_LOG("waiting for device to drain\n");
230                         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
231                                 &pad->drain_barrier);
232                         return;
233                 }
234                 if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
235                         goto err;
236                 return;
237         }
238         if (!pad) {
239                 int32_t val;
240
241                 if (bytes == 0) /* no data available */
242                         return;
243                 pad = para_calloc(sizeof(*pad));
244                 get_btr_sample_rate(btrn, &val);
245                 pad->sample_rate = val;
246                 get_btr_channels(btrn, &val);
247                 pad->channels = val;
248                 get_btr_sample_format(btrn, &val);
249                 pad->sample_format = get_alsa_pcm_format(val);
250
251                 PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels,
252                         pad->sample_rate);
253                 ret = alsa_init(pad, wn->conf);
254                 if (ret < 0) {
255                         free(pad);
256                         goto err;
257                 }
258                 wn->private_data = pad;
259                 wn->min_iqs = pad->bytes_per_frame;
260                 goto again;
261         }
262         if (pad->poll_fd < 0 || !FD_ISSET(pad->poll_fd, &s->rfds))
263                 return;
264         frames = bytes / pad->bytes_per_frame;
265         frames = snd_pcm_writei(pad->handle, data, frames);
266         if (frames == 0 || frames == -EAGAIN) {
267                 /*
268                  * The alsa poll fd was ready for IO but we failed to write to
269                  * the alsa handle. This means another event is pending. We
270                  * don't care about that but we have to dispatch the event in
271                  * order to avoid a busy loop. So we simply read from the poll
272                  * fd.
273                  */
274                 char buf[100];
275                 if (read(pad->poll_fd, buf, 100))
276                         do_nothing;
277                 return;
278         }
279         if (frames > 0) {
280                 btr_consume(btrn, frames * pad->bytes_per_frame);
281                 goto again;
282         }
283         if (frames == -EPIPE) {
284                 PARA_WARNING_LOG("underrun (tried to write %zu bytes)\n", bytes);
285                 snd_pcm_prepare(pad->handle);
286                 return;
287         }
288         PARA_WARNING_LOG("%s\n", snd_strerror(-frames));
289         ret = -E_ALSA_WRITE;
290 err:
291         assert(ret < 0);
292         btr_remove_node(btrn);
293         t->error = ret;
294 }
295
296 __malloc static void *alsa_parse_config_or_die(const char *options)
297 {
298         struct alsa_write_args_info *conf = para_calloc(sizeof(*conf));
299
300         /* exits on errors */
301         alsa_cmdline_parser_string(options, conf, "alsa_write");
302         return conf;
303 }
304
305 static void alsa_free_config(void *conf)
306 {
307         alsa_cmdline_parser_free(conf);
308 }
309
310 /**
311  * The init function of the alsa writer.
312  *
313  * \param w Pointer to the writer to initialize.
314  *
315  * \sa struct \ref writer.
316  */
317 void alsa_write_init(struct writer *w)
318 {
319         struct alsa_write_args_info dummy;
320
321         alsa_cmdline_parser_init(&dummy);
322         w->close = alsa_close;
323         w->pre_select = alsa_write_pre_select;
324         w->post_select = alsa_write_post_select;
325         w->parse_config_or_die = alsa_parse_config_or_die;
326         w->shutdown = NULL; /* nothing to do */
327         w->free_config = alsa_free_config;
328         w->help = (struct ggo_help) {
329                 .short_help = alsa_write_args_info_help,
330                 .detailed_help = alsa_write_args_info_detailed_help
331         };
332         alsa_cmdline_parser_free(&dummy);
333 }