make para_play use the error subsystem
[paraslash.git] / play.c
1 /*
2 * Copyright (C) 2005-2006 Andre Noll <maan@systemlinux.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
17 */
18
19 /*
20 * Based in parts on aplay.c from the alsa-utils-1.0.8 package,
21 * Copyright (c) by Jaroslav Kysela <perex@suse.cz>, which is
22 * based on the vplay program by Michael Beck.
23 */
24
25 #define WAV_HEADER_LEN 44
26 #include <sys/time.h> /* gettimeofday */
27 #include "para.h"
28 #include "fd.h"
29 #include "play.cmdline.h"
30 #include <alsa/asoundlib.h>
31 #include "string.h"
32 #include "error.h"
33
34 #define FORMAT SND_PCM_FORMAT_S16_LE
35
36 static snd_pcm_t *handle;
37 static snd_pcm_uframes_t chunk_size;
38 static unsigned char *audiobuf;
39 static size_t bytes_per_frame;
40 static struct timeval *start_time;
41 static struct gengetopt_args_info conf;
42
43 INIT_PLAY_ERRLISTS;
44
45 void para_log(__a_unused int ll, const char* fmt,...)
46 {
47 va_list argp;
48
49 va_start(argp, fmt);
50 vfprintf(stderr, fmt, argp);
51 va_end(argp);
52 }
53
54 /**
55 * read WAV_HEADER_LEN bytes from stdin to audio buffer
56 *
57 * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
58 * read. A positive return value indicates success.
59 */
60 static int read_wav_header(void)
61 {
62 ssize_t ret, count = 0;
63
64 while (count < WAV_HEADER_LEN) {
65 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
66 if (ret <= 0)
67 return -E_READ_HDR;
68 count += ret;
69 }
70 return 1;
71 }
72
73 /*
74 * open and prepare the PCM handle for writing
75 *
76 * Install PCM software and hardware configuration. Exit on errors.
77 */
78 static int alsa_init(void)
79 {
80 snd_pcm_hw_params_t *hwparams;
81 snd_pcm_sw_params_t *swparams;
82 snd_pcm_uframes_t buffer_size, xfer_align, start_threshold,
83 stop_threshold;
84 unsigned buffer_time = 0;
85 int err;
86 snd_pcm_info_t *info;
87 snd_output_t *log;
88
89 snd_pcm_info_alloca(&info);
90 if (snd_output_stdio_attach(&log, stderr, 0) < 0)
91 return -E_ALSA_LOG;
92 err = snd_pcm_open(&handle, conf.device_arg,
93 SND_PCM_STREAM_PLAYBACK, 0);
94 if (err < 0)
95 return -E_PCM_OPEN;
96 if ((err = snd_pcm_info(handle, info)) < 0)
97 return -E_SND_PCM_INFO;
98
99 snd_pcm_hw_params_alloca(&hwparams);
100 snd_pcm_sw_params_alloca(&swparams);
101 if (snd_pcm_hw_params_any(handle, hwparams) < 0)
102 return -E_BROKEN_CONF;
103 if (snd_pcm_hw_params_set_access(handle, hwparams,
104 SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
105 return -E_ACCESS_TYPE;
106 if (snd_pcm_hw_params_set_format(handle, hwparams, FORMAT) < 0)
107 return -E_SAMPLE_FORMAT;
108 if (snd_pcm_hw_params_set_channels(handle, hwparams, conf.channels_arg) < 0)
109 return -E_CHANNEL_COUNT;
110 if (snd_pcm_hw_params_set_rate_near(handle, hwparams,
111 (unsigned int*) &conf.sample_rate_arg, 0) < 0)
112 return -E_SET_RATE;
113 err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
114 if (err < 0 || !buffer_time)
115 return -E_GET_BUFFER_TIME;
116 PARA_DEBUG_LOG("buffer time: %d\n", buffer_time);
117 if (snd_pcm_hw_params_set_buffer_time_near(handle, hwparams,
118 &buffer_time, 0) < 0)
119 return -E_SET_BUFFER_TIME;
120 if (snd_pcm_hw_params(handle, hwparams) < 0)
121 return -E_HW_PARAMS;
122 snd_pcm_hw_params_get_period_size(hwparams, &chunk_size, 0);
123 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
124 PARA_DEBUG_LOG("buffer size: %lu, period_size: %lu\n", buffer_size, chunk_size);
125 if (chunk_size == buffer_size)
126 return -E_BAD_PERIOD;
127 snd_pcm_sw_params_current(handle, swparams);
128 err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
129 if (err < 0 || !xfer_align)
130 return -E_GET_XFER;
131 // snd_pcm_sw_params_set_sleep_min(handle, swparams, 0);
132 snd_pcm_sw_params_set_avail_min(handle, swparams, chunk_size);
133 /* round to closest transfer boundary */
134 start_threshold = (buffer_size / xfer_align) * xfer_align;
135 if (start_threshold < 1)
136 start_threshold = 1;
137 if (snd_pcm_sw_params_set_start_threshold(handle, swparams,
138 start_threshold) < 0)
139 return -E_START_THRESHOLD;
140 stop_threshold = buffer_size;
141 if (snd_pcm_sw_params_set_stop_threshold(handle, swparams,
142 stop_threshold) < 0)
143 return -E_STOP_THRESHOLD;
144 if (snd_pcm_sw_params_set_xfer_align(handle, swparams, xfer_align) < 0)
145 return -E_SET_XFER;
146 if (snd_pcm_sw_params(handle, swparams) < 0)
147 return -E_SW_PARAMS;
148 bytes_per_frame = snd_pcm_format_physical_width(FORMAT) * conf.channels_arg / 8;
149 return chunk_size * bytes_per_frame;
150 }
151
152 /**
153 * push out pcm frames
154 * \param data pointer do data to be written
155 * \param nbytes number of bytes (not frames)
156 *
157 * \return Number of bytes written, -E_ALSA_WRITE on errors.
158 */
159 static int alsa_write(u_char *data, size_t nbytes)
160 {
161 size_t frames = nbytes / bytes_per_frame;
162 snd_pcm_sframes_t r, result = 0;
163 while (frames > 0) {
164 /* write interleaved frames */
165 r = snd_pcm_writei(handle, data, frames);
166 if (r < 0)
167 PARA_ERROR_LOG("write error: %s\n", snd_strerror(r));
168 if (r == -EAGAIN || (r >= 0 && r < frames))
169 snd_pcm_wait(handle, 1);
170 else if (r == -EPIPE)
171 snd_pcm_prepare(handle);
172 else if (r < 0)
173 return -E_ALSA_WRITE;
174 if (r > 0) {
175 result += r;
176 frames -= r;
177 data += r * bytes_per_frame;
178 }
179 }
180 return result * bytes_per_frame;
181 }
182
183 static void alsa_shutdown(void)
184 {
185 snd_pcm_drain(handle);
186 snd_pcm_close(handle);
187 snd_config_update_free_global();
188 }
189
190 /**
191 * check if current time is later than start_time
192 * \param diff pointer to write remaining time to
193 *
194 * If start_time was not given, or current time is later than given
195 * start_time, return 0. Otherwise, return 1 and write the time
196 * difference between current time and start_time to diff. diff may be
197 * NULL.
198 *
199 */
200 static int start_time_in_future(struct timeval *diff)
201 {
202 struct timeval now;
203
204 if (!conf.start_time_given)
205 return 0;
206 gettimeofday(&now, NULL);
207 return tv_diff(start_time, &now, diff) > 0? 1 : 0;
208 }
209
210 /**
211 * sleep until time given at command line
212 *
213 * This is called if the initial buffer is filled. It returns
214 * immediately if no start_time was given at the command line
215 * or if the given start time is in the past.
216 *
217 */
218 static void do_initial_delay(struct timeval *delay)
219 {
220 do
221 para_select(1, NULL, NULL, delay);
222 while (start_time_in_future(delay));
223 }
224
225 /**
226 * play raw pcm data
227 * \param loaded number of bytes already loaded
228 *
229 * If start_time was given, prebuffer data until buffer is full or
230 * start_time is reached. In any case, do not start playing before
231 * start_time.
232 *
233 * \return positive on success, negative on errors.
234 */
235 static int play_pcm(size_t loaded)
236 {
237 size_t bufsize, written = 0, prebuf_size;
238 unsigned char *p;
239 struct timeval delay;
240 int chunk_bytes, ret = alsa_init();
241
242 if (ret < 0)
243 goto out;
244 chunk_bytes = ret;
245 bufsize = (conf.bufsize_arg * 1024 / chunk_bytes) * chunk_bytes;
246 audiobuf = para_realloc(audiobuf, bufsize);
247 prebuf_size = conf.prebuffer_arg * bufsize / 100;
248 again:
249 if (!written) {
250 if (loaded < prebuf_size)
251 goto read;
252 if (start_time && start_time_in_future(&delay)) {
253 do_initial_delay(&delay);
254 start_time = NULL;
255 }
256 }
257 p = audiobuf;
258 while (loaded >= chunk_bytes) {
259 ret = alsa_write(p, chunk_bytes);
260 if (ret < 0)
261 goto out;
262 p += ret;
263 written += ret;
264 loaded -= ret;
265 }
266 if (loaded && p != audiobuf)
267 memmove(audiobuf, p, loaded);
268 read:
269 ret = read(STDIN_FILENO, audiobuf + loaded, bufsize - loaded);
270 if (ret < 0) {
271 ret = -E_READ_STDIN;
272 goto out;
273 }
274 if (ret) {
275 loaded += ret;
276 goto again;
277 }
278 ret = 1;
279 out:
280 alsa_shutdown();
281 return ret;
282 }
283
284 /**
285 * test if audio buffer contains a valid wave header
286 *
287 * \return If not, return 0, otherwise, store number of channels and sample rate
288 * in struct conf and return WAV_HEADER_LEN.
289 */
290 static size_t check_wave(void)
291 {
292 unsigned char *a = audiobuf;
293 if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
294 return WAV_HEADER_LEN;
295 conf.channels_arg = (unsigned) a[22];
296 conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
297 return 0;
298 }
299
300 int main(int argc, char *argv[])
301 {
302 struct timeval tv;
303 int ret;
304
305 cmdline_parser(argc, argv, &conf);
306 if (conf.start_time_given) {
307 ret = -E_PLAY_SYNTAX;
308 if (sscanf(conf.start_time_arg, "%lu:%lu",
309 &tv.tv_sec, &tv.tv_usec) != 2)
310 goto out;
311 start_time = &tv;
312 }
313 audiobuf = para_malloc(WAV_HEADER_LEN);
314 ret = read_wav_header();
315 if (ret < 0)
316 goto out;
317 ret = play_pcm(check_wave());
318 out:
319 free(audiobuf);
320 if (ret < 0)
321 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
322 return ret;
323 }