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