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>
34 #define FORMAT SND_PCM_FORMAT_S16_LE
36 struct private_alsa_data {
38 size_t bytes_per_frame;
42 struct writer *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 *);
54 struct writer_node_group {
56 struct writer_node *writer_nodes;
58 size_t max_chunk_bytes;
63 #define FOR_EACH_WRITER_NODE(i, wng) for (i = 0; i < (wng)->num_writers; i++)
66 static struct writer writers[NUM_WRITERS];
67 #define FOR_EACH_WRITER(i) for (i = 0; i < NUM_WRITERS, i++)
70 static unsigned char *audiobuf;
71 static struct timeval *start_time;
72 static struct gengetopt_args_info conf;
76 void para_log(int ll, const char* fmt,...)
80 if (ll < conf.loglevel_arg)
83 vfprintf(stderr, fmt, argp);
88 * read WAV_HEADER_LEN bytes from stdin to audio buffer
90 * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
91 * read. A positive return value indicates success.
93 static int read_wav_header(void)
95 ssize_t ret, count = 0;
97 while (count < WAV_HEADER_LEN) {
98 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
107 * open and prepare the PCM handle for writing
109 * Install PCM software and hardware configuration. Exit on errors.
111 static int alsa_open(struct writer_node *w)
113 snd_pcm_hw_params_t *hwparams;
114 snd_pcm_sw_params_t *swparams;
115 snd_pcm_uframes_t buffer_size, xfer_align, start_threshold,
117 unsigned buffer_time = 0;
119 snd_pcm_info_t *info;
121 snd_pcm_uframes_t period_size;
122 struct private_alsa_data *pad = para_malloc(sizeof(struct private_alsa_data));
123 w->private_data = pad;
125 snd_pcm_info_alloca(&info);
126 if (snd_output_stdio_attach(&log, stderr, 0) < 0)
128 err = snd_pcm_open(&pad->handle, conf.device_arg,
129 SND_PCM_STREAM_PLAYBACK, 0);
132 if ((err = snd_pcm_info(pad->handle, info)) < 0)
133 return -E_SND_PCM_INFO;
135 snd_pcm_hw_params_alloca(&hwparams);
136 snd_pcm_sw_params_alloca(&swparams);
137 if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
138 return -E_BROKEN_CONF;
139 if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
140 SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
141 return -E_ACCESS_TYPE;
142 if (snd_pcm_hw_params_set_format(pad->handle, hwparams, FORMAT) < 0)
143 return -E_SAMPLE_FORMAT;
144 if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
145 conf.channels_arg) < 0)
146 return -E_CHANNEL_COUNT;
147 if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
148 (unsigned int*) &conf.sample_rate_arg, 0) < 0)
150 err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
151 if (err < 0 || !buffer_time)
152 return -E_GET_BUFFER_TIME;
153 PARA_DEBUG_LOG("buffer time: %d\n", buffer_time);
154 if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
155 &buffer_time, 0) < 0)
156 return -E_SET_BUFFER_TIME;
157 if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
159 snd_pcm_hw_params_get_period_size(hwparams, &period_size, 0);
160 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
161 PARA_DEBUG_LOG("buffer size: %lu, period_size: %lu\n", buffer_size,
163 if (period_size == buffer_size)
164 return -E_BAD_PERIOD;
165 snd_pcm_sw_params_current(pad->handle, swparams);
166 err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
167 if (err < 0 || !xfer_align)
169 snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
170 /* round to closest transfer boundary */
171 start_threshold = (buffer_size / xfer_align) * xfer_align;
172 if (start_threshold < 1)
174 if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
175 start_threshold) < 0)
176 return -E_START_THRESHOLD;
177 stop_threshold = buffer_size;
178 if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
180 return -E_STOP_THRESHOLD;
181 if (snd_pcm_sw_params_set_xfer_align(pad->handle, swparams,
184 if (snd_pcm_sw_params(pad->handle, swparams) < 0)
186 pad->bytes_per_frame = snd_pcm_format_physical_width(FORMAT)
187 * conf.channels_arg / 8;
188 return period_size * pad->bytes_per_frame;
192 * push out pcm frames
193 * \param data pointer do data to be written
194 * \param nbytes number of bytes (not frames)
196 * \return Number of bytes written, -E_ALSA_WRITE on errors.
198 static int alsa_write(char *data, size_t nbytes, struct writer_node *wn)
200 struct private_alsa_data *pad = wn->private_data;
201 size_t frames = nbytes / pad->bytes_per_frame;
202 unsigned char *d = data;
203 snd_pcm_sframes_t r, result = 0;
206 /* write interleaved frames */
207 r = snd_pcm_writei(pad->handle, d, frames);
209 PARA_ERROR_LOG("write error: %s\n", snd_strerror(r));
210 if (r == -EAGAIN || (r >= 0 && r < frames))
211 snd_pcm_wait(pad->handle, 1);
212 else if (r == -EPIPE)
213 snd_pcm_prepare(pad->handle);
215 return -E_ALSA_WRITE;
219 d += r * pad->bytes_per_frame;
222 return result * pad->bytes_per_frame;
225 static void alsa_close(struct writer_node *wn)
227 struct private_alsa_data *pad = wn->private_data;
228 snd_pcm_drain(pad->handle);
229 snd_pcm_close(pad->handle);
230 snd_config_update_free_global();
234 void alsa_writer_init(struct writer *w)
237 w->write = alsa_write;
238 w->close = alsa_close;
239 w->shutdown = NULL; /* nothing to do */
244 * check if current time is later than start_time
245 * \param diff pointer to write remaining time to
247 * If start_time was not given, or current time is later than given
248 * start_time, return 0. Otherwise, return 1 and write the time
249 * difference between current time and start_time to diff. diff may be
253 static int start_time_in_future(struct timeval *diff)
257 if (!conf.start_time_given)
259 gettimeofday(&now, NULL);
260 return tv_diff(start_time, &now, diff) > 0? 1 : 0;
264 * sleep until time given at command line
266 * This is called if the initial buffer is filled. It returns
267 * immediately if no start_time was given at the command line
268 * or if the given start time is in the past.
271 static void do_initial_delay(struct timeval *delay)
274 para_select(1, NULL, NULL, delay);
275 while (start_time_in_future(delay));
278 static int read_stdin(char *buf, size_t bytes_to_load, size_t *loaded)
282 while (*loaded < bytes_to_load) {
283 ret = read(STDIN_FILENO, buf + *loaded, bytes_to_load - *loaded);
294 int wng_write(struct writer_node_group *g, char *buf, size_t *loaded)
296 int ret, i, need_more_writes = 1;
297 size_t min_written = 0;
299 while (need_more_writes) {
300 need_more_writes = 0;
301 FOR_EACH_WRITER_NODE(i, g) {
302 size_t w = g->written[i];
303 unsigned char *p = buf + w;
305 struct writer_node *wn = &g->writer_nodes[i];
309 min_written = PARA_MIN(min_written, w);
312 if (!g->eof && (*loaded < wn->chunk_bytes + w))
314 bytes_to_write = PARA_MIN(wn->chunk_bytes,
316 ret = wn->writer->write(p, bytes_to_write, wn);
319 if (ret != bytes_to_write)
320 PARA_WARNING_LOG("short write: %d/%d\n", ret,
322 g->written[i] += ret;
323 need_more_writes = 1;
326 *loaded -= min_written;
331 memmove(buf, buf + min_written, *loaded);
332 FOR_EACH_WRITER_NODE(i, g)
333 g->written[i] -= min_written;
339 int wng_open(struct writer_node_group *g)
343 FOR_EACH_WRITER_NODE(i, g) {
344 struct writer_node *wn = &g->writer_nodes[i];
345 ret = wn->writer->open(wn);
348 wn->chunk_bytes = ret;
349 g->max_chunk_bytes = PARA_MAX(g->max_chunk_bytes, ret);
355 void wng_close(struct writer_node_group *g)
359 FOR_EACH_WRITER_NODE(i, g) {
360 struct writer_node *wn = &g->writer_nodes[i];
361 wn->writer->close(wn);
367 * \param loaded number of bytes already loaded
369 * If start_time was given, prebuffer data until buffer is full or
370 * start_time is reached. In any case, do not start playing before
373 * \return positive on success, negative on errors.
375 static int pcm_write(struct writer_node_group *wng, size_t loaded)
377 size_t bufsize, prebuf_size, bytes_to_load;
378 struct timeval delay;
379 int ret, not_yet_started = 1;
384 PARA_INFO_LOG("max chunk_bytes: %d\n", wng->max_chunk_bytes);
385 bufsize = (conf.bufsize_arg * 1024 / wng->max_chunk_bytes)
386 * wng->max_chunk_bytes;
387 audiobuf = para_realloc(audiobuf, bufsize);
388 prebuf_size = conf.prebuffer_arg * bufsize / 100;
389 bytes_to_load = PARA_MAX(prebuf_size, wng->max_chunk_bytes);
390 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
391 if (ret <= 0 || loaded < bytes_to_load) {
393 ret = -E_PREMATURE_END;
396 if (not_yet_started && start_time && start_time_in_future(&delay))
397 do_initial_delay(&delay);
400 ret = wng_write(wng, audiobuf, &loaded);
403 ret = -E_PLAY_OVERRUN;
404 if (loaded >= bufsize)
406 bytes_to_load = PARA_MIN(wng->max_chunk_bytes, bufsize);
407 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
418 struct writer_node_group *wng_new(unsigned num_writers)
420 struct writer_node_group *g = para_calloc(sizeof(struct writer_node_group));
421 g->num_writers = num_writers;
422 g->writer_nodes = para_calloc(num_writers
423 * sizeof(struct writer_node));
424 g->written = para_calloc(num_writers * sizeof(size_t));
428 void wng_destroy(struct writer_node_group *g)
433 free(g->writer_nodes);
438 * test if audio buffer contains a valid wave header
440 * \return If not, return 0, otherwise, store number of channels and sample rate
441 * in struct conf and return WAV_HEADER_LEN.
443 static size_t check_wave(void)
445 unsigned char *a = audiobuf;
446 if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
447 return WAV_HEADER_LEN;
448 conf.channels_arg = (unsigned) a[22];
449 conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
453 int main(int argc, char *argv[])
456 int ret = -E_PLAY_SYNTAX;
457 struct writer_node_group *wng = NULL;
459 cmdline_parser(argc, argv, &conf);
460 if (conf.prebuffer_arg < 0 || conf.prebuffer_arg > 100)
462 if (conf.start_time_given) {
463 if (sscanf(conf.start_time_arg, "%lu:%lu",
464 &tv.tv_sec, &tv.tv_usec) != 2)
468 /* call init for each supported writer */
469 alsa_writer_init(&writers[0]);
472 wng->writer_nodes[0].writer = &writers[0]; /* alsa */
474 audiobuf = para_malloc(WAV_HEADER_LEN);
475 ret = read_wav_header();
478 ret = pcm_write(wng, check_wave());
483 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));