Merge branch 'refs/heads/t/sqrt'
[paraslash.git] / alsa_write.c
1 /*
2  * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
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 <lopsub.h>
19
20 #include "write_cmd.lsg.h"
21 #include "para.h"
22 #include "fd.h"
23 #include "string.h"
24 #include "list.h"
25 #include "sched.h"
26 #include "buffer_tree.h"
27 #include "write.h"
28 #include "error.h"
29
30 /** Data specific to the alsa writer. */
31 struct private_alsa_write_data {
32         /** The alsa handle */
33         snd_pcm_t *handle;
34         /** Determined and set by alsa_init(). */
35         int bytes_per_frame;
36         /*
37          * If the sample rate is not given at the command line and no wav
38          * header was detected, the btr exec mechanism is employed to query the
39          * ancestor buffer tree nodes for this information. In a typical setup
40          * the decoder passes the sample rate back to the alsa writer.
41          *
42          *  \sa \ref btr_exec_up().
43          */
44         unsigned sample_rate;
45         /*
46          * The sample format (8/16 bit, signed/unsigned, little/big endian) is
47          * determined in the same way as the \a sample_rate.
48          */
49         snd_pcm_format_t sample_format;
50         /* The number of channels, again determined like \a sample_rate. */
51         unsigned channels;
52         /* time until buffer underrun occurs, in milliseconds */
53         unsigned buffer_time;
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 writer_node *wn)
74 {
75         struct private_alsa_write_data *pad = wn->private_data;
76         snd_pcm_hw_params_t *hwparams = NULL;
77         snd_pcm_sw_params_t *swparams = NULL;
78         snd_pcm_uframes_t start_threshold, stop_threshold;
79         snd_pcm_uframes_t buffer_size, period_size;
80         snd_output_t *output_log;
81         int ret;
82         const char *msg, *dev = WRITE_CMD_OPT_STRING_VAL(ALSA, DEVICE, wn->lpr);
83         unsigned period_time;
84
85         PARA_INFO_LOG("opening %s\n", dev);
86         msg = "unable to open pcm";
87         ret = snd_pcm_open(&pad->handle, dev, SND_PCM_STREAM_PLAYBACK,
88                 SND_PCM_NONBLOCK);
89         if (ret < 0)
90                 goto fail;
91         ret = snd_pcm_hw_params_malloc(&hwparams);
92         assert(ret >= 0);
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         /* alsa wants microseconds */
118         pad->buffer_time = 1000U * WRITE_CMD_OPT_UINT32_VAL(ALSA, BUFFER_TIME,
119                 wn->lpr);
120         msg = "could not set buffer time";
121         ret = snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
122                 &pad->buffer_time, NULL);
123         if (ret < 0)
124                 goto fail;
125         pad->buffer_time /= 1000; /* we prefer milliseconds */
126         period_time = pad->buffer_time * 250; /* buffer time / 4 */
127         msg = "could not set period time";
128         ret = snd_pcm_hw_params_set_period_time_near(pad->handle, hwparams,
129                 &period_time, NULL);
130         if (ret < 0)
131                 goto fail;
132
133         msg = "unable to install hw params";
134         ret = snd_pcm_hw_params(pad->handle, hwparams);
135         if (ret < 0)
136                 goto fail;
137         snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
138         snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
139         msg = "period size equals buffer size";
140         if (period_size == buffer_size)
141                 goto fail;
142
143         /* software parameter setup */
144         ret = snd_pcm_sw_params_malloc(&swparams);
145         assert(ret >= 0);
146         snd_pcm_sw_params_current(pad->handle, swparams);
147         snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
148         if (buffer_size < 1)
149                 start_threshold = 1;
150         else
151                 start_threshold = PARA_MIN(buffer_size,
152                         (snd_pcm_uframes_t)pad->sample_rate);
153         msg = "could not set start threshold";
154         ret = snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
155                 start_threshold);
156         if (ret < 0)
157                 goto fail;
158         stop_threshold = buffer_size;
159         msg = "could not set stop threshold";
160         ret = snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
161                 stop_threshold);
162         if (ret < 0)
163                 goto fail;
164         msg = "unable to install sw params";
165         ret = snd_pcm_sw_params(pad->handle, swparams);
166         if (ret < 0)
167                 goto fail;
168         msg = "unable to determine bytes per frame";
169         ret = snd_pcm_format_physical_width(pad->sample_format);
170         if (ret <= 0)
171                 goto fail;
172         pad->bytes_per_frame = ret * pad->channels / 8;
173         msg = "failed to set alsa handle to nonblock mode";
174         ret = snd_pcm_nonblock(pad->handle, 1);
175         if (ret < 0)
176                 goto fail;
177         ret = snd_output_buffer_open(&output_log);
178         if (ret == 0) {
179                 char *buf, *p;
180                 size_t sz;
181                 PARA_DEBUG_LOG("dumping alsa configuration\n");
182                 snd_pcm_dump(pad->handle, output_log);
183                 snd_pcm_hw_params_dump(hwparams, output_log);
184                 sz = snd_output_buffer_string(output_log, &buf);
185                 for (p = buf; p < buf + sz;) {
186                         char *q = memchr(p, '\n', buf + sz - p);
187                         if (!q)
188                                 break;
189                         *q = '\0';
190                         PARA_DEBUG_LOG("%s\n", p);
191                         p = q + 1;
192                 }
193                 snd_output_close(output_log);
194         }
195         ret = 1;
196         goto out;
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         ret = -E_ALSA;
203 out:
204         snd_pcm_hw_params_free(hwparams);
205         snd_pcm_sw_params_free(swparams);
206         return ret;
207 }
208
209 static void alsa_write_pre_select(struct sched *s, void *context)
210 {
211         struct pollfd pfd;
212         struct writer_node *wn = context;
213         struct private_alsa_write_data *pad = wn->private_data;
214         int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
215
216         if (pad)
217                 pad->poll_fd = -1;
218         if (ret == 0)
219                 return;
220         if (!pad) {
221                 sched_min_delay(s);
222                 return;
223         }
224         if (ret < 0) {
225                 sched_request_barrier_or_min_delay(&pad->drain_barrier, s);
226                 return;
227         }
228         /* wait at most 50% of the buffer time */
229         sched_request_timeout_ms(pad->buffer_time / 2, s);
230         ret = snd_pcm_poll_descriptors(pad->handle, &pfd, 1);
231         if (ret < 0) {
232                 PARA_ERROR_LOG("could not get alsa poll fd: %s\n",
233                         snd_strerror(-ret));
234                 return;
235         }
236         pad->poll_fd = pfd.fd;
237         para_fd_set(pfd.fd, &s->rfds, &s->max_fileno);
238 }
239
240 static void alsa_close(struct writer_node *wn)
241 {
242         struct private_alsa_write_data *pad = wn->private_data;
243         PARA_INFO_LOG("closing writer node %p\n", wn);
244
245         if (!pad)
246                 return;
247         /*
248          * It's OK to have a blocking operation here because we already made
249          * sure that the PCM output buffer is (nearly) empty.
250          */
251         snd_pcm_nonblock(pad->handle, 0);
252         snd_pcm_drain(pad->handle);
253         snd_pcm_close(pad->handle);
254         snd_config_update_free_global();
255         free(pad);
256 }
257
258 static int alsa_write_post_select(__a_unused struct sched *s, void *context)
259 {
260         struct writer_node *wn = context;
261         struct private_alsa_write_data *pad = wn->private_data;
262         struct btr_node *btrn = wn->btrn;
263         char *data;
264         size_t bytes;
265         snd_pcm_sframes_t frames;
266         int ret;
267
268         ret = task_get_notification(wn->task);
269         if (ret < 0)
270                 goto err;
271 again:
272         ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
273         if (ret == 0)
274                 return 0;
275         btr_merge(btrn, wn->min_iqs);
276         bytes = btr_next_buffer(btrn, &data);
277         if (ret < 0 || bytes < wn->min_iqs) { /* eof */
278                 assert(btr_no_parent(btrn));
279                 ret = -E_WRITE_COMMON_EOF;
280                 if (!pad)
281                         goto err;
282                 /* wait until pending frames are played */
283                 if (pad->drain_barrier.tv_sec == 0) {
284                         PARA_DEBUG_LOG("waiting for device to drain\n");
285                         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
286                                 &pad->drain_barrier);
287                         return 0;
288                 }
289                 if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
290                         goto err;
291                 return 0;
292         }
293         if (!pad) {
294                 int32_t val;
295
296                 if (bytes == 0) /* no data available */
297                         return 0;
298                 pad = wn->private_data = para_calloc(sizeof(*pad));
299                 get_btr_sample_rate(btrn, &val);
300                 pad->sample_rate = val;
301                 get_btr_channels(btrn, &val);
302                 pad->channels = val;
303                 get_btr_sample_format(btrn, &val);
304                 pad->sample_format = get_alsa_pcm_format(val);
305
306                 PARA_INFO_LOG("%u channel(s), %uHz\n", pad->channels,
307                         pad->sample_rate);
308                 ret = alsa_init(wn);
309                 if (ret < 0) {
310                         free(wn->private_data);
311                         wn->private_data = NULL;
312                         goto err;
313                 }
314                 wn->min_iqs = pad->bytes_per_frame;
315                 goto again;
316         }
317         frames = bytes / pad->bytes_per_frame;
318         frames = snd_pcm_writei(pad->handle, data, frames);
319         if (frames == 0 || frames == -EAGAIN) {
320                 char buf[100];
321                 if (pad->poll_fd >= 0 && FD_ISSET(pad->poll_fd, &s->rfds))
322                         if (read(pad->poll_fd, buf, 100))
323                                 do_nothing;
324                 return 0;
325         }
326         if (frames > 0) {
327                 btr_consume(btrn, frames * pad->bytes_per_frame);
328                 goto again;
329         }
330         if (frames == -EPIPE) {
331                 PARA_WARNING_LOG("underrun (tried to write %zu bytes)\n", bytes);
332                 snd_pcm_prepare(pad->handle);
333                 return 0;
334         }
335         PARA_ERROR_LOG("alsa write error: %s\n", snd_strerror(-frames));
336         ret = -E_ALSA;
337 err:
338         assert(ret < 0);
339         btr_remove_node(&wn->btrn);
340         return ret;
341 }
342
343 struct writer lsg_write_cmd_com_alsa_user_data = {
344
345         .pre_select = alsa_write_pre_select,
346         .post_select = alsa_write_post_select,
347         .close = alsa_close,
348 };