add new writer to para_play: file
[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 /*
35 files:
36 ~~~~~~
37 write.c
38 write.h wr
39 write_common.c
40 write_common.h: decratation of the wng funcs
41 alsa_writer.c
42 */
43
44 /* write.h */
45 enum writer_enum {WRITER_ENUM};
46
47 /* write.h */
48 struct writer_node {
49 struct writer *writer;
50 void *private_data;
51 int chunk_bytes;
52 };
53
54 /* write.h */
55 struct writer {
56 void (*init)(struct writer *w);
57 int (*open)(struct writer_node *);
58 int (*write)(char *data, size_t nbytes, struct writer_node *);
59 void (*close)(struct writer_node *);
60 void (*shutdown)(struct writer_node *);
61 };
62
63 /* write.h */
64 struct writer_node_group {
65 unsigned num_writers;
66 struct writer_node *writer_nodes;
67 int *written;
68 size_t max_chunk_bytes;
69 int eof;
70 };
71
72 /* write.h */
73 #define FOR_EACH_WRITER_NODE(i, wng) for (i = 0; i < (wng)->num_writers; i++)
74 #define FOR_EACH_WRITER(i) for (i = 0; i < NUM_SUPPORTED_WRITERS; i++)
75
76 DECLARE_WRITER_INITS;
77
78
79 /* write.c */
80 static unsigned char *audiobuf;
81 static struct timeval *start_time;
82 static struct gengetopt_args_info conf;
83
84 /* write.c */
85 INIT_PLAY_ERRLISTS;
86
87 /* write.c */
88 void para_log(int ll, const char* fmt,...)
89 {
90 va_list argp;
91
92 if (ll < conf.loglevel_arg)
93 return;
94 va_start(argp, fmt);
95 vfprintf(stderr, fmt, argp);
96 va_end(argp);
97 }
98
99 /* write.c */
100 /**
101 * read WAV_HEADER_LEN bytes from stdin to audio buffer
102 *
103 * \return -E_READ_HDR on errors and on eof before WAV_HEADER_LEN could be
104 * read. A positive return value indicates success.
105 */
106 static int read_wav_header(void)
107 {
108 ssize_t ret, count = 0;
109
110 while (count < WAV_HEADER_LEN) {
111 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
112 if (ret <= 0)
113 return -E_READ_HDR;
114 count += ret;
115 }
116 return 1;
117 }
118
119 /* alsa_writer.c */
120 #define FORMAT SND_PCM_FORMAT_S16_LE
121 struct private_alsa_data {
122 snd_pcm_t *handle;
123 size_t bytes_per_frame;
124 };
125
126 /*
127 * open and prepare the PCM handle for writing
128 *
129 * Install PCM software and hardware configuration. Exit on errors.
130 */
131 static int alsa_open(struct writer_node *w)
132 {
133 snd_pcm_hw_params_t *hwparams;
134 snd_pcm_sw_params_t *swparams;
135 snd_pcm_uframes_t buffer_size, xfer_align, start_threshold,
136 stop_threshold;
137 unsigned buffer_time = 0;
138 int err;
139 snd_pcm_info_t *info;
140 snd_output_t *log;
141 snd_pcm_uframes_t period_size;
142 struct private_alsa_data *pad = para_malloc(sizeof(struct private_alsa_data));
143 w->private_data = pad;
144
145 snd_pcm_info_alloca(&info);
146 if (snd_output_stdio_attach(&log, stderr, 0) < 0)
147 return -E_ALSA_LOG;
148 err = snd_pcm_open(&pad->handle, conf.device_arg,
149 SND_PCM_STREAM_PLAYBACK, 0);
150 if (err < 0)
151 return -E_PCM_OPEN;
152 if ((err = snd_pcm_info(pad->handle, info)) < 0)
153 return -E_SND_PCM_INFO;
154
155 snd_pcm_hw_params_alloca(&hwparams);
156 snd_pcm_sw_params_alloca(&swparams);
157 if (snd_pcm_hw_params_any(pad->handle, hwparams) < 0)
158 return -E_BROKEN_CONF;
159 if (snd_pcm_hw_params_set_access(pad->handle, hwparams,
160 SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
161 return -E_ACCESS_TYPE;
162 if (snd_pcm_hw_params_set_format(pad->handle, hwparams, FORMAT) < 0)
163 return -E_SAMPLE_FORMAT;
164 if (snd_pcm_hw_params_set_channels(pad->handle, hwparams,
165 conf.channels_arg) < 0)
166 return -E_CHANNEL_COUNT;
167 if (snd_pcm_hw_params_set_rate_near(pad->handle, hwparams,
168 (unsigned int*) &conf.sample_rate_arg, 0) < 0)
169 return -E_SET_RATE;
170 err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
171 if (err < 0 || !buffer_time)
172 return -E_GET_BUFFER_TIME;
173 PARA_DEBUG_LOG("buffer time: %d\n", buffer_time);
174 if (snd_pcm_hw_params_set_buffer_time_near(pad->handle, hwparams,
175 &buffer_time, 0) < 0)
176 return -E_SET_BUFFER_TIME;
177 if (snd_pcm_hw_params(pad->handle, hwparams) < 0)
178 return -E_HW_PARAMS;
179 snd_pcm_hw_params_get_period_size(hwparams, &period_size, 0);
180 snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
181 PARA_DEBUG_LOG("buffer size: %lu, period_size: %lu\n", buffer_size,
182 period_size);
183 if (period_size == buffer_size)
184 return -E_BAD_PERIOD;
185 snd_pcm_sw_params_current(pad->handle, swparams);
186 err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
187 if (err < 0 || !xfer_align)
188 return -E_GET_XFER;
189 snd_pcm_sw_params_set_avail_min(pad->handle, swparams, period_size);
190 /* round to closest transfer boundary */
191 start_threshold = (buffer_size / xfer_align) * xfer_align;
192 if (start_threshold < 1)
193 start_threshold = 1;
194 if (snd_pcm_sw_params_set_start_threshold(pad->handle, swparams,
195 start_threshold) < 0)
196 return -E_START_THRESHOLD;
197 stop_threshold = buffer_size;
198 if (snd_pcm_sw_params_set_stop_threshold(pad->handle, swparams,
199 stop_threshold) < 0)
200 return -E_STOP_THRESHOLD;
201 if (snd_pcm_sw_params_set_xfer_align(pad->handle, swparams,
202 xfer_align) < 0)
203 return -E_SET_XFER;
204 if (snd_pcm_sw_params(pad->handle, swparams) < 0)
205 return -E_SW_PARAMS;
206 pad->bytes_per_frame = snd_pcm_format_physical_width(FORMAT)
207 * conf.channels_arg / 8;
208 return period_size * pad->bytes_per_frame;
209 }
210
211 /* alsa_writer.c */
212 /**
213 * push out pcm frames
214 * \param data pointer do data to be written
215 * \param nbytes number of bytes (not frames)
216 *
217 * \return Number of bytes written, -E_ALSA_WRITE on errors.
218 */
219 static int alsa_write(char *data, size_t nbytes, struct writer_node *wn)
220 {
221 struct private_alsa_data *pad = wn->private_data;
222 size_t frames = nbytes / pad->bytes_per_frame;
223 unsigned char *d = data;
224 snd_pcm_sframes_t r, result = 0;
225
226 while (frames > 0) {
227 /* write interleaved frames */
228 r = snd_pcm_writei(pad->handle, d, frames);
229 if (r < 0)
230 PARA_ERROR_LOG("write error: %s\n", snd_strerror(r));
231 if (r == -EAGAIN || (r >= 0 && r < frames))
232 snd_pcm_wait(pad->handle, 1);
233 else if (r == -EPIPE)
234 snd_pcm_prepare(pad->handle);
235 else if (r < 0)
236 return -E_ALSA_WRITE;
237 if (r > 0) {
238 result += r;
239 frames -= r;
240 d += r * pad->bytes_per_frame;
241 }
242 }
243 return result * pad->bytes_per_frame;
244 }
245
246 /* alsa_writer.c */
247 static void alsa_close(struct writer_node *wn)
248 {
249 struct private_alsa_data *pad = wn->private_data;
250 snd_pcm_drain(pad->handle);
251 snd_pcm_close(pad->handle);
252 snd_config_update_free_global();
253 free(pad);
254 }
255
256 /* alsa_writer.c */
257 void alsa_writer_init(struct writer *w)
258 {
259 w->open = alsa_open;
260 w->write = alsa_write;
261 w->close = alsa_close;
262 w->shutdown = NULL; /* nothing to do */
263 }
264
265
266
267
268 /* file_writer.c */
269
270 struct private_file_writer_data {
271 int fd;
272 };
273 static int file_writer_open(struct writer_node *w)
274 {
275 struct private_file_writer_data *pfwd = para_calloc(
276 sizeof(struct private_file_writer_data));
277 char *tmp = para_tmpname(), *home = para_homedir(),
278 *filename = make_message("%s/.paraslash/%s", home, tmp);
279
280 free(home);
281 free(tmp);
282 w->private_data = pfwd;
283 pfwd->fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
284 free(filename);
285 if (pfwd->fd >= 0)
286 return 8192;
287 free(pfwd);
288 return -E_FW_OPEN;
289 }
290
291 static int file_writer_write(char *data, size_t nbytes, struct writer_node *wn)
292 {
293 struct private_file_writer_data *pfwd = wn->private_data;
294 int ret = write(pfwd->fd, data, nbytes);
295 if (ret < 0)
296 ret = -E_FW_WRITE;
297 return ret;
298 }
299
300 static void file_writer_close(struct writer_node *wn)
301 {
302 struct private_file_writer_data *pfwd = wn->private_data;
303 close(pfwd->fd);
304 free(pfwd);
305 }
306
307 void file_writer_init(struct writer *w)
308 {
309 w->open = file_writer_open;
310 w->write = file_writer_write;
311 w->close = file_writer_close;
312 w->shutdown = NULL; /* nothing to do */
313 }
314
315
316 /* write.c */
317 /**
318 * check if current time is later than start_time
319 * \param diff pointer to write remaining time to
320 *
321 * If start_time was not given, or current time is later than given
322 * start_time, return 0. Otherwise, return 1 and write the time
323 * difference between current time and start_time to diff. diff may be
324 * NULL.
325 *
326 */
327 static int start_time_in_future(struct timeval *diff)
328 {
329 struct timeval now;
330
331 if (!conf.start_time_given)
332 return 0;
333 gettimeofday(&now, NULL);
334 return tv_diff(start_time, &now, diff) > 0? 1 : 0;
335 }
336
337 /* write.c */
338 /**
339 * sleep until time given at command line
340 *
341 * This is called if the initial buffer is filled. It returns
342 * immediately if no start_time was given at the command line
343 * or if the given start time is in the past.
344 *
345 */
346 static void do_initial_delay(struct timeval *delay)
347 {
348 do
349 para_select(1, NULL, NULL, delay);
350 while (start_time_in_future(delay));
351 }
352
353 /* write.c */
354 static int read_stdin(char *buf, size_t bytes_to_load, size_t *loaded)
355 {
356 ssize_t ret;
357
358 while (*loaded < bytes_to_load) {
359 ret = read(STDIN_FILENO, buf + *loaded, bytes_to_load - *loaded);
360 if (ret <= 0) {
361 if (ret < 0)
362 ret = -E_READ_STDIN;
363 return ret;
364 }
365 *loaded += ret;
366 }
367 return 1;
368 }
369
370 /* write_common.c */
371
372 const char *writer_names[] ={WRITER_NAMES};
373 static struct writer writers[NUM_SUPPORTED_WRITERS] = {WRITER_ARRAY};
374
375 int wng_write(struct writer_node_group *g, char *buf, size_t *loaded)
376 {
377 int ret, i, need_more_writes = 1;
378 size_t min_written = 0;
379
380 while (need_more_writes) {
381 need_more_writes = 0;
382 FOR_EACH_WRITER_NODE(i, g) {
383 size_t w = g->written[i];
384 unsigned char *p = buf + w;
385 int bytes_to_write;
386 struct writer_node *wn = &g->writer_nodes[i];
387 if (!i)
388 min_written = w;
389 else
390 min_written = PARA_MIN(min_written, w);
391 if (w == *loaded)
392 continue;
393 if (!g->eof && (*loaded < wn->chunk_bytes + w))
394 continue;
395 bytes_to_write = PARA_MIN(wn->chunk_bytes,
396 *loaded - w);
397 ret = wn->writer->write(p, bytes_to_write, wn);
398 if (ret < 0)
399 goto out;
400 if (ret != bytes_to_write)
401 PARA_WARNING_LOG("short write: %d/%d\n", ret,
402 bytes_to_write);
403 g->written[i] += ret;
404 need_more_writes = 1;
405 }
406 }
407 *loaded -= min_written;
408 ret = 0;
409 if (g->eof)
410 goto out;
411 if (*loaded)
412 memmove(buf, buf + min_written, *loaded);
413 FOR_EACH_WRITER_NODE(i, g)
414 g->written[i] -= min_written;
415 ret = 1;
416 out:
417 return ret;
418 }
419
420 /* write_common.c */
421 int wng_open(struct writer_node_group *g)
422 {
423 int i, ret = 1;
424
425 FOR_EACH_WRITER_NODE(i, g) {
426 struct writer_node *wn = &g->writer_nodes[i];
427 ret = wn->writer->open(wn);
428 if (ret < 0)
429 goto out;
430 wn->chunk_bytes = ret;
431 g->max_chunk_bytes = PARA_MAX(g->max_chunk_bytes, ret);
432 }
433 out:
434 return ret;
435 }
436
437 /* write_common.c */
438 void wng_close(struct writer_node_group *g)
439 {
440 int i;
441
442 FOR_EACH_WRITER_NODE(i, g) {
443 struct writer_node *wn = &g->writer_nodes[i];
444 wn->writer->close(wn);
445 }
446 }
447
448 /* write.c */
449 /**
450 * play raw pcm data
451 * \param loaded number of bytes already loaded
452 *
453 * If start_time was given, prebuffer data until buffer is full or
454 * start_time is reached. In any case, do not start playing before
455 * start_time.
456 *
457 * \return positive on success, negative on errors.
458 */
459 static int pcm_write(struct writer_node_group *wng, size_t loaded)
460 {
461 size_t bufsize, prebuf_size, bytes_to_load;
462 struct timeval delay;
463 int ret, not_yet_started = 1;
464
465 ret = wng_open(wng);
466 if (ret < 0)
467 goto out;
468 PARA_INFO_LOG("max chunk_bytes: %d\n", wng->max_chunk_bytes);
469 bufsize = (conf.bufsize_arg * 1024 / wng->max_chunk_bytes)
470 * wng->max_chunk_bytes;
471 audiobuf = para_realloc(audiobuf, bufsize);
472 prebuf_size = conf.prebuffer_arg * bufsize / 100;
473 bytes_to_load = PARA_MAX(prebuf_size, wng->max_chunk_bytes);
474 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
475 if (ret <= 0 || loaded < bytes_to_load) {
476 if (ret >= 0)
477 ret = -E_PREMATURE_END;
478 goto out;
479 }
480 if (not_yet_started && start_time && start_time_in_future(&delay))
481 do_initial_delay(&delay);
482 not_yet_started = 0;
483 again:
484 ret = wng_write(wng, audiobuf, &loaded);
485 if (ret <= 0)
486 goto out;
487 ret = -E_PLAY_OVERRUN;
488 if (loaded >= bufsize)
489 goto out;
490 bytes_to_load = PARA_MIN(wng->max_chunk_bytes, bufsize);
491 ret = read_stdin(audiobuf, bytes_to_load, &loaded);
492 if (ret < 0)
493 goto out;
494 if (!ret)
495 wng->eof = 1;
496 goto again;
497 out:
498 wng_close(wng);
499 return ret;
500 }
501
502 /* writer_node.c */
503 struct writer_node_group *wng_new(unsigned num_writers)
504 {
505 struct writer_node_group *g = para_calloc(sizeof(struct writer_node_group));
506 g->num_writers = num_writers;
507 g->writer_nodes = para_calloc(num_writers
508 * sizeof(struct writer_node));
509 g->written = para_calloc(num_writers * sizeof(size_t));
510 return g;
511 }
512
513 /* writer_node.c */
514 void wng_destroy(struct writer_node_group *g)
515 {
516 if (!g)
517 return;
518 free(g->written);
519 free(g->writer_nodes);
520 free(g);
521 }
522
523 void init_supported_writers(void)
524 {
525 int i;
526
527 FOR_EACH_WRITER(i)
528 writers[i].init(&writers[i]);
529 }
530
531 int check_writer_arg(const char *arg)
532 {
533 int i, ret = -E_PLAY_SYNTAX;
534 char *a = para_strdup(arg), *p = strchr(a, ':');
535 if (p)
536 *p = '\0';
537 p++;
538 FOR_EACH_WRITER(i) {
539 if (strcmp(writer_names[i], a))
540 continue;
541 ret = i;
542 goto out;
543 }
544 out:
545 free(a);
546 return ret;
547 }
548
549 struct writer_node_group *setup_default_wng(void)
550 {
551 struct writer_node_group *wng = wng_new(1);
552 enum writer_enum default_writer;
553
554 if (NUM_SUPPORTED_WRITERS == 1)
555 default_writer = FILE_WRITE;
556 else
557 default_writer = 1;
558 wng->writer_nodes[0].writer = &writers[default_writer];
559 PARA_INFO_LOG("using default writer: %s\n",
560 writer_names[default_writer]);
561 return wng;
562 }
563
564 /* write.c */
565
566 struct writer_node_group *check_args(void)
567 {
568 int i, ret = -E_PLAY_SYNTAX;
569 static struct timeval tv;
570 struct writer_node_group *wng = NULL;
571
572 if (conf.list_writers_given) {
573 char *msg = NULL;
574 FOR_EACH_WRITER(i) {
575 char *tmp = make_message("%s%s%s",
576 i? msg : "",
577 i? " " : "",
578 writer_names[i]);
579 free(msg);
580 msg = tmp;
581 }
582 fprintf(stderr, "%s\n", msg);
583 free(msg);
584 exit(EXIT_SUCCESS);
585 }
586 if (conf.prebuffer_arg < 0 || conf.prebuffer_arg > 100)
587 goto out;
588 if (conf.start_time_given) {
589 long unsigned sec, usec;
590 if (sscanf(conf.start_time_arg, "%lu:%lu",
591 &sec, &usec) != 2)
592 goto out;
593 tv.tv_sec = sec;
594 tv.tv_usec = usec;
595 start_time = &tv;
596 }
597 if (!conf.writer_given) {
598 wng = setup_default_wng();
599 ret = 1;
600 goto out;
601 }
602 wng = wng_new(conf.writer_given);
603 for (i = 0; i < conf.writer_given; i++) {
604 ret = check_writer_arg(conf.writer_arg[i]);
605 if (ret < 0)
606 goto out;
607 wng->writer_nodes[i].writer = &writers[ret];
608 }
609 ret = 1;
610 out:
611 if (ret > 0)
612 return wng;
613 free(wng);
614 return NULL;
615 }
616
617 /**
618 * test if audio buffer contains a valid wave header
619 *
620 * \return If not, return 0, otherwise, store number of channels and sample rate
621 * in struct conf and return WAV_HEADER_LEN.
622 */
623 static size_t check_wave(void)
624 {
625 unsigned char *a = audiobuf;
626 if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
627 return WAV_HEADER_LEN;
628 conf.channels_arg = (unsigned) a[22];
629 conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
630 return 0;
631 }
632
633 /* write.c */
634 int main(int argc, char *argv[])
635 {
636 int ret = -E_PLAY_SYNTAX;
637 struct writer_node_group *wng = NULL;
638
639 cmdline_parser(argc, argv, &conf);
640 wng = check_args();
641 if (!wng)
642 goto out;
643 init_supported_writers();
644 audiobuf = para_malloc(WAV_HEADER_LEN);
645 ret = read_wav_header();
646 if (ret < 0)
647 goto out;
648 ret = pcm_write(wng, check_wave());
649 out:
650 wng_destroy(wng);
651 free(audiobuf);
652 if (ret < 0)
653 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
654 return ret;
655 }