Merge branch 't/bits_per_sample'
[paraslash.git] / alsa_write.c
1 /*
2  * Copyright (C) 2005-2010 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 "write_common.h"
31 #include "alsa_write.cmdline.h"
32 #include "error.h"
33
34 /** Data specific to the alsa writer. */
35 struct private_alsa_write_data {
36         /** The alsa handle */
37         snd_pcm_t *handle;
38         /** Determined and set by alsa_open(). */
39         int bytes_per_frame;
40         /** The approximate maximum buffer duration in us. */
41         unsigned buffer_time;
42         /* Number of frames that fit into the buffer. */
43         snd_pcm_uframes_t buffer_frames;
44         /**
45          * The sample rate given by command line option or the decoder
46          * of the writer node group.
47          */
48         unsigned sample_rate;
49
50         snd_pcm_format_t sample_format;
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         struct timeval drain_barrier;
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 private_alsa_write_data *pad,
74                 struct alsa_write_args_info *conf)
75 {
76         snd_pcm_hw_params_t *hwparams;
77         snd_pcm_sw_params_t *swparams;
78         snd_pcm_uframes_t start_threshold, stop_threshold;
79         snd_pcm_uframes_t period_size;
80         int err;
81
82         PARA_INFO_LOG("opening %s\n", conf->device_arg);
83         err = snd_pcm_open(&pad->handle, conf->device_arg,
84                 SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
85         if (err < 0)
86                 return -E_PCM_OPEN;
87
88         snd_pcm_hw_params_alloca(&hwparams);
89         snd_pcm_sw_params_alloca(&swparams);
90         if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
91                 return -E_BROKEN_CONF;
92         if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
93                         SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
94                 return -E_ACCESS_TYPE;
95         if (snd_pcm_hw_params_set_format(pad->handle, hwparams,
96                         pad->sample_format) < 0)
97                 return -E_SAMPLE_FORMAT;
98         if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
99                         pad->channels) < 0)
100                 return -E_CHANNEL_COUNT;
101         if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
102                         &pad->sample_rate, NULL) < 0)
103                 return -E_SET_RATE;
104         err = snd_pcm_hw_params_get_buffer_time_max(hwparams,
105                 &pad->buffer_time, NULL);
106         if (err < 0 || !pad->buffer_time)
107                 return -E_GET_BUFFER_TIME;
108         PARA_INFO_LOG("buffer time: %d\n", pad->buffer_time);
109         if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
110                         &pad->buffer_time, NULL) < 0)
111                 return -E_SET_BUFFER_TIME;
112         if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
113                 return -E_HW_PARAMS;
114         snd_pcm_hw_params_get_period_size(hwparams, &period_size, NULL);
115         snd_pcm_hw_params_get_buffer_size(hwparams, &pad->buffer_frames);
116         PARA_INFO_LOG("buffer size: %lu, period_size: %lu\n", pad->buffer_frames,
117                 period_size);
118         if (period_size == pad->buffer_frames)
119                 return -E_BAD_PERIOD;
120         snd_pcm_sw_params_current(pad->handle, swparams);
121         snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
122         if (pad->buffer_frames < 1)
123                 start_threshold = 1;
124         else
125                 start_threshold = PARA_MIN(pad->buffer_frames,
126                         (snd_pcm_uframes_t)pad->sample_rate);
127         if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
128                         start_threshold) < 0)
129                 return -E_START_THRESHOLD;
130         stop_threshold = pad->buffer_frames;
131         if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
132                         stop_threshold) < 0)
133                 return -E_STOP_THRESHOLD;
134         if (snd_pcm_sw_params(pad->handle, swparams) < 0)
135                 PARA_WARNING_LOG("unable to install sw params\n");
136         pad->bytes_per_frame = snd_pcm_format_physical_width(pad->sample_format)
137                 * pad->channels / 8;
138         if (pad->bytes_per_frame <= 0)
139                 return -E_PHYSICAL_WIDTH;
140         PARA_INFO_LOG("bytes per frame: %d\n", pad->bytes_per_frame);
141         if (snd_pcm_nonblock(pad->handle, 1))
142                 PARA_ERROR_LOG("failed to set nonblock mode\n");
143         return 1;
144 }
145
146 /* Open an instance of the alsa writer. */
147 static int alsa_open(struct writer_node *wn)
148 {
149         wn->private_data = para_calloc(sizeof(struct private_alsa_write_data));
150         return 1;
151 }
152
153 static void alsa_write_pre_select(struct sched *s, struct task *t)
154 {
155         struct writer_node *wn = container_of(t, struct writer_node, task);
156         struct private_alsa_write_data *pad = wn->private_data;
157         struct timeval tv;
158         snd_pcm_sframes_t avail, underrun;
159         int ret;
160
161         if (!pad->handle)
162                 return;
163         ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
164         if (ret < 0)
165                 sched_request_timeout_ms(20, s);
166         if (ret <= 0)
167                 return;
168         /*
169          * Data is available to be written to the alsa handle.  Compute number
170          * of milliseconds until next buffer underrun would occur.
171          *
172          * snd_pcm_avail_update() updates the current available count of
173          * samples for writing.  It is a light method to obtain current stream
174          * position, because it does not require the user <-> kernel context
175          * switch, but the value is less accurate, because ring buffer pointers
176          * are updated in kernel drivers only when an interrupt occurs.
177          */
178         avail = snd_pcm_avail_update(pad->handle);
179         if (avail < 0)
180                 avail = 0;
181         underrun = (pad->buffer_frames - avail) * pad->buffer_time
182                 / pad->buffer_frames / 1000;
183         if (underrun < 50)
184                 underrun = 50;
185         underrun -= 50;
186         ms2tv(underrun, &tv);
187         if (tv_diff(&s->timeout, &tv, NULL) > 0)
188                 s->timeout = tv;
189 }
190
191 static void alsa_close(struct writer_node *wn)
192 {
193         struct private_alsa_write_data *pad = wn->private_data;
194         PARA_INFO_LOG("closing writer node %p\n", wn);
195
196         if (pad->handle) {
197                 /*
198                  * It's OK to have a blocking operation here because we already
199                  * made sure that the PCM output buffer is (nearly) empty.
200                  */
201                 snd_pcm_nonblock(pad->handle, 0);
202                 snd_pcm_drain(pad->handle);
203                 snd_pcm_close(pad->handle);
204                 snd_config_update_free_global();
205         }
206         free(pad);
207 }
208
209 static void alsa_write_post_select(__a_unused struct sched *s,
210                 struct task *t)
211 {
212         struct writer_node *wn = container_of(t, struct writer_node, task);
213         struct private_alsa_write_data *pad = wn->private_data;
214         struct btr_node *btrn = wn->btrn;
215         char *data;
216         size_t bytes;
217         snd_pcm_sframes_t frames;
218         int ret;
219
220 again:
221         t->error = 0;
222         ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
223         if (ret == 0)
224                 return;
225         btr_merge(btrn, wn->min_iqs);
226         bytes = btr_next_buffer(btrn, &data);
227         if (ret < 0 || bytes < pad->bytes_per_frame) { /* eof */
228                 assert(btr_no_parent(btrn));
229                 ret = -E_ALSA_EOF;
230                 if (!pad->handle)
231                         goto err;
232                 /* wait until pending frames are played */
233                 if (pad->drain_barrier.tv_sec == 0) {
234                         PARA_DEBUG_LOG("waiting for device to drain\n");
235                         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
236                                 &pad->drain_barrier);
237                         return;
238                 }
239                 if (tv_diff(now, &pad->drain_barrier, NULL) > 0)
240                         goto err;
241                 return;
242         }
243         if (!pad->handle) {
244                 int32_t val;
245
246                 if (bytes == 0) /* no data available */
247                         return;
248                 get_btr_sample_rate(btrn, &val);
249                 pad->sample_rate = val;
250                 get_btr_channels(btrn, &val);
251                 pad->channels = val;
252                 get_btr_sample_format(btrn, &val);
253                 pad->sample_format = get_alsa_pcm_format(val);
254
255                 PARA_INFO_LOG("%d channel(s), %dHz\n", pad->channels,
256                         pad->sample_rate);
257                 ret = alsa_init(pad, wn->conf);
258                 if (ret < 0)
259                         goto err;
260                 wn->min_iqs = pad->bytes_per_frame;
261                 goto again;
262         }
263         frames = bytes / pad->bytes_per_frame;
264         frames = snd_pcm_writei(pad->handle, data, frames);
265         if (frames >= 0) {
266                 btr_consume(btrn, frames * pad->bytes_per_frame);
267                 goto again;
268         }
269         if (frames == -EPIPE) {
270                 PARA_WARNING_LOG("underrun (tried to write %zu bytes)\n", bytes);
271                 snd_pcm_prepare(pad->handle);
272                 return;
273         }
274         if (frames == -EAGAIN)
275                 return;
276         PARA_WARNING_LOG("%s\n", snd_strerror(-frames));
277         ret = -E_ALSA_WRITE;
278 err:
279         assert(ret < 0);
280         btr_remove_node(btrn);
281         t->error = ret;
282 }
283
284 __malloc static void *alsa_parse_config(const char *options)
285 {
286         int ret;
287         struct alsa_write_args_info *conf
288                 = para_calloc(sizeof(struct alsa_write_args_info));
289
290         PARA_INFO_LOG("options: %s, %zd\n", options, strcspn(options, " \t"));
291         ret = alsa_cmdline_parser_string(options, conf, "alsa_write");
292         if (ret)
293                 goto err_out;
294         PARA_INFO_LOG("help given: %d\n", conf->help_given);
295         return conf;
296 err_out:
297         free(conf);
298         return NULL;
299 }
300
301 static void alsa_free_config(void *conf)
302 {
303         alsa_cmdline_parser_free(conf);
304 }
305
306 /**
307  * The init function of the alsa writer.
308  *
309  * \param w Pointer to the writer to initialize.
310  *
311  * \sa struct \ref writer.
312  */
313 void alsa_write_init(struct writer *w)
314 {
315         struct alsa_write_args_info dummy;
316
317         alsa_cmdline_parser_init(&dummy);
318         w->open = alsa_open;
319         w->close = alsa_close;
320         w->pre_select = alsa_write_pre_select;
321         w->post_select = alsa_write_post_select;
322         w->parse_config = alsa_parse_config;
323         w->shutdown = NULL; /* nothing to do */
324         w->free_config = alsa_free_config;
325         w->help = (struct ggo_help) {
326                 .short_help = alsa_write_args_info_help,
327                 .detailed_help = alsa_write_args_info_detailed_help
328         };
329         alsa_cmdline_parser_free(&dummy);
330 }