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