switch to the new struct writer/writer_node abstraction
[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 struct private_alsa_data {
37 snd_pcm_t *handle;
38 size_t bytes_per_frame;
39 };
40
41 struct writer_node {
42 struct writer *writer;
43 void *private_data;
44 int chunk_bytes;
45 };
46
47 struct writer {
48 int (*open)(struct writer_node *);
49 int (*write)(char *data, size_t nbytes, struct writer_node *);
50 void (*close)(struct writer_node *);
51 void (*shutdown)(struct writer_node *);
52 };
53
54 #define NUM_WRITERS 1
55 static struct writer writers[NUM_WRITERS];
56 #define FOR_EACH_WRITER(i) for (i = 0; i < NUM_WRITERS, i++)
57 static struct writer_node *writer_nodes;
58
59
60 static unsigned char *audiobuf;
61 static struct timeval *start_time;
62 static struct gengetopt_args_info conf;
63
64 INIT_PLAY_ERRLISTS;
65
66 void para_log(int ll, const char* fmt,...)
67 {
68 va_list argp;
69
70 if (ll < conf.loglevel_arg)
71 return;
72 va_start(argp, fmt);
73 vfprintf(stderr, fmt, argp);
74 va_end(argp);
75 }
76
77 /**
78 * read WAV_HEADER_LEN bytes from stdin to audio buffer
79 *
80 * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
81 * read. A positive return value indicates success.
82 */
83 static int read_wav_header(void)
84 {
85 ssize_t ret, count = 0;
86
87 while (count < WAV_HEADER_LEN) {
88 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
89 if (ret <= 0)
90 return -E_READ_HDR;
91 count += ret;
92 }
93 return 1;
94 }
95
96 /*
97 * open and prepare the PCM handle for writing
98 *
99 * Install PCM software and hardware configuration. Exit on errors.
100 */
101 static int alsa_open(struct writer_node *w)
102 {
103 snd_pcm_hw_params_t *hwparams;
104 snd_pcm_sw_params_t *swparams;
105 snd_pcm_uframes_t buffer_size, xfer_align, start_threshold,
106 stop_threshold;
107 unsigned buffer_time = 0;
108 int err;
109 snd_pcm_info_t *info;
110 snd_output_t *log;
111 snd_pcm_uframes_t period_size;
112 struct private_alsa_data *pad = para_malloc(sizeof(struct private_alsa_data));
113 w->private_data = pad;
114
115 snd_pcm_info_alloca(&info);
116 if (snd_output_stdio_attach(&log, stderr, 0) < 0)
117 return -E_ALSA_LOG;
118 err = snd_pcm_open(&pad->handle, conf.device_arg,
119 SND_PCM_STREAM_PLAYBACK, 0);
120 if (err < 0)
121 return -E_PCM_OPEN;
122 if ((err = snd_pcm_info(pad->handle, info)) < 0)
123 return -E_SND_PCM_INFO;
124
125 snd_pcm_hw_params_alloca(&hwparams);
126 snd_pcm_sw_params_alloca(&swparams);
127 if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
128 return -E_BROKEN_CONF;
129 if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
130 SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
131 return -E_ACCESS_TYPE;
132 if (snd_pcm_hw_params_set_format(pad->handle, hwparams, FORMAT) < 0)
133 return -E_SAMPLE_FORMAT;
134 if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
135 conf.channels_arg) < 0)
136 return -E_CHANNEL_COUNT;
137 if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
138 (unsigned int*) &conf.sample_rate_arg, 0) < 0)
139 return -E_SET_RATE;
140 err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
141 if (err < 0 || !buffer_time)
142 return -E_GET_BUFFER_TIME;
143 PARA_DEBUG_LOG("buffer time: %d\n", buffer_time);
144 if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
145 &buffer_time, 0) < 0)
146 return -E_SET_BUFFER_TIME;
147 if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
148 return -E_HW_PARAMS;
149 snd_pcm_hw_params_get_period_size(hwparams, &period_size, 0);
150 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
151 PARA_DEBUG_LOG("buffer size: %lu, period_size: %lu\n", buffer_size,
152 period_size);
153 if (period_size == buffer_size)
154 return -E_BAD_PERIOD;
155 snd_pcm_sw_params_current(pad->handle, swparams);
156 err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
157 if (err < 0 || !xfer_align)
158 return -E_GET_XFER;
159 snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
160 /* round to closest transfer boundary */
161 start_threshold = (buffer_size / xfer_align) * xfer_align;
162 if (start_threshold < 1)
163 start_threshold = 1;
164 if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
165 start_threshold) < 0)
166 return -E_START_THRESHOLD;
167 stop_threshold = buffer_size;
168 if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
169 stop_threshold) < 0)
170 return -E_STOP_THRESHOLD;
171 if (snd_pcm_sw_params_set_xfer_align(pad->handle, swparams,
172 xfer_align) < 0)
173 return -E_SET_XFER;
174 if (snd_pcm_sw_params(pad->handle, swparams) < 0)
175 return -E_SW_PARAMS;
176 pad->bytes_per_frame = snd_pcm_format_physical_width(FORMAT)
177 * conf.channels_arg / 8;
178 return period_size * pad->bytes_per_frame;
179 }
180
181 /**
182 * push out pcm frames
183 * \param data pointer do data to be written
184 * \param nbytes number of bytes (not frames)
185 *
186 * \return Number of bytes written, -E_ALSA_WRITE on errors.
187 */
188 static int alsa_write(char *data, size_t nbytes, struct writer_node *wn)
189 {
190 struct private_alsa_data *pad = wn->private_data;
191 size_t frames = nbytes / pad->bytes_per_frame;
192 unsigned char *d = data;
193 snd_pcm_sframes_t r, result = 0;
194
195 while (frames > 0) {
196 /* write interleaved frames */
197 r = snd_pcm_writei(pad->handle, d, frames);
198 if (r < 0)
199 PARA_ERROR_LOG("write error: %s\n", snd_strerror(r));
200 if (r == -EAGAIN || (r >= 0 && r < frames))
201 snd_pcm_wait(pad->handle, 1);
202 else if (r == -EPIPE)
203 snd_pcm_prepare(pad->handle);
204 else if (r < 0)
205 return -E_ALSA_WRITE;
206 if (r > 0) {
207 result += r;
208 frames -= r;
209 d += r * pad->bytes_per_frame;
210 }
211 }
212 return result * pad->bytes_per_frame;
213 }
214
215 static void alsa_close(struct writer_node *wn)
216 {
217 struct private_alsa_data *pad = wn->private_data;
218 snd_pcm_drain(pad->handle);
219 snd_pcm_close(pad->handle);
220 snd_config_update_free_global();
221 free(pad);
222 }
223
224 void alsa_writer_init(struct writer *w)
225 {
226 w->open = alsa_open;
227 w->write = alsa_write;
228 w->close = alsa_close;
229 w->shutdown = NULL; /* nothing to do */
230 }
231
232
233 /**
234 * check if current time is later than start_time
235 * \param diff pointer to write remaining time to
236 *
237 * If start_time was not given, or current time is later than given
238 * start_time, return 0. Otherwise, return 1 and write the time
239 * difference between current time and start_time to diff. diff may be
240 * NULL.
241 *
242 */
243 static int start_time_in_future(struct timeval *diff)
244 {
245 struct timeval now;
246
247 if (!conf.start_time_given)
248 return 0;
249 gettimeofday(&now, NULL);
250 return tv_diff(start_time, &now, diff) > 0? 1 : 0;
251 }
252
253 /**
254 * sleep until time given at command line
255 *
256 * This is called if the initial buffer is filled. It returns
257 * immediately if no start_time was given at the command line
258 * or if the given start time is in the past.
259 *
260 */
261 static void do_initial_delay(struct timeval *delay)
262 {
263 do
264 para_select(1, NULL, NULL, delay);
265 while (start_time_in_future(delay));
266 }
267
268 static int read_stdin(char *buf, size_t bytes_to_load, size_t *loaded)
269 {
270 ssize_t ret;
271
272 while (*loaded < bytes_to_load) {
273 ret = read(STDIN_FILENO, buf + *loaded, bytes_to_load - *loaded);
274 if (ret <= 0) {
275 if (ret < 0)
276 ret = -E_READ_STDIN;
277 return ret;
278 }
279 *loaded += ret;
280 }
281 return 1;
282 }
283
284 /**
285 * play raw pcm data
286 * \param loaded number of bytes already loaded
287 *
288 * If start_time was given, prebuffer data until buffer is full or
289 * start_time is reached. In any case, do not start playing before
290 * start_time.
291 *
292 * \return positive on success, negative on errors.
293 */
294 static int play_pcm(size_t loaded)
295 {
296 size_t bufsize, min_written = 0, prebuf_size, bytes_to_load;
297 struct timeval delay;
298 int i, max_chunk_bytes = 0, ret, not_yet_started = 1, need_more_writes;
299 struct writer_node *wn;
300 size_t *written = para_calloc(1 * sizeof(size_t));
301
302 for (i = 0; i < 1; i++) {
303 wn = &writer_nodes[i];
304 ret = wn->writer->open(wn);
305 if (ret < 0)
306 goto out;
307 wn->chunk_bytes = ret;
308 max_chunk_bytes = PARA_MAX(max_chunk_bytes, ret);
309 }
310 PARA_INFO_LOG("max chunk_bytes: %d\n", max_chunk_bytes);
311 bufsize = (conf.bufsize_arg * 1024 / max_chunk_bytes) * max_chunk_bytes;
312 audiobuf = para_realloc(audiobuf, bufsize);
313 prebuf_size = conf.prebuffer_arg * bufsize / 100;
314 bytes_to_load = PARA_MAX(prebuf_size, max_chunk_bytes);
315 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
316 if (ret <= 0 || loaded < bytes_to_load) {
317 if (ret >= 0)
318 ret = -E_PREMATURE_END;
319 goto out;
320 }
321 if (not_yet_started && start_time && start_time_in_future(&delay))
322 do_initial_delay(&delay);
323 not_yet_started = 0;
324 again:
325 need_more_writes = 1;
326 while (need_more_writes) {
327 need_more_writes = 0;
328 for (i = 0; i < 1; i++) {
329 unsigned char *p = audiobuf + written[i];
330 wn = &writer_nodes[i];
331 if (!i)
332 min_written = written[i];
333 else
334 min_written = PARA_MIN(min_written, written[i]);
335 if (loaded < wn->chunk_bytes + written[i])
336 continue;
337 ret = wn->writer->write(p, wn->chunk_bytes, wn);
338 if (ret < 0)
339 goto out;
340 if (ret != wn->chunk_bytes)
341 PARA_WARNING_LOG("short write: %d/%d", ret,
342 wn->chunk_bytes);
343 written[i] += ret;
344 need_more_writes = 1;
345 }
346 }
347 loaded -= min_written;
348 if (loaded > 0) {
349 if (loaded >= bufsize) {
350 ret = -E_PLAY_OVERRUN;
351 goto out;
352 }
353 memmove(audiobuf, audiobuf + min_written, loaded);
354 }
355 for (i = 0; i < 1; i++)
356 written[i] -= min_written;
357 bytes_to_load = PARA_MIN(max_chunk_bytes, bufsize);
358 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
359 if (ret < 0)
360 goto out;
361 if (ret)
362 goto again;
363 for (i = 0; i < 1; i++) {
364 unsigned char *p = audiobuf + written[i];
365 wn = &writer_nodes[i];
366 int bytes_to_write;
367 if (written[i] >= loaded)
368 continue;
369 bytes_to_write = PARA_MIN(wn->chunk_bytes, loaded - written[i]);
370 ret = wn->writer->write(p, bytes_to_write, wn);
371 if (ret < 0)
372 goto out;
373 written[i] += ret;
374 }
375 ret = 0;
376 out:
377 free(written);
378 for (i = 0; i < 1; i++) {
379 wn = &writer_nodes[i];
380 wn->writer->close(wn);
381 }
382 return ret;
383 }
384
385 /**
386 * test if audio buffer contains a valid wave header
387 *
388 * \return If not, return 0, otherwise, store number of channels and sample rate
389 * in struct conf and return WAV_HEADER_LEN.
390 */
391 static size_t check_wave(void)
392 {
393 unsigned char *a = audiobuf;
394 if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
395 return WAV_HEADER_LEN;
396 conf.channels_arg = (unsigned) a[22];
397 conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
398 return 0;
399 }
400
401 int main(int argc, char *argv[])
402 {
403 struct timeval tv;
404 int ret = -E_PLAY_SYNTAX;
405
406 cmdline_parser(argc, argv, &conf);
407 if (conf.prebuffer_arg < 0 || conf.prebuffer_arg > 100)
408 goto out;
409 if (conf.start_time_given) {
410 if (sscanf(conf.start_time_arg, "%lu:%lu",
411 &tv.tv_sec, &tv.tv_usec) != 2)
412 goto out;
413 start_time = &tv;
414 }
415 /* call init for each supported writer */
416 alsa_writer_init(&writers[0]);
417 /* one for each given writer */
418 writer_nodes = para_calloc(2 * sizeof(struct writer_node));
419 writer_nodes[0].writer = &writers[0]; /* alsa */
420
421 audiobuf = para_malloc(WAV_HEADER_LEN);
422 ret = read_wav_header();
423 if (ret < 0)
424 goto out;
425 ret = play_pcm(check_wave());
426 out:
427 free(audiobuf);
428 free(writer_nodes);
429 if (ret < 0)
430 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
431 return ret;
432 }