Introduce and use generic_filter_pre_select().
[paraslash.git] / alsa_write.c
1 /*
2  * Copyright (C) 2005-2009 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 <dirent.h>
18 #include <alsa/asoundlib.h>
19 #include <sys/time.h>
20 #include <stdbool.h>
21
22 #include "para.h"
23 #include "fd.h"
24 #include "string.h"
25 #include "list.h"
26 #include "sched.h"
27 #include "ggo.h"
28 #include "buffer_tree.h"
29 #include "write.h"
30 #include "alsa_write.cmdline.h"
31 #include "error.h"
32
33 /** always use 16 bit little endian */
34 #define FORMAT SND_PCM_FORMAT_S16_LE
35
36 /** Data specific to the alsa writer. */
37 struct private_alsa_write_data {
38         /** The alsa handle */
39         snd_pcm_t *handle;
40         /** Determined and set by alsa_open(). */
41         int bytes_per_frame;
42         /** The approximate maximum buffer duration in us. */
43         unsigned buffer_time;
44         /* Number of frames that fit into the buffer. */
45         unsigned buffer_frames;
46         /**
47          * The samplerate given by command line option or the decoder
48          * of the writer node group.
49          */
50         unsigned samplerate;
51         /**
52          * The number of channels, given by command line option or the
53          * decoder of the writer node group.
54          */
55         unsigned channels;
56 };
57
58 /* Install PCM software and hardware configuration. */
59 static int alsa_init(struct private_alsa_write_data *pad,
60                 struct alsa_write_args_info *conf)
61 {
62         snd_pcm_hw_params_t *hwparams;
63         snd_pcm_sw_params_t *swparams;
64         snd_pcm_uframes_t buffer_size, start_threshold, stop_threshold;
65         snd_pcm_uframes_t period_size;
66         int err;
67
68         err = snd_pcm_open(&pad->handle, conf->device_arg,
69                 SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
70         if (err < 0)
71                 return -E_PCM_OPEN;
72
73         snd_pcm_hw_params_alloca(&hwparams);
74         snd_pcm_sw_params_alloca(&swparams);
75         if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
76                 return -E_BROKEN_CONF;
77         if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
78                         SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
79                 return -E_ACCESS_TYPE;
80         if (snd_pcm_hw_params_set_format(pad->handle, hwparams, FORMAT) < 0)
81                 return -E_SAMPLE_FORMAT;
82         if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
83                         pad->channels) < 0)
84                 return -E_CHANNEL_COUNT;
85         if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
86                         &pad->samplerate, NULL) < 0)
87                 return -E_SET_RATE;
88         err = snd_pcm_hw_params_get_buffer_time_max(hwparams,
89                 &pad->buffer_time, NULL);
90         if (err < 0 || !pad->buffer_time)
91                 return -E_GET_BUFFER_TIME;
92         PARA_INFO_LOG("buffer time: %d\n", pad->buffer_time);
93         if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
94                         &pad->buffer_time, NULL) < 0)
95                 return -E_SET_BUFFER_TIME;
96         if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
97                 return -E_HW_PARAMS;
98         snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
99         snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
100         PARA_INFO_LOG("buffer size: %lu, period_size: %lu\n", buffer_size,
101                 period_size);
102         if (period_size == buffer_size)
103                 return -E_BAD_PERIOD;
104         snd_pcm_sw_params_current(pad->handle, swparams);
105         snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
106         if (buffer_size < 1)
107                 start_threshold = 1;
108         else
109                 start_threshold = PARA_MIN(buffer_size,
110                         (snd_pcm_uframes_t)pad->samplerate);
111         if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
112                         start_threshold) < 0)
113                 return -E_START_THRESHOLD;
114         stop_threshold = buffer_size;
115         if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
116                         stop_threshold) < 0)
117                 return -E_STOP_THRESHOLD;
118         if (snd_pcm_sw_params(pad->handle, swparams) < 0)
119                 PARA_WARNING_LOG("unable to install sw params\n");
120         pad->bytes_per_frame = snd_pcm_format_physical_width(FORMAT)
121                 * pad->channels / 8;
122         if (pad->bytes_per_frame <= 0)
123                 return -E_PHYSICAL_WIDTH;
124         PARA_INFO_LOG("bytes per frame: %d\n", pad->bytes_per_frame);
125         if (snd_pcm_nonblock(pad->handle, 1))
126                 PARA_ERROR_LOG("failed to set nonblock mode\n");
127         pad->buffer_frames = 1000 * pad->buffer_time / pad->samplerate;
128         PARA_INFO_LOG("max buffered frames: %d\n", pad->buffer_frames);
129         return 1;
130 }
131
132 /* Open an instance of the alsa writer. */
133 static int alsa_open_nobtr(struct writer_node *wn)
134 {
135         struct alsa_write_args_info *conf = wn->conf;
136         struct writer_node_group *wng = wn->wng;
137         struct private_alsa_write_data *pad = para_calloc(sizeof(*pad));
138
139         wn->private_data = pad;
140         if (!conf->samplerate_given && wng->samplerate)
141                 pad->samplerate = *wng->samplerate;
142         else
143                 pad->samplerate = conf->samplerate_arg;
144         if (!conf->channels_given && wng->channels)
145                 pad->channels = *wng->channels;
146         else
147                 pad->channels = conf->channels_arg;
148         PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels, pad->samplerate);
149         return 1;
150 }
151
152 static int alsa_open_btr(struct writer_node *wn)
153 {
154         struct private_alsa_write_data *pad = para_calloc(sizeof(*pad));
155
156         sprintf(wn->task.status, "alsa writer");
157         wn->private_data = pad;
158         return 1;
159 }
160 static int alsa_open(struct writer_node *wn)
161 {
162         if (wn->btrn)
163                 return alsa_open_btr(wn);
164         return alsa_open_nobtr(wn);
165 }
166
167 static int alsa_write_pre_select(struct sched *s, struct writer_node *wn)
168 {
169         struct private_alsa_write_data *pad = wn->private_data;
170         struct writer_node_group *wng = wn->wng;
171         struct timeval tv;
172         snd_pcm_sframes_t avail, underrun;
173
174         if (!pad->handle)
175                 return 1;
176         if (wn->btrn) {
177                 size_t sz = btr_get_input_queue_size(wn->btrn);
178                 if (sz < pad->bytes_per_frame)
179                         return 1;
180         } else {
181                 if (*wng->loaded - wn->written < pad->bytes_per_frame)
182                         return 1;
183         }
184         /*
185          * Data is available to be written to the alsa handle.  Compute number
186          * of milliseconds until next buffer underrun would occur.
187          *
188          * snd_pcm_avail_update() updates the current available count of
189          * samples for writing.  It is a light method to obtain current stream
190          * position, because it does not require the user <-> kernel context
191          * switch, but the value is less accurate, because ring buffer pointers
192          * are updated in kernel drivers only when an interrupt occurs.
193          */
194         avail = snd_pcm_avail_update(pad->handle);
195         if (avail < 0)
196                 avail = 0;
197         underrun = (pad->buffer_frames - avail) * pad->buffer_time
198                 / pad->buffer_frames / 1000;
199         if (underrun < 50)
200                 underrun = 50;
201         underrun -= 50;
202         ms2tv(underrun, &tv);
203         if (tv_diff(&s->timeout, &tv, NULL) > 0)
204                 s->timeout = tv;
205         //PARA_CRIT_LOG("timout: %lu\n", tv2ms(&s->timeout));
206         return 1;
207 }
208
209 static void alsa_write_pre_select_btr(struct sched *s, struct task *t)
210 {
211         struct writer_node *wn = container_of(t, struct writer_node, task);
212         t->error = alsa_write_pre_select(s, wn);
213 }
214
215 static void xrun(snd_pcm_t *handle)
216 {
217         snd_pcm_status_t *status;
218         int ret;
219         struct timeval tv, diff;
220
221         snd_pcm_status_alloca(&status);
222         ret = snd_pcm_status(handle, status);
223         if (ret < 0)
224                 return;
225         if (snd_pcm_status_get_state(status) != SND_PCM_STATE_XRUN)
226                 return;
227         snd_pcm_status_get_trigger_tstamp(status, &tv);
228         tv_diff(now, &tv, &diff);
229         PARA_WARNING_LOG("underrun: %lums\n", tv2ms(&diff));
230 }
231
232 static int alsa_write_post_select(__a_unused struct sched *s,
233                 struct writer_node *wn)
234 {
235         struct private_alsa_write_data *pad = wn->private_data;
236         struct writer_node_group *wng = wn->wng;
237         size_t bytes = *wng->loaded - wn->written;
238         unsigned char *data = (unsigned char*)*wng->bufp + wn->written;
239         snd_pcm_sframes_t ret, frames, avail;
240
241         if (*wng->input_error < 0 && (!pad->handle || bytes < pad->bytes_per_frame)) {
242                 wn->written = *wng->loaded;
243                 return *wng->input_error;
244         }
245         if (!bytes) /* no data available */
246                 return 0;
247         if (!pad->handle) {
248                 int err = alsa_init(pad, wn->conf);
249                 if (err < 0)
250                         return err;
251         }
252         frames = bytes / pad->bytes_per_frame;
253         if (!frames) /* less than a single frame available */
254                 return 0;
255         avail = snd_pcm_avail_update(pad->handle);
256         if (avail <= 0)
257                 return 0;
258         frames = PARA_MIN(frames, avail);
259         ret = snd_pcm_writei(pad->handle, data, frames);
260         if (ret >= 0) {
261                 wn->written += ret * pad->bytes_per_frame;
262                 return 1;
263         }
264         if (ret == -EPIPE) {
265                 xrun(pad->handle);
266                 snd_pcm_prepare(pad->handle);
267                 return 0;
268         }
269         PARA_WARNING_LOG("%s\n", snd_strerror(-ret));
270         if (ret == -EAGAIN)
271                 return 0;
272         return -E_ALSA_WRITE;
273 }
274
275 static void alsa_close(struct writer_node *wn)
276 {
277         struct private_alsa_write_data *pad = wn->private_data;
278         PARA_INFO_LOG("closing writer node %p\n", wn);
279
280         if (pad->handle) {
281                 snd_pcm_drain(pad->handle);
282                 snd_pcm_close(pad->handle);
283                 snd_config_update_free_global();
284         }
285         free(pad);
286 }
287
288 static void alsa_write_post_select_btr(__a_unused struct sched *s,
289                 struct task *t)
290 {
291         struct writer_node *wn = container_of(t, struct writer_node, task);
292         struct private_alsa_write_data *pad = wn->private_data;
293         char *data;
294         size_t bytes;
295         snd_pcm_sframes_t frames, avail;
296         int ret;
297
298 again:
299         bytes = btr_next_buffer(wn->btrn, &data);
300         //PARA_CRIT_LOG("have: %zu\n", bytes);
301         t->error = 0;
302         ret = -E_ALSA_ORPHAN;
303         if (btr_no_parent(wn->btrn) && (!pad->handle || bytes < pad->bytes_per_frame))
304                 goto err;
305         if (!pad->handle) {
306                 char *buf;
307                 struct alsa_write_args_info *conf = wn->conf;
308                 if (bytes == 0) /* no data available */
309                         return;
310                 PARA_CRIT_LOG("alsa init\n");
311                 /* defaults */
312                 pad->samplerate = conf->samplerate_arg;
313                 pad->channels = conf->channels_arg;
314                 if (!conf->samplerate_given) { /* config option trumps btr_exec */
315                         /* ask parent btr nodes */
316                         buf = NULL;
317                         ret = btr_exec_up(wn->btrn, "samplerate", &buf);
318                         PARA_CRIT_LOG("ret: %d\n", ret);
319                         if (ret >= 0) {
320                                 int32_t rate;
321
322                                 ret = para_atoi32(buf, &rate);
323                                 free(buf);
324                                 if (ret < 0) /* should not happen */
325                                         goto err;
326                                 pad->samplerate = rate;
327                         }
328                 }
329                 if (!conf->channels_given) {
330                         buf = NULL;
331                         ret = btr_exec_up(wn->btrn, "channels", &buf);
332                         if (ret >= 0) {
333                                 int32_t ch;
334
335                                 ret = para_atoi32(buf, &ch);
336                                 freep(&buf);
337                                 if (ret < 0)
338                                         goto err;
339                                 pad->channels = ch;
340                         }
341                 }
342                 PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels, pad->samplerate);
343                 ret = 1;
344                 ret = alsa_init(pad, wn->conf);
345                 if (ret < 0)
346                         goto err;
347         }
348         for (;;) {
349                 if (bytes == 0)
350                         return;
351                 if (bytes >= pad->bytes_per_frame)
352                         break;
353                 /* should not be possible to reach this */
354                 PARA_CRIT_LOG("dropping %zu byte buffer\n", bytes);
355                 btr_consume(wn->btrn, bytes);
356                 bytes = btr_next_buffer(wn->btrn, &data);
357         }
358         frames = bytes / pad->bytes_per_frame;
359         avail = snd_pcm_avail_update(pad->handle);
360         if (avail <= 0)
361                 return;
362         frames = PARA_MIN(frames, avail);
363         //PARA_CRIT_LOG("writing %ld frames\n", frames);
364         frames = snd_pcm_writei(pad->handle, data, frames);
365         if (frames >= 0) {
366                 btr_consume(wn->btrn, frames * pad->bytes_per_frame);
367                 goto again;
368         }
369         if (frames == -EPIPE) {
370                 xrun(pad->handle);
371                 snd_pcm_prepare(pad->handle);
372                 return;
373         }
374         PARA_WARNING_LOG("%s\n", snd_strerror(-frames));
375         if (frames == -EAGAIN)
376                 return;
377         ret = -E_ALSA_WRITE;
378 err:
379         assert(ret < 0);
380         alsa_close(wn);
381         btr_del_node(wn->btrn);
382         wn->btrn = NULL;
383         t->error = ret;
384 }
385
386 __malloc static void *alsa_parse_config(const char *options)
387 {
388         int ret;
389         struct alsa_write_args_info *conf
390                 = para_calloc(sizeof(struct alsa_write_args_info));
391
392         PARA_INFO_LOG("options: %s, %zd\n", options, strcspn(options, " \t"));
393         ret = alsa_cmdline_parser_string(options, conf, "alsa_write");
394         if (ret)
395                 goto err_out;
396         PARA_INFO_LOG("help given: %d\n", conf->help_given);
397         return conf;
398 err_out:
399         free(conf);
400         return NULL;
401 }
402
403 /**
404  * the init function of the alsa writer
405  *
406  * \param w pointer to the writer to initialize
407  *
408  * \sa struct writer
409  */
410 void alsa_write_init(struct writer *w)
411 {
412         struct alsa_write_args_info dummy;
413
414         alsa_cmdline_parser_init(&dummy);
415         w->open = alsa_open;
416         w->close = alsa_close;
417         w->pre_select = alsa_write_pre_select;
418         w->pre_select_btr = alsa_write_pre_select_btr;
419         w->post_select = alsa_write_post_select;
420         w->post_select_btr = alsa_write_post_select_btr;
421         w->parse_config = alsa_parse_config;
422         w->shutdown = NULL; /* nothing to do */
423         w->help = (struct ggo_help) {
424                 .short_help = alsa_write_args_info_help,
425                 .detailed_help = alsa_write_args_info_detailed_help
426         };
427         alsa_cmdline_parser_free(&dummy);
428 }