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