2 * aplay.c - plays and records
4 * CREATIVE LABS CHANNEL-files
6 * SPARC AUDIO .AU-files
9 * Copyright (c) by Jaroslav Kysela <perex@perex.cz>
10 * Based on vplay program by Michael Beck
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
46 #include <alsa/asoundlib.h>
58 #include "os_compat.h"
60 #define ABS(a) (a) < 0 ? -(a) : (a)
62 #ifdef SND_CHMAP_API_VERSION
63 #define CONFIG_SUPPORT_CHMAP 1
67 #define LLONG_MAX 9223372036854775807LL
71 #include <asm/byteorder.h>
72 #define le16toh(x) __le16_to_cpu(x)
73 #define be16toh(x) __be16_to_cpu(x)
74 #define le32toh(x) __le32_to_cpu(x)
75 #define be32toh(x) __be32_to_cpu(x)
78 #define DEFAULT_FORMAT SND_PCM_FORMAT_U8
79 #define DEFAULT_SPEED 8000
81 #define FORMAT_DEFAULT -1
89 static snd_pcm_sframes_t (*readi_func)(snd_pcm_t *handle, void *buffer, snd_pcm_uframes_t size);
90 static snd_pcm_sframes_t (*writei_func)(snd_pcm_t *handle, const void *buffer, snd_pcm_uframes_t size);
91 static snd_pcm_sframes_t (*readn_func)(snd_pcm_t *handle, void **bufs, snd_pcm_uframes_t size);
92 static snd_pcm_sframes_t (*writen_func)(snd_pcm_t *handle, void **bufs, snd_pcm_uframes_t size);
100 static char *command;
101 static snd_pcm_t *handle;
103 snd_pcm_format_t format;
104 snd_pcm_subformat_t subformat;
105 unsigned int channels;
107 } hwparams, rhwparams;
108 static int timelimit = 0;
109 static int sampleslimit = 0;
110 static int quiet_mode = 0;
111 static int file_type = FORMAT_DEFAULT;
112 static int open_mode = 0;
113 static snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
114 static int mmap_flag = 0;
115 static int interleaved = 1;
116 static int nonblock = 0;
117 static volatile sig_atomic_t in_aborting = 0;
118 static uint8_t *audiobuf = NULL;
119 static snd_pcm_uframes_t chunk_size = 0;
120 static unsigned period_time = 0;
121 static unsigned buffer_time = 0;
122 static snd_pcm_uframes_t period_frames = 0;
123 static snd_pcm_uframes_t buffer_frames = 0;
124 static int avail_min = -1;
125 static int start_delay = 0;
126 static int stop_delay = 0;
127 static int monotonic = 0;
128 static int interactive = 0;
129 static int can_pause = 0;
130 static int fatal_errors = 0;
131 static int verbose = 0;
132 static int vumeter = VUMETER_NONE;
133 static int buffer_pos = 0;
134 static size_t significant_bits_per_sample, bits_per_sample, bits_per_frame;
135 static size_t chunk_bytes;
136 static int test_position = 0;
137 static int test_coef = 8;
138 static int test_nowait = 0;
139 static snd_output_t *log;
140 static long long max_file_size = 0;
141 static int max_file_time = 0;
142 static int use_strftime = 0;
143 static volatile int recycle_capture_file = 0;
144 static long term_c_lflag = -1;
145 static int dump_hw_params = 0;
148 static off_t pbrec_count = LLONG_MAX, fdcount;
149 static int vocmajor, vocminor;
151 static char *pidfile_name = NULL;
153 static int pidfile_written = 0;
155 #ifdef CONFIG_SUPPORT_CHMAP
156 static snd_pcm_chmap_t *channel_map = NULL; /* chmap to override */
157 static unsigned int *hw_map = NULL; /* chmap to follow */
160 /* needed prototypes */
162 static void done_stdin(void);
164 static void playback(char *filename);
165 static void capture(char *filename);
166 static void playbackv(char **filenames, unsigned int count);
167 static void capturev(char **filenames, unsigned int count);
169 static void begin_voc(int fd, size_t count);
170 static void end_voc(int fd);
171 static void begin_wave(int fd, size_t count);
172 static void end_wave(int fd);
173 static void begin_au(int fd, size_t count);
174 static void end_au(int fd);
176 static void suspend(void);
178 static const struct fmt_capture {
179 void (*start) (int fd, size_t count);
180 void (*end) (int fd);
182 long long max_filesize;
183 } fmt_rec_table[] = {
184 { NULL, NULL, N_("raw data"), LLONG_MAX },
185 { begin_voc, end_voc, N_("VOC"), 16000000LL },
186 /* FIXME: can WAV handle exactly 2GB or less than it? */
187 { begin_wave, end_wave, N_("WAVE"), 2147483648LL },
188 { begin_au, end_au, N_("Sparc Audio"), LLONG_MAX }
191 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
192 #define error(...) do {\
193 fprintf(stderr, "%s: %s:%d: ", command, __func__, __LINE__); \
194 fprintf(stderr, __VA_ARGS__); \
195 putc('\n', stderr); \
198 #define error(args...) do {\
199 fprintf(stderr, "%s: %s:%d: ", command, __func__, __LINE__); \
200 fprintf(stderr, ##args); \
201 putc('\n', stderr); \
205 static void usage(char *command)
209 _("Usage: %s [OPTION]... [FILE]...\n"
212 " --version print current version\n"
213 "-l, --list-devices list all soundcards and digital audio devices\n"
214 "-L, --list-pcms list device names\n"
215 "-D, --device=NAME select PCM by name\n"
216 "-q, --quiet quiet mode\n"
217 "-t, --file-type TYPE file type (voc, wav, raw or au)\n"
218 "-c, --channels=# channels\n"
219 "-f, --format=FORMAT sample format (case insensitive)\n"
220 " --subformat=SUBFORMAT sample subformat (case insensitive)\n"
221 "-r, --rate=# sample rate\n"
222 "-d, --duration=# interrupt after # seconds\n"
223 "-s, --samples=# interrupt after # samples per channel\n"
224 "-M, --mmap mmap stream\n"
225 "-N, --nonblock nonblocking mode\n"
226 "-F, --period-time=# distance between interrupts is # microseconds\n"
227 "-B, --buffer-time=# buffer duration is # microseconds\n"
228 " --period-size=# distance between interrupts is # frames\n"
229 " --buffer-size=# buffer duration is # frames\n"
230 "-A, --avail-min=# min available space for wakeup is # microseconds\n"
231 "-R, --start-delay=# delay for automatic PCM start is # microseconds \n"
232 " (relative to buffer size if <= 0)\n"
233 "-T, --stop-delay=# delay for automatic PCM stop is # microseconds from xrun\n"
234 "-v, --verbose show PCM structure and setup (accumulative)\n"
235 "-V, --vumeter=TYPE enable VU meter (TYPE: mono or stereo)\n"
236 "-I, --separate-channels one file for each channel\n"
237 "-i, --interactive allow interactive operation from stdin\n"
238 "-m, --chmap=ch1,ch2,.. Give the channel map to override or follow\n"
239 " --disable-resample disable automatic rate resample\n"
240 " --disable-channels disable automatic channel conversions\n"
241 " --disable-format disable automatic format conversions\n"
242 " --disable-softvol disable software volume control (softvol)\n"
243 " --test-position test ring buffer position\n"
244 " --test-coef=# test coefficient for ring buffer position (default 8)\n"
245 " expression for validation is: coef * (buffer_size / 2)\n"
246 " --test-nowait do not wait for ring buffer - eats whole CPU\n"
247 " --max-file-time=# start another output file when the old file has recorded\n"
248 " for this many seconds\n"
249 " --process-id-file write the process ID here\n"
250 " --use-strftime apply the strftime facility to the output file name\n"
251 " --dump-hw-params dump hw_params of the device\n"
252 " --fatal-errors treat all errors as fatal\n"
255 printf(_("Recognized sample formats are:"));
256 for (k = 0; k <= SND_PCM_FORMAT_LAST; ++k) {
257 const char *s = snd_pcm_format_name(k);
261 printf(_("\nSome of these may not be available on selected hardware\n"));
262 printf(_("The available format shortcuts are:\n"));
263 printf(_("-f cd (16 bit little endian, 44100, stereo)\n"));
264 printf(_("-f cdr (16 bit big endian, 44100, stereo)\n"));
265 printf(_("-f dat (16 bit little endian, 48000, stereo)\n"));
268 static void device_list(void)
271 int card, err, dev, idx;
272 snd_ctl_card_info_t *info;
273 snd_pcm_info_t *pcminfo;
274 snd_ctl_card_info_alloca(&info);
275 snd_pcm_info_alloca(&pcminfo);
278 if (snd_card_next(&card) < 0 || card < 0) {
279 error(_("no soundcards found..."));
282 printf(_("**** List of %s Hardware Devices ****\n"),
283 snd_pcm_stream_name(stream));
286 snprintf(name, sizeof(name), "hw:%d", card);
287 if ((err = snd_ctl_open(&handle, name, 0)) < 0) {
288 error("control open (%i): %s", card, snd_strerror(err));
291 if ((err = snd_ctl_card_info(handle, info)) < 0) {
292 error("control hardware info (%i): %s", card, snd_strerror(err));
293 snd_ctl_close(handle);
299 if (snd_ctl_pcm_next_device(handle, &dev)<0)
300 error("snd_ctl_pcm_next_device");
303 snd_pcm_info_set_device(pcminfo, dev);
304 snd_pcm_info_set_subdevice(pcminfo, 0);
305 snd_pcm_info_set_stream(pcminfo, stream);
306 if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
308 error("control digital audio info (%i): %s", card, snd_strerror(err));
311 printf(_("card %i: %s [%s], device %i: %s [%s]\n"),
312 card, snd_ctl_card_info_get_id(info), snd_ctl_card_info_get_name(info),
314 snd_pcm_info_get_id(pcminfo),
315 snd_pcm_info_get_name(pcminfo));
316 count = snd_pcm_info_get_subdevices_count(pcminfo);
317 printf( _(" Subdevices: %i/%i\n"),
318 snd_pcm_info_get_subdevices_avail(pcminfo), count);
319 for (idx = 0; idx < (int)count; idx++) {
320 snd_pcm_info_set_subdevice(pcminfo, idx);
321 if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
322 error("control digital audio playback info (%i): %s", card, snd_strerror(err));
324 printf(_(" Subdevice #%i: %s\n"),
325 idx, snd_pcm_info_get_subdevice_name(pcminfo));
329 snd_ctl_close(handle);
331 if (snd_card_next(&card) < 0) {
332 error("snd_card_next");
338 static void pcm_list(void)
341 char *name, *descr, *descr1, *io;
344 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
347 filter = stream == SND_PCM_STREAM_CAPTURE ? "Input" : "Output";
349 name = snd_device_name_get_hint(*n, "NAME");
350 descr = snd_device_name_get_hint(*n, "DESC");
351 io = snd_device_name_get_hint(*n, "IOID");
352 if (io != NULL && strcmp(io, filter) != 0)
354 printf("%s\n", name);
355 if ((descr1 = descr) != NULL) {
375 snd_device_name_free_hint(hints);
378 static void version(void)
380 printf("%s: version " SND_UTIL_VERSION_STR " by Jaroslav Kysela <perex@perex.cz>\n", command);
384 * Subroutine to clean up before exit.
386 static void prg_exit(int code)
390 snd_pcm_close(handle);
392 remove (pidfile_name);
396 static void signal_handler(int sig)
405 fprintf(stderr, _("Aborted by signal %s...\n"), strsignal(sig));
407 snd_pcm_abort(handle);
408 if (sig == SIGABRT) {
409 /* do not call snd_pcm_close() and abort immediately */
411 prg_exit(EXIT_FAILURE);
413 signal(sig, SIG_DFL);
416 /* call on SIGUSR1 signal. */
417 static void signal_handler_recycle(int sig ATTRIBUTE_UNUSED)
419 /* flag the capture loop to start a new output file */
420 recycle_capture_file = 1;
427 OPT_DISABLE_RESAMPLE,
428 OPT_DISABLE_CHANNELS,
443 * make sure we write all bytes or return an error
445 static ssize_t xwrite(int fd, const void *buf, size_t count)
450 while (offset < count) {
451 written = write(fd, (char *)buf + offset, count - offset);
461 static long parse_long(const char *str, int *err)
467 val = strtol(str, &endptr, 0);
469 if (errno != 0 || *endptr != '\0')
477 int main(int argc, char *argv[])
479 int duration_or_sample = 0;
481 static const char short_options[] = "hnlLD:qt:c:f:r:d:s:MNF:A:R:T:B:vV:IPCi"
482 #ifdef CONFIG_SUPPORT_CHMAP
486 static const struct option long_options[] = {
488 {"version", 0, 0, OPT_VERSION},
489 {"list-devnames", 0, 0, 'n'},
490 {"list-devices", 0, 0, 'l'},
491 {"list-pcms", 0, 0, 'L'},
492 {"device", 1, 0, 'D'},
493 {"quiet", 0, 0, 'q'},
494 {"file-type", 1, 0, 't'},
495 {"channels", 1, 0, 'c'},
496 {"format", 1, 0, 'f'},
497 {"subformat", 1, 0, OPT_SUBFORMAT},
499 {"duration", 1, 0 ,'d'},
500 {"samples", 1, 0, 's'},
502 {"nonblock", 0, 0, 'N'},
503 {"period-time", 1, 0, 'F'},
504 {"period-size", 1, 0, OPT_PERIOD_SIZE},
505 {"avail-min", 1, 0, 'A'},
506 {"start-delay", 1, 0, 'R'},
507 {"stop-delay", 1, 0, 'T'},
508 {"buffer-time", 1, 0, 'B'},
509 {"buffer-size", 1, 0, OPT_BUFFER_SIZE},
510 {"verbose", 0, 0, 'v'},
511 {"vumeter", 1, 0, 'V'},
512 {"separate-channels", 0, 0, 'I'},
513 {"playback", 0, 0, 'P'},
514 {"capture", 0, 0, 'C'},
515 {"disable-resample", 0, 0, OPT_DISABLE_RESAMPLE},
516 {"disable-channels", 0, 0, OPT_DISABLE_CHANNELS},
517 {"disable-format", 0, 0, OPT_DISABLE_FORMAT},
518 {"disable-softvol", 0, 0, OPT_DISABLE_SOFTVOL},
519 {"test-position", 0, 0, OPT_TEST_POSITION},
520 {"test-coef", 1, 0, OPT_TEST_COEF},
521 {"test-nowait", 0, 0, OPT_TEST_NOWAIT},
522 {"max-file-time", 1, 0, OPT_MAX_FILE_TIME},
523 {"process-id-file", 1, 0, OPT_PROCESS_ID_FILE},
524 {"use-strftime", 0, 0, OPT_USE_STRFTIME},
525 {"interactive", 0, 0, 'i'},
526 {"dump-hw-params", 0, 0, OPT_DUMP_HWPARAMS},
527 {"fatal-errors", 0, 0, OPT_FATAL_ERRORS},
528 #ifdef CONFIG_SUPPORT_CHMAP
529 {"chmap", 1, 0, 'm'},
533 char *pcm_name = "default";
535 int do_device_list = 0, do_pcm_list = 0, force_sample_format = 0;
536 snd_pcm_info_t *info;
540 setlocale(LC_ALL, "");
544 snd_pcm_info_alloca(&info);
546 err = snd_output_stdio_attach(&log, stderr, 0);
550 file_type = FORMAT_DEFAULT;
551 if (strstr(argv[0], "arecord")) {
552 stream = SND_PCM_STREAM_CAPTURE;
553 file_type = FORMAT_WAVE;
557 } else if (strstr(argv[0], "aplay")) {
558 stream = SND_PCM_STREAM_PLAYBACK;
562 error(_("command should be named either arecord or aplay"));
566 if (isatty(fileno(direction)) && (argc == 1)) {
572 rhwparams.format = DEFAULT_FORMAT;
573 rhwparams.subformat = SND_PCM_SUBFORMAT_STD;
574 rhwparams.rate = DEFAULT_SPEED;
575 rhwparams.channels = 1;
577 while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) {
598 if (strcasecmp(optarg, "raw") == 0)
599 file_type = FORMAT_RAW;
600 else if (strcasecmp(optarg, "voc") == 0)
601 file_type = FORMAT_VOC;
602 else if (strcasecmp(optarg, "wav") == 0)
603 file_type = FORMAT_WAVE;
604 else if (strcasecmp(optarg, "au") == 0 || strcasecmp(optarg, "sparc") == 0)
605 file_type = FORMAT_AU;
607 error(_("unrecognized file format %s"), optarg);
612 rhwparams.channels = parse_long(optarg, &err);
614 error(_("invalid channels argument '%s'"), optarg);
617 if (rhwparams.channels < 1 || rhwparams.channels > 256) {
618 error(_("value %i for channels is invalid"), rhwparams.channels);
623 force_sample_format = 1;
624 if (strcasecmp(optarg, "cd") == 0 || strcasecmp(optarg, "cdr") == 0) {
625 if (strcasecmp(optarg, "cdr") == 0)
626 rhwparams.format = SND_PCM_FORMAT_S16_BE;
628 rhwparams.format = file_type == FORMAT_AU ? SND_PCM_FORMAT_S16_BE : SND_PCM_FORMAT_S16_LE;
629 rhwparams.rate = 44100;
630 rhwparams.channels = 2;
631 } else if (strcasecmp(optarg, "dat") == 0) {
632 rhwparams.format = file_type == FORMAT_AU ? SND_PCM_FORMAT_S16_BE : SND_PCM_FORMAT_S16_LE;
633 rhwparams.rate = 48000;
634 rhwparams.channels = 2;
636 rhwparams.format = snd_pcm_format_value(optarg);
637 if (rhwparams.format == SND_PCM_FORMAT_UNKNOWN) {
638 error(_("wrong extended format '%s'"), optarg);
639 prg_exit(EXIT_FAILURE);
644 #if SND_LIB_VER(1, 2, 10) < SND_LIB_VERSION
645 rhwparams.subformat = snd_pcm_subformat_value(optarg);
646 if (rhwparams.subformat == SND_PCM_SUBFORMAT_UNKNOWN) {
648 if (strcasecmp(optarg, "std") != 0 && strcasecmp(optarg, "standard") != 0) {
650 error(_("wrong extended subformat '%s'"), optarg);
651 prg_exit(EXIT_FAILURE);
655 tmp = parse_long(optarg, &err);
657 error(_("invalid rate argument '%s'"), optarg);
662 rhwparams.rate = tmp;
663 if (tmp < 2000 || tmp > 768000) {
664 error(_("bad speed value %i"), tmp);
669 if (duration_or_sample) {
670 error(_("duration and samples arguments cannot be used together"));
673 timelimit = parse_long(optarg, &err);
675 error(_("invalid duration argument '%s'"), optarg);
678 duration_or_sample = 1;
681 if (duration_or_sample) {
682 error(_("samples and duration arguments cannot be used together"));
685 sampleslimit = parse_long(optarg, &err);
687 error(_("invalid samples argument '%s'"), optarg);
690 duration_or_sample = 1;
694 open_mode |= SND_PCM_NONBLOCK;
697 period_time = parse_long(optarg, &err);
699 error(_("invalid period time argument '%s'"), optarg);
704 buffer_time = parse_long(optarg, &err);
706 error(_("invalid buffer time argument '%s'"), optarg);
710 case OPT_PERIOD_SIZE:
711 period_frames = parse_long(optarg, &err);
713 error(_("invalid period size argument '%s'"), optarg);
717 case OPT_BUFFER_SIZE:
718 buffer_frames = parse_long(optarg, &err);
720 error(_("invalid buffer size argument '%s'"), optarg);
725 avail_min = parse_long(optarg, &err);
727 error(_("invalid min available space argument '%s'"), optarg);
732 start_delay = parse_long(optarg, &err);
734 error(_("invalid start delay argument '%s'"), optarg);
739 stop_delay = parse_long(optarg, &err);
741 error(_("invalid stop delay argument '%s'"), optarg);
747 if (verbose > 1 && !vumeter)
748 vumeter = VUMETER_MONO;
752 vumeter = VUMETER_STEREO;
753 else if (*optarg == 'm')
754 vumeter = VUMETER_MONO;
756 vumeter = VUMETER_NONE;
765 stream = SND_PCM_STREAM_PLAYBACK;
769 stream = SND_PCM_STREAM_CAPTURE;
772 if (file_type == FORMAT_DEFAULT)
773 file_type = FORMAT_WAVE;
778 case OPT_DISABLE_RESAMPLE:
779 open_mode |= SND_PCM_NO_AUTO_RESAMPLE;
781 case OPT_DISABLE_CHANNELS:
782 open_mode |= SND_PCM_NO_AUTO_CHANNELS;
784 case OPT_DISABLE_FORMAT:
785 open_mode |= SND_PCM_NO_AUTO_FORMAT;
787 case OPT_DISABLE_SOFTVOL:
788 open_mode |= SND_PCM_NO_SOFTVOL;
790 case OPT_TEST_POSITION:
794 test_coef = parse_long(optarg, &err);
796 error(_("invalid test coef argument '%s'"), optarg);
802 case OPT_TEST_NOWAIT:
805 case OPT_MAX_FILE_TIME:
806 max_file_time = parse_long(optarg, &err);
808 error(_("invalid max file time argument '%s'"), optarg);
812 case OPT_PROCESS_ID_FILE:
813 pidfile_name = optarg;
815 case OPT_USE_STRFTIME:
818 case OPT_DUMP_HWPARAMS:
821 case OPT_FATAL_ERRORS:
824 #ifdef CONFIG_SUPPORT_CHMAP
826 channel_map = snd_pcm_chmap_parse_string(optarg);
828 fprintf(stderr, _("Unable to parse channel map string: %s\n"), optarg);
834 fprintf(stderr, _("Try `%s --help' for more information.\n"), command);
839 if (do_device_list) {
840 if (do_pcm_list) pcm_list();
843 } else if (do_pcm_list) {
848 err = snd_pcm_open(&handle, pcm_name, stream, open_mode);
850 error(_("audio open error: %s"), snd_strerror(err));
854 if ((err = snd_pcm_info(handle, info)) < 0) {
855 error(_("info error: %s"), snd_strerror(err));
860 err = snd_pcm_nonblock(handle, 1);
862 error(_("nonblock setting error: %s"), snd_strerror(err));
867 if (!force_sample_format &&
868 isatty(fileno(stdin)) &&
869 stream == SND_PCM_STREAM_CAPTURE &&
870 snd_pcm_format_width(rhwparams.format) <= 8)
871 fprintf(stderr, "Warning: Some sources (like microphones) may produce inaudible results\n"
872 " with 8-bit sampling. Use '-f' argument to increase resolution\n"
873 " e.g. '-f S16_LE'.\n");
876 hwparams = rhwparams;
878 audiobuf = (uint8_t *)malloc(1024);
879 if (audiobuf == NULL) {
880 error(_("not enough memory"));
885 writei_func = snd_pcm_mmap_writei;
886 readi_func = snd_pcm_mmap_readi;
887 writen_func = snd_pcm_mmap_writen;
888 readn_func = snd_pcm_mmap_readn;
890 writei_func = snd_pcm_writei;
891 readi_func = snd_pcm_readi;
892 writen_func = snd_pcm_writen;
893 readn_func = snd_pcm_readn;
898 pidf = fopen (pidfile_name, "w");
900 (void)fprintf (pidf, "%d\n", getpid());
904 error(_("Cannot create process ID file %s: %s"),
905 pidfile_name, strerror (errno));
910 signal(SIGINT, signal_handler);
911 signal(SIGTERM, signal_handler);
912 signal(SIGABRT, signal_handler);
913 signal(SIGUSR1, signal_handler_recycle);
915 if (optind > argc - 1) {
916 if (stream == SND_PCM_STREAM_PLAYBACK)
921 while (optind <= argc - 1) {
922 if (stream == SND_PCM_STREAM_PLAYBACK)
923 playback(argv[optind++]);
925 capture(argv[optind++]);
929 if (stream == SND_PCM_STREAM_PLAYBACK)
930 playbackv(&argv[optind], argc - optind);
932 capturev(&argv[optind], argc - optind);
936 snd_pcm_close(handle);
940 snd_output_close(log);
941 snd_config_update_free_global();
942 prg_exit(EXIT_SUCCESS);
948 * Safe read (for pipes)
951 static ssize_t safe_read(int fd, void *buf, size_t count)
953 ssize_t result = 0, res;
955 while (count > 0 && !in_aborting) {
956 if ((res = read(fd, buf, count)) == 0)
959 return result > 0 ? result : res;
962 buf = (char *)buf + res;
968 * Test, if it is a .VOC file and return >=0 if ok (this is the length of rest)
971 static int test_vocfile(void *buffer)
973 VocHeader *vp = buffer;
975 if (!memcmp(vp->magic, VOC_MAGIC_STRING, 20)) {
976 vocminor = LE_SHORT(vp->version) & 0xFF;
977 vocmajor = LE_SHORT(vp->version) / 256;
978 if (LE_SHORT(vp->version) != (0x1233 - LE_SHORT(vp->coded_ver)))
979 return -2; /* coded version mismatch */
980 return LE_SHORT(vp->headerlen) - sizeof(VocHeader); /* 0 mostly */
982 return -1; /* magic string fail */
986 * helper for test_wavefile
989 static size_t test_wavefile_read(int fd, uint8_t *buffer, size_t *size, size_t reqsize, int line)
991 if (*size >= reqsize)
993 if ((size_t)safe_read(fd, buffer + *size, reqsize - *size) != reqsize - *size) {
994 error(_("read error (called from line %i)"), line);
995 prg_exit(EXIT_FAILURE);
997 return *size = reqsize;
1000 #define check_wavefile_space(buffer, len, blimit) \
1001 if (len > blimit) { \
1003 if ((buffer = realloc(buffer, blimit)) == NULL) { \
1004 error(_("not enough memory")); \
1005 prg_exit(EXIT_FAILURE); \
1010 * test, if it's a .WAV file, > 0 if ok (and set the speed, stereo etc.)
1012 * Value returned is bytes to be discarded.
1014 static ssize_t test_wavefile(int fd, uint8_t *_buffer, size_t size)
1016 WaveHeader *h = (WaveHeader *)_buffer;
1017 uint8_t *buffer = NULL;
1022 unsigned short format, channels;
1023 int big_endian, native_format;
1026 if (size < sizeof(WaveHeader))
1028 if (h->magic == WAV_RIFF)
1030 else if (h->magic == WAV_RIFX)
1034 if (h->type != WAV_WAVE)
1037 if (size > sizeof(WaveHeader)) {
1038 check_wavefile_space(buffer, size - sizeof(WaveHeader), blimit);
1039 memcpy(buffer, _buffer + sizeof(WaveHeader), size - sizeof(WaveHeader));
1041 size -= sizeof(WaveHeader);
1043 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
1044 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
1045 c = (WaveChunkHeader*)buffer;
1047 len = TO_CPU_INT(c->length, big_endian);
1049 if (size > sizeof(WaveChunkHeader))
1050 memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
1051 size -= sizeof(WaveChunkHeader);
1052 if (type == WAV_FMT)
1054 check_wavefile_space(buffer, len, blimit);
1055 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1057 memmove(buffer, buffer + len, size - len);
1061 if (len < sizeof(WaveFmtBody)) {
1062 error(_("unknown length of 'fmt ' chunk (read %u, should be %u at least)"),
1063 len, (uint32_t)sizeof(WaveFmtBody));
1064 prg_exit(EXIT_FAILURE);
1066 check_wavefile_space(buffer, len, blimit);
1067 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1068 f = (WaveFmtBody*) buffer;
1069 format = TO_CPU_SHORT(f->format, big_endian);
1070 if (format == WAV_FMT_EXTENSIBLE) {
1071 WaveFmtExtensibleBody *fe = (WaveFmtExtensibleBody*)buffer;
1072 if (len < sizeof(WaveFmtExtensibleBody)) {
1073 error(_("unknown length of extensible 'fmt ' chunk (read %u, should be %u at least)"),
1074 len, (unsigned int)sizeof(WaveFmtExtensibleBody));
1075 prg_exit(EXIT_FAILURE);
1077 if (memcmp(fe->guid_tag, WAV_GUID_TAG, 14) != 0) {
1078 error(_("wrong format tag in extensible 'fmt ' chunk"));
1079 prg_exit(EXIT_FAILURE);
1081 vbps = TO_CPU_SHORT(fe->bit_p_spl, big_endian);
1082 format = TO_CPU_SHORT(fe->guid_format, big_endian);
1084 if (format != WAV_FMT_PCM &&
1085 format != WAV_FMT_IEEE_FLOAT) {
1086 error(_("can't play WAVE-file format 0x%04x which is not PCM or FLOAT encoded"), format);
1087 prg_exit(EXIT_FAILURE);
1089 channels = TO_CPU_SHORT(f->channels, big_endian);
1091 error(_("can't play WAVE-files with %d tracks"), channels);
1092 prg_exit(EXIT_FAILURE);
1094 hwparams.channels = channels;
1095 if (vbps > TO_CPU_SHORT(f->bit_p_spl, big_endian)) {
1096 error(_("valid bps greater than bps: %d > %d"), vbps, TO_CPU_SHORT(f->bit_p_spl, big_endian));
1097 prg_exit(EXIT_FAILURE);
1099 switch (TO_CPU_SHORT(f->bit_p_spl, big_endian)) {
1101 if (hwparams.format != DEFAULT_FORMAT &&
1102 hwparams.format != SND_PCM_FORMAT_U8)
1103 fprintf(stderr, _("Warning: format is changed to U8\n"));
1104 hwparams.format = SND_PCM_FORMAT_U8;
1108 native_format = SND_PCM_FORMAT_S16_BE;
1110 native_format = SND_PCM_FORMAT_S16_LE;
1111 if (hwparams.format != DEFAULT_FORMAT &&
1112 hwparams.format != native_format)
1113 fprintf(stderr, _("Warning: format is changed to %s\n"),
1114 snd_pcm_format_name(native_format));
1115 hwparams.format = native_format;
1118 switch (TO_CPU_SHORT(f->byte_p_spl, big_endian) / hwparams.channels) {
1121 native_format = SND_PCM_FORMAT_S24_3BE;
1123 native_format = SND_PCM_FORMAT_S24_3LE;
1124 if (hwparams.format != DEFAULT_FORMAT &&
1125 hwparams.format != native_format)
1126 fprintf(stderr, _("Warning: format is changed to %s\n"),
1127 snd_pcm_format_name(native_format));
1128 hwparams.format = native_format;
1132 native_format = SND_PCM_FORMAT_S24_BE;
1134 native_format = SND_PCM_FORMAT_S24_LE;
1135 if (hwparams.format != DEFAULT_FORMAT &&
1136 hwparams.format != native_format)
1137 fprintf(stderr, _("Warning: format is changed to %s\n"),
1138 snd_pcm_format_name(native_format));
1139 hwparams.format = native_format;
1142 error(_(" can't play WAVE-files with sample %d bits in %d bytes wide (%d channels)"),
1143 TO_CPU_SHORT(f->bit_p_spl, big_endian),
1144 TO_CPU_SHORT(f->byte_p_spl, big_endian),
1146 prg_exit(EXIT_FAILURE);
1150 if (format == WAV_FMT_PCM) {
1154 native_format = SND_PCM_FORMAT_S24_BE;
1156 native_format = SND_PCM_FORMAT_S24_LE;
1160 native_format = SND_PCM_FORMAT_S32_BE;
1162 native_format = SND_PCM_FORMAT_S32_LE;
1165 hwparams.format = native_format;
1166 } else if (format == WAV_FMT_IEEE_FLOAT) {
1168 native_format = SND_PCM_FORMAT_FLOAT_BE;
1170 native_format = SND_PCM_FORMAT_FLOAT_LE;
1171 hwparams.format = native_format;
1175 error(_(" can't play WAVE-files with sample %d bits wide"),
1176 TO_CPU_SHORT(f->bit_p_spl, big_endian));
1177 prg_exit(EXIT_FAILURE);
1179 hwparams.rate = TO_CPU_INT(f->sample_fq, big_endian);
1182 memmove(buffer, buffer + len, size - len);
1188 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
1189 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
1190 c = (WaveChunkHeader*)buffer;
1192 len = TO_CPU_INT(c->length, big_endian);
1193 if (size > sizeof(WaveChunkHeader))
1194 memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
1195 size -= sizeof(WaveChunkHeader);
1196 if (type == WAV_DATA) {
1197 if (len < pbrec_count && len < 0x7ffffffe)
1200 memcpy(_buffer, buffer, size);
1205 check_wavefile_space(buffer, len, blimit);
1206 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1208 memmove(buffer, buffer + len, size - len);
1212 /* shouldn't be reached */
1220 static int test_au(int fd, void *buffer)
1222 AuHeader *ap = buffer;
1224 if (ap->magic != AU_MAGIC)
1226 if (BE_INT(ap->hdr_size) > 128 || BE_INT(ap->hdr_size) < 24)
1228 pbrec_count = BE_INT(ap->data_size);
1229 switch (BE_INT(ap->encoding)) {
1231 if (hwparams.format != DEFAULT_FORMAT &&
1232 hwparams.format != SND_PCM_FORMAT_MU_LAW)
1233 fprintf(stderr, _("Warning: format is changed to MU_LAW\n"));
1234 hwparams.format = SND_PCM_FORMAT_MU_LAW;
1237 if (hwparams.format != DEFAULT_FORMAT &&
1238 hwparams.format != SND_PCM_FORMAT_U8)
1239 fprintf(stderr, _("Warning: format is changed to U8\n"));
1240 hwparams.format = SND_PCM_FORMAT_U8;
1243 if (hwparams.format != DEFAULT_FORMAT &&
1244 hwparams.format != SND_PCM_FORMAT_S16_BE)
1245 fprintf(stderr, _("Warning: format is changed to S16_BE\n"));
1246 hwparams.format = SND_PCM_FORMAT_S16_BE;
1249 if (hwparams.format != DEFAULT_FORMAT &&
1250 hwparams.format != SND_PCM_FORMAT_A_LAW)
1251 fprintf(stderr, _("Warning: format is changed to A_LAW\n"));
1252 hwparams.format = SND_PCM_FORMAT_A_LAW;
1257 hwparams.rate = BE_INT(ap->sample_rate);
1258 if (hwparams.rate < 2000 || hwparams.rate > 256000)
1260 hwparams.channels = BE_INT(ap->channels);
1261 if (hwparams.channels < 1 || hwparams.channels > 256)
1263 if ((size_t)safe_read(fd, (char *)buffer + sizeof(AuHeader), BE_INT(ap->hdr_size) - sizeof(AuHeader)) != BE_INT(ap->hdr_size) - sizeof(AuHeader)) {
1264 error(_("read error"));
1265 prg_exit(EXIT_FAILURE);
1270 static void show_available_sample_formats(snd_pcm_hw_params_t* params)
1272 snd_pcm_format_t format;
1274 fprintf(stderr, "Available formats:\n");
1275 for (format = 0; format <= SND_PCM_FORMAT_LAST; format++) {
1276 if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
1277 fprintf(stderr, "- %s\n", snd_pcm_format_name(format));
1281 #ifdef CONFIG_SUPPORT_CHMAP
1282 static int setup_chmap(void)
1284 snd_pcm_chmap_t *chmap = channel_map;
1285 char mapped[hwparams.channels];
1286 snd_pcm_chmap_t *hw_chmap;
1293 if (chmap->channels != hwparams.channels) {
1294 error(_("Channel numbers don't match between hw_params and channel map"));
1297 err = snd_pcm_set_chmap(handle, chmap);
1301 hw_chmap = snd_pcm_get_chmap(handle);
1303 fprintf(stderr, _("Warning: unable to get channel map\n"));
1307 if (hw_chmap->channels == chmap->channels &&
1308 !memcmp(hw_chmap, chmap, 4 * (chmap->channels + 1))) {
1309 /* maps are identical, so no need to convert */
1314 hw_map = calloc(hwparams.channels, sizeof(int));
1316 error(_("not enough memory"));
1321 memset(mapped, 0, sizeof(mapped));
1322 for (ch = 0; ch < hw_chmap->channels; ch++) {
1323 if (chmap->pos[ch] == hw_chmap->pos[ch]) {
1328 for (i = 0; i < hw_chmap->channels; i++) {
1329 if (!mapped[i] && chmap->pos[ch] == hw_chmap->pos[i]) {
1335 if (i >= hw_chmap->channels) {
1337 error(_("Channel %d doesn't match with hw_params"), ch);
1338 snd_pcm_chmap_print(hw_chmap, sizeof(buf), buf);
1339 fprintf(stderr, "hardware chmap = %s\n", buf);
1348 #define setup_chmap() 0
1351 static void set_params(void)
1353 snd_pcm_hw_params_t *params;
1354 snd_pcm_sw_params_t *swparams;
1355 snd_pcm_uframes_t buffer_size;
1359 snd_pcm_uframes_t start_threshold, stop_threshold;
1360 snd_pcm_hw_params_alloca(¶ms);
1361 snd_pcm_sw_params_alloca(&swparams);
1362 err = snd_pcm_hw_params_any(handle, params);
1364 error(_("Broken configuration for this PCM: no configurations available"));
1365 prg_exit(EXIT_FAILURE);
1367 if (dump_hw_params) {
1368 fprintf(stderr, _("HW Params of device \"%s\":\n"),
1369 snd_pcm_name(handle));
1370 fprintf(stderr, "--------------------\n");
1371 snd_pcm_hw_params_dump(params, log);
1372 fprintf(stderr, "--------------------\n");
1375 snd_pcm_access_mask_t *mask = alloca(snd_pcm_access_mask_sizeof());
1376 snd_pcm_access_mask_none(mask);
1377 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_INTERLEAVED);
1378 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_NONINTERLEAVED);
1379 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_COMPLEX);
1380 err = snd_pcm_hw_params_set_access_mask(handle, params, mask);
1381 } else if (interleaved)
1382 err = snd_pcm_hw_params_set_access(handle, params,
1383 SND_PCM_ACCESS_RW_INTERLEAVED);
1385 err = snd_pcm_hw_params_set_access(handle, params,
1386 SND_PCM_ACCESS_RW_NONINTERLEAVED);
1388 error(_("Access type not available"));
1389 prg_exit(EXIT_FAILURE);
1391 err = snd_pcm_hw_params_set_format(handle, params, hwparams.format);
1393 error(_("Sample format non available"));
1394 show_available_sample_formats(params);
1395 prg_exit(EXIT_FAILURE);
1397 err = snd_pcm_hw_params_set_subformat(handle, params, hwparams.subformat);
1399 error(_("Sample subformat not available"));
1400 prg_exit(EXIT_FAILURE);
1402 err = snd_pcm_hw_params_set_channels(handle, params, hwparams.channels);
1404 error(_("Channels count non available"));
1405 prg_exit(EXIT_FAILURE);
1409 err = snd_pcm_hw_params_set_periods_min(handle, params, 2);
1412 rate = hwparams.rate;
1413 err = snd_pcm_hw_params_set_rate_near(handle, params, &hwparams.rate, 0);
1415 if ((float)rate * 1.05 < hwparams.rate || (float)rate * 0.95 > hwparams.rate) {
1418 const char *pcmname = snd_pcm_name(handle);
1419 fprintf(stderr, _("Warning: rate is not accurate (requested = %iHz, got = %iHz)\n"), rate, hwparams.rate);
1420 if (! pcmname || strchr(snd_pcm_name(handle), ':'))
1423 snprintf(plugex, sizeof(plugex), "(-Dplug:%s)",
1424 snd_pcm_name(handle));
1425 fprintf(stderr, _(" please, try the plug plugin %s\n"),
1429 rate = hwparams.rate;
1430 if (buffer_time == 0 && buffer_frames == 0) {
1431 err = snd_pcm_hw_params_get_buffer_time_max(params,
1434 if (buffer_time > 500000)
1435 buffer_time = 500000;
1437 if (period_time == 0 && period_frames == 0) {
1438 if (buffer_time > 0)
1439 period_time = buffer_time / 4;
1441 period_frames = buffer_frames / 4;
1443 if (period_time > 0)
1444 err = snd_pcm_hw_params_set_period_time_near(handle, params,
1447 err = snd_pcm_hw_params_set_period_size_near(handle, params,
1450 if (buffer_time > 0) {
1451 err = snd_pcm_hw_params_set_buffer_time_near(handle, params,
1454 err = snd_pcm_hw_params_set_buffer_size_near(handle, params,
1458 monotonic = snd_pcm_hw_params_is_monotonic(params);
1459 can_pause = snd_pcm_hw_params_can_pause(params);
1460 err = snd_pcm_hw_params(handle, params);
1462 error(_("Unable to install hw params:"));
1463 snd_pcm_hw_params_dump(params, log);
1464 prg_exit(EXIT_FAILURE);
1466 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
1467 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
1468 if (chunk_size == buffer_size) {
1469 error(_("Can't use period equal to buffer size (%lu == %lu)"),
1470 chunk_size, buffer_size);
1471 prg_exit(EXIT_FAILURE);
1473 if (dump_hw_params) {
1474 fprintf(stderr, _("HW Params of device \"%s\":\n"),
1475 snd_pcm_name(handle));
1476 fprintf(stderr, "--------------------\n");
1477 snd_pcm_hw_params_dump(params, log);
1478 fprintf(stderr, "--------------------\n");
1480 err = snd_pcm_sw_params_current(handle, swparams);
1482 error(_("Unable to get current sw params."));
1483 prg_exit(EXIT_FAILURE);
1488 n = (double) rate * avail_min / 1000000;
1489 err = snd_pcm_sw_params_set_avail_min(handle, swparams, n);
1491 /* round up to closest transfer boundary */
1493 if (start_delay <= 0) {
1494 start_threshold = n + (double) rate * start_delay / 1000000;
1496 start_threshold = (double) rate * start_delay / 1000000;
1497 if (start_threshold < 1)
1498 start_threshold = 1;
1499 if (start_threshold > n)
1500 start_threshold = n;
1501 err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
1503 if (stop_delay <= 0)
1504 stop_threshold = buffer_size + (double) rate * stop_delay / 1000000;
1506 stop_threshold = (double) rate * stop_delay / 1000000;
1507 err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
1511 err = snd_pcm_sw_params_set_tstamp_mode(handle, swparams, SND_PCM_TSTAMP_ENABLE);
1515 err = snd_pcm_sw_params_set_tstamp_type(handle, swparams, SND_PCM_TSTAMP_TYPE_MONOTONIC);
1517 err = snd_pcm_sw_params_set_tstamp_type(handle, swparams, SND_PCM_TSTAMP_TYPE_GETTIMEOFDAY);
1521 if (snd_pcm_sw_params(handle, swparams) < 0) {
1522 error(_("unable to install sw params:"));
1523 snd_pcm_sw_params_dump(swparams, log);
1524 prg_exit(EXIT_FAILURE);
1528 prg_exit(EXIT_FAILURE);
1531 snd_pcm_dump(handle, log);
1533 bits_per_sample = snd_pcm_format_physical_width(hwparams.format);
1534 significant_bits_per_sample = snd_pcm_format_width(hwparams.format);
1535 bits_per_frame = bits_per_sample * hwparams.channels;
1536 chunk_bytes = chunk_size * bits_per_frame / 8;
1537 audiobuf = realloc(audiobuf, chunk_bytes);
1538 if (audiobuf == NULL) {
1539 error(_("not enough memory"));
1540 prg_exit(EXIT_FAILURE);
1542 // fprintf(stderr, "real chunk_size = %i, frags = %i, total = %i\n", chunk_size, setup.buf.block.frags, setup.buf.block.frags * chunk_size);
1544 /* stereo VU-meter isn't always available... */
1545 if (vumeter == VUMETER_STEREO) {
1546 if (hwparams.channels != 2 || !interleaved || verbose > 2)
1547 vumeter = VUMETER_MONO;
1550 /* show mmap buffer arragment */
1551 if (mmap_flag && verbose) {
1552 const snd_pcm_channel_area_t *areas;
1553 snd_pcm_uframes_t offset, size = chunk_size;
1555 err = snd_pcm_mmap_begin(handle, &areas, &offset, &size);
1557 error(_("snd_pcm_mmap_begin problem: %s"), snd_strerror(err));
1558 prg_exit(EXIT_FAILURE);
1560 for (i = 0; i < (int)hwparams.channels; i++)
1561 fprintf(stderr, "mmap_area[%i] = %p,%u,%u (%u)\n", i, areas[i].addr, areas[i].first, areas[i].step, snd_pcm_format_physical_width(hwparams.format));
1562 /* not required, but for sure */
1563 snd_pcm_mmap_commit(handle, offset, 0);
1566 buffer_frames = buffer_size; /* for position test */
1569 static void init_stdin(void)
1571 struct termios term;
1576 if (!isatty(fileno(stdin))) {
1580 tcgetattr(fileno(stdin), &term);
1581 term_c_lflag = term.c_lflag;
1582 if (fd == fileno(stdin))
1584 flags = fcntl(fileno(stdin), F_GETFL);
1585 if (flags < 0 || fcntl(fileno(stdin), F_SETFL, flags|O_NONBLOCK) < 0)
1586 fprintf(stderr, _("stdin O_NONBLOCK flag setup failed\n"));
1587 term.c_lflag &= ~ICANON;
1588 tcsetattr(fileno(stdin), TCSANOW, &term);
1591 static void done_stdin(void)
1593 struct termios term;
1597 if (fd == fileno(stdin) || term_c_lflag == -1)
1599 tcgetattr(fileno(stdin), &term);
1600 term.c_lflag = term_c_lflag;
1601 tcsetattr(fileno(stdin), TCSANOW, &term);
1604 static char wait_for_input(void)
1610 pfd.fd = fileno(stdin);
1611 pfd.events = POLLIN;
1613 } while (read(fileno(stdin), &b, 1) != 1);
1617 static void do_pause(void)
1623 fprintf(stderr, _("\rPAUSE command ignored (no hw support)\n"));
1626 if (snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED)
1629 err = snd_pcm_pause(handle, 1);
1631 error(_("pause push error: %s"), snd_strerror(err));
1634 fprintf(stderr, _("\r=== PAUSE === "));
1637 b = wait_for_input();
1638 if (b == ' ' || b == '\r') {
1639 while (read(fileno(stdin), &b, 1) == 1);
1640 if (snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED)
1642 err = snd_pcm_pause(handle, 0);
1644 error(_("pause release error: %s"), snd_strerror(err));
1650 static void check_stdin(void)
1656 if (fd != fileno(stdin)) {
1657 while (read(fileno(stdin), &b, 1) == 1) {
1658 if (b == ' ' || b == '\r') {
1659 while (read(fileno(stdin), &b, 1) == 1);
1661 fprintf(stderr, " \r");
1669 #define timersub(a, b, result) \
1671 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
1672 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
1673 if ((result)->tv_usec < 0) { \
1674 --(result)->tv_sec; \
1675 (result)->tv_usec += 1000000; \
1681 #define timermsub(a, b, result) \
1683 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
1684 (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
1685 if ((result)->tv_nsec < 0) { \
1686 --(result)->tv_sec; \
1687 (result)->tv_nsec += 1000000000L; \
1692 /* I/O error handler */
1693 static void xrun(void)
1695 snd_pcm_status_t *status;
1698 snd_pcm_status_alloca(&status);
1699 if ((res = snd_pcm_status(handle, status))<0) {
1700 error(_("status error: %s"), snd_strerror(res));
1701 prg_exit(EXIT_FAILURE);
1703 if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) {
1705 #ifdef HAVE_CLOCK_GETTIME
1706 struct timespec now, diff, tstamp;
1707 clock_gettime(CLOCK_MONOTONIC, &now);
1708 snd_pcm_status_get_trigger_htstamp(status, &tstamp);
1709 timermsub(&now, &tstamp, &diff);
1710 fprintf(stderr, _("%s!!! (at least %.3f ms long)\n"),
1711 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1712 diff.tv_sec * 1000 + diff.tv_nsec / 1000000.0);
1714 fprintf(stderr, "%s !!!\n", _("underrun"));
1717 struct timeval now, diff, tstamp;
1718 gettimeofday(&now, 0);
1719 snd_pcm_status_get_trigger_tstamp(status, &tstamp);
1720 timersub(&now, &tstamp, &diff);
1721 fprintf(stderr, _("%s!!! (at least %.3f ms long)\n"),
1722 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1723 diff.tv_sec * 1000 + diff.tv_usec / 1000.0);
1726 fprintf(stderr, _("Status:\n"));
1727 snd_pcm_status_dump(status, log);
1730 error(_("fatal %s: %s"),
1731 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1733 prg_exit(EXIT_FAILURE);
1735 if ((res = snd_pcm_prepare(handle))<0) {
1736 error(_("xrun: prepare error: %s"), snd_strerror(res));
1737 prg_exit(EXIT_FAILURE);
1739 return; /* ok, data should be accepted again */
1741 if (snd_pcm_status_get_state(status) == SND_PCM_STATE_DRAINING) {
1743 fprintf(stderr, _("Status(DRAINING):\n"));
1744 snd_pcm_status_dump(status, log);
1746 if (stream == SND_PCM_STREAM_CAPTURE) {
1747 fprintf(stderr, _("capture stream format change? attempting recover...\n"));
1748 if ((res = snd_pcm_prepare(handle))<0) {
1749 error(_("xrun(DRAINING): prepare error: %s"), snd_strerror(res));
1750 prg_exit(EXIT_FAILURE);
1756 fprintf(stderr, _("Status(R/W):\n"));
1757 snd_pcm_status_dump(status, log);
1759 error(_("read/write error, state = %s"), snd_pcm_state_name(snd_pcm_status_get_state(status)));
1760 prg_exit(EXIT_FAILURE);
1763 /* I/O suspend handler */
1764 static void suspend(void)
1769 fprintf(stderr, _("Suspended. Trying resume. ")); fflush(stderr);
1771 while ((res = snd_pcm_resume(handle)) == -EAGAIN)
1772 sleep(1); /* wait until suspend flag is released */
1775 fprintf(stderr, _("Failed. Restarting stream. ")); fflush(stderr);
1777 if ((res = snd_pcm_prepare(handle)) < 0) {
1778 error(_("suspend: prepare error: %s"), snd_strerror(res));
1779 prg_exit(EXIT_FAILURE);
1783 fprintf(stderr, _("Done.\n"));
1786 static void print_vu_meter_mono(int perc, int maxperc)
1788 const int bar_length = 50;
1792 for (val = 0; val <= perc * bar_length / 100 && val < bar_length; val++)
1794 for (; val <= maxperc * bar_length / 100 && val < bar_length; val++)
1797 for (++val; val <= bar_length; val++)
1800 sprintf(line + val, "| MAX");
1802 sprintf(line + val, "| %02i%%", maxperc);
1803 fputs(line, stderr);
1805 fprintf(stderr, _(" !clip "));
1808 static void print_vu_meter_stereo(int *perc, int *maxperc)
1810 const int bar_length = 35;
1814 memset(line, ' ', sizeof(line) - 1);
1815 line[bar_length + 3] = '|';
1817 for (c = 0; c < 2; c++) {
1818 int p = perc[c] * bar_length / 100;
1823 memset(line + bar_length + 6 + 1, '#', p);
1825 memset(line + bar_length - p, '#', p);
1826 p = maxperc[c] * bar_length / 100 - 1;
1829 else if (p >= bar_length)
1832 line[bar_length + 6 + 1 + p] = '+';
1834 line[bar_length - p - 1] = '+';
1835 if (ABS(maxperc[c]) > 99)
1836 sprintf(tmp, "MAX");
1838 sprintf(tmp, "%02d%%", maxperc[c]);
1840 memcpy(line + bar_length + 3 + 1, tmp, 3);
1842 memcpy(line + bar_length, tmp, 3);
1844 line[bar_length * 2 + 6 + 2] = 0;
1845 fputs(line, stderr);
1848 static void print_vu_meter(signed int *perc, signed int *maxperc)
1850 if (vumeter == VUMETER_STEREO)
1851 print_vu_meter_stereo(perc, maxperc);
1853 print_vu_meter_mono(*perc, *maxperc);
1857 static void compute_max_peak(uint8_t *data, size_t samples)
1859 signed int val, max, perc[2], max_peak[2];
1861 size_t osamples = samples;
1862 int format_little_endian = snd_pcm_format_little_endian(hwparams.format);
1865 if (vumeter == VUMETER_STEREO)
1870 memset(max_peak, 0, sizeof(max_peak));
1871 switch (bits_per_sample) {
1873 signed char *valp = (signed char *)data;
1874 signed char mask = snd_pcm_format_silence(hwparams.format);
1876 while (samples-- > 0) {
1877 val = *valp++ ^ mask;
1879 if (max_peak[c] < val)
1881 if (vumeter == VUMETER_STEREO)
1887 signed short *valp = (signed short *)data;
1888 signed short mask = snd_pcm_format_silence_16(hwparams.format);
1892 while (samples-- > 0) {
1893 if (format_little_endian)
1894 sval = le16toh(*valp);
1896 sval = be16toh(*valp);
1899 if (max_peak[c] < val)
1902 if (vumeter == VUMETER_STEREO)
1908 unsigned char *valp = data;
1909 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1912 while (samples-- > 0) {
1913 if (format_little_endian) {
1914 val = valp[0] | (valp[1]<<8) | (valp[2]<<16);
1916 val = (valp[0]<<16) | (valp[1]<<8) | valp[2];
1919 /* Correct signed bit in 32-bit value */
1920 if (val & (1<<(bits_per_sample-1))) {
1921 val |= 0xff<<24; /* Negate upper bits too */
1924 if (max_peak[c] < val)
1927 if (vumeter == VUMETER_STEREO)
1933 signed int *valp = (signed int *)data;
1934 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1937 while (samples-- > 0) {
1938 if (format_little_endian)
1939 val = le32toh(*valp);
1941 val = be32toh(*valp);
1943 if ((unsigned int)val == 0x80000000U)
1947 if (max_peak[c] < val)
1950 if (vumeter == VUMETER_STEREO)
1957 fprintf(stderr, _("Unsupported bit size %d.\n"), (int)bits_per_sample);
1962 max = 1 << (significant_bits_per_sample-1);
1966 for (c = 0; c < ichans; c++) {
1967 if (max_peak[c] > max)
1969 if (bits_per_sample > 16)
1970 perc[c] = max_peak[c] / (max / 100);
1972 perc[c] = max_peak[c] * 100 / max;
1975 if (interleaved && verbose <= 2) {
1976 static int maxperc[2];
1978 const time_t tt=time(NULL);
1984 for (c = 0; c < ichans; c++)
1985 if (perc[c] > maxperc[c])
1986 maxperc[c] = perc[c];
1989 print_vu_meter(perc, maxperc);
1992 else if (verbose==3) {
1993 fprintf(stderr, _("Max peak (%li samples): 0x%08x "), (long)osamples, max_peak[0]);
1994 for (val = 0; val < 20; val++)
1995 if (val <= perc[0] / 5)
1999 fprintf(stderr, " %i%%\n", perc[0]);
2004 static void do_test_position(void)
2006 static long counter = 0;
2007 static time_t tmr = -1;
2009 static float availsum, delaysum, samples;
2010 static snd_pcm_sframes_t maxavail, maxdelay;
2011 static snd_pcm_sframes_t minavail, mindelay;
2012 static snd_pcm_sframes_t badavail = 0, baddelay = 0;
2013 snd_pcm_sframes_t outofrange;
2014 snd_pcm_sframes_t avail, delay, savail, sdelay;
2015 snd_pcm_status_t *status;
2018 snd_pcm_status_alloca(&status);
2019 err = snd_pcm_avail_delay(handle, &avail, &delay);
2022 err = snd_pcm_status(handle, status);
2025 savail = snd_pcm_status_get_avail(status);
2026 sdelay = snd_pcm_status_get_delay(status);
2027 outofrange = (test_coef * (snd_pcm_sframes_t)buffer_frames) / 2;
2028 if (avail > outofrange || avail < -outofrange ||
2029 delay > outofrange || delay < -outofrange) {
2030 badavail = avail; baddelay = delay;
2031 availsum = delaysum = samples = 0;
2032 maxavail = maxdelay = 0;
2033 minavail = mindelay = buffer_frames * 16;
2034 fprintf(stderr, _("Suspicious buffer position (%li total): "
2035 "avail = %li, delay = %li, buffer = %li\n"),
2036 ++counter, (long)avail, (long)delay, (long)buffer_frames);
2037 } else if (savail > outofrange || savail < -outofrange ||
2038 sdelay > outofrange || sdelay < -outofrange) {
2039 badavail = savail; baddelay = sdelay;
2040 availsum = delaysum = samples = 0;
2041 maxavail = maxdelay = 0;
2042 minavail = mindelay = buffer_frames * 16;
2043 fprintf(stderr, _("Suspicious status buffer position (%li total): "
2044 "avail = %li, delay = %li, buffer = %li\n"),
2045 ++counter, (long)savail, (long)sdelay, (long)buffer_frames);
2046 } else if (stream == SND_PCM_STREAM_CAPTURE && avail > delay) {
2047 fprintf(stderr, _("Suspicious buffer position avail > delay (%li total): "
2048 "avail = %li, delay = %li\n"),
2049 ++counter, (long)avail, (long)delay);
2050 } else if (stream == SND_PCM_STREAM_CAPTURE && savail > sdelay) {
2051 fprintf(stderr, _("Suspicious status buffer position avail > delay (%li total): "
2052 "avail = %li, delay = %li\n"),
2053 ++counter, (long)savail, (long)sdelay);
2054 } else if (verbose) {
2056 if (tmr == (time_t) -1) {
2058 availsum = delaysum = samples = 0;
2059 maxavail = maxdelay = 0;
2060 minavail = mindelay = buffer_frames * 16;
2062 if (avail > maxavail)
2064 if (savail > maxavail)
2066 if (delay > maxdelay)
2068 if (sdelay > maxdelay)
2070 if (avail < minavail)
2072 if (savail < minavail)
2074 if (delay < mindelay)
2076 if (sdelay < mindelay)
2081 if ((maxavail != 0 || maxdelay != 0) && now != tmr) {
2082 fprintf(stderr, "BUFPOS: avg%li/%li "
2083 "min%li/%li max%li/%li (%li) (%li:%li/%li)\n",
2084 (long)(availsum / samples),
2085 (long)(delaysum / samples),
2086 (long)minavail, (long)mindelay,
2087 (long)maxavail, (long)maxdelay,
2088 (long)buffer_frames,
2089 counter, badavail, baddelay);
2094 fprintf(stderr, _("Status(R/W) (standalone avail=%li delay=%li):\n"), (long)avail, (long)delay);
2095 snd_pcm_status_dump(status, log);
2101 #ifdef CONFIG_SUPPORT_CHMAP
2102 static uint8_t *remap_data(uint8_t *data, size_t count)
2104 static uint8_t *tmp, *src, *dst;
2105 static size_t tmp_size;
2106 size_t sample_bytes = bits_per_sample / 8;
2107 size_t step = bits_per_frame / 8;
2114 chunk_bytes = count * bits_per_frame / 8;
2115 if (tmp_size < chunk_bytes) {
2117 tmp = malloc(chunk_bytes);
2119 error(_("not enough memory"));
2127 for (i = 0; i < count; i++) {
2128 for (ch = 0; ch < hwparams.channels; ch++) {
2129 memcpy(dst, src + sample_bytes * hw_map[ch],
2131 dst += sample_bytes;
2138 static uint8_t **remap_datav(uint8_t **data, size_t count ATTRIBUTE_UNUSED)
2140 static uint8_t **tmp;
2147 tmp = malloc(sizeof(*tmp) * hwparams.channels);
2149 error(_("not enough memory"));
2152 for (ch = 0; ch < hwparams.channels; ch++)
2153 tmp[ch] = data[hw_map[ch]];
2158 #define remap_data(data, count) (data)
2159 #define remap_datav(data, count) (data)
2166 static ssize_t pcm_write(uint8_t *data, size_t count)
2171 if (count < chunk_size) {
2172 snd_pcm_format_set_silence(hwparams.format, data + count * bits_per_frame / 8, (chunk_size - count) * hwparams.channels);
2175 data = remap_data(data, count);
2176 while (count > 0 && !in_aborting) {
2180 r = writei_func(handle, data, count);
2183 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2185 snd_pcm_wait(handle, 100);
2186 } else if (r == -EPIPE) {
2188 } else if (r == -ESTRPIPE) {
2191 error(_("write error: %s"), snd_strerror(r));
2192 prg_exit(EXIT_FAILURE);
2196 compute_max_peak(data, r * hwparams.channels);
2199 data += r * bits_per_frame / 8;
2205 static ssize_t pcm_writev(uint8_t **data, unsigned int channels, size_t count)
2210 if (count != chunk_size) {
2211 unsigned int channel;
2212 size_t offset = count;
2213 size_t remaining = chunk_size - count;
2214 for (channel = 0; channel < channels; channel++)
2215 snd_pcm_format_set_silence(hwparams.format, data[channel] + offset * bits_per_sample / 8, remaining);
2218 data = remap_datav(data, count);
2219 while (count > 0 && !in_aborting) {
2220 unsigned int channel;
2221 void *bufs[channels];
2222 size_t offset = result;
2223 for (channel = 0; channel < channels; channel++)
2224 bufs[channel] = data[channel] + offset * bits_per_sample / 8;
2228 r = writen_func(handle, bufs, count);
2231 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2233 snd_pcm_wait(handle, 100);
2234 } else if (r == -EPIPE) {
2236 } else if (r == -ESTRPIPE) {
2239 error(_("writev error: %s"), snd_strerror(r));
2240 prg_exit(EXIT_FAILURE);
2244 for (channel = 0; channel < channels; channel++)
2245 compute_max_peak(data[channel], r);
2258 static ssize_t pcm_read(uint8_t *data, size_t rcount)
2262 size_t count = rcount;
2264 if (count != chunk_size) {
2274 r = readi_func(handle, data, count);
2277 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2279 snd_pcm_wait(handle, 100);
2280 } else if (r == -EPIPE) {
2282 } else if (r == -ESTRPIPE) {
2285 error(_("read error: %s"), snd_strerror(r));
2286 prg_exit(EXIT_FAILURE);
2290 compute_max_peak(data, r * hwparams.channels);
2293 data += r * bits_per_frame / 8;
2297 return result > rcount ? rcount : result;
2300 static ssize_t pcm_readv(uint8_t **data, unsigned int channels, size_t rcount)
2304 size_t count = rcount;
2306 if (count != chunk_size) {
2313 unsigned int channel;
2314 void *bufs[channels];
2315 size_t offset = result;
2316 for (channel = 0; channel < channels; channel++)
2317 bufs[channel] = data[channel] + offset * bits_per_sample / 8;
2321 r = readn_func(handle, bufs, count);
2324 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2326 snd_pcm_wait(handle, 100);
2327 } else if (r == -EPIPE) {
2329 } else if (r == -ESTRPIPE) {
2332 error(_("readv error: %s"), snd_strerror(r));
2333 prg_exit(EXIT_FAILURE);
2337 for (channel = 0; channel < channels; channel++)
2338 compute_max_peak(data[channel], r);
2349 * ok, let's play a .voc file
2352 static ssize_t voc_pcm_write(uint8_t *data, size_t count)
2354 ssize_t result = count, r;
2357 while (count > 0 && !in_aborting) {
2359 if (size > chunk_bytes - buffer_pos)
2360 size = chunk_bytes - buffer_pos;
2361 memcpy(audiobuf + buffer_pos, data, size);
2365 if ((size_t)buffer_pos == chunk_bytes) {
2366 if ((size_t)(r = pcm_write(audiobuf, chunk_size)) != chunk_size)
2374 static void voc_write_silence(unsigned x)
2379 buf = (uint8_t *) malloc(chunk_bytes);
2381 error(_("can't allocate buffer for silence"));
2382 return; /* not fatal error */
2384 snd_pcm_format_set_silence(hwparams.format, buf, chunk_size * hwparams.channels);
2385 while (x > 0 && !in_aborting) {
2389 if (voc_pcm_write(buf, l) != (ssize_t)l) {
2390 error(_("write error"));
2391 prg_exit(EXIT_FAILURE);
2398 static void voc_pcm_flush(void)
2400 if (buffer_pos > 0) {
2402 if (snd_pcm_format_set_silence(hwparams.format, audiobuf + buffer_pos, chunk_bytes - buffer_pos * 8 / bits_per_sample) < 0)
2403 fprintf(stderr, _("voc_pcm_flush - silence error"));
2405 if (pcm_write(audiobuf, b) != (ssize_t)b)
2406 error(_("voc_pcm_flush error"));
2408 snd_pcm_nonblock(handle, 0);
2409 snd_pcm_drain(handle);
2410 snd_pcm_nonblock(handle, nonblock);
2413 static void voc_play(int fd, int ofs, char *name)
2419 size_t nextblock, in_buffer;
2420 uint8_t *data, *buf;
2421 char was_extended = 0, output = 0;
2422 uint16_t *sp, repeat = 0;
2425 #define COUNT(x) nextblock -= x; in_buffer -= x; data += x
2426 #define COUNT1(x) in_buffer -= x; data += x
2428 data = buf = (uint8_t *)malloc(64 * 1024);
2431 error(_("malloc error"));
2432 prg_exit(EXIT_FAILURE);
2435 fprintf(stderr, _("Playing Creative Labs Channel file '%s'...\n"), name);
2437 /* first we waste the rest of header, ugly but we don't need seek */
2438 while (ofs > (ssize_t)chunk_bytes) {
2439 if ((size_t)safe_read(fd, buf, chunk_bytes) != chunk_bytes) {
2440 error(_("read error"));
2441 prg_exit(EXIT_FAILURE);
2446 if (safe_read(fd, buf, ofs) != ofs) {
2447 error(_("read error"));
2448 prg_exit(EXIT_FAILURE);
2451 hwparams.format = DEFAULT_FORMAT;
2452 hwparams.subformat = SND_PCM_SUBFORMAT_STD;
2453 hwparams.channels = 1;
2454 hwparams.rate = DEFAULT_SPEED;
2457 in_buffer = nextblock = 0;
2458 while (!in_aborting) {
2459 Fill_the_buffer: /* need this for repeat */
2460 if (in_buffer < 32) {
2461 /* move the rest of buffer to pos 0 and fill the buf up */
2463 memcpy(buf, data, in_buffer);
2465 if ((l = safe_read(fd, buf + in_buffer, chunk_bytes - in_buffer)) > 0)
2467 else if (!in_buffer) {
2468 /* the file is truncated, so simulate 'Terminator'
2469 and reduce the datablock for safe landing */
2470 nextblock = buf[0] = 0;
2473 prg_exit(EXIT_FAILURE);
2477 while (!nextblock) { /* this is a new block */
2478 if (in_buffer < sizeof(VocBlockType))
2480 bp = (VocBlockType *) data;
2481 COUNT1(sizeof(VocBlockType));
2482 nextblock = VOC_DATALEN(bp);
2483 if (output && !quiet_mode)
2484 fprintf(stderr, "\n"); /* write /n after ASCII-out */
2489 d_printf("Terminator\n");
2491 return; /* VOC-file stop */
2493 vd = (VocVoiceData *) data;
2494 COUNT1(sizeof(VocVoiceData));
2495 /* we need a SYNC, before we can set new SPEED, STEREO ... */
2497 if (!was_extended) {
2498 hwparams.rate = (int) (vd->tc);
2499 hwparams.rate = 1000000 / (256 - hwparams.rate);
2501 d_printf("Channel data %d Hz\n", dsp_speed);
2503 if (vd->pack) { /* /dev/dsp can't it */
2504 error(_("can't play packed .voc files"));
2507 if (hwparams.channels == 2) /* if we are in Stereo-Mode, switch back */
2508 hwparams.channels = 1;
2509 } else { /* there was extended block */
2510 hwparams.channels = 2;
2515 case 2: /* nothing to do, pure data */
2517 d_printf("Channel continuation\n");
2520 case 3: /* a silence block, no data, only a count */
2521 sp = (uint16_t *) data;
2522 COUNT1(sizeof(uint16_t));
2523 hwparams.rate = (int) (*data);
2525 hwparams.rate = 1000000 / (256 - hwparams.rate);
2530 silence = (((size_t) * sp) * 1000) / hwparams.rate;
2531 d_printf("Silence for %d ms\n", (int) silence);
2534 voc_write_silence(*sp);
2536 case 4: /* a marker for syncronisation, no effect */
2537 sp = (uint16_t *) data;
2538 COUNT1(sizeof(uint16_t));
2540 d_printf("Marker %d\n", *sp);
2543 case 5: /* ASCII text, we copy to stderr */
2546 d_printf("ASCII - text :\n");
2549 case 6: /* repeat marker, says repeatcount */
2550 /* my specs don't say it: maybe this can be recursive, but
2551 I don't think somebody use it */
2552 repeat = *(uint16_t *) data;
2553 COUNT1(sizeof(uint16_t));
2555 d_printf("Repeat loop %d times\n", repeat);
2557 if (filepos >= 0) { /* if < 0, one seek fails, why test another */
2558 if ((filepos = lseek(fd, 0, 1)) < 0) {
2559 error(_("can't play loops; %s isn't seekable\n"), name);
2562 filepos -= in_buffer; /* set filepos after repeat */
2568 case 7: /* ok, lets repeat that be rewinding tape */
2570 if (repeat != 0xFFFF) {
2572 d_printf("Repeat loop %d\n", repeat);
2578 d_printf("Neverending loop\n");
2580 lseek(fd, filepos, 0);
2581 in_buffer = 0; /* clear the buffer */
2582 goto Fill_the_buffer;
2586 d_printf("End repeat loop\n");
2589 case 8: /* the extension to play Stereo, I have SB 1.0 :-( */
2591 eb = (VocExtBlock *) data;
2592 COUNT1(sizeof(VocExtBlock));
2593 hwparams.rate = (int) (eb->tc);
2594 hwparams.rate = 256000000L / (65536 - hwparams.rate);
2595 hwparams.channels = eb->mode == VOC_MODE_STEREO ? 2 : 1;
2596 if (hwparams.channels == 2)
2597 hwparams.rate = hwparams.rate >> 1;
2598 if (eb->pack) { /* /dev/dsp can't it */
2599 error(_("can't play packed .voc files"));
2603 d_printf("Extended block %s %d Hz\n",
2604 (eb->mode ? "Stereo" : "Mono"), dsp_speed);
2608 error(_("unknown blocktype %d. terminate."), bp->type);
2610 } /* switch (bp->type) */
2611 } /* while (! nextblock) */
2612 /* put nextblock data bytes to dsp */
2614 if (nextblock < (size_t)l)
2617 if (output && !quiet_mode) {
2618 if (xwrite(2, data, l) != l) { /* to stderr */
2619 error(_("write error"));
2620 prg_exit(EXIT_FAILURE);
2623 if (voc_pcm_write(data, l) != l) {
2624 error(_("write error"));
2625 prg_exit(EXIT_FAILURE);
2637 /* that was a big one, perhaps somebody split it :-) */
2639 /* setting the globals for playing raw data */
2640 static void init_raw_data(void)
2642 hwparams = rhwparams;
2645 /* calculate the data count to read from/to dsp */
2646 static off_t calc_count(void)
2651 if (sampleslimit == 0)
2652 count = pbrec_count;
2654 count = snd_pcm_format_size(hwparams.format, sampleslimit * hwparams.channels);
2656 count = snd_pcm_format_size(hwparams.format, hwparams.rate * hwparams.channels);
2657 count *= (off_t)timelimit;
2659 return count < pbrec_count ? count : pbrec_count;
2662 /* write a .VOC-header */
2663 static void begin_voc(int fd, size_t cnt)
2670 memcpy(vh.magic, VOC_MAGIC_STRING, 20);
2671 vh.headerlen = LE_SHORT(sizeof(VocHeader));
2672 vh.version = LE_SHORT(VOC_ACTUAL_VERSION);
2673 vh.coded_ver = LE_SHORT(0x1233 - VOC_ACTUAL_VERSION);
2675 if (xwrite(fd, &vh, sizeof(VocHeader)) != sizeof(VocHeader)) {
2676 error(_("write error"));
2677 prg_exit(EXIT_FAILURE);
2679 if (hwparams.channels > 1) {
2680 /* write an extended block */
2683 bt.datalen_m = bt.datalen_h = 0;
2684 if (xwrite(fd, &bt, sizeof(VocBlockType)) != sizeof(VocBlockType)) {
2685 error(_("write error"));
2686 prg_exit(EXIT_FAILURE);
2688 eb.tc = LE_SHORT(65536 - 256000000L / (hwparams.rate << 1));
2691 if (xwrite(fd, &eb, sizeof(VocExtBlock)) != sizeof(VocExtBlock)) {
2692 error(_("write error"));
2693 prg_exit(EXIT_FAILURE);
2697 cnt += sizeof(VocVoiceData); /* Channel_data block follows */
2698 bt.datalen = (uint8_t) (cnt & 0xFF);
2699 bt.datalen_m = (uint8_t) ((cnt & 0xFF00) >> 8);
2700 bt.datalen_h = (uint8_t) ((cnt & 0xFF0000) >> 16);
2701 if (xwrite(fd, &bt, sizeof(VocBlockType)) != sizeof(VocBlockType)) {
2702 error(_("write error"));
2703 prg_exit(EXIT_FAILURE);
2705 vd.tc = (uint8_t) (256 - (1000000 / hwparams.rate));
2707 if (xwrite(fd, &vd, sizeof(VocVoiceData)) != sizeof(VocVoiceData)) {
2708 error(_("write error"));
2709 prg_exit(EXIT_FAILURE);
2713 /* write a WAVE-header */
2714 static void begin_wave(int fd, size_t cnt)
2718 WaveChunkHeader cf, cd;
2719 int width, physical_width;
2723 /* WAVE cannot handle greater than 32bit (signed?) int */
2724 if (cnt == (size_t)-2)
2727 width = snd_pcm_format_physical_width(hwparams.format);
2728 physical_width = snd_pcm_format_width(hwparams.format);
2730 if (width < 0 || physical_width < 0)
2733 switch ((unsigned long) hwparams.format) {
2734 case SND_PCM_FORMAT_U8:
2735 case SND_PCM_FORMAT_S16_LE:
2736 case SND_PCM_FORMAT_S24_LE: /* S24_LE is 24 bits stored in 32 bit width with 8 bit padding */
2737 case SND_PCM_FORMAT_S32_LE:
2738 case SND_PCM_FORMAT_FLOAT_LE:
2739 case SND_PCM_FORMAT_S24_3LE:
2743 error(_("Wave doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2744 prg_exit(EXIT_FAILURE);
2747 tmp = cnt + sizeof(WaveHeader) + sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + sizeof(WaveChunkHeader) - 8;
2748 h.length = LE_INT(tmp);
2752 cf.length = LE_INT(16);
2754 if (hwparams.format == SND_PCM_FORMAT_FLOAT_LE)
2755 f.format = LE_SHORT(WAV_FMT_IEEE_FLOAT);
2757 f.format = LE_SHORT(WAV_FMT_PCM);
2758 f.channels = LE_SHORT(hwparams.channels);
2759 f.sample_fq = LE_INT(hwparams.rate);
2760 tmp2 = hwparams.channels * physical_width / 8;
2761 f.byte_p_spl = LE_SHORT(tmp2);
2762 tmp = (uint32_t) tmp2 * hwparams.rate;
2763 f.byte_p_sec = LE_INT(tmp);
2764 f.bit_p_spl = LE_SHORT(width);
2767 cd.length = LE_INT(cnt);
2769 if (xwrite(fd, &h, sizeof(WaveHeader)) != sizeof(WaveHeader) ||
2770 xwrite(fd, &cf, sizeof(WaveChunkHeader)) != sizeof(WaveChunkHeader) ||
2771 xwrite(fd, &f, sizeof(WaveFmtBody)) != sizeof(WaveFmtBody) ||
2772 xwrite(fd, &cd, sizeof(WaveChunkHeader)) != sizeof(WaveChunkHeader)) {
2773 error(_("write error"));
2774 prg_exit(EXIT_FAILURE);
2778 /* write a Au-header */
2779 static void begin_au(int fd, size_t cnt)
2783 ah.magic = AU_MAGIC;
2784 ah.hdr_size = BE_INT(24);
2785 ah.data_size = BE_INT(cnt);
2786 switch ((unsigned long) hwparams.format) {
2787 case SND_PCM_FORMAT_MU_LAW:
2788 ah.encoding = BE_INT(AU_FMT_ULAW);
2790 case SND_PCM_FORMAT_U8:
2791 ah.encoding = BE_INT(AU_FMT_LIN8);
2793 case SND_PCM_FORMAT_S16_BE:
2794 ah.encoding = BE_INT(AU_FMT_LIN16);
2796 case SND_PCM_FORMAT_A_LAW:
2797 ah.encoding = BE_INT(AU_FMT_ALAW);
2800 error(_("Sparc Audio doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2801 prg_exit(EXIT_FAILURE);
2803 ah.sample_rate = BE_INT(hwparams.rate);
2804 ah.channels = BE_INT(hwparams.channels);
2805 if (xwrite(fd, &ah, sizeof(AuHeader)) != sizeof(AuHeader)) {
2806 error(_("write error"));
2807 prg_exit(EXIT_FAILURE);
2812 static void end_voc(int fd)
2817 char dummy = 0; /* Write a Terminator */
2819 if (xwrite(fd, &dummy, 1) != 1) {
2820 error(_("write error"));
2821 prg_exit(EXIT_FAILURE);
2823 length_seek = sizeof(VocHeader);
2824 if (hwparams.channels > 1)
2825 length_seek += sizeof(VocBlockType) + sizeof(VocExtBlock);
2828 cnt += sizeof(VocVoiceData); /* Channel_data block follows */
2829 if (cnt > 0x00ffffff)
2831 bt.datalen = (uint8_t) (cnt & 0xFF);
2832 bt.datalen_m = (uint8_t) ((cnt & 0xFF00) >> 8);
2833 bt.datalen_h = (uint8_t) ((cnt & 0xFF0000) >> 16);
2834 if (lseek(fd, length_seek, SEEK_SET) == length_seek)
2835 xwrite(fd, &bt, sizeof(VocBlockType));
2838 static void end_wave(int fd)
2839 { /* only close output */
2845 length_seek = sizeof(WaveHeader) +
2846 sizeof(WaveChunkHeader) +
2847 sizeof(WaveFmtBody);
2849 cd.length = fdcount > 0x7fffffff ? LE_INT(0x7fffffff) : LE_INT(fdcount);
2850 filelen = fdcount + 2*sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + 4;
2851 rifflen = filelen > 0x7fffffff ? LE_INT(0x7fffffff) : LE_INT(filelen);
2852 if (lseek(fd, 4, SEEK_SET) == 4)
2853 xwrite(fd, &rifflen, 4);
2854 if (lseek(fd, length_seek, SEEK_SET) == length_seek)
2855 xwrite(fd, &cd, sizeof(WaveChunkHeader));
2858 static void end_au(int fd)
2859 { /* only close output */
2863 length_seek = (char *)&ah.data_size - (char *)&ah;
2864 ah.data_size = fdcount > 0xffffffff ? 0xffffffff : BE_INT(fdcount);
2865 if (lseek(fd, length_seek, SEEK_SET) == length_seek)
2866 xwrite(fd, &ah.data_size, sizeof(ah.data_size));
2869 static void header(int rtype, char *name)
2873 name = (stream == SND_PCM_STREAM_PLAYBACK) ? "stdout" : "stdin";
2874 fprintf(stderr, "%s %s '%s' : ",
2875 (stream == SND_PCM_STREAM_PLAYBACK) ? _("Playing") : _("Recording"),
2876 gettext(fmt_rec_table[rtype].what),
2878 fprintf(stderr, "%s, ", snd_pcm_format_description(hwparams.format));
2879 fprintf(stderr, _("Rate %d Hz, "), hwparams.rate);
2880 if (hwparams.channels == 1)
2881 fprintf(stderr, _("Mono"));
2882 else if (hwparams.channels == 2)
2883 fprintf(stderr, _("Stereo"));
2885 fprintf(stderr, _("Channels %i"), hwparams.channels);
2886 fprintf(stderr, "\n");
2890 /* playing raw data */
2892 static void playback_go(int fd, size_t loaded, off_t count, int rtype, char *name)
2898 header(rtype, name);
2901 while (loaded > chunk_bytes && written < count && !in_aborting) {
2902 if (pcm_write(audiobuf + written, chunk_size) <= 0)
2904 written += chunk_bytes;
2905 loaded -= chunk_bytes;
2907 if (written > 0 && loaded > 0)
2908 memmove(audiobuf, audiobuf + written, loaded);
2911 while (written < count && !in_aborting) {
2913 c = count - written;
2914 if (c > (off_t)chunk_bytes)
2917 /* c < l, there is more data loaded
2918 * then we actually need to write
2927 r = safe_read(fd, audiobuf + l, c);
2930 prg_exit(EXIT_FAILURE);
2936 } while ((size_t)l < chunk_bytes);
2937 l = l * 8 / bits_per_frame;
2938 r = pcm_write(audiobuf, l);
2941 r = r * bits_per_frame / 8;
2946 snd_pcm_nonblock(handle, 0);
2947 snd_pcm_drain(handle);
2948 snd_pcm_nonblock(handle, nonblock);
2952 static int read_header(int *loaded, int header_size)
2957 ret = fstat(fd, &buf);
2960 prg_exit(EXIT_FAILURE);
2963 /* don't be adventurous, get out if file size is smaller than
2964 * requested header size */
2965 if ((buf.st_mode & S_IFMT) == S_IFREG &&
2966 buf.st_size < header_size)
2969 if (*loaded < header_size) {
2970 header_size -= *loaded;
2971 ret = safe_read(fd, audiobuf + *loaded, header_size);
2972 if (ret != header_size) {
2973 error(_("read error"));
2974 prg_exit(EXIT_FAILURE);
2976 *loaded += header_size;
2981 static int playback_au(char *name, int *loaded)
2983 if (read_header(loaded, sizeof(AuHeader)) < 0)
2986 if (test_au(fd, audiobuf) < 0)
2989 rhwparams.format = hwparams.format;
2990 pbrec_count = calc_count();
2991 playback_go(fd, *loaded - sizeof(AuHeader), pbrec_count, FORMAT_AU, name);
2996 static int playback_voc(char *name, int *loaded)
3000 if (read_header(loaded, sizeof(VocHeader)) < 0)
3003 if ((ofs = test_vocfile(audiobuf)) < 0)
3006 pbrec_count = calc_count();
3007 voc_play(fd, ofs, name);
3012 static int playback_wave(char *name, int *loaded)
3016 if (read_header(loaded, sizeof(WaveHeader)) < 0)
3019 if ((dtawave = test_wavefile(fd, audiobuf, *loaded)) < 0)
3022 pbrec_count = calc_count();
3023 playback_go(fd, dtawave, pbrec_count, FORMAT_WAVE, name);
3028 static int playback_raw(char *name, int *loaded)
3031 pbrec_count = calc_count();
3032 playback_go(fd, *loaded, pbrec_count, FORMAT_RAW, name);
3038 * let's play or capture it (capture_type says VOC/WAVE/raw)
3041 static void playback(char *name)
3045 pbrec_count = LLONG_MAX;
3047 if (!name || !strcmp(name, "-")) {
3052 if ((fd = open(name, O_RDONLY, 0)) == -1) {
3054 prg_exit(EXIT_FAILURE);
3060 playback_au(name, &loaded);
3063 playback_voc(name, &loaded);
3066 playback_wave(name, &loaded);
3069 playback_raw(name, &loaded);
3072 /* parse the file header */
3073 if (playback_au(name, &loaded) < 0 &&
3074 playback_voc(name, &loaded) < 0 &&
3075 playback_wave(name, &loaded) < 0)
3076 playback_raw(name, &loaded); /* should be raw data */
3080 if (fd != fileno(stdin))
3087 * Variant of strftime(3) that supports additional format
3088 * specifiers in the format string.
3092 * s - destination string
3093 * max - max number of bytes to write
3094 * userformat - format string
3095 * tm - time information
3096 * filenumber - the number of the file, starting at 1
3098 * Returns: number of bytes written to the string s
3100 size_t mystrftime(char *s, size_t max, const char *userformat,
3101 const struct tm *tm, const int filenumber)
3103 char formatstring[PATH_MAX] = "";
3104 char tempstring[PATH_MAX] = "";
3105 char *format, *tempstr;
3106 const char *pos_userformat;
3108 format = formatstring;
3110 /* if mystrftime is called with userformat = NULL we return a zero length string */
3111 if (userformat == NULL) {
3116 for (pos_userformat = userformat; *pos_userformat; ++pos_userformat) {
3117 if (*pos_userformat == '%') {
3118 tempstr = tempstring;
3120 switch (*++pos_userformat) {
3122 case '\0': // end of string
3126 case 'v': // file number
3127 sprintf(tempstr, "%02d", filenumber);
3130 default: // All other codes will be handled by strftime
3132 *format++ = *pos_userformat;
3136 /* If a format specifier was found and used, copy the result. */
3138 while ((*format = *tempstr++) != '\0')
3144 /* For any other character than % we simply copy the character */
3145 *format++ = *pos_userformat;
3149 format = formatstring;
3150 return strftime(s, max, format, tm);
3153 static int new_capture_file(char *name, char *namebuf, size_t namelen,
3157 char buf[PATH_MAX-10];
3163 tmp = localtime(&t);
3165 perror("localtime");
3166 prg_exit(EXIT_FAILURE);
3168 if (mystrftime(namebuf, namelen, name, tmp, filecount+1) == 0) {
3169 fprintf(stderr, "mystrftime returned 0");
3170 prg_exit(EXIT_FAILURE);
3175 /* get a copy of the original filename */
3176 strncpy(buf, name, sizeof(buf));
3177 buf[sizeof(buf)-1] = '\0';
3179 /* separate extension from filename */
3180 s = buf + strlen(buf);
3181 while (s > buf && *s != '.' && *s != '/')
3186 s = buf + strlen(buf);
3188 /* upon first jump to this if block rename the first file */
3189 if (filecount == 1) {
3191 snprintf(namebuf, namelen, "%s-01.%s", buf, s);
3193 snprintf(namebuf, namelen, "%s-01", buf);
3195 rename(name, namebuf);
3199 /* name of the current file */
3201 snprintf(namebuf, namelen, "%s-%02i.%s", buf, filecount, s);
3203 snprintf(namebuf, namelen, "%s-%02i", buf, filecount);
3211 * This function creates a file path, like mkdir -p.
3215 * path - the path to create
3217 * Returns: 0 on success, -1 on failure
3218 * On failure, a message has been printed to stderr.
3220 int create_path(const char *path)
3223 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
3226 start = strchr(path + 1, '/');
3228 start = strchr(path, '/');
3231 char *buffer = strdup(path);
3232 buffer[start-path] = 0x00;
3234 if (mkdir(buffer, mode) == -1 && errno != EEXIST) {
3235 fprintf(stderr, "Problem creating directory %s", buffer);
3241 start = strchr(start + 1, '/');
3246 static int safe_open(const char *name)
3250 fd = open(name, O_WRONLY | O_CREAT, 0644);
3252 if (errno != ENOENT || !use_strftime)
3254 if (create_path(name) == 0)
3255 fd = open(name, O_WRONLY | O_CREAT, 0644);
3260 static void capture(char *orig_name)
3262 int tostdout=0; /* boolean which describes output stream */
3263 int filecount=0; /* number of files written */
3264 char *name = orig_name; /* current filename */
3265 char namebuf[PATH_MAX+2];
3266 off_t count, rest; /* number of bytes to capture */
3267 struct stat statbuf;
3269 /* setup sound hardware */
3272 /* get number of bytes to capture */
3273 count = calc_count();
3276 /* compute the number of bytes per file */
3277 max_file_size = (long long) max_file_time *
3278 snd_pcm_format_size(hwparams.format,
3279 hwparams.rate * hwparams.channels);
3280 /* WAVE-file should be even (I'm not sure), but wasting one byte
3281 isn't a problem (this can only be in 8 bit mono) */
3282 if (count < LLONG_MAX)
3287 /* display verbose output to console */
3288 header(file_type, name);
3290 /* write to stdout? */
3291 if (!name || !strcmp(name, "-")) {
3292 fd = fileno(stdout);
3295 if (count > fmt_rec_table[file_type].max_filesize)
3296 count = fmt_rec_table[file_type].max_filesize;
3301 /* open a file to write */
3303 /* upon the second file we start the numbering scheme */
3304 if (filecount || use_strftime) {
3305 filecount = new_capture_file(orig_name, namebuf,
3311 /* open a new file */
3312 if (!lstat(name, &statbuf)) {
3313 if (S_ISREG(statbuf.st_mode))
3316 fd = safe_open(name);
3319 prg_exit(EXIT_FAILURE);
3325 if (rest > fmt_rec_table[file_type].max_filesize)
3326 rest = fmt_rec_table[file_type].max_filesize;
3327 if (max_file_size && (rest > max_file_size))
3328 rest = max_file_size;
3330 /* setup sample header */
3331 if (fmt_rec_table[file_type].start)
3332 fmt_rec_table[file_type].start(fd, rest);
3336 while (rest > 0 && recycle_capture_file == 0 && !in_aborting) {
3337 size_t c = (rest <= (off_t)chunk_bytes) ?
3338 (size_t)rest : chunk_bytes;
3339 size_t f = c * 8 / bits_per_frame;
3340 size_t read = pcm_read(audiobuf, f);
3344 save = read * bits_per_frame / 8;
3345 if (xwrite(fd, audiobuf, save) != (ssize_t)save) {
3355 /* re-enable SIGUSR1 signal */
3356 if (recycle_capture_file) {
3357 recycle_capture_file = 0;
3358 signal(SIGUSR1, signal_handler_recycle);
3361 /* finish sample container */
3363 if (fmt_rec_table[file_type].end)
3364 fmt_rec_table[file_type].end(fd);
3370 prg_exit(EXIT_FAILURE);
3372 /* repeat the loop when format is raw without timelimit or
3373 * requested counts of data are recorded
3375 } while ((file_type == FORMAT_RAW && !timelimit && !sampleslimit) || count > 0);
3378 static void playbackv_go(int* fds, unsigned int channels, size_t loaded, off_t count, int rtype, char **names)
3383 unsigned int channel;
3384 uint8_t *bufs[channels];
3386 header(rtype, names[0]);
3389 vsize = chunk_bytes / channels;
3391 // Not yet implemented
3392 assert(loaded == 0);
3394 for (channel = 0; channel < channels; ++channel)
3395 bufs[channel] = audiobuf + vsize * channel;
3397 while (count > 0 && !in_aborting) {
3399 size_t expected = count / channels;
3400 if (expected > vsize)
3403 r = safe_read(fds[0], bufs[0], expected);
3406 prg_exit(EXIT_FAILURE);
3408 for (channel = 1; channel < channels; ++channel) {
3409 if (safe_read(fds[channel], bufs[channel], r) != r) {
3410 perror(names[channel]);
3411 prg_exit(EXIT_FAILURE);
3417 } while (c < expected);
3418 c = c * 8 / bits_per_sample;
3419 r = pcm_writev(bufs, channels, c);
3422 r = r * bits_per_frame / 8;
3426 snd_pcm_nonblock(handle, 0);
3427 snd_pcm_drain(handle);
3428 snd_pcm_nonblock(handle, nonblock);
3432 static void capturev_go(int* fds, unsigned int channels, off_t count, int rtype, char **names)
3436 unsigned int channel;
3438 uint8_t *bufs[channels];
3440 header(rtype, names[0]);
3443 vsize = chunk_bytes / channels;
3445 for (channel = 0; channel < channels; ++channel)
3446 bufs[channel] = audiobuf + vsize * channel;
3448 while (count > 0 && !in_aborting) {
3451 if (c > chunk_bytes)
3453 c = c * 8 / bits_per_frame;
3454 if ((size_t)(r = pcm_readv(bufs, channels, c)) != c)
3456 rv = r * bits_per_sample / 8;
3457 for (channel = 0; channel < channels; ++channel) {
3458 if ((size_t)xwrite(fds[channel], bufs[channel], rv) != rv) {
3459 perror(names[channel]);
3460 prg_exit(EXIT_FAILURE);
3463 r = r * bits_per_frame / 8;
3469 static void playbackv(char **names, unsigned int count)
3472 unsigned int channel;
3473 unsigned int channels = rhwparams.channels;
3476 for (channel = 0; channel < channels; ++channel)
3479 if (count == 1 && channels > 1) {
3480 size_t len = strlen(names[0]);
3482 strcpy(buf, names[0]);
3483 /* 1 for "." + 3 for channel (<= 256) + 1 for null terminator */
3485 names = malloc(sizeof(*names) * channels);
3486 for (channel = 0; channel < channels; ++channel) {
3487 names[channel] = malloc(len);
3488 snprintf(names[channel], len, "%s.%d", buf, channel);
3491 } else if (count != channels) {
3492 error(_("You need to specify %u files"), channels);
3493 prg_exit(EXIT_FAILURE);
3496 for (channel = 0; channel < channels; ++channel) {
3497 fds[channel] = open(names[channel], O_RDONLY, 0);
3498 if (fds[channel] < 0) {
3499 perror(names[channel]);
3504 /* should be raw data */
3506 pbrec_count = calc_count();
3507 playbackv_go(fds, channels, 0, pbrec_count, FORMAT_RAW, names);
3510 for (channel = 0; channel < channels; ++channel) {
3511 if (fds[channel] >= 0)
3512 close(fds[channel]);
3514 free(names[channel]);
3522 static void capturev(char **names, unsigned int count)
3525 unsigned int channel;
3526 unsigned int channels = rhwparams.channels;
3529 for (channel = 0; channel < channels; ++channel)
3533 size_t len = strlen(names[0]);
3535 strcpy(buf, names[0]);
3536 /* 1 for "." + 3 for channel (<= 256) + 1 for null terminator */
3538 names = malloc(sizeof(*names) * channels);
3539 for (channel = 0; channel < channels; ++channel) {
3540 names[channel] = malloc(len);
3541 snprintf(names[channel], len, "%s.%d", buf, channel);
3544 } else if (count != channels) {
3545 error(_("You need to specify %d files"), channels);
3546 prg_exit(EXIT_FAILURE);
3549 for (channel = 0; channel < channels; ++channel) {
3550 fds[channel] = open(names[channel], O_WRONLY + O_CREAT, 0644);
3551 if (fds[channel] < 0) {
3552 perror(names[channel]);
3557 /* should be raw data */
3559 pbrec_count = calc_count();
3560 capturev_go(fds, channels, pbrec_count, FORMAT_RAW, names);
3563 for (channel = 0; channel < channels; ++channel) {
3564 if (fds[channel] >= 0)
3565 close(fds[channel]);
3567 free(names[channel]);