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