]> git.tuebingen.mpg.de Git - paraslash.git/blob - alsa_write.c
Merge topic branch t/sf_float into pu
[paraslash.git] / alsa_write.c
1 /* Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file alsa_write.c paraslash's alsa output plugin */
4
5 /*
6  * Based in parts on aplay.c from the alsa-utils-1.0.8 package,
7  * Copyright (c) by Jaroslav Kysela <perex@suse.cz>, which is
8  * based on the vplay program by Michael Beck.
9  */
10
11 #include <regex.h>
12 #include <sys/types.h>
13 #include <alsa/asoundlib.h>
14 #include <lopsub.h>
15
16 #include "write_cmd.lsg.h"
17 #include "para.h"
18 #include "fd.h"
19 #include "string.h"
20 #include "list.h"
21 #include "sched.h"
22 #include "buffer_tree.h"
23 #include "write.h"
24 #include "error.h"
25
26 /** Data specific to the alsa writer. */
27 struct private_alsa_write_data {
28         /** The alsa handle */
29         snd_pcm_t *handle;
30         /** Determined and set by alsa_init(). */
31         int bytes_per_frame;
32         /*
33          * If the sample rate is not given at the command line and no wav
34          * header was detected, the btr exec mechanism is employed to query the
35          * ancestor buffer tree nodes for this information. In a typical setup
36          * the decoder passes the sample rate back to the alsa writer.
37          *
38          *  \sa \ref btr_exec_up().
39          */
40         unsigned sample_rate;
41         /*
42          * The sample format (8/16 bit, signed/unsigned, little/big endian) is
43          * determined in the same way as the \a sample_rate.
44          */
45         snd_pcm_format_t sample_format;
46         /* The number of channels, again determined like \a sample_rate. */
47         unsigned channels;
48         /* time until buffer underrun occurs, in milliseconds */
49         unsigned buffer_time;
50         struct timeval drain_barrier;
51         /* File descriptor to monitor for reading. */
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         case SF_FLOAT_LE: return SND_PCM_FORMAT_FLOAT_LE;
65         case SF_FLOAT_BE: return SND_PCM_FORMAT_FLOAT_BE;
66         default: return SND_PCM_FORMAT_S16_LE;
67         }
68 }
69
70 /* Install PCM software and hardware configuration. */
71 static int alsa_init(struct writer_node *wn)
72 {
73         struct private_alsa_write_data *pad = wn->private_data;
74         snd_pcm_hw_params_t *hwparams = NULL;
75         snd_pcm_sw_params_t *swparams = NULL;
76         snd_pcm_uframes_t start_threshold, stop_threshold;
77         snd_pcm_uframes_t buffer_size, period_size;
78         snd_output_t *output_log;
79         int ret;
80         const char *msg, *dev = WRITE_CMD_OPT_STRING_VAL(ALSA, DEVICE, wn->lpr);
81         unsigned period_time;
82
83         PARA_INFO_LOG("opening %s\n", dev);
84         msg = "unable to open pcm";
85         ret = snd_pcm_open(&pad->handle, dev, SND_PCM_STREAM_PLAYBACK,
86                 SND_PCM_NONBLOCK);
87         if (ret < 0)
88                 goto fail;
89         ret = snd_pcm_hw_params_malloc(&hwparams);
90         assert(ret >= 0);
91         msg = "Broken alsa configuration";
92         ret = snd_pcm_hw_params_any(pad->handle, hwparams);
93         if (ret < 0)
94                 goto fail;
95         msg = "access type not available";
96         ret = snd_pcm_hw_params_set_access(pad->handle, hwparams,
97                 SND_PCM_ACCESS_RW_INTERLEAVED);
98         if (ret < 0)
99                 goto fail;
100         msg = "sample format not available";
101         ret = snd_pcm_hw_params_set_format(pad->handle, hwparams,
102                 pad->sample_format);
103         if (ret < 0)
104                 goto fail;
105         msg = "channels count not available";
106         ret = snd_pcm_hw_params_set_channels(pad->handle, hwparams,
107                 pad->channels);
108         if (ret < 0)
109                 goto fail;
110         msg = "could not set sample rate";
111         ret = snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
112                 &pad->sample_rate, NULL);
113         if (ret < 0)
114                 goto fail;
115         /* alsa wants microseconds */
116         pad->buffer_time = 1000U * WRITE_CMD_OPT_UINT32_VAL(ALSA, BUFFER_TIME,
117                 wn->lpr);
118         msg = "could not set buffer time";
119         ret = snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
120                 &pad->buffer_time, NULL);
121         if (ret < 0)
122                 goto fail;
123         pad->buffer_time /= 1000; /* we prefer milliseconds */
124         period_time = pad->buffer_time * 250; /* buffer time / 4 */
125         msg = "could not set period time";
126         ret = snd_pcm_hw_params_set_period_time_near(pad->handle, hwparams,
127                 &period_time, NULL);
128         if (ret < 0)
129                 goto fail;
130
131         msg = "unable to install hw params";
132         ret = snd_pcm_hw_params(pad->handle, hwparams);
133         if (ret < 0)
134                 goto fail;
135         snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
136         snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
137         msg = "period size equals buffer size";
138         if (period_size == buffer_size)
139                 goto fail;
140
141         /* software parameter setup */
142         ret = snd_pcm_sw_params_malloc(&swparams);
143         assert(ret >= 0);
144         snd_pcm_sw_params_current(pad->handle, swparams);
145         snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
146         if (buffer_size < 1)
147                 start_threshold = 1;
148         else
149                 start_threshold = PARA_MIN(buffer_size,
150                         (snd_pcm_uframes_t)pad->sample_rate);
151         msg = "could not set start threshold";
152         ret = snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
153                 start_threshold);
154         if (ret < 0)
155                 goto fail;
156         stop_threshold = buffer_size;
157         msg = "could not set stop threshold";
158         ret = snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
159                 stop_threshold);
160         if (ret < 0)
161                 goto fail;
162         msg = "unable to install sw params";
163         ret = snd_pcm_sw_params(pad->handle, swparams);
164         if (ret < 0)
165                 goto fail;
166         msg = "unable to determine bytes per frame";
167         ret = snd_pcm_format_physical_width(pad->sample_format);
168         if (ret <= 0)
169                 goto fail;
170         pad->bytes_per_frame = ret * pad->channels / 8;
171         msg = "failed to set alsa handle to nonblock mode";
172         ret = snd_pcm_nonblock(pad->handle, 1);
173         if (ret < 0)
174                 goto fail;
175         ret = snd_output_buffer_open(&output_log);
176         if (ret == 0) {
177                 char *buf, *p;
178                 size_t sz;
179                 PARA_DEBUG_LOG("dumping alsa configuration\n");
180                 snd_pcm_dump(pad->handle, output_log);
181                 snd_pcm_hw_params_dump(hwparams, output_log);
182                 sz = snd_output_buffer_string(output_log, &buf);
183                 for (p = buf; p < buf + sz;) {
184                         char *q = memchr(p, '\n', buf + sz - p);
185                         if (!q)
186                                 break;
187                         *q = '\0';
188                         PARA_DEBUG_LOG("%s\n", p);
189                         p = q + 1;
190                 }
191                 snd_output_close(output_log);
192         }
193         ret = 1;
194         goto out;
195 fail:
196         if (ret < 0)
197                 PARA_ERROR_LOG("%s: %s\n", msg, snd_strerror(-ret));
198         else
199                 PARA_ERROR_LOG("%s\n", msg);
200         ret = -E_ALSA;
201 out:
202         snd_pcm_hw_params_free(hwparams);
203         snd_pcm_sw_params_free(swparams);
204         return ret;
205 }
206
207 static void alsa_write_pre_monitor(struct sched *s, void *context)
208 {
209         struct pollfd pfd;
210         struct writer_node *wn = context;
211         struct private_alsa_write_data *pad = wn->private_data;
212         int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
213
214         if (pad)
215                 pad->poll_fd = -1;
216         if (ret == 0)
217                 return;
218         if (!pad) {
219                 sched_min_delay(s);
220                 return;
221         }
222         if (ret < 0) {
223                 sched_request_barrier_or_min_delay(&pad->drain_barrier, s);
224                 return;
225         }
226         /* wait at most 50% of the buffer time */
227         sched_request_timeout_ms(pad->buffer_time / 2, s);
228         ret = snd_pcm_poll_descriptors(pad->handle, &pfd, 1);
229         if (ret < 0) {
230                 PARA_ERROR_LOG("could not get alsa poll fd: %s\n",
231                         snd_strerror(-ret));
232                 return;
233         }
234         pad->poll_fd = pfd.fd;
235         sched_monitor_readfd(pfd.fd, s);
236 }
237
238 static void alsa_close(struct writer_node *wn)
239 {
240         struct private_alsa_write_data *pad = wn->private_data;
241         PARA_INFO_LOG("closing writer node %p\n", wn);
242
243         if (!pad)
244                 return;
245         if (!pad->handle)
246                 goto free_pad;
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         free(pad);
257 }
258
259 static int alsa_write_post_monitor(__a_unused struct sched *s, void *context)
260 {
261         struct writer_node *wn = context;
262         struct private_alsa_write_data *pad = wn->private_data;
263         struct btr_node *btrn = wn->btrn;
264         char *data;
265         size_t bytes;
266         snd_pcm_sframes_t frames;
267         int ret;
268
269         ret = task_get_notification(wn->task);
270         if (ret < 0)
271                 goto err;
272 again:
273         ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
274         if (ret < 0)
275                 goto err;
276         if (ret == 0)
277                 return 0;
278         btr_merge(btrn, wn->min_iqs);
279         bytes = btr_next_buffer(btrn, &data);
280         if (ret < 0 || bytes < wn->min_iqs) { /* eof */
281                 assert(btr_no_parent(btrn));
282                 ret = -E_EOF;
283                 if (!pad)
284                         goto err;
285                 /* wait until pending frames are played */
286                 if (pad->drain_barrier.tv_sec == 0) {
287                         PARA_DEBUG_LOG("waiting for device to drain\n");
288                         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
289                                 &pad->drain_barrier);
290                         return 0;
291                 }
292                 if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
293                         goto err;
294                 return 0;
295         }
296         if (!pad) {
297                 int32_t val;
298
299                 if (bytes == 0) /* no data available */
300                         return 0;
301                 pad = wn->private_data = zalloc(sizeof(*pad));
302                 ret = get_btr_sample_rate(btrn, &val);
303                 if (ret < 0)
304                         goto err;
305                 pad->sample_rate = val;
306                 ret = get_btr_channels(btrn, &val);
307                 if (ret < 0)
308                         goto err;
309                 pad->channels = val;
310                 ret = get_btr_sample_format(btrn, &val);
311                 if (ret < 0)
312                         goto err;
313                 pad->sample_format = get_alsa_pcm_format(val);
314                 PARA_INFO_LOG("%u channel(s), %uHz\n", pad->channels,
315                         pad->sample_rate);
316                 ret = alsa_init(wn);
317                 if (ret < 0)
318                         goto err;
319                 wn->min_iqs = pad->bytes_per_frame;
320                 goto again;
321         }
322         frames = bytes / pad->bytes_per_frame;
323         frames = snd_pcm_writei(pad->handle, data, frames);
324         if (frames == 0 || frames == -EAGAIN) {
325                 char buf[100];
326                 if (pad->poll_fd >= 0 && sched_read_ok(pad->poll_fd, s))
327                         if (read(pad->poll_fd, buf, 100))
328                                 do_nothing;
329                 return 0;
330         }
331         if (frames > 0) {
332                 btr_consume(btrn, frames * pad->bytes_per_frame);
333                 goto again;
334         }
335         if (frames == -EPIPE) {
336                 snd_pcm_status_t *status;
337                 snd_pcm_status_malloc(&status);
338                 if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN)
339                         PARA_WARNING_LOG("underrun\n");
340                 snd_pcm_status_free(status);
341                 snd_pcm_prepare(pad->handle);
342                 return 0;
343         }
344         PARA_ERROR_LOG("alsa write error: %s\n", snd_strerror(-frames));
345         ret = -E_ALSA;
346 err:
347         assert(ret < 0);
348         btr_remove_node(&wn->btrn);
349         return ret;
350 }
351
352 struct writer lsg_write_cmd_com_alsa_user_data = {
353
354         .pre_monitor = alsa_write_pre_monitor,
355         .post_monitor = alsa_write_post_monitor,
356         .close = alsa_close,
357 };