f312626cf5917e63c45af3b2258561d0f65c9318
[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         int chunk_bytes;
45 };
46
47 struct 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 *);
52 };
53
54 struct writer_node_group {
55         unsigned num_writers;
56         struct writer_node *writer_nodes;
57         int *written;
58         size_t max_chunk_bytes;
59         int eof;
60 };
61
62
63 #define FOR_EACH_WRITER_NODE(i, wng) for (i = 0; i < (wng)->num_writers; i++)
64
65 #define NUM_WRITERS 1
66 static struct writer writers[NUM_WRITERS];
67 #define FOR_EACH_WRITER(i) for (i = 0; i < NUM_WRITERS, i++)
68
69
70 static unsigned char *audiobuf;
71 static struct timeval *start_time;
72 static struct gengetopt_args_info conf;
73
74 INIT_PLAY_ERRLISTS;
75
76 void para_log(int ll, const char* fmt,...)
77 {
78         va_list argp;
79
80         if (ll < conf.loglevel_arg)
81                 return;
82         va_start(argp, fmt);
83         vfprintf(stderr, fmt, argp);
84         va_end(argp);
85 }
86
87 /**
88  * read WAV_HEADER_LEN bytes from stdin to audio buffer
89  *
90  * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
91  * read. A positive return value indicates success.
92  */
93 static int read_wav_header(void)
94 {
95         ssize_t ret, count = 0;
96
97         while (count < WAV_HEADER_LEN) {
98                 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
99                 if (ret <= 0)
100                         return -E_READ_HDR;
101                 count += ret;
102         }
103         return 1;
104 }
105
106 /*
107  * open and prepare the PCM handle for writing
108  *
109  * Install PCM software and hardware configuration. Exit on errors.
110  */
111 static int alsa_open(struct writer_node *w)
112 {
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,
116                 stop_threshold;
117         unsigned buffer_time = 0;
118         int err;
119         snd_pcm_info_t *info;
120         snd_output_t *log;
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;
124
125         snd_pcm_info_alloca(&info);
126         if (snd_output_stdio_attach(&log, stderr, 0) < 0)
127                 return -E_ALSA_LOG;
128         err = snd_pcm_open(&pad->handle, conf.device_arg,
129                 SND_PCM_STREAM_PLAYBACK, 0);
130         if (err < 0)
131                 return -E_PCM_OPEN;
132         if ((err = snd_pcm_info(pad->handle, info)) < 0)
133                 return -E_SND_PCM_INFO;
134
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)
149                 return -E_SET_RATE;
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)
158                 return -E_HW_PARAMS;
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,
162                 period_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)
168                 return -E_GET_XFER;
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)
173                 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,
179                         stop_threshold) < 0)
180                 return -E_STOP_THRESHOLD;
181         if (snd_pcm_sw_params_set_xfer_align(pad->handle, swparams,
182                         xfer_align) < 0)
183                 return -E_SET_XFER;
184         if (snd_pcm_sw_params(pad->handle, swparams) < 0)
185                 return -E_SW_PARAMS;
186         pad->bytes_per_frame = snd_pcm_format_physical_width(FORMAT)
187                 * conf.channels_arg / 8;
188         return period_size * pad->bytes_per_frame;
189 }
190
191 /**
192  * push out pcm frames
193  * \param data pointer do data to be written
194  * \param nbytes number of bytes (not frames)
195  *
196  * \return Number of bytes written, -E_ALSA_WRITE on errors.
197  */
198 static int alsa_write(char *data, size_t nbytes, struct writer_node *wn)
199 {
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;
204
205         while (frames > 0) {
206                 /* write interleaved frames */
207                 r = snd_pcm_writei(pad->handle, d, frames);
208                 if (r < 0)
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);
214                 else if (r < 0)
215                         return -E_ALSA_WRITE;
216                 if (r > 0) {
217                         result += r;
218                         frames -= r;
219                         d += r * pad->bytes_per_frame;
220                 }
221         }
222         return result * pad->bytes_per_frame;
223 }
224
225 static void alsa_close(struct writer_node *wn)
226 {
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();
231         free(pad);
232 }
233
234 void alsa_writer_init(struct writer *w)
235 {
236         w->open = alsa_open;
237         w->write = alsa_write;
238         w->close = alsa_close;
239         w->shutdown = NULL; /* nothing to do */
240 }
241
242
243 /**
244  * check if current time is later than start_time
245  * \param diff pointer to write remaining time to
246  *
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
250  * NULL.
251  *
252  */
253 static int start_time_in_future(struct timeval *diff)
254 {
255         struct timeval now;
256
257         if (!conf.start_time_given)
258                 return 0;
259         gettimeofday(&now, NULL);
260         return tv_diff(start_time, &now, diff) > 0? 1 : 0;
261 }
262
263 /**
264  * sleep until time given at command line
265  *
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.
269  *
270  */
271 static void do_initial_delay(struct timeval *delay)
272 {
273         do
274                 para_select(1, NULL, NULL, delay);
275         while (start_time_in_future(delay));
276 }
277
278 static int read_stdin(char *buf, size_t bytes_to_load, size_t *loaded)
279 {
280         ssize_t ret;
281
282         while (*loaded < bytes_to_load) {
283                 ret = read(STDIN_FILENO, buf + *loaded, bytes_to_load - *loaded);
284                 if (ret <= 0) {
285                         if (ret < 0)
286                                 ret = -E_READ_STDIN;
287                         return ret;
288                 }
289                 *loaded += ret;
290         }
291         return 1;
292 }
293
294 int wng_write(struct writer_node_group *g, char *buf, size_t *loaded)
295 {
296         int ret, i, need_more_writes = 1;
297         size_t min_written = 0;
298
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;
304                         int bytes_to_write;
305                         struct writer_node *wn = &g->writer_nodes[i];
306                         if (!i)
307                                 min_written = w;
308                         else
309                                 min_written = PARA_MIN(min_written, w);
310                         if (w == *loaded)
311                                 continue;
312                         if (!g->eof && (*loaded < wn->chunk_bytes + w))
313                                 continue;
314                         bytes_to_write = PARA_MIN(wn->chunk_bytes,
315                                 *loaded - w);
316                         ret = wn->writer->write(p, bytes_to_write, wn);
317                         if (ret < 0)
318                                 goto out;
319                         if (ret != bytes_to_write)
320                                 PARA_WARNING_LOG("short write: %d/%d\n", ret,
321                                         bytes_to_write);
322                         g->written[i] += ret;
323                         need_more_writes = 1;
324                 }
325         }
326         *loaded -= min_written;
327         ret = 0;
328         if (g->eof)
329                 goto out;
330         if (*loaded)
331                 memmove(buf, buf + min_written, *loaded);
332         FOR_EACH_WRITER_NODE(i, g)
333                 g->written[i] -= min_written;
334         ret = 1;
335 out:
336         return ret;
337 }
338
339 int wng_open(struct writer_node_group *g)
340 {
341         int i, ret = 1;
342
343         FOR_EACH_WRITER_NODE(i, g) {
344                 struct writer_node *wn = &g->writer_nodes[i];
345                 ret = wn->writer->open(wn);
346                 if (ret < 0)
347                         goto out;
348                 wn->chunk_bytes = ret;
349                 g->max_chunk_bytes = PARA_MAX(g->max_chunk_bytes, ret);
350         }
351 out:
352         return ret;
353 }
354
355 void wng_close(struct writer_node_group *g)
356 {
357         int i;
358
359         FOR_EACH_WRITER_NODE(i, g) {
360                 struct writer_node *wn = &g->writer_nodes[i];
361                 wn->writer->close(wn);
362         }
363 }
364
365 /**
366  * play raw pcm data
367  * \param loaded number of bytes already loaded
368  *
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
371  * start_time.
372  *
373  * \return positive on success, negative on errors.
374  */
375 static int pcm_write(struct writer_node_group *wng, size_t loaded)
376 {
377         size_t bufsize, prebuf_size, bytes_to_load;
378         struct timeval delay;
379         int ret, not_yet_started = 1;
380
381         ret = wng_open(wng);
382         if (ret < 0)
383                 goto out;
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) {
392                 if (ret >= 0)
393                         ret = -E_PREMATURE_END;
394                 goto out;
395         }
396         if (not_yet_started && start_time && start_time_in_future(&delay))
397                 do_initial_delay(&delay);
398         not_yet_started = 0;
399 again:
400         ret = wng_write(wng, audiobuf, &loaded);
401         if (ret <= 0)
402                 goto out;
403         ret = -E_PLAY_OVERRUN;
404         if (loaded >= bufsize)
405                 goto out;
406         bytes_to_load = PARA_MIN(wng->max_chunk_bytes, bufsize);
407         ret = read_stdin(audiobuf, bytes_to_load, &loaded);
408         if (ret < 0)
409                 goto out;
410         if (!ret)
411                 wng->eof = 1;
412         goto again;
413 out:
414         wng_close(wng);
415         return ret;
416 }
417
418 struct writer_node_group *wng_new(unsigned num_writers)
419 {
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));
425         return g;
426 }
427
428 void wng_destroy(struct writer_node_group *g)
429 {
430         if (!g)
431                 return;
432         free(g->written);
433         free(g->writer_nodes);
434         free(g);
435 }
436
437 /**
438  * test if audio buffer contains a valid wave header
439  *
440  * \return If not, return 0, otherwise, store number of channels and sample rate
441  * in struct conf and return WAV_HEADER_LEN.
442  */
443 static size_t check_wave(void)
444 {
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);
450         return 0;
451 }
452
453 int main(int argc, char *argv[])
454 {
455         struct timeval tv;
456         int ret = -E_PLAY_SYNTAX;
457         struct writer_node_group *wng = NULL;
458
459         cmdline_parser(argc, argv, &conf);
460         if (conf.prebuffer_arg < 0 || conf.prebuffer_arg > 100)
461                 goto out;
462         if (conf.start_time_given) {
463                 if (sscanf(conf.start_time_arg, "%lu:%lu",
464                                 &tv.tv_sec, &tv.tv_usec) != 2)
465                         goto out;
466                 start_time = &tv;
467         }
468         /* call init for each supported writer */
469         alsa_writer_init(&writers[0]);
470
471         wng = wng_new(1);
472         wng->writer_nodes[0].writer = &writers[0]; /* alsa */
473
474         audiobuf = para_malloc(WAV_HEADER_LEN);
475         ret = read_wav_header();
476         if (ret < 0)
477                 goto out;
478         ret = pcm_write(wng, check_wave());
479 out:
480         wng_destroy(wng);
481         free(audiobuf);
482         if (ret < 0)
483                 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
484         return ret;
485 }