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