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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
42 #include <alsa/asoundlib.h>
50 #include <sys/types.h>
57 #ifdef SND_CHMAP_API_VERSION
58 #define CONFIG_SUPPORT_CHMAP 1
62 #define LLONG_MAX 9223372036854775807LL
66 #include <asm/byteorder.h>
67 #define le16toh(x) __le16_to_cpu(x)
68 #define be16toh(x) __be16_to_cpu(x)
69 #define le32toh(x) __le32_to_cpu(x)
70 #define be32toh(x) __be32_to_cpu(x)
73 #define DEFAULT_FORMAT SND_PCM_FORMAT_U8
74 #define DEFAULT_SPEED 8000
76 #define FORMAT_DEFAULT -1
84 static snd_pcm_sframes_t (*readi_func)(snd_pcm_t *handle, void *buffer, snd_pcm_uframes_t size);
85 static snd_pcm_sframes_t (*writei_func)(snd_pcm_t *handle, const void *buffer, snd_pcm_uframes_t size);
86 static snd_pcm_sframes_t (*readn_func)(snd_pcm_t *handle, void **bufs, snd_pcm_uframes_t size);
87 static snd_pcm_sframes_t (*writen_func)(snd_pcm_t *handle, void **bufs, snd_pcm_uframes_t size);
96 static snd_pcm_t *handle;
98 snd_pcm_format_t format;
99 unsigned int channels;
101 } hwparams, rhwparams;
102 static int timelimit = 0;
103 static int quiet_mode = 0;
104 static int file_type = FORMAT_DEFAULT;
105 static int open_mode = 0;
106 static snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
107 static int mmap_flag = 0;
108 static int interleaved = 1;
109 static int nonblock = 0;
110 static int in_aborting = 0;
111 static u_char *audiobuf = NULL;
112 static snd_pcm_uframes_t chunk_size = 0;
113 static unsigned period_time = 0;
114 static unsigned buffer_time = 0;
115 static snd_pcm_uframes_t period_frames = 0;
116 static snd_pcm_uframes_t buffer_frames = 0;
117 static int avail_min = -1;
118 static int start_delay = 0;
119 static int stop_delay = 0;
120 static int monotonic = 0;
121 static int interactive = 0;
122 static int can_pause = 0;
123 static int fatal_errors = 0;
124 static int verbose = 0;
125 static int vumeter = VUMETER_NONE;
126 static int buffer_pos = 0;
127 static size_t bits_per_sample, bits_per_frame;
128 static size_t chunk_bytes;
129 static int test_position = 0;
130 static int test_coef = 8;
131 static int test_nowait = 0;
132 static snd_output_t *log;
133 static long long max_file_size = 0;
134 static int max_file_time = 0;
135 static int use_strftime = 0;
136 volatile static int recycle_capture_file = 0;
137 static long term_c_lflag = -1;
138 static int dump_hw_params = 0;
141 static off64_t pbrec_count = LLONG_MAX, fdcount;
142 static int vocmajor, vocminor;
144 static char *pidfile_name = NULL;
146 static int pidfile_written = 0;
148 #ifdef CONFIG_SUPPORT_CHMAP
149 static snd_pcm_chmap_t *channel_map = NULL; /* chmap to override */
150 static unsigned int *hw_map = NULL; /* chmap to follow */
153 /* needed prototypes */
155 static void done_stdin(void);
157 static void playback(char *filename);
158 static void capture(char *filename);
159 static void playbackv(char **filenames, unsigned int count);
160 static void capturev(char **filenames, unsigned int count);
162 static void begin_voc(int fd, size_t count);
163 static void end_voc(int fd);
164 static void begin_wave(int fd, size_t count);
165 static void end_wave(int fd);
166 static void begin_au(int fd, size_t count);
167 static void end_au(int fd);
169 static const struct fmt_capture {
170 void (*start) (int fd, size_t count);
171 void (*end) (int fd);
173 long long max_filesize;
174 } fmt_rec_table[] = {
175 { NULL, NULL, N_("raw data"), LLONG_MAX },
176 { begin_voc, end_voc, N_("VOC"), 16000000LL },
177 /* FIXME: can WAV handle exactly 2GB or less than it? */
178 { begin_wave, end_wave, N_("WAVE"), 2147483648LL },
179 { begin_au, end_au, N_("Sparc Audio"), LLONG_MAX }
182 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
183 #define error(...) do {\
184 fprintf(stderr, "%s: %s:%d: ", command, __FUNCTION__, __LINE__); \
185 fprintf(stderr, __VA_ARGS__); \
186 putc('\n', stderr); \
189 #define error(args...) do {\
190 fprintf(stderr, "%s: %s:%d: ", command, __FUNCTION__, __LINE__); \
191 fprintf(stderr, ##args); \
192 putc('\n', stderr); \
196 static void usage(char *command)
200 _("Usage: %s [OPTION]... [FILE]...\n"
203 " --version print current version\n"
204 "-l, --list-devices list all soundcards and digital audio devices\n"
205 "-L, --list-pcms list device names\n"
206 "-D, --device=NAME select PCM by name\n"
207 "-q, --quiet quiet mode\n"
208 "-t, --file-type TYPE file type (voc, wav, raw or au)\n"
209 "-c, --channels=# channels\n"
210 "-f, --format=FORMAT sample format (case insensitive)\n"
211 "-r, --rate=# sample rate\n"
212 "-d, --duration=# interrupt after # seconds\n"
213 "-M, --mmap mmap stream\n"
214 "-N, --nonblock nonblocking mode\n"
215 "-F, --period-time=# distance between interrupts is # microseconds\n"
216 "-B, --buffer-time=# buffer duration is # microseconds\n"
217 " --period-size=# distance between interrupts is # frames\n"
218 " --buffer-size=# buffer duration is # frames\n"
219 "-A, --avail-min=# min available space for wakeup is # microseconds\n"
220 "-R, --start-delay=# delay for automatic PCM start is # microseconds \n"
221 " (relative to buffer size if <= 0)\n"
222 "-T, --stop-delay=# delay for automatic PCM stop is # microseconds from xrun\n"
223 "-v, --verbose show PCM structure and setup (accumulative)\n"
224 "-V, --vumeter=TYPE enable VU meter (TYPE: mono or stereo)\n"
225 "-I, --separate-channels one file for each channel\n"
226 "-i, --interactive allow interactive operation from stdin\n"
227 "-m, --chmap=ch1,ch2,.. Give the channel map to override or follow\n"
228 " --disable-resample disable automatic rate resample\n"
229 " --disable-channels disable automatic channel conversions\n"
230 " --disable-format disable automatic format conversions\n"
231 " --disable-softvol disable software volume control (softvol)\n"
232 " --test-position test ring buffer position\n"
233 " --test-coef=# test coefficient for ring buffer position (default 8)\n"
234 " expression for validation is: coef * (buffer_size / 2)\n"
235 " --test-nowait do not wait for ring buffer - eats whole CPU\n"
236 " --max-file-time=# start another output file when the old file has recorded\n"
237 " for this many seconds\n"
238 " --process-id-file write the process ID here\n"
239 " --use-strftime apply the strftime facility to the output file name\n"
240 " --dump-hw-params dump hw_params of the device\n"
241 " --fatal-errors treat all errors as fatal\n"
244 printf(_("Recognized sample formats are:"));
245 for (k = 0; k <= SND_PCM_FORMAT_LAST; ++k) {
246 const char *s = snd_pcm_format_name(k);
250 printf(_("\nSome of these may not be available on selected hardware\n"));
251 printf(_("The available format shortcuts are:\n"));
252 printf(_("-f cd (16 bit little endian, 44100, stereo)\n"));
253 printf(_("-f cdr (16 bit big endian, 44100, stereo)\n"));
254 printf(_("-f dat (16 bit little endian, 48000, stereo)\n"));
257 static void device_list(void)
260 int card, err, dev, idx;
261 snd_ctl_card_info_t *info;
262 snd_pcm_info_t *pcminfo;
263 snd_ctl_card_info_alloca(&info);
264 snd_pcm_info_alloca(&pcminfo);
267 if (snd_card_next(&card) < 0 || card < 0) {
268 error(_("no soundcards found..."));
271 printf(_("**** List of %s Hardware Devices ****\n"),
272 snd_pcm_stream_name(stream));
275 sprintf(name, "hw:%d", card);
276 if ((err = snd_ctl_open(&handle, name, 0)) < 0) {
277 error("control open (%i): %s", card, snd_strerror(err));
280 if ((err = snd_ctl_card_info(handle, info)) < 0) {
281 error("control hardware info (%i): %s", card, snd_strerror(err));
282 snd_ctl_close(handle);
288 if (snd_ctl_pcm_next_device(handle, &dev)<0)
289 error("snd_ctl_pcm_next_device");
292 snd_pcm_info_set_device(pcminfo, dev);
293 snd_pcm_info_set_subdevice(pcminfo, 0);
294 snd_pcm_info_set_stream(pcminfo, stream);
295 if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
297 error("control digital audio info (%i): %s", card, snd_strerror(err));
300 printf(_("card %i: %s [%s], device %i: %s [%s]\n"),
301 card, snd_ctl_card_info_get_id(info), snd_ctl_card_info_get_name(info),
303 snd_pcm_info_get_id(pcminfo),
304 snd_pcm_info_get_name(pcminfo));
305 count = snd_pcm_info_get_subdevices_count(pcminfo);
306 printf( _(" Subdevices: %i/%i\n"),
307 snd_pcm_info_get_subdevices_avail(pcminfo), count);
308 for (idx = 0; idx < (int)count; idx++) {
309 snd_pcm_info_set_subdevice(pcminfo, idx);
310 if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) {
311 error("control digital audio playback info (%i): %s", card, snd_strerror(err));
313 printf(_(" Subdevice #%i: %s\n"),
314 idx, snd_pcm_info_get_subdevice_name(pcminfo));
318 snd_ctl_close(handle);
320 if (snd_card_next(&card) < 0) {
321 error("snd_card_next");
327 static void pcm_list(void)
330 char *name, *descr, *descr1, *io;
333 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
336 filter = stream == SND_PCM_STREAM_CAPTURE ? "Input" : "Output";
338 name = snd_device_name_get_hint(*n, "NAME");
339 descr = snd_device_name_get_hint(*n, "DESC");
340 io = snd_device_name_get_hint(*n, "IOID");
341 if (io != NULL && strcmp(io, filter) != 0)
343 printf("%s\n", name);
344 if ((descr1 = descr) != NULL) {
364 snd_device_name_free_hint(hints);
367 static void version(void)
369 printf("%s: version " SND_UTIL_VERSION_STR " by Jaroslav Kysela <perex@perex.cz>\n", command);
373 * Subroutine to clean up before exit.
375 static void prg_exit(int code)
379 snd_pcm_close(handle);
381 remove (pidfile_name);
385 static void signal_handler(int sig)
394 fprintf(stderr, _("Aborted by signal %s...\n"), strsignal(sig));
396 snd_pcm_abort(handle);
397 if (sig == SIGABRT) {
398 /* do not call snd_pcm_close() and abort immediately */
400 prg_exit(EXIT_FAILURE);
402 signal(sig, signal_handler);
405 /* call on SIGUSR1 signal. */
406 static void signal_handler_recycle (int sig)
408 /* flag the capture loop to start a new output file */
409 recycle_capture_file = 1;
416 OPT_DISABLE_RESAMPLE,
417 OPT_DISABLE_CHANNELS,
430 int main(int argc, char *argv[])
433 static const char short_options[] = "hnlLD:qt:c:f:r:d:MNF:A:R:T:B:vV:IPCi"
434 #ifdef CONFIG_SUPPORT_CHMAP
438 static const struct option long_options[] = {
440 {"version", 0, 0, OPT_VERSION},
441 {"list-devnames", 0, 0, 'n'},
442 {"list-devices", 0, 0, 'l'},
443 {"list-pcms", 0, 0, 'L'},
444 {"device", 1, 0, 'D'},
445 {"quiet", 0, 0, 'q'},
446 {"file-type", 1, 0, 't'},
447 {"channels", 1, 0, 'c'},
448 {"format", 1, 0, 'f'},
450 {"duration", 1, 0 ,'d'},
452 {"nonblock", 0, 0, 'N'},
453 {"period-time", 1, 0, 'F'},
454 {"period-size", 1, 0, OPT_PERIOD_SIZE},
455 {"avail-min", 1, 0, 'A'},
456 {"start-delay", 1, 0, 'R'},
457 {"stop-delay", 1, 0, 'T'},
458 {"buffer-time", 1, 0, 'B'},
459 {"buffer-size", 1, 0, OPT_BUFFER_SIZE},
460 {"verbose", 0, 0, 'v'},
461 {"vumeter", 1, 0, 'V'},
462 {"separate-channels", 0, 0, 'I'},
463 {"playback", 0, 0, 'P'},
464 {"capture", 0, 0, 'C'},
465 {"disable-resample", 0, 0, OPT_DISABLE_RESAMPLE},
466 {"disable-channels", 0, 0, OPT_DISABLE_CHANNELS},
467 {"disable-format", 0, 0, OPT_DISABLE_FORMAT},
468 {"disable-softvol", 0, 0, OPT_DISABLE_SOFTVOL},
469 {"test-position", 0, 0, OPT_TEST_POSITION},
470 {"test-coef", 1, 0, OPT_TEST_COEF},
471 {"test-nowait", 0, 0, OPT_TEST_NOWAIT},
472 {"max-file-time", 1, 0, OPT_MAX_FILE_TIME},
473 {"process-id-file", 1, 0, OPT_PROCESS_ID_FILE},
474 {"use-strftime", 0, 0, OPT_USE_STRFTIME},
475 {"interactive", 0, 0, 'i'},
476 {"dump-hw-params", 0, 0, OPT_DUMP_HWPARAMS},
477 {"fatal-errors", 0, 0, OPT_FATAL_ERRORS},
478 #ifdef CONFIG_SUPPORT_CHMAP
479 {"chmap", 1, 0, 'm'},
483 char *pcm_name = "default";
485 int do_device_list = 0, do_pcm_list = 0;
486 snd_pcm_info_t *info;
490 setlocale(LC_ALL, "");
494 snd_pcm_info_alloca(&info);
496 err = snd_output_stdio_attach(&log, stderr, 0);
500 file_type = FORMAT_DEFAULT;
501 if (strstr(argv[0], "arecord")) {
502 stream = SND_PCM_STREAM_CAPTURE;
503 file_type = FORMAT_WAVE;
507 } else if (strstr(argv[0], "aplay")) {
508 stream = SND_PCM_STREAM_PLAYBACK;
512 error(_("command should be named either arecord or aplay"));
516 if (isatty(fileno(direction)) && (argc == 1)) {
522 rhwparams.format = DEFAULT_FORMAT;
523 rhwparams.rate = DEFAULT_SPEED;
524 rhwparams.channels = 1;
526 while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) {
547 if (strcasecmp(optarg, "raw") == 0)
548 file_type = FORMAT_RAW;
549 else if (strcasecmp(optarg, "voc") == 0)
550 file_type = FORMAT_VOC;
551 else if (strcasecmp(optarg, "wav") == 0)
552 file_type = FORMAT_WAVE;
553 else if (strcasecmp(optarg, "au") == 0 || strcasecmp(optarg, "sparc") == 0)
554 file_type = FORMAT_AU;
556 error(_("unrecognized file format %s"), optarg);
561 rhwparams.channels = strtol(optarg, NULL, 0);
562 if (rhwparams.channels < 1 || rhwparams.channels > 256) {
563 error(_("value %i for channels is invalid"), rhwparams.channels);
568 if (strcasecmp(optarg, "cd") == 0 || strcasecmp(optarg, "cdr") == 0) {
569 if (strcasecmp(optarg, "cdr") == 0)
570 rhwparams.format = SND_PCM_FORMAT_S16_BE;
572 rhwparams.format = file_type == FORMAT_AU ? SND_PCM_FORMAT_S16_BE : SND_PCM_FORMAT_S16_LE;
573 rhwparams.rate = 44100;
574 rhwparams.channels = 2;
575 } else if (strcasecmp(optarg, "dat") == 0) {
576 rhwparams.format = file_type == FORMAT_AU ? SND_PCM_FORMAT_S16_BE : SND_PCM_FORMAT_S16_LE;
577 rhwparams.rate = 48000;
578 rhwparams.channels = 2;
580 rhwparams.format = snd_pcm_format_value(optarg);
581 if (rhwparams.format == SND_PCM_FORMAT_UNKNOWN) {
582 error(_("wrong extended format '%s'"), optarg);
583 prg_exit(EXIT_FAILURE);
588 tmp = strtol(optarg, NULL, 0);
591 rhwparams.rate = tmp;
592 if (tmp < 2000 || tmp > 192000) {
593 error(_("bad speed value %i"), tmp);
598 timelimit = strtol(optarg, NULL, 0);
602 open_mode |= SND_PCM_NONBLOCK;
605 period_time = strtol(optarg, NULL, 0);
608 buffer_time = strtol(optarg, NULL, 0);
610 case OPT_PERIOD_SIZE:
611 period_frames = strtol(optarg, NULL, 0);
613 case OPT_BUFFER_SIZE:
614 buffer_frames = strtol(optarg, NULL, 0);
617 avail_min = strtol(optarg, NULL, 0);
620 start_delay = strtol(optarg, NULL, 0);
623 stop_delay = strtol(optarg, NULL, 0);
627 if (verbose > 1 && !vumeter)
628 vumeter = VUMETER_MONO;
632 vumeter = VUMETER_STEREO;
633 else if (*optarg == 'm')
634 vumeter = VUMETER_MONO;
636 vumeter = VUMETER_NONE;
645 stream = SND_PCM_STREAM_PLAYBACK;
649 stream = SND_PCM_STREAM_CAPTURE;
652 if (file_type == FORMAT_DEFAULT)
653 file_type = FORMAT_WAVE;
658 case OPT_DISABLE_RESAMPLE:
659 open_mode |= SND_PCM_NO_AUTO_RESAMPLE;
661 case OPT_DISABLE_CHANNELS:
662 open_mode |= SND_PCM_NO_AUTO_CHANNELS;
664 case OPT_DISABLE_FORMAT:
665 open_mode |= SND_PCM_NO_AUTO_FORMAT;
667 case OPT_DISABLE_SOFTVOL:
668 open_mode |= SND_PCM_NO_SOFTVOL;
670 case OPT_TEST_POSITION:
674 test_coef = strtol(optarg, NULL, 0);
678 case OPT_TEST_NOWAIT:
681 case OPT_MAX_FILE_TIME:
682 max_file_time = strtol(optarg, NULL, 0);
684 case OPT_PROCESS_ID_FILE:
685 pidfile_name = optarg;
687 case OPT_USE_STRFTIME:
690 case OPT_DUMP_HWPARAMS:
693 case OPT_FATAL_ERRORS:
696 #ifdef CONFIG_SUPPORT_CHMAP
698 channel_map = snd_pcm_chmap_parse_string(optarg);
700 fprintf(stderr, _("Unable to parse channel map string: %s\n"), optarg);
706 fprintf(stderr, _("Try `%s --help' for more information.\n"), command);
711 if (do_device_list) {
712 if (do_pcm_list) pcm_list();
715 } else if (do_pcm_list) {
720 err = snd_pcm_open(&handle, pcm_name, stream, open_mode);
722 error(_("audio open error: %s"), snd_strerror(err));
726 if ((err = snd_pcm_info(handle, info)) < 0) {
727 error(_("info error: %s"), snd_strerror(err));
732 err = snd_pcm_nonblock(handle, 1);
734 error(_("nonblock setting error: %s"), snd_strerror(err));
740 hwparams = rhwparams;
742 audiobuf = (u_char *)malloc(1024);
743 if (audiobuf == NULL) {
744 error(_("not enough memory"));
749 writei_func = snd_pcm_mmap_writei;
750 readi_func = snd_pcm_mmap_readi;
751 writen_func = snd_pcm_mmap_writen;
752 readn_func = snd_pcm_mmap_readn;
754 writei_func = snd_pcm_writei;
755 readi_func = snd_pcm_readi;
756 writen_func = snd_pcm_writen;
757 readn_func = snd_pcm_readn;
762 pidf = fopen (pidfile_name, "w");
764 (void)fprintf (pidf, "%d\n", getpid());
768 error(_("Cannot create process ID file %s: %s"),
769 pidfile_name, strerror (errno));
774 signal(SIGINT, signal_handler);
775 signal(SIGTERM, signal_handler);
776 signal(SIGABRT, signal_handler);
777 signal(SIGUSR1, signal_handler_recycle);
779 if (optind > argc - 1) {
780 if (stream == SND_PCM_STREAM_PLAYBACK)
785 while (optind <= argc - 1) {
786 if (stream == SND_PCM_STREAM_PLAYBACK)
787 playback(argv[optind++]);
789 capture(argv[optind++]);
793 if (stream == SND_PCM_STREAM_PLAYBACK)
794 playbackv(&argv[optind], argc - optind);
796 capturev(&argv[optind], argc - optind);
800 snd_pcm_close(handle);
804 snd_output_close(log);
805 snd_config_update_free_global();
806 prg_exit(EXIT_SUCCESS);
812 * Safe read (for pipes)
815 static ssize_t safe_read(int fd, void *buf, size_t count)
817 ssize_t result = 0, res;
819 while (count > 0 && !in_aborting) {
820 if ((res = read(fd, buf, count)) == 0)
823 return result > 0 ? result : res;
826 buf = (char *)buf + res;
832 * Test, if it is a .VOC file and return >=0 if ok (this is the length of rest)
835 static int test_vocfile(void *buffer)
837 VocHeader *vp = buffer;
839 if (!memcmp(vp->magic, VOC_MAGIC_STRING, 20)) {
840 vocminor = LE_SHORT(vp->version) & 0xFF;
841 vocmajor = LE_SHORT(vp->version) / 256;
842 if (LE_SHORT(vp->version) != (0x1233 - LE_SHORT(vp->coded_ver)))
843 return -2; /* coded version mismatch */
844 return LE_SHORT(vp->headerlen) - sizeof(VocHeader); /* 0 mostly */
846 return -1; /* magic string fail */
850 * helper for test_wavefile
853 static size_t test_wavefile_read(int fd, u_char *buffer, size_t *size, size_t reqsize, int line)
855 if (*size >= reqsize)
857 if ((size_t)safe_read(fd, buffer + *size, reqsize - *size) != reqsize - *size) {
858 error(_("read error (called from line %i)"), line);
859 prg_exit(EXIT_FAILURE);
861 return *size = reqsize;
864 #define check_wavefile_space(buffer, len, blimit) \
865 if (len > blimit) { \
867 if ((buffer = realloc(buffer, blimit)) == NULL) { \
868 error(_("not enough memory")); \
869 prg_exit(EXIT_FAILURE); \
874 * test, if it's a .WAV file, > 0 if ok (and set the speed, stereo etc.)
876 * Value returned is bytes to be discarded.
878 static ssize_t test_wavefile(int fd, u_char *_buffer, size_t size)
880 WaveHeader *h = (WaveHeader *)_buffer;
881 u_char *buffer = NULL;
886 unsigned short format, channels;
887 int big_endian, native_format;
889 if (size < sizeof(WaveHeader))
891 if (h->magic == WAV_RIFF)
893 else if (h->magic == WAV_RIFX)
897 if (h->type != WAV_WAVE)
900 if (size > sizeof(WaveHeader)) {
901 check_wavefile_space(buffer, size - sizeof(WaveHeader), blimit);
902 memcpy(buffer, _buffer + sizeof(WaveHeader), size - sizeof(WaveHeader));
904 size -= sizeof(WaveHeader);
906 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
907 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
908 c = (WaveChunkHeader*)buffer;
910 len = TO_CPU_INT(c->length, big_endian);
912 if (size > sizeof(WaveChunkHeader))
913 memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
914 size -= sizeof(WaveChunkHeader);
917 check_wavefile_space(buffer, len, blimit);
918 test_wavefile_read(fd, buffer, &size, len, __LINE__);
920 memmove(buffer, buffer + len, size - len);
924 if (len < sizeof(WaveFmtBody)) {
925 error(_("unknown length of 'fmt ' chunk (read %u, should be %u at least)"),
926 len, (u_int)sizeof(WaveFmtBody));
927 prg_exit(EXIT_FAILURE);
929 check_wavefile_space(buffer, len, blimit);
930 test_wavefile_read(fd, buffer, &size, len, __LINE__);
931 f = (WaveFmtBody*) buffer;
932 format = TO_CPU_SHORT(f->format, big_endian);
933 if (format == WAV_FMT_EXTENSIBLE) {
934 WaveFmtExtensibleBody *fe = (WaveFmtExtensibleBody*)buffer;
935 if (len < sizeof(WaveFmtExtensibleBody)) {
936 error(_("unknown length of extensible 'fmt ' chunk (read %u, should be %u at least)"),
937 len, (u_int)sizeof(WaveFmtExtensibleBody));
938 prg_exit(EXIT_FAILURE);
940 if (memcmp(fe->guid_tag, WAV_GUID_TAG, 14) != 0) {
941 error(_("wrong format tag in extensible 'fmt ' chunk"));
942 prg_exit(EXIT_FAILURE);
944 format = TO_CPU_SHORT(fe->guid_format, big_endian);
946 if (format != WAV_FMT_PCM &&
947 format != WAV_FMT_IEEE_FLOAT) {
948 error(_("can't play WAVE-file format 0x%04x which is not PCM or FLOAT encoded"), format);
949 prg_exit(EXIT_FAILURE);
951 channels = TO_CPU_SHORT(f->channels, big_endian);
953 error(_("can't play WAVE-files with %d tracks"), channels);
954 prg_exit(EXIT_FAILURE);
956 hwparams.channels = channels;
957 switch (TO_CPU_SHORT(f->bit_p_spl, big_endian)) {
959 if (hwparams.format != DEFAULT_FORMAT &&
960 hwparams.format != SND_PCM_FORMAT_U8)
961 fprintf(stderr, _("Warning: format is changed to U8\n"));
962 hwparams.format = SND_PCM_FORMAT_U8;
966 native_format = SND_PCM_FORMAT_S16_BE;
968 native_format = SND_PCM_FORMAT_S16_LE;
969 if (hwparams.format != DEFAULT_FORMAT &&
970 hwparams.format != native_format)
971 fprintf(stderr, _("Warning: format is changed to %s\n"),
972 snd_pcm_format_name(native_format));
973 hwparams.format = native_format;
976 switch (TO_CPU_SHORT(f->byte_p_spl, big_endian) / hwparams.channels) {
979 native_format = SND_PCM_FORMAT_S24_3BE;
981 native_format = SND_PCM_FORMAT_S24_3LE;
982 if (hwparams.format != DEFAULT_FORMAT &&
983 hwparams.format != native_format)
984 fprintf(stderr, _("Warning: format is changed to %s\n"),
985 snd_pcm_format_name(native_format));
986 hwparams.format = native_format;
990 native_format = SND_PCM_FORMAT_S24_BE;
992 native_format = SND_PCM_FORMAT_S24_LE;
993 if (hwparams.format != DEFAULT_FORMAT &&
994 hwparams.format != native_format)
995 fprintf(stderr, _("Warning: format is changed to %s\n"),
996 snd_pcm_format_name(native_format));
997 hwparams.format = native_format;
1000 error(_(" can't play WAVE-files with sample %d bits in %d bytes wide (%d channels)"),
1001 TO_CPU_SHORT(f->bit_p_spl, big_endian),
1002 TO_CPU_SHORT(f->byte_p_spl, big_endian),
1004 prg_exit(EXIT_FAILURE);
1008 if (format == WAV_FMT_PCM) {
1010 native_format = SND_PCM_FORMAT_S32_BE;
1012 native_format = SND_PCM_FORMAT_S32_LE;
1013 hwparams.format = native_format;
1014 } else if (format == WAV_FMT_IEEE_FLOAT) {
1016 native_format = SND_PCM_FORMAT_FLOAT_BE;
1018 native_format = SND_PCM_FORMAT_FLOAT_LE;
1019 hwparams.format = native_format;
1023 error(_(" can't play WAVE-files with sample %d bits wide"),
1024 TO_CPU_SHORT(f->bit_p_spl, big_endian));
1025 prg_exit(EXIT_FAILURE);
1027 hwparams.rate = TO_CPU_INT(f->sample_fq, big_endian);
1030 memmove(buffer, buffer + len, size - len);
1036 check_wavefile_space(buffer, sizeof(WaveChunkHeader), blimit);
1037 test_wavefile_read(fd, buffer, &size, sizeof(WaveChunkHeader), __LINE__);
1038 c = (WaveChunkHeader*)buffer;
1040 len = TO_CPU_INT(c->length, big_endian);
1041 if (size > sizeof(WaveChunkHeader))
1042 memmove(buffer, buffer + sizeof(WaveChunkHeader), size - sizeof(WaveChunkHeader));
1043 size -= sizeof(WaveChunkHeader);
1044 if (type == WAV_DATA) {
1045 if (len < pbrec_count && len < 0x7ffffffe)
1048 memcpy(_buffer, buffer, size);
1053 check_wavefile_space(buffer, len, blimit);
1054 test_wavefile_read(fd, buffer, &size, len, __LINE__);
1056 memmove(buffer, buffer + len, size - len);
1060 /* shouldn't be reached */
1068 static int test_au(int fd, void *buffer)
1070 AuHeader *ap = buffer;
1072 if (ap->magic != AU_MAGIC)
1074 if (BE_INT(ap->hdr_size) > 128 || BE_INT(ap->hdr_size) < 24)
1076 pbrec_count = BE_INT(ap->data_size);
1077 switch (BE_INT(ap->encoding)) {
1079 if (hwparams.format != DEFAULT_FORMAT &&
1080 hwparams.format != SND_PCM_FORMAT_MU_LAW)
1081 fprintf(stderr, _("Warning: format is changed to MU_LAW\n"));
1082 hwparams.format = SND_PCM_FORMAT_MU_LAW;
1085 if (hwparams.format != DEFAULT_FORMAT &&
1086 hwparams.format != SND_PCM_FORMAT_U8)
1087 fprintf(stderr, _("Warning: format is changed to U8\n"));
1088 hwparams.format = SND_PCM_FORMAT_U8;
1091 if (hwparams.format != DEFAULT_FORMAT &&
1092 hwparams.format != SND_PCM_FORMAT_S16_BE)
1093 fprintf(stderr, _("Warning: format is changed to S16_BE\n"));
1094 hwparams.format = SND_PCM_FORMAT_S16_BE;
1099 hwparams.rate = BE_INT(ap->sample_rate);
1100 if (hwparams.rate < 2000 || hwparams.rate > 256000)
1102 hwparams.channels = BE_INT(ap->channels);
1103 if (hwparams.channels < 1 || hwparams.channels > 256)
1105 if ((size_t)safe_read(fd, buffer + sizeof(AuHeader), BE_INT(ap->hdr_size) - sizeof(AuHeader)) != BE_INT(ap->hdr_size) - sizeof(AuHeader)) {
1106 error(_("read error"));
1107 prg_exit(EXIT_FAILURE);
1112 static void show_available_sample_formats(snd_pcm_hw_params_t* params)
1114 snd_pcm_format_t format;
1116 fprintf(stderr, "Available formats:\n");
1117 for (format = 0; format <= SND_PCM_FORMAT_LAST; format++) {
1118 if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
1119 fprintf(stderr, "- %s\n", snd_pcm_format_name(format));
1123 #ifdef CONFIG_SUPPORT_CHMAP
1124 static int setup_chmap(void)
1126 snd_pcm_chmap_t *chmap = channel_map;
1127 char mapped[hwparams.channels];
1128 snd_pcm_chmap_t *hw_chmap;
1135 if (chmap->channels != hwparams.channels) {
1136 error(_("Channel numbers don't match between hw_params and channel map"));
1139 err = snd_pcm_set_chmap(handle, chmap);
1143 hw_chmap = snd_pcm_get_chmap(handle);
1145 fprintf(stderr, _("Warning: unable to get channel map\n"));
1149 if (hw_chmap->channels == chmap->channels &&
1150 !memcmp(hw_chmap, chmap, 4 * (chmap->channels + 1))) {
1151 /* maps are identical, so no need to convert */
1156 hw_map = calloc(hwparams.channels, sizeof(int));
1158 error(_("not enough memory"));
1162 memset(mapped, 0, sizeof(mapped));
1163 for (ch = 0; ch < hw_chmap->channels; ch++) {
1164 if (chmap->pos[ch] == hw_chmap->pos[ch]) {
1169 for (i = 0; i < hw_chmap->channels; i++) {
1170 if (!mapped[i] && chmap->pos[ch] == hw_chmap->pos[i]) {
1176 if (i >= hw_chmap->channels) {
1178 error(_("Channel %d doesn't match with hw_parmas"), ch);
1179 snd_pcm_chmap_print(hw_chmap, sizeof(buf), buf);
1180 fprintf(stderr, "hardware chmap = %s\n", buf);
1188 #define setup_chmap() 0
1191 static void set_params(void)
1193 snd_pcm_hw_params_t *params;
1194 snd_pcm_sw_params_t *swparams;
1195 snd_pcm_uframes_t buffer_size;
1199 snd_pcm_uframes_t start_threshold, stop_threshold;
1200 snd_pcm_hw_params_alloca(¶ms);
1201 snd_pcm_sw_params_alloca(&swparams);
1202 err = snd_pcm_hw_params_any(handle, params);
1204 error(_("Broken configuration for this PCM: no configurations available"));
1205 prg_exit(EXIT_FAILURE);
1207 if (dump_hw_params) {
1208 fprintf(stderr, _("HW Params of device \"%s\":\n"),
1209 snd_pcm_name(handle));
1210 fprintf(stderr, "--------------------\n");
1211 snd_pcm_hw_params_dump(params, log);
1212 fprintf(stderr, "--------------------\n");
1215 snd_pcm_access_mask_t *mask = alloca(snd_pcm_access_mask_sizeof());
1216 snd_pcm_access_mask_none(mask);
1217 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_INTERLEAVED);
1218 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_NONINTERLEAVED);
1219 snd_pcm_access_mask_set(mask, SND_PCM_ACCESS_MMAP_COMPLEX);
1220 err = snd_pcm_hw_params_set_access_mask(handle, params, mask);
1221 } else if (interleaved)
1222 err = snd_pcm_hw_params_set_access(handle, params,
1223 SND_PCM_ACCESS_RW_INTERLEAVED);
1225 err = snd_pcm_hw_params_set_access(handle, params,
1226 SND_PCM_ACCESS_RW_NONINTERLEAVED);
1228 error(_("Access type not available"));
1229 prg_exit(EXIT_FAILURE);
1231 err = snd_pcm_hw_params_set_format(handle, params, hwparams.format);
1233 error(_("Sample format non available"));
1234 show_available_sample_formats(params);
1235 prg_exit(EXIT_FAILURE);
1237 err = snd_pcm_hw_params_set_channels(handle, params, hwparams.channels);
1239 error(_("Channels count non available"));
1240 prg_exit(EXIT_FAILURE);
1244 err = snd_pcm_hw_params_set_periods_min(handle, params, 2);
1247 rate = hwparams.rate;
1248 err = snd_pcm_hw_params_set_rate_near(handle, params, &hwparams.rate, 0);
1250 if ((float)rate * 1.05 < hwparams.rate || (float)rate * 0.95 > hwparams.rate) {
1253 const char *pcmname = snd_pcm_name(handle);
1254 fprintf(stderr, _("Warning: rate is not accurate (requested = %iHz, got = %iHz)\n"), rate, hwparams.rate);
1255 if (! pcmname || strchr(snd_pcm_name(handle), ':'))
1258 snprintf(plugex, sizeof(plugex), "(-Dplug:%s)",
1259 snd_pcm_name(handle));
1260 fprintf(stderr, _(" please, try the plug plugin %s\n"),
1264 rate = hwparams.rate;
1265 if (buffer_time == 0 && buffer_frames == 0) {
1266 err = snd_pcm_hw_params_get_buffer_time_max(params,
1269 if (buffer_time > 500000)
1270 buffer_time = 500000;
1272 if (period_time == 0 && period_frames == 0) {
1273 if (buffer_time > 0)
1274 period_time = buffer_time / 4;
1276 period_frames = buffer_frames / 4;
1278 if (period_time > 0)
1279 err = snd_pcm_hw_params_set_period_time_near(handle, params,
1282 err = snd_pcm_hw_params_set_period_size_near(handle, params,
1285 if (buffer_time > 0) {
1286 err = snd_pcm_hw_params_set_buffer_time_near(handle, params,
1289 err = snd_pcm_hw_params_set_buffer_size_near(handle, params,
1293 monotonic = snd_pcm_hw_params_is_monotonic(params);
1294 can_pause = snd_pcm_hw_params_can_pause(params);
1295 err = snd_pcm_hw_params(handle, params);
1297 error(_("Unable to install hw params:"));
1298 snd_pcm_hw_params_dump(params, log);
1299 prg_exit(EXIT_FAILURE);
1301 snd_pcm_hw_params_get_period_size(params, &chunk_size, 0);
1302 snd_pcm_hw_params_get_buffer_size(params, &buffer_size);
1303 if (chunk_size == buffer_size) {
1304 error(_("Can't use period equal to buffer size (%lu == %lu)"),
1305 chunk_size, buffer_size);
1306 prg_exit(EXIT_FAILURE);
1308 snd_pcm_sw_params_current(handle, swparams);
1312 n = (double) rate * avail_min / 1000000;
1313 err = snd_pcm_sw_params_set_avail_min(handle, swparams, n);
1315 /* round up to closest transfer boundary */
1317 if (start_delay <= 0) {
1318 start_threshold = n + (double) rate * start_delay / 1000000;
1320 start_threshold = (double) rate * start_delay / 1000000;
1321 if (start_threshold < 1)
1322 start_threshold = 1;
1323 if (start_threshold > n)
1324 start_threshold = n;
1325 err = snd_pcm_sw_params_set_start_threshold(handle, swparams, start_threshold);
1327 if (stop_delay <= 0)
1328 stop_threshold = buffer_size + (double) rate * stop_delay / 1000000;
1330 stop_threshold = (double) rate * stop_delay / 1000000;
1331 err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, stop_threshold);
1334 if (snd_pcm_sw_params(handle, swparams) < 0) {
1335 error(_("unable to install sw params:"));
1336 snd_pcm_sw_params_dump(swparams, log);
1337 prg_exit(EXIT_FAILURE);
1341 prg_exit(EXIT_FAILURE);
1344 snd_pcm_dump(handle, log);
1346 bits_per_sample = snd_pcm_format_physical_width(hwparams.format);
1347 bits_per_frame = bits_per_sample * hwparams.channels;
1348 chunk_bytes = chunk_size * bits_per_frame / 8;
1349 audiobuf = realloc(audiobuf, chunk_bytes);
1350 if (audiobuf == NULL) {
1351 error(_("not enough memory"));
1352 prg_exit(EXIT_FAILURE);
1354 // fprintf(stderr, "real chunk_size = %i, frags = %i, total = %i\n", chunk_size, setup.buf.block.frags, setup.buf.block.frags * chunk_size);
1356 /* stereo VU-meter isn't always available... */
1357 if (vumeter == VUMETER_STEREO) {
1358 if (hwparams.channels != 2 || !interleaved || verbose > 2)
1359 vumeter = VUMETER_MONO;
1362 /* show mmap buffer arragment */
1363 if (mmap_flag && verbose) {
1364 const snd_pcm_channel_area_t *areas;
1365 snd_pcm_uframes_t offset, size = chunk_size;
1367 err = snd_pcm_mmap_begin(handle, &areas, &offset, &size);
1369 error(_("snd_pcm_mmap_begin problem: %s"), snd_strerror(err));
1370 prg_exit(EXIT_FAILURE);
1372 for (i = 0; i < hwparams.channels; i++)
1373 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));
1374 /* not required, but for sure */
1375 snd_pcm_mmap_commit(handle, offset, 0);
1378 buffer_frames = buffer_size; /* for position test */
1381 static void init_stdin(void)
1383 struct termios term;
1388 if (!isatty(fileno(stdin))) {
1392 tcgetattr(fileno(stdin), &term);
1393 term_c_lflag = term.c_lflag;
1394 if (fd == fileno(stdin))
1396 flags = fcntl(fileno(stdin), F_GETFL);
1397 if (flags < 0 || fcntl(fileno(stdin), F_SETFL, flags|O_NONBLOCK) < 0)
1398 fprintf(stderr, _("stdin O_NONBLOCK flag setup failed\n"));
1399 term.c_lflag &= ~ICANON;
1400 tcsetattr(fileno(stdin), TCSANOW, &term);
1403 static void done_stdin(void)
1405 struct termios term;
1409 if (fd == fileno(stdin) || term_c_lflag == -1)
1411 tcgetattr(fileno(stdin), &term);
1412 term.c_lflag = term_c_lflag;
1413 tcsetattr(fileno(stdin), TCSANOW, &term);
1416 static void do_pause(void)
1422 fprintf(stderr, _("\rPAUSE command ignored (no hw support)\n"));
1425 err = snd_pcm_pause(handle, 1);
1427 error(_("pause push error: %s"), snd_strerror(err));
1431 while (read(fileno(stdin), &b, 1) != 1);
1432 if (b == ' ' || b == '\r') {
1433 while (read(fileno(stdin), &b, 1) == 1);
1434 err = snd_pcm_pause(handle, 0);
1436 error(_("pause release error: %s"), snd_strerror(err));
1442 static void check_stdin(void)
1448 if (fd != fileno(stdin)) {
1449 while (read(fileno(stdin), &b, 1) == 1) {
1450 if (b == ' ' || b == '\r') {
1451 while (read(fileno(stdin), &b, 1) == 1);
1452 fprintf(stderr, _("\r=== PAUSE === "));
1455 fprintf(stderr, " \r");
1463 #define timersub(a, b, result) \
1465 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
1466 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
1467 if ((result)->tv_usec < 0) { \
1468 --(result)->tv_sec; \
1469 (result)->tv_usec += 1000000; \
1475 #define timermsub(a, b, result) \
1477 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
1478 (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
1479 if ((result)->tv_nsec < 0) { \
1480 --(result)->tv_sec; \
1481 (result)->tv_nsec += 1000000000L; \
1486 /* I/O error handler */
1487 static void xrun(void)
1489 snd_pcm_status_t *status;
1492 snd_pcm_status_alloca(&status);
1493 if ((res = snd_pcm_status(handle, status))<0) {
1494 error(_("status error: %s"), snd_strerror(res));
1495 prg_exit(EXIT_FAILURE);
1497 if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) {
1499 error(_("fatal %s: %s"),
1500 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1502 prg_exit(EXIT_FAILURE);
1505 #ifdef HAVE_CLOCK_GETTIME
1506 struct timespec now, diff, tstamp;
1507 clock_gettime(CLOCK_MONOTONIC, &now);
1508 snd_pcm_status_get_trigger_htstamp(status, &tstamp);
1509 timermsub(&now, &tstamp, &diff);
1510 fprintf(stderr, _("%s!!! (at least %.3f ms long)\n"),
1511 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1512 diff.tv_sec * 1000 + diff.tv_nsec / 1000000.0);
1514 fprintf(stderr, "%s !!!\n", _("underrun"));
1517 struct timeval now, diff, tstamp;
1518 gettimeofday(&now, 0);
1519 snd_pcm_status_get_trigger_tstamp(status, &tstamp);
1520 timersub(&now, &tstamp, &diff);
1521 fprintf(stderr, _("%s!!! (at least %.3f ms long)\n"),
1522 stream == SND_PCM_STREAM_PLAYBACK ? _("underrun") : _("overrun"),
1523 diff.tv_sec * 1000 + diff.tv_usec / 1000.0);
1526 fprintf(stderr, _("Status:\n"));
1527 snd_pcm_status_dump(status, log);
1529 if ((res = snd_pcm_prepare(handle))<0) {
1530 error(_("xrun: prepare error: %s"), snd_strerror(res));
1531 prg_exit(EXIT_FAILURE);
1533 return; /* ok, data should be accepted again */
1534 } if (snd_pcm_status_get_state(status) == SND_PCM_STATE_DRAINING) {
1536 fprintf(stderr, _("Status(DRAINING):\n"));
1537 snd_pcm_status_dump(status, log);
1539 if (stream == SND_PCM_STREAM_CAPTURE) {
1540 fprintf(stderr, _("capture stream format change? attempting recover...\n"));
1541 if ((res = snd_pcm_prepare(handle))<0) {
1542 error(_("xrun(DRAINING): prepare error: %s"), snd_strerror(res));
1543 prg_exit(EXIT_FAILURE);
1549 fprintf(stderr, _("Status(R/W):\n"));
1550 snd_pcm_status_dump(status, log);
1552 error(_("read/write error, state = %s"), snd_pcm_state_name(snd_pcm_status_get_state(status)));
1553 prg_exit(EXIT_FAILURE);
1556 /* I/O suspend handler */
1557 static void suspend(void)
1562 fprintf(stderr, _("Suspended. Trying resume. ")); fflush(stderr);
1563 while ((res = snd_pcm_resume(handle)) == -EAGAIN)
1564 sleep(1); /* wait until suspend flag is released */
1567 fprintf(stderr, _("Failed. Restarting stream. ")); fflush(stderr);
1568 if ((res = snd_pcm_prepare(handle)) < 0) {
1569 error(_("suspend: prepare error: %s"), snd_strerror(res));
1570 prg_exit(EXIT_FAILURE);
1574 fprintf(stderr, _("Done.\n"));
1577 static void print_vu_meter_mono(int perc, int maxperc)
1579 const int bar_length = 50;
1583 for (val = 0; val <= perc * bar_length / 100 && val < bar_length; val++)
1585 for (; val <= maxperc * bar_length / 100 && val < bar_length; val++)
1588 for (++val; val <= bar_length; val++)
1591 sprintf(line + val, "| MAX");
1593 sprintf(line + val, "| %02i%%", maxperc);
1594 fputs(line, stderr);
1596 fprintf(stderr, _(" !clip "));
1599 static void print_vu_meter_stereo(int *perc, int *maxperc)
1601 const int bar_length = 35;
1605 memset(line, ' ', sizeof(line) - 1);
1606 line[bar_length + 3] = '|';
1608 for (c = 0; c < 2; c++) {
1609 int p = perc[c] * bar_length / 100;
1614 memset(line + bar_length + 6 + 1, '#', p);
1616 memset(line + bar_length - p - 1, '#', p);
1617 p = maxperc[c] * bar_length / 100;
1621 line[bar_length + 6 + 1 + p] = '+';
1623 line[bar_length - p - 1] = '+';
1624 if (maxperc[c] > 99)
1625 sprintf(tmp, "MAX");
1627 sprintf(tmp, "%02d%%", maxperc[c]);
1629 memcpy(line + bar_length + 3 + 1, tmp, 3);
1631 memcpy(line + bar_length, tmp, 3);
1633 line[bar_length * 2 + 6 + 2] = 0;
1634 fputs(line, stderr);
1637 static void print_vu_meter(signed int *perc, signed int *maxperc)
1639 if (vumeter == VUMETER_STEREO)
1640 print_vu_meter_stereo(perc, maxperc);
1642 print_vu_meter_mono(*perc, *maxperc);
1646 static void compute_max_peak(u_char *data, size_t count)
1648 signed int val, max, perc[2], max_peak[2];
1650 size_t ocount = count;
1651 int format_little_endian = snd_pcm_format_little_endian(hwparams.format);
1654 if (vumeter == VUMETER_STEREO)
1659 memset(max_peak, 0, sizeof(max_peak));
1660 switch (bits_per_sample) {
1662 signed char *valp = (signed char *)data;
1663 signed char mask = snd_pcm_format_silence(hwparams.format);
1665 while (count-- > 0) {
1666 val = *valp++ ^ mask;
1668 if (max_peak[c] < val)
1670 if (vumeter == VUMETER_STEREO)
1676 signed short *valp = (signed short *)data;
1677 signed short mask = snd_pcm_format_silence_16(hwparams.format);
1682 while (count-- > 0) {
1683 if (format_little_endian)
1684 sval = le16toh(*valp);
1686 sval = be16toh(*valp);
1687 sval = abs(sval) ^ mask;
1688 if (max_peak[c] < sval)
1691 if (vumeter == VUMETER_STEREO)
1697 unsigned char *valp = data;
1698 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1702 while (count-- > 0) {
1703 if (format_little_endian) {
1704 val = valp[0] | (valp[1]<<8) | (valp[2]<<16);
1706 val = (valp[0]<<16) | (valp[1]<<8) | valp[2];
1708 /* Correct signed bit in 32-bit value */
1709 if (val & (1<<(bits_per_sample-1))) {
1710 val |= 0xff<<24; /* Negate upper bits too */
1712 val = abs(val) ^ mask;
1713 if (max_peak[c] < val)
1716 if (vumeter == VUMETER_STEREO)
1722 signed int *valp = (signed int *)data;
1723 signed int mask = snd_pcm_format_silence_32(hwparams.format);
1727 while (count-- > 0) {
1728 if (format_little_endian)
1729 val = le32toh(*valp);
1731 val = be32toh(*valp);
1732 val = abs(val) ^ mask;
1733 if (max_peak[c] < val)
1736 if (vumeter == VUMETER_STEREO)
1743 fprintf(stderr, _("Unsupported bit size %d.\n"), (int)bits_per_sample);
1748 max = 1 << (bits_per_sample-1);
1752 for (c = 0; c < ichans; c++) {
1753 if (bits_per_sample > 16)
1754 perc[c] = max_peak[c] / (max / 100);
1756 perc[c] = max_peak[c] * 100 / max;
1759 if (interleaved && verbose <= 2) {
1760 static int maxperc[2];
1762 const time_t tt=time(NULL);
1768 for (c = 0; c < ichans; c++)
1769 if (perc[c] > maxperc[c])
1770 maxperc[c] = perc[c];
1773 print_vu_meter(perc, maxperc);
1776 else if(verbose==3) {
1777 fprintf(stderr, _("Max peak (%li samples): 0x%08x "), (long)ocount, max_peak[0]);
1778 for (val = 0; val < 20; val++)
1779 if (val <= perc[0] / 5)
1783 fprintf(stderr, " %i%%\n", perc[0]);
1788 static void do_test_position(void)
1790 static long counter = 0;
1791 static time_t tmr = -1;
1793 static float availsum, delaysum, samples;
1794 static snd_pcm_sframes_t maxavail, maxdelay;
1795 static snd_pcm_sframes_t minavail, mindelay;
1796 static snd_pcm_sframes_t badavail = 0, baddelay = 0;
1797 snd_pcm_sframes_t outofrange;
1798 snd_pcm_sframes_t avail, delay;
1801 err = snd_pcm_avail_delay(handle, &avail, &delay);
1804 outofrange = (test_coef * (snd_pcm_sframes_t)buffer_frames) / 2;
1805 if (avail > outofrange || avail < -outofrange ||
1806 delay > outofrange || delay < -outofrange) {
1807 badavail = avail; baddelay = delay;
1808 availsum = delaysum = samples = 0;
1809 maxavail = maxdelay = 0;
1810 minavail = mindelay = buffer_frames * 16;
1811 fprintf(stderr, _("Suspicious buffer position (%li total): "
1812 "avail = %li, delay = %li, buffer = %li\n"),
1813 ++counter, (long)avail, (long)delay, (long)buffer_frames);
1814 } else if (verbose) {
1816 if (tmr == (time_t) -1) {
1818 availsum = delaysum = samples = 0;
1819 maxavail = maxdelay = 0;
1820 minavail = mindelay = buffer_frames * 16;
1822 if (avail > maxavail)
1824 if (delay > maxdelay)
1826 if (avail < minavail)
1828 if (delay < mindelay)
1833 if (avail != 0 && now != tmr) {
1834 fprintf(stderr, "BUFPOS: avg%li/%li "
1835 "min%li/%li max%li/%li (%li) (%li:%li/%li)\n",
1836 (long)(availsum / samples),
1837 (long)(delaysum / samples),
1838 (long)minavail, (long)mindelay,
1839 (long)maxavail, (long)maxdelay,
1840 (long)buffer_frames,
1841 counter, badavail, baddelay);
1849 #ifdef CONFIG_SUPPORT_CHMAP
1850 static u_char *remap_data(u_char *data, size_t count)
1852 static u_char *tmp, *src, *dst;
1853 static size_t tmp_size;
1854 size_t sample_bytes = bits_per_sample / 8;
1855 size_t step = bits_per_frame / 8;
1862 chunk_bytes = count * bits_per_frame / 8;
1863 if (tmp_size < chunk_bytes) {
1865 tmp = malloc(chunk_bytes);
1867 error(_("not enough memory"));
1875 for (i = 0; i < count; i++) {
1876 for (ch = 0; ch < hwparams.channels; ch++) {
1877 memcpy(dst, src + sample_bytes * hw_map[ch],
1879 dst += sample_bytes;
1886 static u_char **remap_datav(u_char **data, size_t count)
1888 static u_char **tmp;
1895 tmp = malloc(sizeof(*tmp) * hwparams.channels);
1897 error(_("not enough memory"));
1900 for (ch = 0; ch < hwparams.channels; ch++)
1901 tmp[ch] = data[hw_map[ch]];
1906 #define remap_data(data, count) (data)
1907 #define remap_datav(data, count) (data)
1914 static ssize_t pcm_write(u_char *data, size_t count)
1919 if (count < chunk_size) {
1920 snd_pcm_format_set_silence(hwparams.format, data + count * bits_per_frame / 8, (chunk_size - count) * hwparams.channels);
1923 data = remap_data(data, count);
1924 while (count > 0 && !in_aborting) {
1928 r = writei_func(handle, data, count);
1931 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
1933 snd_pcm_wait(handle, 100);
1934 } else if (r == -EPIPE) {
1936 } else if (r == -ESTRPIPE) {
1939 error(_("write error: %s"), snd_strerror(r));
1940 prg_exit(EXIT_FAILURE);
1944 compute_max_peak(data, r * hwparams.channels);
1947 data += r * bits_per_frame / 8;
1953 static ssize_t pcm_writev(u_char **data, unsigned int channels, size_t count)
1958 if (count != chunk_size) {
1959 unsigned int channel;
1960 size_t offset = count;
1961 size_t remaining = chunk_size - count;
1962 for (channel = 0; channel < channels; channel++)
1963 snd_pcm_format_set_silence(hwparams.format, data[channel] + offset * bits_per_sample / 8, remaining);
1966 data = remap_datav(data, count);
1967 while (count > 0 && !in_aborting) {
1968 unsigned int channel;
1969 void *bufs[channels];
1970 size_t offset = result;
1971 for (channel = 0; channel < channels; channel++)
1972 bufs[channel] = data[channel] + offset * bits_per_sample / 8;
1976 r = writen_func(handle, bufs, count);
1979 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
1981 snd_pcm_wait(handle, 100);
1982 } else if (r == -EPIPE) {
1984 } else if (r == -ESTRPIPE) {
1987 error(_("writev error: %s"), snd_strerror(r));
1988 prg_exit(EXIT_FAILURE);
1992 for (channel = 0; channel < channels; channel++)
1993 compute_max_peak(data[channel], r);
2006 static ssize_t pcm_read(u_char *data, size_t rcount)
2010 size_t count = rcount;
2012 if (count != chunk_size) {
2016 while (count > 0 && !in_aborting) {
2020 r = readi_func(handle, data, count);
2023 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2025 snd_pcm_wait(handle, 100);
2026 } else if (r == -EPIPE) {
2028 } else if (r == -ESTRPIPE) {
2031 error(_("read error: %s"), snd_strerror(r));
2032 prg_exit(EXIT_FAILURE);
2036 compute_max_peak(data, r * hwparams.channels);
2039 data += r * bits_per_frame / 8;
2045 static ssize_t pcm_readv(u_char **data, unsigned int channels, size_t rcount)
2049 size_t count = rcount;
2051 if (count != chunk_size) {
2055 while (count > 0 && !in_aborting) {
2056 unsigned int channel;
2057 void *bufs[channels];
2058 size_t offset = result;
2059 for (channel = 0; channel < channels; channel++)
2060 bufs[channel] = data[channel] + offset * bits_per_sample / 8;
2064 r = readn_func(handle, bufs, count);
2067 if (r == -EAGAIN || (r >= 0 && (size_t)r < count)) {
2069 snd_pcm_wait(handle, 100);
2070 } else if (r == -EPIPE) {
2072 } else if (r == -ESTRPIPE) {
2075 error(_("readv error: %s"), snd_strerror(r));
2076 prg_exit(EXIT_FAILURE);
2080 for (channel = 0; channel < channels; channel++)
2081 compute_max_peak(data[channel], r);
2091 * ok, let's play a .voc file
2094 static ssize_t voc_pcm_write(u_char *data, size_t count)
2096 ssize_t result = count, r;
2101 if (size > chunk_bytes - buffer_pos)
2102 size = chunk_bytes - buffer_pos;
2103 memcpy(audiobuf + buffer_pos, data, size);
2107 if ((size_t)buffer_pos == chunk_bytes) {
2108 if ((size_t)(r = pcm_write(audiobuf, chunk_size)) != chunk_size)
2116 static void voc_write_silence(unsigned x)
2121 buf = (u_char *) malloc(chunk_bytes);
2123 error(_("can't allocate buffer for silence"));
2124 return; /* not fatal error */
2126 snd_pcm_format_set_silence(hwparams.format, buf, chunk_size * hwparams.channels);
2127 while (x > 0 && !in_aborting) {
2131 if (voc_pcm_write(buf, l) != (ssize_t)l) {
2132 error(_("write error"));
2133 prg_exit(EXIT_FAILURE);
2140 static void voc_pcm_flush(void)
2142 if (buffer_pos > 0) {
2144 if (snd_pcm_format_set_silence(hwparams.format, audiobuf + buffer_pos, chunk_bytes - buffer_pos * 8 / bits_per_sample) < 0)
2145 fprintf(stderr, _("voc_pcm_flush - silence error"));
2147 if (pcm_write(audiobuf, b) != (ssize_t)b)
2148 error(_("voc_pcm_flush error"));
2150 snd_pcm_nonblock(handle, 0);
2151 snd_pcm_drain(handle);
2152 snd_pcm_nonblock(handle, nonblock);
2155 static void voc_play(int fd, int ofs, char *name)
2161 size_t nextblock, in_buffer;
2163 char was_extended = 0, output = 0;
2164 u_short *sp, repeat = 0;
2165 off64_t filepos = 0;
2167 #define COUNT(x) nextblock -= x; in_buffer -= x; data += x
2168 #define COUNT1(x) in_buffer -= x; data += x
2170 data = buf = (u_char *)malloc(64 * 1024);
2173 error(_("malloc error"));
2174 prg_exit(EXIT_FAILURE);
2177 fprintf(stderr, _("Playing Creative Labs Channel file '%s'...\n"), name);
2179 /* first we waste the rest of header, ugly but we don't need seek */
2180 while (ofs > (ssize_t)chunk_bytes) {
2181 if ((size_t)safe_read(fd, buf, chunk_bytes) != chunk_bytes) {
2182 error(_("read error"));
2183 prg_exit(EXIT_FAILURE);
2188 if (safe_read(fd, buf, ofs) != ofs) {
2189 error(_("read error"));
2190 prg_exit(EXIT_FAILURE);
2193 hwparams.format = DEFAULT_FORMAT;
2194 hwparams.channels = 1;
2195 hwparams.rate = DEFAULT_SPEED;
2198 in_buffer = nextblock = 0;
2199 while (!in_aborting) {
2200 Fill_the_buffer: /* need this for repeat */
2201 if (in_buffer < 32) {
2202 /* move the rest of buffer to pos 0 and fill the buf up */
2204 memcpy(buf, data, in_buffer);
2206 if ((l = safe_read(fd, buf + in_buffer, chunk_bytes - in_buffer)) > 0)
2208 else if (!in_buffer) {
2209 /* the file is truncated, so simulate 'Terminator'
2210 and reduce the datablock for safe landing */
2211 nextblock = buf[0] = 0;
2214 prg_exit(EXIT_FAILURE);
2218 while (!nextblock) { /* this is a new block */
2219 if (in_buffer < sizeof(VocBlockType))
2221 bp = (VocBlockType *) data;
2222 COUNT1(sizeof(VocBlockType));
2223 nextblock = VOC_DATALEN(bp);
2224 if (output && !quiet_mode)
2225 fprintf(stderr, "\n"); /* write /n after ASCII-out */
2230 d_printf("Terminator\n");
2232 return; /* VOC-file stop */
2234 vd = (VocVoiceData *) data;
2235 COUNT1(sizeof(VocVoiceData));
2236 /* we need a SYNC, before we can set new SPEED, STEREO ... */
2238 if (!was_extended) {
2239 hwparams.rate = (int) (vd->tc);
2240 hwparams.rate = 1000000 / (256 - hwparams.rate);
2242 d_printf("Channel data %d Hz\n", dsp_speed);
2244 if (vd->pack) { /* /dev/dsp can't it */
2245 error(_("can't play packed .voc files"));
2248 if (hwparams.channels == 2) /* if we are in Stereo-Mode, switch back */
2249 hwparams.channels = 1;
2250 } else { /* there was extended block */
2251 hwparams.channels = 2;
2256 case 2: /* nothing to do, pure data */
2258 d_printf("Channel continuation\n");
2261 case 3: /* a silence block, no data, only a count */
2262 sp = (u_short *) data;
2263 COUNT1(sizeof(u_short));
2264 hwparams.rate = (int) (*data);
2266 hwparams.rate = 1000000 / (256 - hwparams.rate);
2271 silence = (((size_t) * sp) * 1000) / hwparams.rate;
2272 d_printf("Silence for %d ms\n", (int) silence);
2275 voc_write_silence(*sp);
2277 case 4: /* a marker for syncronisation, no effect */
2278 sp = (u_short *) data;
2279 COUNT1(sizeof(u_short));
2281 d_printf("Marker %d\n", *sp);
2284 case 5: /* ASCII text, we copy to stderr */
2287 d_printf("ASCII - text :\n");
2290 case 6: /* repeat marker, says repeatcount */
2291 /* my specs don't say it: maybe this can be recursive, but
2292 I don't think somebody use it */
2293 repeat = *(u_short *) data;
2294 COUNT1(sizeof(u_short));
2296 d_printf("Repeat loop %d times\n", repeat);
2298 if (filepos >= 0) { /* if < 0, one seek fails, why test another */
2299 if ((filepos = lseek64(fd, 0, 1)) < 0) {
2300 error(_("can't play loops; %s isn't seekable\n"), name);
2303 filepos -= in_buffer; /* set filepos after repeat */
2309 case 7: /* ok, lets repeat that be rewinding tape */
2311 if (repeat != 0xFFFF) {
2313 d_printf("Repeat loop %d\n", repeat);
2319 d_printf("Neverending loop\n");
2321 lseek64(fd, filepos, 0);
2322 in_buffer = 0; /* clear the buffer */
2323 goto Fill_the_buffer;
2327 d_printf("End repeat loop\n");
2330 case 8: /* the extension to play Stereo, I have SB 1.0 :-( */
2332 eb = (VocExtBlock *) data;
2333 COUNT1(sizeof(VocExtBlock));
2334 hwparams.rate = (int) (eb->tc);
2335 hwparams.rate = 256000000L / (65536 - hwparams.rate);
2336 hwparams.channels = eb->mode == VOC_MODE_STEREO ? 2 : 1;
2337 if (hwparams.channels == 2)
2338 hwparams.rate = hwparams.rate >> 1;
2339 if (eb->pack) { /* /dev/dsp can't it */
2340 error(_("can't play packed .voc files"));
2344 d_printf("Extended block %s %d Hz\n",
2345 (eb->mode ? "Stereo" : "Mono"), dsp_speed);
2349 error(_("unknown blocktype %d. terminate."), bp->type);
2351 } /* switch (bp->type) */
2352 } /* while (! nextblock) */
2353 /* put nextblock data bytes to dsp */
2355 if (nextblock < (size_t)l)
2358 if (output && !quiet_mode) {
2359 if (write(2, data, l) != l) { /* to stderr */
2360 error(_("write error"));
2361 prg_exit(EXIT_FAILURE);
2364 if (voc_pcm_write(data, l) != l) {
2365 error(_("write error"));
2366 prg_exit(EXIT_FAILURE);
2376 /* that was a big one, perhaps somebody split it :-) */
2378 /* setting the globals for playing raw data */
2379 static void init_raw_data(void)
2381 hwparams = rhwparams;
2384 /* calculate the data count to read from/to dsp */
2385 static off64_t calc_count(void)
2389 if (timelimit == 0) {
2390 count = pbrec_count;
2392 count = snd_pcm_format_size(hwparams.format, hwparams.rate * hwparams.channels);
2393 count *= (off64_t)timelimit;
2395 return count < pbrec_count ? count : pbrec_count;
2398 /* write a .VOC-header */
2399 static void begin_voc(int fd, size_t cnt)
2406 memcpy(vh.magic, VOC_MAGIC_STRING, 20);
2407 vh.headerlen = LE_SHORT(sizeof(VocHeader));
2408 vh.version = LE_SHORT(VOC_ACTUAL_VERSION);
2409 vh.coded_ver = LE_SHORT(0x1233 - VOC_ACTUAL_VERSION);
2411 if (write(fd, &vh, sizeof(VocHeader)) != sizeof(VocHeader)) {
2412 error(_("write error"));
2413 prg_exit(EXIT_FAILURE);
2415 if (hwparams.channels > 1) {
2416 /* write an extended block */
2419 bt.datalen_m = bt.datalen_h = 0;
2420 if (write(fd, &bt, sizeof(VocBlockType)) != sizeof(VocBlockType)) {
2421 error(_("write error"));
2422 prg_exit(EXIT_FAILURE);
2424 eb.tc = LE_SHORT(65536 - 256000000L / (hwparams.rate << 1));
2427 if (write(fd, &eb, sizeof(VocExtBlock)) != sizeof(VocExtBlock)) {
2428 error(_("write error"));
2429 prg_exit(EXIT_FAILURE);
2433 cnt += sizeof(VocVoiceData); /* Channel_data block follows */
2434 bt.datalen = (u_char) (cnt & 0xFF);
2435 bt.datalen_m = (u_char) ((cnt & 0xFF00) >> 8);
2436 bt.datalen_h = (u_char) ((cnt & 0xFF0000) >> 16);
2437 if (write(fd, &bt, sizeof(VocBlockType)) != sizeof(VocBlockType)) {
2438 error(_("write error"));
2439 prg_exit(EXIT_FAILURE);
2441 vd.tc = (u_char) (256 - (1000000 / hwparams.rate));
2443 if (write(fd, &vd, sizeof(VocVoiceData)) != sizeof(VocVoiceData)) {
2444 error(_("write error"));
2445 prg_exit(EXIT_FAILURE);
2449 /* write a WAVE-header */
2450 static void begin_wave(int fd, size_t cnt)
2454 WaveChunkHeader cf, cd;
2459 /* WAVE cannot handle greater than 32bit (signed?) int */
2460 if (cnt == (size_t)-2)
2464 switch ((unsigned long) hwparams.format) {
2465 case SND_PCM_FORMAT_U8:
2468 case SND_PCM_FORMAT_S16_LE:
2471 case SND_PCM_FORMAT_S32_LE:
2472 case SND_PCM_FORMAT_FLOAT_LE:
2475 case SND_PCM_FORMAT_S24_LE:
2476 case SND_PCM_FORMAT_S24_3LE:
2480 error(_("Wave doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2481 prg_exit(EXIT_FAILURE);
2484 tmp = cnt + sizeof(WaveHeader) + sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + sizeof(WaveChunkHeader) - 8;
2485 h.length = LE_INT(tmp);
2489 cf.length = LE_INT(16);
2491 if (hwparams.format == SND_PCM_FORMAT_FLOAT_LE)
2492 f.format = LE_SHORT(WAV_FMT_IEEE_FLOAT);
2494 f.format = LE_SHORT(WAV_FMT_PCM);
2495 f.channels = LE_SHORT(hwparams.channels);
2496 f.sample_fq = LE_INT(hwparams.rate);
2498 tmp2 = (samplesize == 8) ? 1 : 2;
2499 f.byte_p_spl = LE_SHORT(tmp2);
2500 tmp = dsp_speed * hwparams.channels * (u_int) tmp2;
2502 tmp2 = hwparams.channels * snd_pcm_format_physical_width(hwparams.format) / 8;
2503 f.byte_p_spl = LE_SHORT(tmp2);
2504 tmp = (u_int) tmp2 * hwparams.rate;
2506 f.byte_p_sec = LE_INT(tmp);
2507 f.bit_p_spl = LE_SHORT(bits);
2510 cd.length = LE_INT(cnt);
2512 if (write(fd, &h, sizeof(WaveHeader)) != sizeof(WaveHeader) ||
2513 write(fd, &cf, sizeof(WaveChunkHeader)) != sizeof(WaveChunkHeader) ||
2514 write(fd, &f, sizeof(WaveFmtBody)) != sizeof(WaveFmtBody) ||
2515 write(fd, &cd, sizeof(WaveChunkHeader)) != sizeof(WaveChunkHeader)) {
2516 error(_("write error"));
2517 prg_exit(EXIT_FAILURE);
2521 /* write a Au-header */
2522 static void begin_au(int fd, size_t cnt)
2526 ah.magic = AU_MAGIC;
2527 ah.hdr_size = BE_INT(24);
2528 ah.data_size = BE_INT(cnt);
2529 switch ((unsigned long) hwparams.format) {
2530 case SND_PCM_FORMAT_MU_LAW:
2531 ah.encoding = BE_INT(AU_FMT_ULAW);
2533 case SND_PCM_FORMAT_U8:
2534 ah.encoding = BE_INT(AU_FMT_LIN8);
2536 case SND_PCM_FORMAT_S16_BE:
2537 ah.encoding = BE_INT(AU_FMT_LIN16);
2540 error(_("Sparc Audio doesn't support %s format..."), snd_pcm_format_name(hwparams.format));
2541 prg_exit(EXIT_FAILURE);
2543 ah.sample_rate = BE_INT(hwparams.rate);
2544 ah.channels = BE_INT(hwparams.channels);
2545 if (write(fd, &ah, sizeof(AuHeader)) != sizeof(AuHeader)) {
2546 error(_("write error"));
2547 prg_exit(EXIT_FAILURE);
2552 static void end_voc(int fd)
2554 off64_t length_seek;
2557 char dummy = 0; /* Write a Terminator */
2559 if (write(fd, &dummy, 1) != 1) {
2560 error(_("write error"));
2561 prg_exit(EXIT_FAILURE);
2563 length_seek = sizeof(VocHeader);
2564 if (hwparams.channels > 1)
2565 length_seek += sizeof(VocBlockType) + sizeof(VocExtBlock);
2568 cnt += sizeof(VocVoiceData); /* Channel_data block follows */
2569 if (cnt > 0x00ffffff)
2571 bt.datalen = (u_char) (cnt & 0xFF);
2572 bt.datalen_m = (u_char) ((cnt & 0xFF00) >> 8);
2573 bt.datalen_h = (u_char) ((cnt & 0xFF0000) >> 16);
2574 if (lseek64(fd, length_seek, SEEK_SET) == length_seek)
2575 write(fd, &bt, sizeof(VocBlockType));
2580 static void end_wave(int fd)
2581 { /* only close output */
2583 off64_t length_seek;
2587 length_seek = sizeof(WaveHeader) +
2588 sizeof(WaveChunkHeader) +
2589 sizeof(WaveFmtBody);
2591 cd.length = fdcount > 0x7fffffff ? LE_INT(0x7fffffff) : LE_INT(fdcount);
2592 filelen = fdcount + 2*sizeof(WaveChunkHeader) + sizeof(WaveFmtBody) + 4;
2593 rifflen = filelen > 0x7fffffff ? LE_INT(0x7fffffff) : LE_INT(filelen);
2594 if (lseek64(fd, 4, SEEK_SET) == 4)
2595 write(fd, &rifflen, 4);
2596 if (lseek64(fd, length_seek, SEEK_SET) == length_seek)
2597 write(fd, &cd, sizeof(WaveChunkHeader));
2602 static void end_au(int fd)
2603 { /* only close output */
2605 off64_t length_seek;
2607 length_seek = (char *)&ah.data_size - (char *)&ah;
2608 ah.data_size = fdcount > 0xffffffff ? 0xffffffff : BE_INT(fdcount);
2609 if (lseek64(fd, length_seek, SEEK_SET) == length_seek)
2610 write(fd, &ah.data_size, sizeof(ah.data_size));
2615 static void header(int rtype, char *name)
2619 name = (stream == SND_PCM_STREAM_PLAYBACK) ? "stdout" : "stdin";
2620 fprintf(stderr, "%s %s '%s' : ",
2621 (stream == SND_PCM_STREAM_PLAYBACK) ? _("Playing") : _("Recording"),
2622 gettext(fmt_rec_table[rtype].what),
2624 fprintf(stderr, "%s, ", snd_pcm_format_description(hwparams.format));
2625 fprintf(stderr, _("Rate %d Hz, "), hwparams.rate);
2626 if (hwparams.channels == 1)
2627 fprintf(stderr, _("Mono"));
2628 else if (hwparams.channels == 2)
2629 fprintf(stderr, _("Stereo"));
2631 fprintf(stderr, _("Channels %i"), hwparams.channels);
2632 fprintf(stderr, "\n");
2636 /* playing raw data */
2638 static void playback_go(int fd, size_t loaded, off64_t count, int rtype, char *name)
2641 off64_t written = 0;
2644 header(rtype, name);
2647 while (loaded > chunk_bytes && written < count && !in_aborting) {
2648 if (pcm_write(audiobuf + written, chunk_size) <= 0)
2650 written += chunk_bytes;
2651 loaded -= chunk_bytes;
2653 if (written > 0 && loaded > 0)
2654 memmove(audiobuf, audiobuf + written, loaded);
2657 while (written < count && !in_aborting) {
2659 c = count - written;
2660 if (c > chunk_bytes)
2666 r = safe_read(fd, audiobuf + l, c);
2669 prg_exit(EXIT_FAILURE);
2675 } while ((size_t)l < chunk_bytes);
2676 l = l * 8 / bits_per_frame;
2677 r = pcm_write(audiobuf, l);
2680 r = r * bits_per_frame / 8;
2684 snd_pcm_nonblock(handle, 0);
2685 snd_pcm_drain(handle);
2686 snd_pcm_nonblock(handle, nonblock);
2691 * let's play or capture it (capture_type says VOC/WAVE/raw)
2694 static void playback(char *name)
2700 pbrec_count = LLONG_MAX;
2702 if (!name || !strcmp(name, "-")) {
2707 if ((fd = open(name, O_RDONLY, 0)) == -1) {
2709 prg_exit(EXIT_FAILURE);
2712 /* read the file header */
2713 dta = sizeof(AuHeader);
2714 if ((size_t)safe_read(fd, audiobuf, dta) != dta) {
2715 error(_("read error"));
2716 prg_exit(EXIT_FAILURE);
2718 if (test_au(fd, audiobuf) >= 0) {
2719 rhwparams.format = hwparams.format;
2720 pbrec_count = calc_count();
2721 playback_go(fd, 0, pbrec_count, FORMAT_AU, name);
2724 dta = sizeof(VocHeader);
2725 if ((size_t)safe_read(fd, audiobuf + sizeof(AuHeader),
2726 dta - sizeof(AuHeader)) != dta - sizeof(AuHeader)) {
2727 error(_("read error"));
2728 prg_exit(EXIT_FAILURE);;
2730 if ((ofs = test_vocfile(audiobuf)) >= 0) {
2731 pbrec_count = calc_count();
2732 voc_play(fd, ofs, name);
2735 /* read bytes for WAVE-header */
2736 if ((dtawave = test_wavefile(fd, audiobuf, dta)) >= 0) {
2737 pbrec_count = calc_count();
2738 playback_go(fd, dtawave, pbrec_count, FORMAT_WAVE, name);
2740 /* should be raw data */
2742 pbrec_count = calc_count();
2743 playback_go(fd, dta, pbrec_count, FORMAT_RAW, name);
2753 * Variant of strftime(3) that supports additional format
2754 * specifiers in the format string.
2758 * s - destination string
2759 * max - max number of bytes to write
2760 * userformat - format string
2761 * tm - time information
2762 * filenumber - the number of the file, starting at 1
2764 * Returns: number of bytes written to the string s
2766 size_t mystrftime(char *s, size_t max, const char *userformat,
2767 const struct tm *tm, const int filenumber)
2769 char formatstring[PATH_MAX] = "";
2770 char tempstring[PATH_MAX] = "";
2771 char *format, *tempstr;
2772 const char *pos_userformat;
2774 format = formatstring;
2776 /* if mystrftime is called with userformat = NULL we return a zero length string */
2777 if (userformat == NULL) {
2782 for (pos_userformat = userformat; *pos_userformat; ++pos_userformat) {
2783 if (*pos_userformat == '%') {
2784 tempstr = tempstring;
2786 switch (*++pos_userformat) {
2788 case '\0': // end of string
2792 case 'v': // file number
2793 sprintf(tempstr, "%02d", filenumber);
2796 default: // All other codes will be handled by strftime
2798 *format++ = *pos_userformat;
2802 /* If a format specifier was found and used, copy the result. */
2804 while ((*format = *tempstr++) != '\0')
2810 /* For any other character than % we simply copy the character */
2811 *format++ = *pos_userformat;
2815 format = formatstring;
2816 return strftime(s, max, format, tm);
2819 static int new_capture_file(char *name, char *namebuf, size_t namelen,
2823 char buf[PATH_MAX+1];
2829 tmp = localtime(&t);
2831 perror("localtime");
2832 prg_exit(EXIT_FAILURE);
2834 if (mystrftime(namebuf, namelen, name, tmp, filecount+1) == 0) {
2835 fprintf(stderr, "mystrftime returned 0");
2836 prg_exit(EXIT_FAILURE);
2841 /* get a copy of the original filename */
2842 strncpy(buf, name, sizeof(buf));
2844 /* separate extension from filename */
2845 s = buf + strlen(buf);
2846 while (s > buf && *s != '.' && *s != '/')
2851 s = buf + strlen(buf);
2853 /* upon first jump to this if block rename the first file */
2854 if (filecount == 1) {
2856 snprintf(namebuf, namelen, "%s-01.%s", buf, s);
2858 snprintf(namebuf, namelen, "%s-01", buf);
2860 rename(name, namebuf);
2864 /* name of the current file */
2866 snprintf(namebuf, namelen, "%s-%02i.%s", buf, filecount, s);
2868 snprintf(namebuf, namelen, "%s-%02i", buf, filecount);
2876 * This function creates a file path, like mkdir -p.
2880 * path - the path to create
2882 * Returns: 0 on success, -1 on failure
2883 * On failure, a message has been printed to stderr.
2885 int create_path(const char *path)
2888 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
2891 start = strchr(path + 1, '/');
2893 start = strchr(path, '/');
2896 char *buffer = strdup(path);
2897 buffer[start-path] = 0x00;
2899 if (mkdir(buffer, mode) == -1 && errno != EEXIST) {
2900 fprintf(stderr, "Problem creating directory %s", buffer);
2906 start = strchr(start + 1, '/');
2911 static int safe_open(const char *name)
2915 fd = open(name, O_WRONLY | O_CREAT, 0644);
2917 if (errno != ENOENT || !use_strftime)
2919 if (create_path(name) == 0)
2920 fd = open(name, O_WRONLY | O_CREAT, 0644);
2925 static void capture(char *orig_name)
2927 int tostdout=0; /* boolean which describes output stream */
2928 int filecount=0; /* number of files written */
2929 char *name = orig_name; /* current filename */
2930 char namebuf[PATH_MAX+1];
2931 off64_t count, rest; /* number of bytes to capture */
2933 /* get number of bytes to capture */
2934 count = calc_count();
2937 /* compute the number of bytes per file */
2938 max_file_size = max_file_time *
2939 snd_pcm_format_size(hwparams.format,
2940 hwparams.rate * hwparams.channels);
2941 /* WAVE-file should be even (I'm not sure), but wasting one byte
2942 isn't a problem (this can only be in 8 bit mono) */
2943 if (count < LLONG_MAX)
2948 /* display verbose output to console */
2949 header(file_type, name);
2951 /* setup sound hardware */
2954 /* write to stdout? */
2955 if (!name || !strcmp(name, "-")) {
2956 fd = fileno(stdout);
2959 if (count > fmt_rec_table[file_type].max_filesize)
2960 count = fmt_rec_table[file_type].max_filesize;
2965 /* open a file to write */
2967 /* upon the second file we start the numbering scheme */
2968 if (filecount || use_strftime) {
2969 filecount = new_capture_file(orig_name, namebuf,
2975 /* open a new file */
2977 fd = safe_open(name);
2980 prg_exit(EXIT_FAILURE);
2986 if (rest > fmt_rec_table[file_type].max_filesize)
2987 rest = fmt_rec_table[file_type].max_filesize;
2988 if (max_file_size && (rest > max_file_size))
2989 rest = max_file_size;
2991 /* setup sample header */
2992 if (fmt_rec_table[file_type].start)
2993 fmt_rec_table[file_type].start(fd, rest);
2997 while (rest > 0 && recycle_capture_file == 0 && !in_aborting) {
2998 size_t c = (rest <= (off64_t)chunk_bytes) ?
2999 (size_t)rest : chunk_bytes;
3000 size_t f = c * 8 / bits_per_frame;
3001 if (pcm_read(audiobuf, f) != f)
3003 if (write(fd, audiobuf, c) != c) {
3005 prg_exit(EXIT_FAILURE);
3012 /* re-enable SIGUSR1 signal */
3013 if (recycle_capture_file) {
3014 recycle_capture_file = 0;
3015 signal(SIGUSR1, signal_handler_recycle);
3018 /* finish sample container */
3019 if (fmt_rec_table[file_type].end && !tostdout) {
3020 fmt_rec_table[file_type].end(fd);
3027 /* repeat the loop when format is raw without timelimit or
3028 * requested counts of data are recorded
3030 } while ((file_type == FORMAT_RAW && !timelimit) || count > 0);
3033 static void playbackv_go(int* fds, unsigned int channels, size_t loaded, off64_t count, int rtype, char **names)
3038 unsigned int channel;
3039 u_char *bufs[channels];
3041 header(rtype, names[0]);
3044 vsize = chunk_bytes / channels;
3046 // Not yet implemented
3047 assert(loaded == 0);
3049 for (channel = 0; channel < channels; ++channel)
3050 bufs[channel] = audiobuf + vsize * channel;
3052 while (count > 0 && !in_aborting) {
3054 size_t expected = count / channels;
3055 if (expected > vsize)
3058 r = safe_read(fds[0], bufs[0], expected);
3060 perror(names[channel]);
3061 prg_exit(EXIT_FAILURE);
3063 for (channel = 1; channel < channels; ++channel) {
3064 if (safe_read(fds[channel], bufs[channel], r) != r) {
3065 perror(names[channel]);
3066 prg_exit(EXIT_FAILURE);
3072 } while (c < expected);
3073 c = c * 8 / bits_per_sample;
3074 r = pcm_writev(bufs, channels, c);
3077 r = r * bits_per_frame / 8;
3080 snd_pcm_nonblock(handle, 0);
3081 snd_pcm_drain(handle);
3082 snd_pcm_nonblock(handle, nonblock);
3085 static void capturev_go(int* fds, unsigned int channels, off64_t count, int rtype, char **names)
3089 unsigned int channel;
3091 u_char *bufs[channels];
3093 header(rtype, names[0]);
3096 vsize = chunk_bytes / channels;
3098 for (channel = 0; channel < channels; ++channel)
3099 bufs[channel] = audiobuf + vsize * channel;
3101 while (count > 0 && !in_aborting) {
3104 if (c > chunk_bytes)
3106 c = c * 8 / bits_per_frame;
3107 if ((size_t)(r = pcm_readv(bufs, channels, c)) != c)
3109 rv = r * bits_per_sample / 8;
3110 for (channel = 0; channel < channels; ++channel) {
3111 if ((size_t)write(fds[channel], bufs[channel], rv) != rv) {
3112 perror(names[channel]);
3113 prg_exit(EXIT_FAILURE);
3116 r = r * bits_per_frame / 8;
3122 static void playbackv(char **names, unsigned int count)
3125 unsigned int channel;
3126 unsigned int channels = rhwparams.channels;
3129 for (channel = 0; channel < channels; ++channel)
3132 if (count == 1 && channels > 1) {
3133 size_t len = strlen(names[0]);
3135 memcpy(format, names[0], len);
3136 strcpy(format + len, ".%d");
3138 names = malloc(sizeof(*names) * channels);
3139 for (channel = 0; channel < channels; ++channel) {
3140 names[channel] = malloc(len);
3141 sprintf(names[channel], format, channel);
3144 } else if (count != channels) {
3145 error(_("You need to specify %d files"), channels);
3146 prg_exit(EXIT_FAILURE);
3149 for (channel = 0; channel < channels; ++channel) {
3150 fds[channel] = open(names[channel], O_RDONLY, 0);
3151 if (fds[channel] < 0) {
3152 perror(names[channel]);
3157 /* should be raw data */
3159 pbrec_count = calc_count();
3160 playbackv_go(fds, channels, 0, pbrec_count, FORMAT_RAW, names);
3163 for (channel = 0; channel < channels; ++channel) {
3164 if (fds[channel] >= 0)
3165 close(fds[channel]);
3167 free(names[channel]);
3175 static void capturev(char **names, unsigned int count)
3178 unsigned int channel;
3179 unsigned int channels = rhwparams.channels;
3182 for (channel = 0; channel < channels; ++channel)
3186 size_t len = strlen(names[0]);
3188 memcpy(format, names[0], len);
3189 strcpy(format + len, ".%d");
3191 names = malloc(sizeof(*names) * channels);
3192 for (channel = 0; channel < channels; ++channel) {
3193 names[channel] = malloc(len);
3194 sprintf(names[channel], format, channel);
3197 } else if (count != channels) {
3198 error(_("You need to specify %d files"), channels);
3199 prg_exit(EXIT_FAILURE);
3202 for (channel = 0; channel < channels; ++channel) {
3203 fds[channel] = open(names[channel], O_WRONLY + O_CREAT, 0644);
3204 if (fds[channel] < 0) {
3205 perror(names[channel]);
3210 /* should be raw data */
3212 pbrec_count = calc_count();
3213 capturev_go(fds, channels, pbrec_count, FORMAT_RAW, names);
3216 for (channel = 0; channel < channels; ++channel) {
3217 if (fds[channel] >= 0)
3218 close(fds[channel]);
3220 free(names[channel]);