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