2 * Copyright (C) 2005-2006 Andre Noll <maan@systemlinux.org>
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.
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.
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.
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.
25 #define WAV_HEADER_LEN 44
26 #include <sys/time.h> /* gettimeofday */
29 #include "play.cmdline.h"
30 #include <alsa/asoundlib.h>
40 write_common.h: decratation of the wng funcs
45 enum writer_enum {WRITER_ENUM};
49 struct writer *writer;
56 void (*init)(struct writer *w);
57 int (*open)(struct writer_node *);
58 int (*write)(char *data, size_t nbytes, struct writer_node *);
59 void (*close)(struct writer_node *);
60 void (*shutdown)(struct writer_node *);
64 struct writer_node_group {
66 struct writer_node *writer_nodes;
68 size_t max_chunk_bytes;
73 #define FOR_EACH_WRITER_NODE(i, wng) for (i = 0; i < (wng)->num_writers; i++)
74 #define FOR_EACH_WRITER(i) for (i = 0; i < NUM_SUPPORTED_WRITERS; i++)
80 static unsigned char *audiobuf;
81 static struct timeval *start_time;
82 static struct gengetopt_args_info conf;
88 void para_log(int ll, const char* fmt,...)
92 if (ll < conf.loglevel_arg)
95 vfprintf(stderr, fmt, argp);
101 * read WAV_HEADER_LEN bytes from stdin to audio buffer
103 * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
104 * read. A positive return value indicates success.
106 static int read_wav_header(void)
108 ssize_t ret, count = 0;
110 while (count < WAV_HEADER_LEN) {
111 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
120 #define FORMAT SND_PCM_FORMAT_S16_LE
121 struct private_alsa_data {
123 size_t bytes_per_frame;
127 * open and prepare the PCM handle for writing
129 * Install PCM software and hardware configuration. Exit on errors.
131 static int alsa_open(struct writer_node *w)
133 snd_pcm_hw_params_t *hwparams;
134 snd_pcm_sw_params_t *swparams;
135 snd_pcm_uframes_t buffer_size, xfer_align, start_threshold,
137 unsigned buffer_time = 0;
139 snd_pcm_info_t *info;
141 snd_pcm_uframes_t period_size;
142 struct private_alsa_data *pad = para_malloc(sizeof(struct private_alsa_data));
143 w->private_data = pad;
145 snd_pcm_info_alloca(&info);
146 if (snd_output_stdio_attach(&log, stderr, 0) < 0)
148 err = snd_pcm_open(&pad->handle, conf.device_arg,
149 SND_PCM_STREAM_PLAYBACK, 0);
152 if ((err = snd_pcm_info(pad->handle, info)) < 0)
153 return -E_SND_PCM_INFO;
155 snd_pcm_hw_params_alloca(&hwparams);
156 snd_pcm_sw_params_alloca(&swparams);
157 if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
158 return -E_BROKEN_CONF;
159 if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
160 SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
161 return -E_ACCESS_TYPE;
162 if (snd_pcm_hw_params_set_format(pad->handle, hwparams, FORMAT) < 0)
163 return -E_SAMPLE_FORMAT;
164 if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
165 conf.channels_arg) < 0)
166 return -E_CHANNEL_COUNT;
167 if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
168 (unsigned int*) &conf.sample_rate_arg, 0) < 0)
170 err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
171 if (err < 0 || !buffer_time)
172 return -E_GET_BUFFER_TIME;
173 PARA_DEBUG_LOG("buffer time: %d\n", buffer_time);
174 if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
175 &buffer_time, 0) < 0)
176 return -E_SET_BUFFER_TIME;
177 if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
179 snd_pcm_hw_params_get_period_size(hwparams, &period_size, 0);
180 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
181 PARA_DEBUG_LOG("buffer size: %lu, period_size: %lu\n", buffer_size,
183 if (period_size == buffer_size)
184 return -E_BAD_PERIOD;
185 snd_pcm_sw_params_current(pad->handle, swparams);
186 err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
187 if (err < 0 || !xfer_align)
189 snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
190 /* round to closest transfer boundary */
191 start_threshold = (buffer_size / xfer_align) * xfer_align;
192 if (start_threshold < 1)
194 if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
195 start_threshold) < 0)
196 return -E_START_THRESHOLD;
197 stop_threshold = buffer_size;
198 if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
200 return -E_STOP_THRESHOLD;
201 if (snd_pcm_sw_params_set_xfer_align(pad->handle, swparams,
204 if (snd_pcm_sw_params(pad->handle, swparams) < 0)
206 pad->bytes_per_frame = snd_pcm_format_physical_width(FORMAT)
207 * conf.channels_arg / 8;
208 return period_size * pad->bytes_per_frame;
213 * push out pcm frames
214 * \param data pointer do data to be written
215 * \param nbytes number of bytes (not frames)
217 * \return Number of bytes written, -E_ALSA_WRITE on errors.
219 static int alsa_write(char *data, size_t nbytes, struct writer_node *wn)
221 struct private_alsa_data *pad = wn->private_data;
222 size_t frames = nbytes / pad->bytes_per_frame;
223 unsigned char *d = data;
224 snd_pcm_sframes_t r, result = 0;
227 /* write interleaved frames */
228 r = snd_pcm_writei(pad->handle, d, frames);
230 PARA_ERROR_LOG("write error: %s\n", snd_strerror(r));
231 if (r == -EAGAIN || (r >= 0 && r < frames))
232 snd_pcm_wait(pad->handle, 1);
233 else if (r == -EPIPE)
234 snd_pcm_prepare(pad->handle);
236 return -E_ALSA_WRITE;
240 d += r * pad->bytes_per_frame;
243 return result * pad->bytes_per_frame;
247 static void alsa_close(struct writer_node *wn)
249 struct private_alsa_data *pad = wn->private_data;
250 snd_pcm_drain(pad->handle);
251 snd_pcm_close(pad->handle);
252 snd_config_update_free_global();
257 void alsa_writer_init(struct writer *w)
260 w->write = alsa_write;
261 w->close = alsa_close;
262 w->shutdown = NULL; /* nothing to do */
270 struct private_file_writer_data {
273 static int file_writer_open(struct writer_node *w)
275 struct private_file_writer_data *pfwd = para_calloc(
276 sizeof(struct private_file_writer_data));
277 char *tmp = para_tmpname(), *home = para_homedir(),
278 *filename = make_message("%s/.paraslash/%s", home, tmp);
282 w->private_data = pfwd;
283 pfwd->fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
291 static int file_writer_write(char *data, size_t nbytes, struct writer_node *wn)
293 struct private_file_writer_data *pfwd = wn->private_data;
294 int ret = write(pfwd->fd, data, nbytes);
300 static void file_writer_close(struct writer_node *wn)
302 struct private_file_writer_data *pfwd = wn->private_data;
307 void file_writer_init(struct writer *w)
309 w->open = file_writer_open;
310 w->write = file_writer_write;
311 w->close = file_writer_close;
312 w->shutdown = NULL; /* nothing to do */
318 * check if current time is later than start_time
319 * \param diff pointer to write remaining time to
321 * If start_time was not given, or current time is later than given
322 * start_time, return 0. Otherwise, return 1 and write the time
323 * difference between current time and start_time to diff. diff may be
327 static int start_time_in_future(struct timeval *diff)
331 if (!conf.start_time_given)
333 gettimeofday(&now, NULL);
334 return tv_diff(start_time, &now, diff) > 0? 1 : 0;
339 * sleep until time given at command line
341 * This is called if the initial buffer is filled. It returns
342 * immediately if no start_time was given at the command line
343 * or if the given start time is in the past.
346 static void do_initial_delay(struct timeval *delay)
349 para_select(1, NULL, NULL, delay);
350 while (start_time_in_future(delay));
354 static int read_stdin(char *buf, size_t bytes_to_load, size_t *loaded)
358 while (*loaded < bytes_to_load) {
359 ret = read(STDIN_FILENO, buf + *loaded, bytes_to_load - *loaded);
372 const char *writer_names[] ={WRITER_NAMES};
373 static struct writer writers[NUM_SUPPORTED_WRITERS] = {WRITER_ARRAY};
375 int wng_write(struct writer_node_group *g, char *buf, size_t *loaded)
377 int ret, i, need_more_writes = 1;
378 size_t min_written = 0;
380 while (need_more_writes) {
381 need_more_writes = 0;
382 FOR_EACH_WRITER_NODE(i, g) {
383 size_t w = g->written[i];
384 unsigned char *p = buf + w;
386 struct writer_node *wn = &g->writer_nodes[i];
390 min_written = PARA_MIN(min_written, w);
393 if (!g->eof && (*loaded < wn->chunk_bytes + w))
395 bytes_to_write = PARA_MIN(wn->chunk_bytes,
397 ret = wn->writer->write(p, bytes_to_write, wn);
400 if (ret != bytes_to_write)
401 PARA_WARNING_LOG("short write: %d/%d\n", ret,
403 g->written[i] += ret;
404 need_more_writes = 1;
407 *loaded -= min_written;
412 memmove(buf, buf + min_written, *loaded);
413 FOR_EACH_WRITER_NODE(i, g)
414 g->written[i] -= min_written;
421 int wng_open(struct writer_node_group *g)
425 FOR_EACH_WRITER_NODE(i, g) {
426 struct writer_node *wn = &g->writer_nodes[i];
427 ret = wn->writer->open(wn);
430 wn->chunk_bytes = ret;
431 g->max_chunk_bytes = PARA_MAX(g->max_chunk_bytes, ret);
438 void wng_close(struct writer_node_group *g)
442 FOR_EACH_WRITER_NODE(i, g) {
443 struct writer_node *wn = &g->writer_nodes[i];
444 wn->writer->close(wn);
451 * \param loaded number of bytes already loaded
453 * If start_time was given, prebuffer data until buffer is full or
454 * start_time is reached. In any case, do not start playing before
457 * \return positive on success, negative on errors.
459 static int pcm_write(struct writer_node_group *wng, size_t loaded)
461 size_t bufsize, prebuf_size, bytes_to_load;
462 struct timeval delay;
463 int ret, not_yet_started = 1;
468 PARA_INFO_LOG("max chunk_bytes: %d\n", wng->max_chunk_bytes);
469 bufsize = (conf.bufsize_arg * 1024 / wng->max_chunk_bytes)
470 * wng->max_chunk_bytes;
471 audiobuf = para_realloc(audiobuf, bufsize);
472 prebuf_size = conf.prebuffer_arg * bufsize / 100;
473 bytes_to_load = PARA_MAX(prebuf_size, wng->max_chunk_bytes);
474 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
475 if (ret <= 0 || loaded < bytes_to_load) {
477 ret = -E_PREMATURE_END;
480 if (not_yet_started && start_time && start_time_in_future(&delay))
481 do_initial_delay(&delay);
484 ret = wng_write(wng, audiobuf, &loaded);
487 ret = -E_PLAY_OVERRUN;
488 if (loaded >= bufsize)
490 bytes_to_load = PARA_MIN(wng->max_chunk_bytes, bufsize);
491 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
503 struct writer_node_group *wng_new(unsigned num_writers)
505 struct writer_node_group *g = para_calloc(sizeof(struct writer_node_group));
506 g->num_writers = num_writers;
507 g->writer_nodes = para_calloc(num_writers
508 * sizeof(struct writer_node));
509 g->written = para_calloc(num_writers * sizeof(size_t));
514 void wng_destroy(struct writer_node_group *g)
519 free(g->writer_nodes);
523 void init_supported_writers(void)
528 writers[i].init(&writers[i]);
531 int check_writer_arg(const char *arg)
533 int i, ret = -E_PLAY_SYNTAX;
534 char *a = para_strdup(arg), *p = strchr(a, ':');
539 if (strcmp(writer_names[i], a))
549 struct writer_node_group *setup_default_wng(void)
551 struct writer_node_group *wng = wng_new(1);
552 enum writer_enum default_writer;
554 if (NUM_SUPPORTED_WRITERS == 1)
555 default_writer = FILE_WRITE;
558 wng->writer_nodes[0].writer = &writers[default_writer];
559 PARA_INFO_LOG("using default writer: %s\n",
560 writer_names[default_writer]);
566 struct writer_node_group *check_args(void)
568 int i, ret = -E_PLAY_SYNTAX;
569 static struct timeval tv;
570 struct writer_node_group *wng = NULL;
572 if (conf.list_writers_given) {
575 char *tmp = make_message("%s%s%s",
582 fprintf(stderr, "%s\n", msg);
586 if (conf.prebuffer_arg < 0 || conf.prebuffer_arg > 100)
588 if (conf.start_time_given) {
589 long unsigned sec, usec;
590 if (sscanf(conf.start_time_arg, "%lu:%lu",
597 if (!conf.writer_given) {
598 wng = setup_default_wng();
602 wng = wng_new(conf.writer_given);
603 for (i = 0; i < conf.writer_given; i++) {
604 ret = check_writer_arg(conf.writer_arg[i]);
607 wng->writer_nodes[i].writer = &writers[ret];
618 * test if audio buffer contains a valid wave header
620 * \return If not, return 0, otherwise, store number of channels and sample rate
621 * in struct conf and return WAV_HEADER_LEN.
623 static size_t check_wave(void)
625 unsigned char *a = audiobuf;
626 if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
627 return WAV_HEADER_LEN;
628 conf.channels_arg = (unsigned) a[22];
629 conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
634 int main(int argc, char *argv[])
636 int ret = -E_PLAY_SYNTAX;
637 struct writer_node_group *wng = NULL;
639 cmdline_parser(argc, argv, &conf);
643 init_supported_writers();
644 audiobuf = para_malloc(WAV_HEADER_LEN);
645 ret = read_wav_header();
648 ret = pcm_write(wng, check_wave());
653 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));