]> git.tuebingen.mpg.de Git - paraslash.git/blob - play.c
play.c: Let alsa_init() return the number of bytes per chunk
[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
32 enum {  E_BROKEN_CONF,          /* Broken configuration for this PCM */
33         E_ACCESS_TYPE,          /* Access type not available */
34         E_SAMPLE_FORMAT,        /* Sample format not available */
35         E_CHANNEL_COUNT,        /* Channels count not available */
36         E_HW_PARAMS,            /* Unable to install hw params */
37         E_SW_PARAMS,            /* Unable to install sw params */
38         E_BAD_PERIOD,           /* Can't use period equal to buffer size */
39         E_GET_XFER,             /* Unable to obtain xfer align */
40         E_SET_XFER,             /* snd_pcm_sw_params_set_xfer_align failed */
41         E_MEM,                  /* not enough memory */
42         E_READ,                 /* read error */
43         E_WRITE,                /* write error */
44         E_PIPE,                 /* write to pipe with other side closed */
45         E_PCM_OPEN,             /* unable to open pcm */
46         E_SND_PCM_INFO,         /* pcm info error */
47         E_GET_BUFFER_TIME,      /* snd_pcm_hw_params_get_buffer_time_max failed */
48         E_SET_BUFFER_TIME,      /* snd_pcm_hw_params_set_buffer_time_near failed */
49         E_SET_RATE,             /* snd_pcm_hw_params_set_rate_near failed */
50         E_START_THRESHOLD,      /* snd_pcm_sw_params_set_start_threshold failed */
51         E_STOP_THRESHOLD,       /* snd_pcm_sw_params_set_stop_threshold failed */
52         E_LOG,                  /* snd_output_stdio_attach failed */
53         E_SYNTAX                /* could not parse start_time option */
54 };
55
56 #define FORMAT SND_PCM_FORMAT_S16_LE
57
58 #define EXIT(EXP) \
59 do { if (EXP) \
60         fprintf (stderr, "error: " #EXP "\n"); exit(EXP);} \
61 while (0)
62
63 static snd_pcm_t *handle;
64 static snd_pcm_uframes_t chunk_size;
65 static unsigned char *audiobuf;
66 static size_t bytes_per_frame;
67 static struct timeval *start_time;
68 static struct gengetopt_args_info conf;
69
70 void para_log(__a_unused int ll, const char* fmt,...)
71 {
72         va_list argp;
73
74         va_start(argp, fmt);
75         vfprintf(stderr, fmt, argp);
76         va_end(argp);
77 }
78
79 /*
80  * read_wav_header - read WAV_HEADER_LEN bytes from stdin to audio buffer
81  *
82  * Exit on errors and on eof before WAV_HEADER_LEN could be read.
83  */
84 static void read_wav_header(void)
85 {
86         ssize_t ret, count = 0;
87
88         while (count < WAV_HEADER_LEN) {
89                 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
90                 if (ret <= 0)
91                         EXIT(E_READ);
92                 count += ret;
93         }
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_init(void)
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
112         snd_pcm_info_alloca(&info);
113         if (snd_output_stdio_attach(&log, stderr, 0) < 0)
114                 EXIT(E_LOG);
115         err = snd_pcm_open(&handle, conf.device_arg,
116                 SND_PCM_STREAM_PLAYBACK, 0);
117         if (err < 0)
118                 EXIT(E_PCM_OPEN);
119         if ((err = snd_pcm_info(handle, info)) < 0)
120                 EXIT(E_SND_PCM_INFO);
121
122         snd_pcm_hw_params_alloca(&hwparams);
123         snd_pcm_sw_params_alloca(&swparams);
124         if (snd_pcm_hw_params_any(handle, hwparams) < 0)
125                 EXIT(E_BROKEN_CONF);
126         if (snd_pcm_hw_params_set_access(handle, hwparams,
127                         SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
128                 EXIT(E_ACCESS_TYPE);
129         if (snd_pcm_hw_params_set_format(handle, hwparams, FORMAT) < 0)
130                 EXIT(E_SAMPLE_FORMAT);
131         if (snd_pcm_hw_params_set_channels(handle, hwparams, conf.channels_arg) < 0)
132                 EXIT(E_CHANNEL_COUNT);
133         if (snd_pcm_hw_params_set_rate_near(handle, hwparams,
134                         (unsigned int*) &conf.sample_rate_arg, 0) < 0)
135                 EXIT(E_SET_RATE);
136         err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
137         if (err < 0 || !buffer_time)
138                 EXIT(E_GET_BUFFER_TIME);
139         PARA_DEBUG_LOG("buffer time: %d\n", buffer_time);
140         if (snd_pcm_hw_params_set_buffer_time_near(handle, hwparams,
141                         &buffer_time, 0) < 0)
142                 EXIT(E_SET_BUFFER_TIME);
143         if (snd_pcm_hw_params(handle, hwparams) < 0)
144                 EXIT(E_HW_PARAMS);
145         snd_pcm_hw_params_get_period_size(hwparams, &chunk_size, 0);
146         snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
147         PARA_DEBUG_LOG("buffer size: %lu, period_size: %lu\n", buffer_size, chunk_size);
148         if (chunk_size == buffer_size)
149                 EXIT(E_BAD_PERIOD);
150         snd_pcm_sw_params_current(handle, swparams);
151         err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
152         if (err < 0 || !xfer_align)
153                 EXIT(E_GET_XFER);
154 //      snd_pcm_sw_params_set_sleep_min(handle, swparams, 0);
155         snd_pcm_sw_params_set_avail_min(handle, swparams, chunk_size);
156         /* round to closest transfer boundary */
157         start_threshold = (buffer_size / xfer_align) * xfer_align;
158         if (start_threshold < 1)
159                 start_threshold = 1;
160         if (snd_pcm_sw_params_set_start_threshold(handle, swparams,
161                         start_threshold) < 0)
162                 EXIT(E_START_THRESHOLD);
163         stop_threshold = buffer_size;
164         if (snd_pcm_sw_params_set_stop_threshold(handle, swparams,
165                         stop_threshold) < 0)
166                 EXIT(E_STOP_THRESHOLD);
167         if (snd_pcm_sw_params_set_xfer_align(handle, swparams, xfer_align) < 0)
168                 EXIT(E_SET_XFER);
169         if (snd_pcm_sw_params(handle, swparams) < 0)
170                 EXIT(E_SW_PARAMS);
171         bytes_per_frame = snd_pcm_format_physical_width(FORMAT) * conf.channels_arg / 8;
172         return chunk_size * bytes_per_frame;
173 }
174
175 /**
176  * push out pcm frames
177  * \param data pointer do data to be written
178  * \param nbytes number of bytes (not frames)
179  *
180  * \return Number of bytes written. Exit on errors.
181  */
182 int alsa_write(u_char *data, size_t nbytes)
183 {
184         size_t frames = nbytes / bytes_per_frame;
185         snd_pcm_sframes_t r, result = 0;
186         while (frames > 0) {
187                 /* write interleaved frames */
188                 r = snd_pcm_writei(handle, data, frames);
189                 if (r < 0)
190                         PARA_ERROR_LOG("write error: %s\n", snd_strerror(r));
191                 if (r == -EAGAIN || (r >= 0 && r < frames))
192                         snd_pcm_wait(handle, 1);
193                 else if (r == -EPIPE)
194                         snd_pcm_prepare(handle);
195                 else if (r < 0)
196                         EXIT(E_WRITE);
197                 if (r > 0) {
198                         result += r;
199                         frames -= r;
200                         data += r * bytes_per_frame;
201                 }
202         }
203         return result * bytes_per_frame;
204 }
205
206 void alsa_shutdown(void)
207 {
208         snd_pcm_drain(handle);
209         snd_pcm_close(handle);
210         snd_config_update_free_global();
211 }
212
213 /*
214  * start_time_in_future - check if current time is later than start_time
215  * \param diff pointer to write remaining time to
216  *
217  * If start_time was not given, or current time is later than given
218  * start_time, return 0. Otherwise, return 1 and write the time
219  * difference between current time and start_time to diff. diff may be
220  * NULL.
221  *
222  */
223 static int start_time_in_future(struct timeval *diff)
224 {
225         struct timeval now;
226
227         if (!conf.start_time_given)
228                 return 0;
229         gettimeofday(&now, NULL);
230         return tv_diff(start_time, &now, diff) > 0? 1 : 0;
231 }
232
233 /*
234  * do_initial_delay - sleep until time given at command line
235  *
236  * This is called if the initial buffer is filled. It returns
237  * immediately if no start_time was given at the command line
238  * or if the given start time is in the past.
239  *
240  */
241 static void do_initial_delay(struct timeval *delay)
242 {
243         do
244                 para_select(1, NULL, NULL, delay);
245         while (start_time_in_future(delay));
246 }
247
248 /*
249  * play_pcm - play raw pcm data
250  * \param loaded number of bytes already loaded
251  *
252  * If start_time was given, prebuffer data until buffer is full or
253  * start_time is reached. In any case, do not start playing before
254  * start_time.
255  */
256 static void play_pcm(size_t loaded)
257 {
258         size_t bufsize, written = 0, prebuf_size;
259         ssize_t ret;
260         unsigned char *p;
261         struct timeval delay;
262         int chunk_bytes = alsa_init();
263
264         bufsize = (conf.bufsize_arg * 1024 / chunk_bytes) * chunk_bytes;
265         audiobuf = realloc(audiobuf, bufsize);
266         if (!audiobuf)
267                 EXIT(E_MEM);
268         prebuf_size = conf.prebuffer_arg * bufsize / 100;
269 again:
270         if (!written) {
271                 if (loaded < prebuf_size)
272                         goto read;
273                 if (start_time && start_time_in_future(&delay)) {
274                         do_initial_delay(&delay);
275                         start_time = NULL;
276                 }
277         }
278         p = audiobuf;
279         while (loaded >= chunk_bytes) {
280                 ret = alsa_write(p, chunk_bytes);
281                 p += ret;
282                 written += ret;
283                 loaded -= ret;
284         }
285         if (loaded && p != audiobuf)
286                 memmove(audiobuf, p, loaded);
287 read:
288         ret = read(STDIN_FILENO, audiobuf + loaded, bufsize - loaded);
289         if (ret < 0)
290                 EXIT(E_READ);
291         if (ret) {
292                 loaded += ret;
293                 goto again;
294         }
295         alsa_shutdown();
296 }
297
298 /*
299  * check_wave - test if audio buffer contains a valid wave header
300  *
301  * If not, return 0, otherwise, store number of channels and sample rate
302  * in struct conf and return WAV_HEADER_LEN.
303  */
304 static size_t check_wave(void)
305 {
306         unsigned char *a = audiobuf;
307         if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
308                 return WAV_HEADER_LEN;
309         conf.channels_arg = (unsigned) a[22];
310         conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
311         return 0;
312 }
313
314 int main(int argc, char *argv[])
315 {
316         struct timeval tv;
317
318         cmdline_parser(argc, argv, &conf);
319         if (conf.start_time_given) {
320                 if (sscanf(conf.start_time_arg, "%lu:%lu",
321                                 &tv.tv_sec, &tv.tv_usec) != 2)
322                         EXIT(E_SYNTAX);
323                 start_time = &tv;
324         }
325         audiobuf = malloc(WAV_HEADER_LEN);
326         read_wav_header();
327         play_pcm(check_wave());
328         free(audiobuf);
329         return EXIT_SUCCESS;
330 }